Annotation spring mvc - no mapping found

Question: I'm fairly new to Spring mvc and would like to make annotation configuration for my app. No web.xml or anything like this. I have written two jsp pages, that I would like to access, two controller classes and one application class with main method as shown below:
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableWebMvc
public class Application extends SpringBootServletInitializer implements WebApplicationInitializer{

    static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Example of controller:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {

    static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @RequestMapping(value = {"/index","/"})
    @ResponseBody
    public ModelAndView index()
    {
        return new ModelAndView("index");
    }
}

and finally my pom.xml which I edited a bit
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.6.RELEASE</version>
    </parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name></name>
    <description></description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>Application</start-class>
        <java.version>1.8</java.version>
        ${basedir}/../..
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>

        <spring.version>3.1.4.RELEASE</spring.version>
        <apache.cxf.version>2.6.1</apache.cxf.version>
        <spring.boot.version>1.1.9.RELEASE</spring.boot.version>
        <spring.version>4.1.2.RELEASE</spring.version>
        <javax.servlet.version>2.5</javax.servlet.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-ws</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.0.RELEASE</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

When I try to access my jsp pages thorugh localhost:8080/index i get :
19:08:36.344 [main] INFO  o.s.b.c.e.t.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080/http
19:08:36.346 [main] INFO  p.e.u.d.s.service.Application - Started Application in 5.493 seconds (JVM running for 6.496)
19:08:42.571 [http-nio-8080-exec-1] INFO  o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring FrameworkServlet 'dispatcherServlet'
19:08:42.571 [http-nio-8080-exec-1] INFO  o.s.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization started
19:08:42.615 [http-nio-8080-exec-1] INFO  o.s.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization completed in 44 ms
19:08:42.651 [http-nio-8080-exec-1] WARN  o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/index] in DispatcherServlet with name 'dispatcherServlet'

Can anyone could provide any help on this issue? I suspect that I should inject a bean with DispatcherServlet but I don't really know where to go with that and how to set it up properly.
Comment: Are your `@Controller` and `@Configuration` classes in the same package?
Comment: First your pom is flawed and you have a problem with your spring version. Just use the Spring Boot provided one. Remove the `spring.version` and remove the `spring-core` dependency. Also remove your `@EnableWebMvc` annotation and the `implements WebApplicationInitializer` those aren't needed. Make sure your `Application` class is either in the same package as your controllers or in the package above that. I tend to place it in a top-level package so that the `@ComponentScan` covers everything.
Comment: Thanks, the tip with moving everything to one package fixed my error.
Answer: Add follow configuration upon webMvcConfig.java
@ComponentScan({ "com.your.controller"})

Answer: It might be your Application.java and IndexController.java in two different package. Then you have to mention like this. @ComponentScan(base = "your packge")
For complete example :- http://www.mydevgeek.com/2017/02/14/building-a-simple-rest-service-with-spring-boot/


How to generate the tone of a specific waveform?

Question: Most synthesizers can generate the common standard types of waveforms, such as sine, triangle, square, sawtooth, pulse, noise, etc. And these can be used to create various types of timbre in a synthesized tone.
Today I found myself wondering how to generate specific custom waveforms, such as the one illustrated below:

It's easy to see that this is a pairing of a square wave and a triangle wave with specific differences in amplitude. Of course this would result in a tone sounding different than just a square wave, or just a triangle wave, or any blending of the two. This is a unique waveform with its own unique timbre.
For such a fundamental sort of audio editing, I was surprised that I couldn't think of any way to craft custom tones like this.
Web searches have led me to several solutions that seemed promising at first, but in the end did not allow quite this level of customization.
What are some methods for generating an audio tone from a specific graphed waveform?
Thanks in advance for any help.
Comment: You could, you know, just use Python or Matlab to generate the numeric sequence.  It's really not that hard to learn those.  (or Octave, the free semi-replacement for Matlab)
Comment: I've reopened it now since it fits our scope much better now
Comment: @CarlWitthoft What resources might you recommend to steer a Python noob in the right direction to do that? I've never used Python to render audio, although I've been curious about it.
Comment: Hi Mentalist. Unfortunately software recommendations are off topic on this SE. You can try the software recs SE if you can make your question fit its guidelines
Comment: @Dom Okay, sorry about that. I was on the fence about which SE to post in, actually. Was hoping the audio expertise of this SE would prove more fruitful than the general recommendations SE. Since it is off-topic should I delete this question?
Comment: @Dom I have re-framed the question in a way that perhaps the question can be answered without relying on software-specific advice.
Comment: How to learn Python?  My recommendation would be to Google "Python Tutorial" and prepare to be buried under an avalanche of free online tutorials
Comment: @CarlWitthoft I meant specifically handling audio with Python. I have studied Python basics, but never used it to create or edit audio data. I'll Google this of course, but was just curious if you had any recommendations for a place to start.
Answer: The zero-skills option is to just freehand-draw the waveform in a dumb GUI editor, even Audacity will do

then copy&paste it a couple of times

and play that in a loop.
This isn't really practical though: waveform drawing is fiddly and even if the waveform is supposed to be smooth, you'll inevitably leave some rough edges which will actually be very noticeable in the sound (sharp edges = transients = unkempt high overtones). Pretty much anything you can produce this way will sound like a simultaneously boring and nasty buzzsaw.
A simple script in some programming language is much more convenient, and easy enough to do, but frankly it's not that useful either. The ear doesn't really hear waveforms, it rather hears frequency spectra. The standard gang of sine, triangle, sawtooth and square is not just easy to generate with analogue electronics, it's also pretty much all you'll ever need as the starting point for any truely periodic-waveform signal. The fine-tuning of how it should sound is most effectively done with subtractive filtering, rather than with waveform manipulation. You can also hard-bake a frequency response in a wavetable waveform, but this doesn't in principle accomplish anything a sawtooth + FIR filter couldn't also accomplish.
To go beyond the standard analogue oscillator sound, what you need isn't so much finer waveform tweaking as time dependence tweaking. Real instrument signals and most decent synths have not truely periodic waveforms, but distinctive attack sounds and/or modulation effects going on. It can make sense to modulate the waveform itself, – that's what FM / phase-modulation and basically also ring modulator circuits accomplish. Explicitly parameterising the waveform in some other way would be trickier and probably not accomplish much more interesting either.
Answer: I don't have any particular musical experience with this but some terminology and ideas that might be useful:

On the electronics test bench, what you are looking for is known as arbitrary waveform generation and is a feature of signal generators. It totally doesn't make sense to buy one if you're just going to convert its output to digital audio right away, but perhaps knowing the name is useful.
If you're up for a bit of programming, you could generate a file containing just the sequence of binary numbers representing the waveform, up to however many repetitions is useful, and then use an audio editor (such as Audacity (which I make no claim is a good choice, just that I know it can do this and it is free)) to convert it to a more typical audio format, if your programming language of choice doesn't have a handy library to write audio files anyway. Just about any language would be able to put the binary data in a file, though some make it easier than others.
I also have learned that Pure Data, a visual programming environment for music among other things, easily allows doing this; you can literally draw a waveform with your mouse (or load it from a file) as it is playing. (I don't have it in front of me so I can't provide an example; I'll see if I can get to that later.)
The technique of using arbitrary waveforms and changing between them to change timbre is called wavetable synthesis. You might have some look finding software intended to do this that also allows loading/creating new waveforms — I don't know whether that's a thing as I only recently learned the concept, but it seemed relevant enough to mention.
You could put it together from scratch using simple audio editing operations (I feel like Audacity should be able to do all of this but I don't have it in front of me to check): generate or import a square wave, delete the low half, generate a triangle, then take the whole thing and duplicate/repeat it for as many periods as you need.
Comment: Thank you for these suggestions and details. I am familiar with granular synthesis and wavetable synthesis (thanks to Reason's Malström, which invented the hybrid: [graintable synthesis](https://www.propellerheads.se/en/reason/instruments/malstrom)). I have never used Pure Data, but just now downloaded it based on your recommendation. I do use Audacity, but in limited scope. In any case I appreciate your answer.
Answer: Based on this answer, here's a modified Python script to approximate your waveform with pyaudio, scipy and numpy:
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

p = pyaudio.PyAudio()

fs = 44100       # sampling rate, Hz, must be integer
duration = 2.0   # in seconds, may be float
f = 440.0        # sine frequency, Hz, may be float

one_cycle = np.linspace(0, 2 * np.pi, int(fs/f), endpoint=False)

waveform = np.concatenate([
    signal.square(one_cycle, duty=1.0) * 0.75 - 0.5, # 3/4 volume and offset
    signal.sawtooth(one_cycle, width=0.5) * 1.0,     # Full volume
    #np.sin(one_cycle)
    ]
)

samples = np.tile(waveform, int(fs * duration / len(waveform)))

print(len(samples))

plt.plot(np.tile(waveform, 2))
plt.show()

# for paFloat32 sample values must be in range [-1.0, 1.0]
stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=fs,
                output=True)

stream.write(samples)

stream.stop_stream()
stream.close()

p.terminate()

The waveform looks like this:

pyaudio plays the tone when the Python script is run.
It's also possible to save it as '.wav' file:
from scipy.io import wavfile
wavfile.write('square_and_triangle.wav', fs, samples)

Here a 2 second example.
Comment: Yeah, seriously, this seems to be a pretty great answer!
Comment: Downvoter : please explain.
Comment: This in my opinion is the superior answer
Answer: The way to create this kind of waveform is to combine oscillator sync with amplitude modulation or ring modulation. Here's a similar waveform created by syncing a slightly asymmetrical pulse wave to a triangle wave tuned around 15 semitones higher, and then modulating the amplitude of the triangle wave with the pulse wave.
(I'm using a virtual analog synth I've made in an old version of Reaktor for this; setting the oscillator mix knob around 80 modulates the amplitude of oscillator 2 by 50% of oscillator 2, which means the pulse signal from oscillator 1 varies from 0 to +1.)

Although this wave may look interesting, it sounds very much like a staightforward square wave, because the two jumps in the waveform have a much greater impact on the sound than the triangle-y bit.
On first-generation samplers like the Casio FZ-1 and the Korg DSS-1, drawing waveforms like these, or combining parts of different waveforms (much like your drawing) was one of the ways to create new sounds. However, on later samplers and synths from these and other manufacturers, this option was rarely present, probably because it's not a very intuitive way to create useful sounds.
In this fragment from a brochure for the Korg DSS-1 you can see the idea of combining the upper half of a sawtooth wave with the lower half of a square wave illustrated, as an example of the sampler's capabilities:


Order of the largest cyclic subgroup of $Z_6 \times Z_{10} \times Z_{15}$

Question: $\mathbb{Z}_6 \times \mathbb{Z}_{10} \times \mathbb{Z}_{15}$ has a cyclic subgroup of order $30$ which is $\mathbb{Z}_2 \times \mathbb{Z}_{5} \times \mathbb{Z}_{3}$.
Is it the largest or not?
Comment: If you pick any element $g=(a,b,c)$ it must satisfy $g^{30}=1$, so there cannot be any larger cyclic subgroups.
Comment: You might be very interested in learning about the [standard forms](https://en.wikipedia.org/wiki/Finitely_generated_abelian_group#Classification) for finite abelian groups, and how to put groups into those standard forms. The largest invariant factor, in particular, is the largest cyclic subgroup of a finite abelian group.
Answer: Using that $\;C_n\times C_m=C_{nm}\;$ for coprime $\;n,m\;$ , you can write
$$C_6\times C_{10}\times C_{15}=C_2\times C_3\times C_2\times C_5\times C_3\times C_5=C_{30}\times C_{30}$$
and now it is much clearer, in my opinion, that for any $\;a\in G:=C_{30}\times C_{30}\;$ we have that $\;a^{30}=1\;$ , so yes: the maximal cyclic subgroup of $\;G\;$ is of order $\;30\;$ .


Cannot gain networking access in CentOS 6.2 installed on Hyper-V

Question: Im trying to test a few pieces of software on a CentOS 6.2 VM installed in Hyper-V on Windows Server 2012 R2. I was able to successfully install CentOS 6.2 in Hyper-V but I am unable to gain access to the internet. If checked the following:
-Running ifconfig and ifconfig -a on lists the default lo
-The file ifcfg-eth0 does not exist on a fresh install (it did exist when I installed CentOS on environments outside of Hyper-V). Creating this file and adding the required contents does not help. Neither ifdown nor ifup will work on eth0 once I create the file. Specifically, it complains that the "directory or file" does not exist.
-The file 70-persistent-net.rules located under /etc/udev/rules.d/ doesn't exist either. I also tried creating the file as well as adding the required contents to it for eth0 and it did not help. As I understand, this file should be automatically regenerated on system start up. It never gets created, no matter how many times the VM is started/restarted. I've looked up a few commands (that I no longer remember) to try to manually force the file to be regenerated. These commands were also unsuccessful.
I should note that I am running the Windows Server as a VM itself within VMware Workstation since our company wants to test and see if the software will work before purchasing the actual software.
Any thoughts?
Comment: Why are you using an out of date version of CentOS?
Comment: The software is currently stable on versions of CentOS up to 6.2
Comment: You should have the software fixed, then. You're going to be three years out of date on security and critical patches.
Answer: RHEL/CentOS did not include the Hyper-V network drivers until 6.4. You should first start with the latest service pack if at all possible (currently 6.6) and test your software with it.
If you're certain you can't update, you need to install the Linux Integration Services, which provides out of tree network drivers.
Answer: For anyone with a similar issue in the future, I found that following the steps in the following guide solved the problem:
http://blog.earth-works.com/2013/04/12/how-to-get-networking-working-in-centos-under-hyper-v/


Generate and validate session in node.js

Question: What is a correct way to generate session and than validate it on every request?
Registration and initial authentication (user identity check for generating session) is handled by external service, so it's out of the question.
To simplify a question, what is the native secure way to generate and encrypt session with secret.

Requirements (alternatives is welcomed):

Session should be of two parts, one stored in cookies, second in database.
User check handled by server using database session part, cookies part and validate function.
Session generating and validating functions stored on server side and not accessible to user.
If database session part or functions is compromised, hacker couldn't make request pretending to be user. For this he will need to steal user cookies or session generate function and database session part.
Multiple device support with the same database session part.
JWT is not usable as logout is needed on server side (database session part will be deleted and all devices wouldn't be able to login with old cookies session part). User had some trust level that can change and it's will require JWT invalidation, so sessions is better choice.

I was thinking of using Crypto AES for this, but after asking "is it ok?" - answer was no, i'm not an expert in crypto, so i didn't fully understood a reason.
Here is my initial idea of implementation:
<code>/**
 * @param {string} data dummy
 * @param {string} userKey from database or create new
 * @return {object} {iv, key, encryptedData}
 */
function encrypt(data, userKey) {
  let key = userKey ? Buffer.from(userKey, 'hex') : crypto.randomBytes(32)
  let iv = crypto.randomBytes(16)
  let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv)
  let encrypted = cipher.update(data)
  encrypted = Buffer.concat([encrypted, cipher.final()])
  return { iv: iv.toString('hex'), key: key.toString('hex'), encryptedData: encrypted.toString('hex') }
}

/**
 * @param {string} iv
 * @param {string} key
 * @param {string} encryptedData
 * @return {string} decrupted dummy data
 */
function decrypt(iv, key, encryptedData) {
  try {
    iv = Buffer.from(iv, 'hex')
    key = Buffer.from(key, 'hex')
    encryptedData = Buffer.from(encryptedData, 'hex')
    let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
    let decrypted = decipher.update(encryptedData)
    decrypted = Buffer.concat([decrypted, decipher.final()])
    return decrypted.toString()
  } catch (err) {
    return false
  }
}
</code>
Comment: I am not sure I understand, but it seems like you want to have a single session for all devices. Usually there is one session per browser per device.
Comment: @Aleuck i have single private key for user and different sessions generated by it for devices.
Answer: A way to make it, is that user generate RSA and use crypto with public and private keys, but the public key must always be sent by the user('device')
<code>    'use strict';
const express = require('express');
const fs = require('fs');
const nodersa = require('node-rsa');
const bodyParser = require('body-parser');

let app = express();
app.use(bodyParser.urlencoded({ extended : false }));
app.use(bodyParser.json());
// req.body.value is public key, this never write in database or file
app.post('/', (req, res)=>{
    let value = req.body.value;
    const privateKey = fs.readFileSync('./store/privateKey.pem', 'utf8');
    const original = new nodersa(privateKey).decrypt(value, 'utf8');
    res.end(original);
});

app.listen(8000, ()=>{
    console.log('on 8000');
});
</code>
if you use a public certificate authority with node, use aditional file called "certification file", node example here, this file is issue by C.A. you could work as C.A. and generarte this file, but It is recommended for closed systems, if you not need a gubernamental allow
Comment: where would the user store the private key?
Comment: on your server but he should generate it with some tool other than you or your service, and it should have expiration
Comment: additionally you can use an authorization entity, so that it keeps the private key, only this entity will say if its public key is valid
Comment: sorry, I have modified my answer, hope help you
Comment: what is public key? How to generate it? It's unique for different users? Can i invalidate this key on user logout so that all devices will logout too? How to use it on localhost?
Comment: You can generate it with tools desktop as 'openssl' or online, and if you need invalidate this, only you need generate new rsa pair in your own server, and send public key to email if is necesary, this link generate rsa pair online https://travistidwell.com/jsencrypt/demo/
Comment: @Soleil after some reading, i don't think that RSA is a way to go for user authentication. I see no examples in web of using it in that way and i already have https.
Comment: in this days, many people use OAuth 2.0, and other variations like it, and they use a third party to request token, this method only requires that you have a component that has logged in, expiration time token, and secret key, It is not a guarantee to be hacked, because it only requires appropriating the device. in another way, rsa plublic key It is only a file known and located by the user, maybe you not need many security


Prometheus Helm Chart: Scrape Target not detected with prometheus.io/scrape annotations

Question: I'm using this prometheus chart. In the documentation it says

In order to get prometheus to scrape pods, you must add annotations to the the pods as below:
metadata:
  annotations:
    prometheus.io/scrape: "true"
    prometheus.io/path: /metrics
    prometheus.io/port: "8080"

So I have created a service like this
apiVersion: v1
kind: Service
metadata:
  name: nodejs-client-service
  labels:
    app: nodejs-client-app
  annotations:
    prometheus.io/scrape: "true"
    prometheus.io/path: /metrics
    prometheus.io/port: "5000"
spec:
  type: LoadBalancer
  selector:
    app: nodejs-client-app
  ports:
    - protocol: TCP
      name: http
      port: 80
      targetPort: 5000

But my Service won't show up in the prometheus targets. What am I missing?
Comment: **...add annotations to the the pods**... By this sentence in my undestandment the annotation must be placed in the pods and not in the service. Have you tried add the annotation to your pods on deployment spec or similar?
Comment: Yes I have tried adding the annotations in my deployment file under `metadata/annotations` and `spec/template/metadata/annotations`, neither are working
Comment: Have you managed to work your way around this? I am having the same [issue](https://stackoverflow.com/questions/66713582/target-does-not-get-scraped-by-prometheus)
Answer: I ran into the same problem with the stable/prometheus-operator chart.  I tried adding the annotations above both to the pods and to the service and neither worked.
For me, the solution was to add a ServiceMonitor object.  Once added, Prometheus dynamically discovered my service:
Fig 1: target list
Fig 2: dynamically added scrape_config
Solution Example
This single command fixed the problem: kubectl apply -f service-monitor.yml
# service-monitor.yml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  labels:
    release: prom
  name: eztype
  namespace: default
spec:
  endpoints:
    - path: /actuator/prometheus
      port: management
  namespaceSelector:
    matchNames:
      - default
  selector:
    matchLabels:
      app.kubernetes.io/name: eztype

Here, my pods and service were annotated with the name eztype and were exposing metrics on port 8282 under the indicated path.  For completeness here's the relavant part of my service definition:
# service definition (partial)
spec:
  clusterIP: 10.128.156.246
  ports:
  - name: http
    port: 80
    protocol: TCP
    targetPort: http
  - name: management
    port: 8282
    protocol: TCP
    targetPort: 8282

It's worth noting that ServiceMonitor objects are used in the Prometheus chart itself:
$ kubectl get servicemonitors -n monitor
NAME                                               AGE
prom-prometheus-operator-alertmanager              14d
prom-prometheus-operator-apiserver                 14d
prom-prometheus-operator-coredns                   14d
prom-prometheus-operator-grafana                   14d
prom-prometheus-operator-kube-controller-manager   14d
prom-prometheus-operator-kube-etcd                 14d
prom-prometheus-operator-kube-proxy                14d
prom-prometheus-operator-kube-scheduler            14d
prom-prometheus-operator-kube-state-metrics        14d
prom-prometheus-operator-kubelet                   14d
prom-prometheus-operator-node-exporter             14d
prom-prometheus-operator-operator                  14d
prom-prometheus-operator-prometheus                14d

Answer: you must add annotations to the the pods.
NOT service
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: For use annotations for pods you need to add job 'kubernetes-pods' to prometheus scrape config  https://github.com/prometheus/prometheus/blob/main/documentation/examples/prometheus-kubernetes.yml#L257
example:
- job_name: 'kubernetes-pods'
  honor_labels: true

  kubernetes_sd_configs:
    - role: pod

  relabel_configs:
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
      action: keep
      regex: true
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape_slow]
      action: drop
      regex: true
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scheme]
      action: replace
      regex: (https?)
      target_label: __scheme__
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
      action: replace
      target_label: __metrics_path__
      regex: (.+)
    - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
      action: replace
      regex: (.+?)(?::\d+)?;(\d+)
      replacement: $1:$2
      target_label: __address__
    - action: labelmap
      regex: __meta_kubernetes_pod_annotation_prometheus_io_param_(.+)
      replacement: __param_$1
    - action: labelmap
      regex: __meta_kubernetes_pod_label_(.+)
    - source_labels: [__meta_kubernetes_namespace]
      action: replace
      target_label: namespace
    - source_labels: [__meta_kubernetes_pod_name]
      action: replace
      target_label: pod
    - source_labels: [__meta_kubernetes_pod_phase]
      regex: Pending|Succeeded|Failed|Completed
      action: drop


VBA Renomear todos os arquivos que começam com "Rel"

Question: Olá
Preciso gerar um código que renomeie todos os arquivos de uma pasta que comecem com "relat" para "X-CT".
O restante do nome do arquivo, inclusive a extenção ".DOC .PDF . XLS" continuaram inalteradas.
Comment: Isso precisa ser na Macro do Excel, pois a renomeação acontece após o evento de criação destes mesmos arquivos. Apos renomear, a Macro irá gerar outro lote de arquivos que começam com "relat", depois preciso renomear novamente.... e assim por diante;
Answer: Talvez o código abaixo te ajude. Basicamente, faz um loop pelos arquivos de um diretório e substitui, no nome de cada arquivo, a sequência de caracteres que deseja substituir pela nova.
Segue o código com a edição proposta pelo usuário @Evert:
Sub changeFileName(ByVal srtExtencion as String)

Dim strFolder As String
Dim strFile As String

  strFolder = "C:\SomeFolder\"
  strFile = Dir(strFolder & "\*." & strExtension)
  Do While Len(strFile) > 0
    If InStr(strFile, "relat") > 0 Then
      Name strFolder & strFile As strFolder & Replace(strFile, "relat", "X-CT")
    End If
    strFile = Dir()
  Loop

End Sub

Depois chame a função com a extensão desejada:
changeFileName doc
changeFileName pdf
changeFileName xls

Extraí essa solução deste fórum, junto da edição proposta pelo usuário @Evert
Comment: Não consigo editar sua resposta... mas se puder, edite e coloque código que nosso amigo precisa e depois apagarei minha resposta.
Comment: Edições feitas! Agradeço pela sugestão.
Abraços!


Underscore.js Find and return element using nested array

Question: I have data-structure like this
        var masterObj = [{
            "_id" : "2i4NGzpEpnKZhkxY8",
            "master_sku" : "UAT43-S",
            "available" : [
                {
                    "marketplace_name" : "xyx",
                    "doc_id" : "WCw8Hsyw4D3ab8TAZ"
                }
            ]
        }
        {
            "_id" : "2mf6hghQ7f32CrA3X",
            "master_sku" : "UAT43-XL",
            "available" : [
                {
                    "marketplace_name" : "abc",
                    "doc_id" : "QduDKpT2HqmuaFHRz",
                }
            ]
        }]

I am using underscor.js and my Query is like this
  var result = _.findWhere(masterObj, { "available.doc_id": "WCw8Hsyw4D3ab8TAZ" });

Required result is
   {
        "_id" : "2i4NGzpEpnKZhkxY8",
        "master_sku" : "UAT43-S",
        "available" : [
            {
                "marketplace_name" : "xyx",
                "doc_id" : "WCw8Hsyw4D3ab8TAZ"
            }
        ]
    }

How can i get desigred output. Thanks in advance.
Answer: You don't need underscore for this. Use JavaScript's native find array method with a callback function to find an element available array that has the correct doc_id.
If you know that available will only have one element:

const arr = [{"_id":"2i4NGzpEpnKZhkxY8","master_sku":"UAT43-S","available":[{"marketplace_name":"xyx","doc_id":"WCw8Hsyw4D3ab8TAZ"}]},{"_id":"2mf6hghQ7f32CrA3X","master_sku":"UAT43-XL","available":[{"marketplace_name":"abc","doc_id":"QduDKpT2HqmuaFHRz"}]}]

const result = arr.find(obj => {
  return obj.available[0].doc_id === 'WCw8Hsyw4D3ab8TAZ';
});

console.log(result);

If available has more than one element use some:

const arr = [{"_id":"2i4NGzpEpnKZhkxY8","master_sku":"UAT43-S","available":[{"marketplace_name":"xyx","doc_id":"WCw8Hsyw4D3ab8TAZ"},{"marketplace_name":"bob","doc_id":"WCw8Hsyw4D3a8TAZ"}]},{"_id":"2mf6hghQ7f32CrA3X","master_sku":"UAT43-XL","available":[{"marketplace_name":"abc","doc_id":"QduDKpT2HqmuaFHRz"}]}]

const result = arr.find(obj => {
  return obj.available.some(el => el.doc_id === 'WCw8Hsyw4D3ab8TAZ');
});

console.log(result);


How to calculate the rotation and scale from a view's transform property ?

Question: I have a UIView which I rotate to certain angle or say scale to a level and then I stretch it from its two ends.
to stretch  I need to change its frame.
Before Changing the frame I need to restore its transform to identity and then only I can change its frame and apply the same rotation and scale again.
Answer: <code>// save it
CGAffineTransform transform = myView.transform;
// reset it
myView.transform = CGAffineTransformIdentity;
// change the frame
myView.frame = CGRectMake(/*do stuff to the frame*/);
// restore it
myView.transform = transform;
</code>


Problem adding html to blocks

Question: I seem to have a problem when adding html to a block (i'm using ckk editor), if i toggle Source it loses them html id tag. If I save the Block without toggling, it works fine, but when I go back in to edit the block afterwards, it has lost the div id tag. I have attached a pic which shows the problem in 3 steps. I have it set to Full HTML throughout.
Comment: Just use switch to plain text editor link
Answer: I thinks, you must twig ckeditor config file, and set config.allowedContent = true. Please, see docs http://docs.ckeditor.com/#!/guide/dev_allowed_content_rules
This links below can help you.
https://stackoverflow.com/questions/15659390/ckeditor-automatically-strips-classes-from-div
CKEDitor removes class names, even with the exception in config
Comment: thats fantastic, looking at the link you provided, i was initially tempted to dive in and add the line to config.js, but further down in the chain, i found you can amend the settings under "Admin >> Configuration >> CKEditor", this is explained really well in the link. many thanks.

Problem adding html to blocks


Show dynamic content with "Show More" button with minimum 3 lines of content visible

Question: I want to show 3 lines of dynamic content which may include Heading, Paragraph or span (without cutting of any content) and by clicking on "Show More" button it will show all the content inside.
Here is the code example: Fix height is not solution here which I am using in this example. Please suggest the better work around. Thanks

$('.show-btn').on('click', function(){
$('.show-less').css("max-height" , "initial");
});
.show-less
{
    max-height: 110px;
    margin-bottom: 0px;
    overflow: hidden;
    font-size: 13px;
    line-height: 25px;
    transition: all 1s;
 }

hi, this is a test description.

hi, this is a test description.

hi, this is a test description.

hi, this is a test description.

hi, this is a test description.

Show More
Comment: Maybe [this](https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_read_more) will solve your problem.
Comment: No it does not help here as It is the dynamic content with variety of tags.
Answer: did you mean something like this?
HTML :

hi, this is a test description.

hi, this is a test description.

hi, this is a test description.

hi, this is a test description.

hi, this is a test description.

Show More/Less

CSS:
.box {
  max-height: 8rem;
  margin-bottom: 0;
  overflow: hidden;
  font-size: 13px !important;
  line-height: 25px !important;
  font-family: "Poppins", sans-serif;
  transition: all 1s;
  clear: both;
}

.box--more-mode {
  max-height: initial;
}

JS:
$(".show-btn").on("click", function () {
  $(".box").toggleClass("box--more-mode");
});

codepen
Comment: No it won't help as you have given static max-height which is not okay with dynamic content which may contains only headings or Ul li or any other tags which can be of different heights.
Comment: so, what about extra div, like this? https://codepen.io/ysilavi/pen/QWMyLQo
Comment: This is the dynamic content as I mentioned in my question.


Take over display of a content type node route

Question: I have a discussion content type. I would like the primary viewing experience (at "discussion/discussion-name") to be a cacheable form using a form mode.
Basically, I'm trying to create something like a web app experience where anyone who can view it, can edit it, so there is no point to separating view and edit, a more integrated experience is desired.
It feels like it should be easy, but I haven't found anything about how to override the routing for just one content type.
How can I override the route for a content type?
Answer: You'll need to alter the entity.node.canonical route to do this. You can do this via a RouteSubscriber::alterRoutes() in a custom module to have the route driven by your custom logic. In src/Routing/RouteSubscriber.php:
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

Then build the logic in your custom controller to redirect based on your node type, in src/Controller/NodeRedirectController.php:
namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Redirect to the edit path on the discussion type
    if ($node->bundle() === 'discussion') {
      return new RedirectResponse('/node/' . $node->id() . '/edit');
    }
    // Otherwise, fall back to the parent route controller.
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

Lastly, register your routeSubscriber service in mymodules.services.yml:
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Documentation is on drupal.org: Altering existing routes and adding new routes based on dynamic ones.
Comment: Thanks Shawn, that's really helpful. You saved me a lot of time with this. For benefits of future people, 2 small points: I think "namespace Drupal\test\Controller;" should be "namespace Drupal\mymodule\Controller;
", and also a mymodule.services.yml entry is needed "  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }". https://www.drupal.org/node/2187643 is the docs for this approach.
Comment: No problem. Yeah the namespace was a typo which I've fixed. Feed free to edit the answer with any further details that help you solved the problem.
Comment: This solves the problem with a redirect, isn't there a way to override the route without redirecting?
Comment: @mpp In the controller, you could render the edit form instead of redirecting.
Comment: Thanks a lot @Shawn, because of your answer here I was able to solve my problem mentioned at https://drupal.stackexchange.com/questions/303048/show-latest-changes-in-node-view-tab-while-using-content-moderation
Really appreciate it :)
Answer: Here is the other answer that was here but for some reason was deleted today.
The answer provided by Shawn works great, but if you would prefer to have separate controllers per content type eg. PageController, ArticleController etc. This is achievable by the Kernel Subscriber.
services:
  app.node_view_subscriber:
    class: Drupal\app\EventSubscriber\NodeViewSubscriber
    arguments: ['@controller_resolver']
    tags:
      - { name: event_subscriber }

The subscriber listens for the KernelEvents::CONTROLLER event, whereupon you can query the Request and check which node type you have - keeping this logic off the controller.
<?php

namespace Drupal\app\EventSubscriber;

use Drupal\node\NodeInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class NodeViewSubscriber implements EventSubscriberInterface {

  /**
   * The controller resolver.
   *
   * @var \Symfony\Component\HttpKernel\Controller\ControllerResolverInterface
   */
  protected $controllerResolver;

  /**
   * Constructs a new PathSubscriber instance.
   */
  public function __construct(ControllerResolverInterface $controllerResolver) {
    $this->controllerResolver = $controllerResolver;
  }

  /**
   * Returns subscribed events.
   *
   * @return string[]
   *   Subscribed events.
   */
  public static function getSubscribedEvents(): array {
    return [
      KernelEvents::CONTROLLER => 'onController'
    ];
  }

  /**
   * Sets custom controller for a content type.
   *
   * @param \Symfony\Component\HttpKernel\Event\ControllerEvent $event
   *   The event.
   */
  public function onController(ControllerEvent $event): void {
    $request = $event->getRequest();
    $attributes = $request->attributes;

    if ($attributes->has('_route') === FALSE) {
      return;
    }

    $route = $attributes->get('_route');

    if ($route === 'entity.node.canonical') {
      $node = $attributes->get('node');
      if ($node instanceof NodeInterface) {
        switch ($node->bundle()) {
          case 'article': // Node type
            $controller = $this->controllerResolver->getControllerFromDefinition('\Drupal\app\Controller\ArticlesController::collection');
            break;

          default:
            $controller = $this->controllerResolver->getControllerFromDefinition('\Drupal\node\Controller\NodeViewController::view');
            break;
        }
        $event->setController($controller);
      }
    }
  }


Factory Girl isn't scoping in an integration spec

Question: Here's my integration spec. I would like to define those users at the global scope so I can make expectations based on them in all of the spec's expectations. However, doing this means the variables @user_0 and the rest aren't available inside the expectation.
Notice I've got that ap @user_0 in the first expectation to print the hash. It returns nil.
First question is, how do I make globally available variables in an integration spec?
It's worth noting that if I build the variables in the expectation, everything works fine then, it's just when the variables are built outside the expectation.
Am I right in thinking that this is an error? I mean surely I'm going to want to write expectations that use users defined in other specs? Or is each spec a sort of self contained thing, and if transitional fixtures are turned on, the test database is wiped between each expectation? It's just odd that these instance variables aren't scoped by default, as though it's been done on purpose.
require 'spec_helper'
require 'factory_girl'

@user_0 = FactoryGirl.build(:user_0)
@user_1 = FactoryGirl.build(:user_1)
@user_2 = FactoryGirl.build(:user_2)
@user_3 = FactoryGirl.build(:user_3)

describe "foo", js: true do
    it "can create a user" do
        ap @user_0 #=> nil
   end
end

Comment: Is there a reason you aren't assigning the instance variables in a `background` or `before` block?
Comment: No, sounds like a good idea ><
Comment: Yeah using a before block did it. I'm new to integration testing and the syntax is a little different so that threw me!
Answer: Add call to :before method to evaluate the specified block before each it operation:
require 'spec_helper'
require 'factory_girl'

describe "foo", js: true do
   before :each do
      @user_0 = FactoryGirl.build(:user_0)
      @user_1 = FactoryGirl.build(:user_1)
      @user_2 = FactoryGirl.build(:user_2)
      @user_3 = FactoryGirl.build(:user_3)
   end

   it "can create a user" do
      ap @user_0 #=> nil
   end
end

And make sure that your user factory has been properly written.


Shortening my IF statement containing both: & and ||

Question: Here's my code:
if(whats.above(x,y)=="g" && whats.onLeft(x,y)=="g") {
    $(this).css("border-top-color","green").css("border-left-color","green");
}

whats.above and whats.onLeft can return some letters. In this case, my statement checks if it's going to return g in both cases.
However, I have more letters now, and I want this statement to be true for more of them. Here, there's only one letter, g, but I want some others, for example n. I know I cannot do something like this:
if(whats.above(x,y)==("g"||"n"))

What can I do to minimalize my code in this case?
Answer: Well, The problem is in your statement is it should be
if(whats.above(x,y)=="g"|| whats.above(x,y) == "n"){    }

For a better solution, I would go with
if (["g","n"].indexOf(whats.above(x,y)) > -1){    }

Comment: I need both, `whats.above` and `whats.onLeft` return `g` or `n` in my statement. My statement is correct and I need to **extend** it. Although, `indexOf();` helped me out here, thanks!
Answer: You could use String#indexOf with a string with the letters.
if ('gn'.indexOf(whats.above(x,y)) !== -1) {


Fatal error when runing es() function in R

Question: es function in smooth package has a weird behavior for some short time-series. Here is a case:
require(smooth) # version 2.4.7

#create two time series of length 10
vec1_ts<-ts(c(36,24,51,7,7,77,1,29,19,2),start=c(2016,1),frequency=12)
vec2_ts<-ts(1:10,start=c(2016,1),frequency=12)

#this works:
es(vec1_ts)

#but this doesn't:
es(vec2_ts)

# another non-working example with a shorter length
vec3_ts<-ts(c(23,5,4,12,2,5),start=c(2016,1),frequency = 12)
es(vec3_ts)

I got a "R encountered a fatal error" message, and then forced to terminate the session when running es for the second time-series.
Answer: This looks like a bug in the function of that package. Can you, please, submit the bug here: https://github.com/config-i1/smooth/issues
The StackOverflow is not for solving problems of specific packages, it is for the solution of more general problems.
Comment: This has been fixed in v22.214.171.124009, which is currently on github: https://github.com/config-i1/smooth


Pegar o intervalo de datas separado por semanas do mês atual

Question: Estou precisando pegar o dia que começa e termina cada semana do mês corrente:

1 - 2019-10-01 à 2019-10-04
2 - 2019-10-07 à 2019-10-11

$today_date = date("Y-m-d");
$currentWeek = ceil((date("d",strtotime($today_date))
                   - date("w",strtotime($today_date)) - 1) / 7) + 1;

$i = 1;
while ($i <= $currentWeek) {
    echo "X";
    //$last_week_end = date("Y-m-d", strtotime("last week friday"));
    $i++;
}

Answer: Utilize formatos relativos https://www.php.net/manual/pt_BR/datetime.formats.relative.php
  $dataInicial = new DateTime('first day of this month');
  $dataFinal = new DateTime('last day of this month');

  echo  'Data Inicial: '.$dataInicial->format("d/m/Y").'
';
  echo  'Data Final: '.$dataFinal->format("d/m/Y").'
';

Answer: Pelos seus exemplos, você quer somente os dias de segunda à sexta do mês atual. Sendo assim, você pode tirar proveito dos formatos relativos para iterar pelas datas:
$data = new DateTime('first day of this month');
$dow = $data->format('N');
if ($dow == 6 || $dow == 7) {
    // se for sábado ou domingo, ajusta para a próxima segunda-feira
    $data->modify('Monday');
}
$mes = $data->format('m');
$mesmo_mes = TRUE;
while ($mesmo_mes) {
    $inicio = $data->format("Y-m-d");
    $data->modify('Friday');
    if ($mes != $data->format('m')) {
        // foi para o mês seguinte, voltar para o mês atual e ajustar para para o último dia
        $data = new DateTime('last day of this month');
        $mesmo_mes = FALSE;
    }
    echo  "{$inicio} - {$data->format('Y-m-d')}
";
    $data->modify('Monday');
    if ($mes != $data->format('m')) {
        break; // se a próxima segunda-feira está no mês seguinte, sai do loop
    }
}

Eu começo no primeiro dia do mês e vou até a próxima sexta-feira (usando modify('Friday')). Caso a sexta-feira esteja no mês seguinte, eu faço um ajuste para o último dia do mês.
Também trato outros casos, como se o primeiro dia do mês cair em um fim de semana, eu ajusto para a próxima segunda-feira. No meio do loop, se a segunda-feira seguinte estiver no próximo mês (ou seja, o mês pode terminar no sábado ou domingo), eu não preciso imprimir a respectiva semana.
Em seguida imprimo o início e fim de cada semana no formato indicado (ano-mês-dia).
Answer: Dependendo do dia, pode ter alguns erros em sua aplicação, por isso é importante verificar em qual semana está se obtendo os dias (isso por causa que alguns lugares a semana começa na segunda, e não no domingo)
    $sunday = new DateTime('2019-10-29');
    $sunday->modify(($sunday->format('w') === '0') ? 'sunday this week' : 'sunday last week');

    $saturday = new DateTime('2019-10-29');
    $saturday->modify(($saturday->format('w') === '6') ? 'now' : 'saturday this week');

    echo 'semana começa em:'. $sunday->format('d/m/y');
    echo '
';
    echo 'semana termina em:'. $saturday->format('d/m/y');

depois disso é só adicionar isso dentro de um foreach ou algun outro loop com a contagem do mês


Viewpager2 and Fragments

Question: ViewPager2 does not support direct child views

I'm trying to transition between fragments using the following code but I get the above error when using viewpager2.
Call in fragment 1 to transition to fragment 2:
getFragmentManager().beginTransaction().replace(R.id.viewPager2, new q2_fragment()).addToBackStack(null).commit();

Viewpager2 XML in Main Layout:
<androidx.viewpager2.widget.ViewPager2
            android:id="@+id/viewPager2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="10"
            android:orientation="horizontal"
            android:scaleType="fitXY" />

Instantiation in Main:
final ViewPager2 viewPager2 = findViewById(R.id.viewPager2);
        viewPager2.setAdapter(new QuestionsActivity.ScreenSlidePagerAdapter(this));
        viewPager2.setUserInputEnabled(false);

How do I avoid this error with viewpager2?
Answer: I got the same error when I put the TabLayout before ViewPager 's closing tag
That is:
<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
</androidx.viewpager2.widget.ViewPager2>

Which is not Allowed!
Just Removing the ending tag and separating TabLayout will work
<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

Answer: Would be happy to help, please elaborate on your requirement. What exactly you want to do.
If you want to go to fragment 2 from  fragment 1, at a particular point then you should use interface between fragment and activity, to tell the activity to move the viewpager to the item which has fragment 2.
Interface Pattern for Fragment to Activity
Interface
public interface FragmentCallback{
    public void goTo(int pos);
}

Activity
public class MyActivity extends AppCompatActivity implements MyStringListener{

  @Override
  public void goTo(int pos){
        yourviewpagerAdapter.setCurrentItem(pos);
  }

}

public class Fragment1 {

        private FragmentCallback callBack;

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                callBack = (FragmentCallback) context;
            } catch (ClassCastException castException) {
                /** The activity does not implement the listener. */
            }
        }

        public void someEvent() {
            if(callBack!=null) {
                callBack.goTo(1);
            }
        }

    }

Comment: Thank you for your answer. I do not recall the specific problem I was facing other than what I stated in this post, but I do believe interfacing is the way to go and what I eventually ended up using in the app I was working on.
Comment: @MAF hope the answer helped you, and ill appreciate it if you could accept the answer.
Answer: As the statement says
ViewPager2 does not support direct child views
So never try to add the fragment to viewPager2 directly
i.e the following lines of code will not work with viewPager2.
getFragmentManager().beginTransaction().replace(R.id.viewPager2, new q2_fragment()).addToBackStack(null).commit();

The exception is produced if you try to add fragment directly to viewPager2 with the help of fragmentManager.
So simply remove the above lines of code to get rid of this exception.
Answer: Lets Say From Fragment_1 to Fragment_2:
In side the button click in Fragment_1
Bundle result = new Bundle(); result.putString("bundleKey", "result"); getParentFragmentManager().setFragmentResult("requestKey", result);

In side the  Fragment_2 onCreate(Bundle savedInstanceState) method
getParentFragmentManager().setFragmentResultListener("requestKey", this, new FragmentResultListener() {
 @Override public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle)
 {
supported String result = bundle.getString("bundleKey"); System.out.println("----------------------------"+result);
}
 });

https://developer.android.com/guide/fragments/communicate#pass-between-fragments
Comment: https://developer.android.com/guide/fragments/communicate#pass-between-fragments
Answer: Use  mPager.setNestedScrollingEnabled(true);
Comment: Please provide more details: why/how your suggestion works? How it addresses the original issue?

Viewpager2 and Fragments


Como fazer para uma imagem com link aparecer um texto

Question: Eu preciso fazer um código pra que um botão (que é uma imagem) quando eu passar o mouse a imagem vai subir e um texto descer (nome do ícone da imagem), ja tentei deixar o botão com opacity(0) e um hover com opacity(1) do texto ai quando a imagem levantar o texto aparece, contudo não deu certo porque o texto fica na frente(z-index não funcionou) se alguém tiver outra ideia...
 -> como fica
 -> como deveria ficar (ai a imagem sobe e o titulo aparece)
[desculpa a qualidade da foto]
Comment: Você pretende usar jQuery? Tenho uma solução que esse framework para criar a animação.
Answer: Amigo se entendi bem esse é o efeito que vc precisa. Fiz do jeito mais simples para ficar mais didático.
Basicamente vc tem um texto com poition:absolute e z-index:-1 quando vc faz o :hover no .wrapper a img faz um transform:translateY(-40px) e o texto aparece por traz.

.wrapper {
    position: relative;
    width: 100px;
    height: 100px;
    overflow:hidden;
}
.wrapper img {
    transition: transform 500ms ease;
}
.wrapper:hover img {
    transform: translateY(-40px);
}
.wrapper .txt {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
    font-family: sans-serif;
    font-size: 2rem;
    color: red;
    z-index: -1;
}

Texto

Answer: Usando transition de CSS, é possível fazer da seguinte maneira. Você pode ver mais sobre essa propriedade na página da MDN

button {
  padding: 8px 14px;
  background: #0084ff;
  background-image: url("https://s19.postimg.cc/4khrr69kz/img_1.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border: none;
  border-radius: 5px;
  font-size: 15px;

  color: transparent;
  background-position: 0 0px;
  transition: .7s ease-in-out 0s;
}

button:hover {
  color: #fff;
  background-position: 0 -50px;
  transition: .7s ease-in-out 0s;
}

  <button>Change color</button>

Uma maneira usando jQuery é a seguinte.

$(document).ready(function() {

// DOM cache
var $banner = $("#banner-message");
var $button = $("button");

// Button properties
var bColor = {
    over : $button.css("color"),
    out  : "transparent"
}

// Set color
$button.css({ "color" : bColor.out });

// Events
$button.on("mouseover", function() {
    var height = $button.css("height");

    $(this).animate({
        "background-position-y" : "-=" + height
    }, 500, function() {
        $(this).css("color", bColor.over);
    });
});

$button.on("mouseout", function() {

    $(this).css("color", bColor.out);
        $(this).animate({
        "background-position-y" : 0
    }, 500);
})

});
button {
  padding: 8px 14px;
  background: #0084ff;
  background-image: url("https://s19.postimg.cc/4khrr69kz/img_1.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border: none;
  border-radius: 5px;
  font-size: 15px;
  color: #fff;
}

  <button>Change color</button>

Mas esse script em jQuery necessitará adaptações se houver mais de um botão na página.
Comment: valeu cara, mesmo eu não tendo conseguido usar esse (muito complexo) valeu
Answer: Uma forma simples é você usar a imagem do botão como background do link, assim você pode colocar um fundo específico para cada botão, e usar uma tag própria para o texto e fazer a transição: o botão sobe e o texto desce:

body{
   background: orange;
}

.botao{
   width: 100px;
   height: 100px;
   position: relative;
   float: left;
   margin: 5px;
}

.botao a{
   width: 100%;
   height: 100%;
   display: inline-block;
   background-size: cover;
   position: absolute;
   left: 0;
   top: 0;
   border-radius: 10px;
   -webkit-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.75);
   -moz-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.75);
   box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.75);
   transition: all .3s ease;
}

.botao a b{
   color: #fff;
   width: 100%;
   text-align: center;
   position: absolute;
   bottom: 0;
   z-index: -1;
   opacity: 0;
   transition: all .3s ease;
}

.botao:hover a{
   top: -15px;
}

.botao:hover a b{
   bottom: -20px;
   opacity: 1;
}

      Astronomia

      Geografia

Comment: valeu man, consegui resolver


Two definitions for regular rings

Question: A noetherian ring $R$ is said to be regular if every localization at a prime ideal is regular local.
On the other hand, there is another definition of regularity for non-noetherian rings:

A (commutative) ring $R$ is said to be regular if every finitely
  generated ideal has finite projective dimension.

In many books (e.g. 'Commutative Coherent Rings' by Sarah Glaz), it is said that these two definitions coincide for noetherian rings.
However, I can't prove it nor find any proof.
Is there any reference or proof? Thanks.
Edit:
By Serre's theorem, two definitions coincide for noetherian local rings and for noetherian rings of finite dimension.
Comment: Could you show how some ideal in  $k[t^2,t^3]$ fails to have a finite projective resolution ?
Comment: It has a cusp at the origin so it is not regular.
Comment: I see; I know that the "homological" regularity implies the "ideal-theoretic" regularity, and the converse is the problem.
Answer: I have proven it!
Let $M$ be a f.g. $R$-mod, and take a projective resolution
$$\cdots \overset{d_2}{\to} P_2 \overset{d_1}{\to} P_1 \overset{d_0}{\to} P_0 \to M \to 0.$$
Put $K_i := \operatorname{Ker}d_i$. It suffices to show that there exists $N \geq 0$ such that $K_N$ is projective.
For each $p \in X:= \operatorname{Spec}R$, set $d(p):= \operatorname{pd}_{R_p} M_p < \infty.$
Then $(K_{d(p)})_p$ is free, and thus there is an open neighbourhood $U_p$ of $p$ in $X$ such that $K_{d(p)}$ is free on $U_p$.
Since $X$ is quasi-compact, we can choose a finite number of primes $p_1, \cdots p_n$ so that
$$X = U_{p_i} \cup \cdots \cup U_{p_n}.$$
Set $N:= \underset{i}{\operatorname{max}} d(p_i )$.
For any $p\in X$, there is an $i$ such that $p \in U_{p_i}$.
Then $(K_{d(p_i)})_p$ is free and thus $d(p) \leq d(p_i) \leq N$.
Thus $(K_N)_p$ is free. Therefore $K_N$ is projective, as wanted.

Two definitions for regular rings


Is the function $\sin x$ a transformation of $\cos x$?

Question: In my study of functions I've briefly learnt about transformation of functions wherein we can reflect, stretch , translate or compress a base function (informally) by adding out multiplying a constant to the variable or function itself. Suddenly the graph of trigonometric functions clicked my mind ( ... which I haven't studied in detail ) and I wondered whether function $\sin x$ is a transformation of funcion $\cos x$.
Algebraically $ \ sin^2 x + cos^2 x = 1 $ which shows a relation between the two functions and may be they could be transformed to each other. But here as I don't have a thorough understanding of transformation I don't know whether squaring a function also yields a transformation.
Though I am a bit unsure about it algebraically, geometrically I am firm about my question. This is so because if the cosine function is shifted towards right,  it can certainly be transformed to sine function what I feel intuitively. I may be wrong but these two aspects ( geometric and algebraic) are pestering me to ask  this question .
Please help and thanks.
Comment: Sure. But I think a more useful relation you can use is that $\sin x=\cos(3\pi/2+x)$.
Comment: We can see [here (scroll down most of the way)](http://www.math-prof.com/Trig/Trig_Ch_09.aspx) that $\sin(x+90^\circ)=\cos x$, that is to say $\sin(x+\pi/2)=\cos x$ in radians
Comment: Thanks a lot. One thing I wanted to ask is that you said that sin x = cos ( 270 degrees + x ) is a better relation . Is that so because we are not allowed to transform a function by multiplying it by itself which is not a constant ?
Answer: As people have commented, yes cosine is a translation of sine (and vice versa) and to be precise $\sin(x + \pi/2) = \cos(x)$ and $\sin(x) = \cos(\pi/2 - x)$. This can be seen if you graph the two function and you will see that they do indeed coincide with one another. If you want a more algebraic proof of this, you can use the sum/difference formulas, which state:
\begin{eqnarray*}
\sin(\alpha \pm \beta) & = & \sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\
\cos(\alpha \pm \beta) & = & \cos \alpha \cos \beta \mp \sin \alpha \sin \beta
\end{eqnarray*}
Using these formulas, we have
\begin{eqnarray*}
\sin(x + \pi/2) & = & \sin x \cos \pi/2 + \cos x \sin \pi/2 \\
& = & \sin x \cdot 0 + \cos x \cdot 1 \\
& = & \cos x
\end{eqnarray*}
and
\begin{eqnarray*}
\cos(\pi/2 - x) & = & \cos \pi/2 \cos x + \sin \pi/2 \sin x\\
& = & 0 \cdot \cos x + 1 \cdot \sin x\\
& = & \sin x
\end{eqnarray*}
Comment: Thanks a lot . One last concern is that while transforming a function can we add or multiply it by a function as we add or multiply constants with variables or function itself to transform it ?
Comment: I am not 100% sure what you are asking. We can certainly add or multiply two functions together and get a new function thought I am not sure many would necessarily consider that a transformation. Most consider ''transformations'' to only include scaling and shifting (both horizontally and vertically). So if you multiplied a function $f(x)$ by the function $g(x) = c$ for some constant $c$, that would correspond to scaling and adding $g(x)$ would correspond to a vertical shift.
Comment: Is it that when we are adding or multiplying a function to a function the results cannot be generalized as in case of constants and that's why we don't consider it as a transformation. I asked this before also in another question . Anyways thanks again .


Banner block (referenced by url) not displayed when using language extensions

Question: I have a Banner View block that appears on pages using a reference url field.
When the url: thispage is entered in the reference field of the banner, it appears on domain.com/thispage.
Now that i enabled 2 other languages en + de this reference is not working. Entering the url with the language extension (en/thispage) neither.
I looked into the Views Block. Maybe some code needs to be added. The block has this code under Visibility settings:
<?php $nids=arg(1); $datas=node_load($nids); if ( $datas->type=='referenced' ) { return false; } else{ return true; } ?>

In the View under contextual filter there is some global php. This might be changed to match the path from other languages (de/thispage)
This is the code from Views:
$match_path = ltrim($_SERVER['REQUEST_URI'], '/');

$match_path=explode("/",$match_path);
$match_path=explode("?",$match_path[0]);
return $match_path[0];
//return $_GET['q'];
Any suggestions about how to resolve this?
Answer: You may want to check your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.
You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.


Schedule Cron/Quartz job immediately

Question: I want to schedule job that would run immediately once the server is up, but run only once. I am not able to find the valid values to do the same. I tried this: 0/1 ? ? ? ? ?, but nothing seems to be getting scheduled. Assuming I am correct about the cron format for Quartz i.e <secs> <mins> <hrs> <dayofmonth> <month> <dayofweek>
Can anyone help me out ?
Answer: Cron trigger is an overkill here, use a SimpleTrigger instead:
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
  .startAt(new Date())  //now
  .build();

Schedule Cron/Quartz job immediately


Integral of total derivative vanishes

Question: I am reading Bertrand Eynard's book on Counting Surfaces.
In this book he mentions that the integral of a total derivative vanishes. What does he mean by this?
Basically, I am trying to understand how the formula 2.5.1 follows.

I know that the total derivative of a function is the best linear approximation of that function at a point, as explained in the Wikipedia article. However, I don't see how this total derivative vanishes upon integration.
Thanks!
Comment: I think it's a direct application of the Fundamental Theorem of Calculus, where we have $\int_a^b \partial_t f(t) dt= f(b)-f(a)$ and assuming the function $f$ vanishes at the boundaries, we have $f(a) = f(b)=0$ and hence the integral vanishes.
Comment: Thanks for your comment! However, in this textbook we're considering these matrix integrals to be formal, in the sense that they're generating functions for maps, and it is mentioned in the book that they need not be convergent. Therefore I think it is not the case that the integrand vanishes at infinity.
Answer: In this setting total derivative is the divergence of a "vector" field: the divergence of $G(M)_{i,j} e^{-\frac{N}{t} \operatorname{Tr} V(M)}$. By the divergence theorem we have
\begin{equation}
\int_V (\nabla \cdot F) \, dV = \oint_{\partial V} F \cdot dS,
\end{equation}
where the second integral is the flux of F trough the boundary of V. If $F$ vanishes on the boundary, the LHS will vanish as well. For example with a vector field in two variables $F(x,y) = (f(x,y),g(x,y))$, we get
\begin{equation}
\int_V \frac{\partial f(x,y)}{\partial x} + \frac{\partial g(x,y)}{\partial y} = 0.
\end{equation}
 If we move on to complex variables, $F(w,z) = (f(w,z),g(w,z))$, by the definition of complex derivative in terms of real and imaginary part, we have
\begin{equation}
\int_V \frac{\partial f(w,z)}{\partial \text{Re}{\,w}} -i \frac{\partial f(w,z)}{\partial \text{Im}{\,w}} +
 \frac{\partial g(w,z)}{\partial \text{Re}{\,z}} -i \frac{\partial g(w,z)}{\partial \text{Im}{\,z}}= 0
\end{equation}
Now you can translate this to the matrix case and obtain equation (2.5.1). In this case since entries of $M$ on the diagonal are real, and only entries with $i\leq j$ are independent variables, we get exactly what's in the text.
Finally we must justify that the flux vanishes at infinity. Note that you can still have vanishing integrals in the formal sense (all the coefficients of the formal series vanishes). As explained in remark 2.5.1, the statement holds for both convergent and formal matrix integrals.
In the convergent case, this is because the potential V(M) goes to infinity and so the weight $e^{-\frac{N}{t} \operatorname{Tr}V(M)}$ kills $G(M)$ (we take $t_3,...,t_d$ negative). In the formal case remember that we first expand the exponential and then perform gaussian integrations with the remaining $e^{-\frac{N}{2t} \operatorname{Tr} M^2}$, and this will also kill any monomial of $G(M)$ together with monomials from the expansion of the other traces.

Integral of total derivative vanishes


Set Windows Firewall to Stateless?

Question: Is there a way to "dumb down" the Windows Firewall on Win2003 or Win2008 from stateful to "stateless", and have it only do basic port filtering on the public interface?
If not, is there a simple, stateless software firewall I can replace Windows Firewall with?
I'm looking to do this for performance reasons.
TIA
Answer: If you're just looking for simple packet-filtering then RRAS with some rules added in should be able to do what you want.
Comment: Any pointers on how to get started? I read about the RRAS static filters and they seem to be the thing I'm looking for, but I thought they only applied to actual RRAS servers, and that seems a bit heavy.
Comment: Actually, just follow the wizards. Got it to work in a couple of minutes. Thanks!
Comment: Well just to be clear for everyone... you install RRAS, then go into its MMC snap-in, and you expand "IP routing" then select the "General" item underneath - NOT "NAT/Basic Firewall".

With "IP routing" selected, right-click your external network interface in the list on the right, select Properties, then click "Inbound Filters".

Set Windows Firewall to Stateless?


Menor e maior valor dentro de Objetos com a mesma data

Question: Possuo o seguinte Json:
{
"cod": "200",
"message": 0.0055,
"cnt": 40,
"list": [
    {
        "dt": 1560319200,
        "main": {
            "temp": 15.15,
            "temp_min": 14.49,
            "temp_max": 15.15,
            "pressure": 1021.11,
            "sea_level": 1021.11,
            "grnd_level": 995.76,
            "humidity": 96,
            "temp_kf": 0.66
        },
        "weather": [
            {
                "id": 801,
                "main": "Clouds",
                "description": "céu pouco nublado",
                "icon": "02n"
            }
        ],
        "clouds": {
            "all": 19
        },
        "wind": {
            "speed": 0.78,
            "deg": 246.743
        },
        "sys": {
            "pod": "n"
        },
        "dt_txt": "2019-06-12 06:00:00"
    },
    {
        "dt": 1560330000,
        "main": {
            "temp": 14.69,
            "temp_min": 14.19,
            "temp_max": 14.69,
            "pressure": 1020.69,
            "sea_level": 1020.69,
            "grnd_level": 995.4,
            "humidity": 95,
            "temp_kf": 0.5
        },
        "weather": [
            {
                "id": 801,
                "main": "Clouds",
                "description": "céu pouco nublado",
                "icon": "02n"
            }
        ],
        "clouds": {
            "all": 17
        },
        "wind": {
            "speed": 0.7,
            "deg": 256.122
        },
        "sys": {
            "pod": "n"
        },
        "dt_txt": "2019-06-12 09:00:00"
    },
    {
        "dt": 1560340800,
        "main": {
            "temp": 19.68,
            "temp_min": 19.35,
            "temp_max": 19.68,
            "pressure": 1021.93,
            "sea_level": 1021.93,
            "grnd_level": 996.86,
            "humidity": 74,
            "temp_kf": 0.33
        },
        "weather": [
            {
                "id": 801,
                "main": "Clouds",
                "description": "céu pouco nublado",
                "icon": "02d"
            }
        ],
        "clouds": {
            "all": 23
        },
        "wind": {
            "speed": 0.26,
            "deg": 210.741
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2019-06-12 12:00:00"
    },
    {
        "dt": 1560351600,
        "main": {
            "temp": 25.72,
            "temp_min": 25.55,
            "temp_max": 25.72,
            "pressure": 1020.78,
            "sea_level": 1020.78,
            "grnd_level": 995.84,
            "humidity": 55,
            "temp_kf": 0.17
        },
        "weather": [
            {
                "id": 802,
                "main": "Clouds",
                "description": "nuvens dispersas",
                "icon": "03d"
            }
        ],
        "clouds": {
            "all": 36
        },
        "wind": {
            "speed": 1.34,
            "deg": 72.064
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2019-06-12 15:00:00"
    },
    {
        "dt": 1560362400,
        "main": {
            "temp": 25.68,
            "temp_min": 25.68,
            "temp_max": 25.68,
            "pressure": 1018.44,
            "sea_level": 1018.44,
            "grnd_level": 993.46,
            "humidity": 59,
            "temp_kf": 0
        },
        "weather": [
            {
                "id": 802,
                "main": "Clouds",
                "description": "nuvens dispersas",
                "icon": "03d"
            }
        ],
        "clouds": {
            "all": 47
        },
        "wind": {
            "speed": 2.12,
            "deg": 81.239
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2019-06-12 18:00:00"
    },
    {
        "dt": 1560373200,
        "main": {
            "temp": 18.45,
            "temp_min": 18.45,
            "temp_max": 18.45,
            "pressure": 1019.96,
            "sea_level": 1019.96,
            "grnd_level": 994.89,
            "humidity": 97,
            "temp_kf": 0
        },
        "weather": [
            {
                "id": 802,
                "main": "Clouds",
                "description": "nuvens dispersas",
                "icon": "03n"
            }
        ],
        "clouds": {
            "all": 25
        },
        "wind": {
            "speed": 0.93,
            "deg": 76.605
        },
        "sys": {
            "pod": "n"
        },
        "dt_txt": "2019-06-12 21:00:00"
    },
    {
        "dt": 1560384000,
        "main": {
            "temp": 17.25,
            "temp_min": 17.25,
            "temp_max": 17.25,
            "pressure": 1021.66,
            "sea_level": 1021.66,
            "grnd_level": 996.24,
            "humidity": 97,
            "temp_kf": 0
        },
        "weather": [
            {
                "id": 803,
                "main": "Clouds",
                "description": "nuvens quebradas",
                "icon": "04n"
            }
        ],
        "clouds": {
            "all": 59
        },
        "wind": {
            "speed": 0.68,
            "deg": 309.784
        },
        "sys": {
            "pod": "n"
        },
        "dt_txt": "2019-06-13 00:00:00"
    }
],
"city": {
    "id": 3459712,
    "name": "Joinville",
    "coord": {
        "lat": -26.3045,
        "lon": -48.8487
    },
    "country": "BR",
    "population": 461304,
    "timezone": -10800
  }
}

Gostaria de saber como posso gerar um novo Json, através do descrito acima com apenas com a maior temperatura e menor temperatura do dia, e não a cada 3 horas da forma que o Json me retorna hoje.
Ex: Para o dia 2019-06-12
A maior temp_max foi: 25.72, e a menor temp_min foi: 14.19.
Gostaria de gerar um novo Json +- assim :
{
  "list":[
  {
     "dia":"2019-06-12",
     "temp_min":14.19,
     "temp_max":2572
  }]
}

Já separei o Json em objetos como abaixo, so não sei como fazer para verificar os objetos com a mesma data, para pegar os maiores e menores valores.

aqui crio o meu objeto:
 namespace HBSIS.Models.WeatherViewModels
 {
   public class RootObjectWeather
   {
    public Response[] list { get; set; }
   }
   public class Response
   {
    public string dt_txt { get; set; }
    public Main main { get; set; }
    public List<Weather> weather { get; set; }
   }

   public class Main
   {
    [JsonProperty("temp")]
    public string Temperature { get; set; }

    [JsonProperty("temp_min")]
    public string MinimumTemperature { get; set; }

    [JsonProperty("temp_max")]
    public string MaximumTemperature { get; set; }

    [JsonProperty("humidity")]
    public string Humidity { get; set; }
   }

   public class Weather
  {
    [JsonProperty("description")]
    public string Description { get; set; }
  }
}

var result = weather.list.Select(x => new { day = x.dt_txt, tempMax = x.main.MaximumTemperature, tempMin = x.main.MinimumTemperature })
                                .OrderBy(x => x.day);

Comment: Adicione o código ao tópico amigo.
Comment: @VictorLaio esta adicionado
Comment: @Leandro Angelo, conseguria me ajudar com esse caso ?
Answer: Você consegue pegar a menor e a maior temperatura fazendo a seguinte consulta:

var menorTemperatura = weather.list.OrderBy(c => c.main.MinimumTemperature).FirstOrDefault();
var maiorTemperatura = weather.list.OrderByDescending(c => c.main.MaximumTemperature).FirstOrDefault();
Answer:  [NomeDaVarDoNovoObejeto].list = [NomeDaVar].list.Select(_ => new { dia = _.dt_txt, temp_min = _.main.temp_min, temp_max = _.main.temp_max});

Comment: depois é so converter o objeto anonimo para json e deve ficar igual


form validation problems with jquery / javascript

Question: This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:

Step 3: Your Details

        <form action="" method="">

                Email:
                <input type="text" placeholder="Email Address" id="email" class="form-control your-details">

                Name:
                <input type="text" placeholder="Full Name" id="name" class="form-control your-details">

                Contact Number:
                <input type="text" placeholder="Contact Number" id="number" class="form-control your-details">

                Date of Birth:
                <input type="date" id="dob" class="form-control your-details">

                        </form>

                <input type="submit" id="submit" value="CONTINUE">

JAVASCRIPT / JQUERY:
//collection of input form fields//
    var formSubmit = $("#submit");
    var emailField = $("#email");
    var nameField = $("#name");
    var numberField = $("#number");

    //Switch to true when each validation has passed//
    emailValidated = false;
    nameValidated = false;
    numberValidated = false;

    //email validation check//
    emailField.on("input",function(){
        var emailInput = $(this).val()
        var testExp = new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/);
        if (emailInput < 1) {
            $("#email-warning").html("Email is required!");
            $("#email-warning").css("visibility","visible");
            emailValidated = false;
        }

        else if (!testExp.test(emailInput)){
            $("#email-warning").html("Please enter a valid email");
            $("#email-warning").css("visibility","visible");
            emailValidated = false;

        }   else {
            $("#email-warning").css("visibility","hidden");
            emailValidated = true;
        }

        })

    //name validation check//
    nameField.on("input",function(){
        var nameInput = $(this).val()
        if (nameInput < 1) {
            $("#name-warning").html("Name is required");
            $("#name-warning").css("visibility","visible");
            nameValidated = false;
        } else {
            $("#name-warning").css("visibility","hidden");
            nameValidated = true;
        }

        })

    //contact number validation check//
    numberField.on("input",function(){
        var numberInput = $(this).val()

        if (typeof numberInput !== "number" && numberInput.length < 9) {
            $("#number-warning").html("Please enter a valid number");
            $("#number-warning").css("visibility","visible");
            numberValidated = false;
        } else {
            $("#number-warning").css("visibility","hidden");
            numberValidated = true;
        }

        })

    if (emailValidated && nameValidated && numberValidated){
        alert("correct");
        }

    })

at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
Answer: There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change

$(document).ready(function () {
    //collection of input form fields//
    var formSubmit = $("#submit");
    var emailField = $("#email");
    var nameField = $("#name");
    var numberField = $("#number");

    //Switch to true when each validation has passed//
    emailValidated = false;
    nameValidated = false;
    numberValidated = false;

    //email validation check//
    emailField.on("input", function () {
        var emailInput = $(this).val()
        var testExp = new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/);
        if (emailInput < 1) {
            $("#email-warning").html("Email is required!");
            $("#email-warning").css("visibility", "visible");
            emailValidated = false;
        }

        else if (!testExp.test(emailInput)) {
            $("#email-warning").html("Please enter a valid email");
            $("#email-warning").css("visibility", "visible");
            emailValidated = false;

        } else {
            $("#email-warning").css("visibility", "hidden");
            emailValidated = true;
            enableContinue();
        }

    });

    //name validation check//
    nameField.on("input", function () {
        var nameInput = $(this).val()
        if (nameInput < 1) {
            $("#name-warning").html("Name is required");
            $("#name-warning").css("visibility", "visible");
            nameValidated = false;
        } else {
            $("#name-warning").css("visibility", "hidden");
            nameValidated = true;
            enableContinue();
        }

    });

    //contact number validation check//
    numberField.on("input", function () {
        var numberInput = $(this).val()

        if (typeof numberInput !== "number" && numberInput.length < 9) {
            $("#number-warning").html("Please enter a valid number");
            $("#number-warning").css("visibility", "visible");
            numberValidated = false;
        } else {
            $("#number-warning").css("visibility", "hidden");
            numberValidated = true;
            enableContinue();
        }

    });

    enableContinue = function () {
        if (emailValidated && nameValidated && numberValidated) {
            $('#submit').prop('disabled', false);
        }
    }

});

Step 3: Your Details

            <form action="" method="">

                    Email:
                    <input type="text" placeholder="Email Address" id="email" class="form-control your-details">

                    Name:
                    <input type="text" placeholder="Full Name" id="name" class="form-control your-details">

                    Contact Number:
                    <input type="text" placeholder="Contact Number" id="number" class="form-control your-details">

                    Date of Birth:
                    <input type="date" id="dob" class="form-control your-details">

            </form>

            <input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">

Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Comment: Thanks so much John! I really appreciate it buddy. So was it just a case of typos? I really need to start learning how to write cleaner code.
Comment: No problem. Glad I could help
Answer: Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
    if (emailValidated && nameValidated && numberValidated){
      alert("correct");
    }
});

Don't forget to set id to your form.
Answer: You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.

$('form').on('submit', function() {
  $(this).find('fieldset').append('<input type="text" required />');
  return false;
});

<form>
  <fieldset>
    <input type="text" required />
  </fieldset>
  <input type="submit" id="submit" value="continue" />
</form>


I want to check before appending if the element is already there or not?

Question: <code>$('.negative').on('click',function() {
  var saveImg = $(this).parents('.img_listing_long').find('img').clone();
  $(list).append(saveImg);
});
</code>
If the element is already present in the list then it shouldn't be cloned.
Comment: Do you have something in each image element which uniquely identifies it? e.g. an ID or a data attribute or something? We need a bit more context about your HTML, I think.
Answer: Update it:
<code>$('.negative').on('click',function() {
  if( $(list).find('img').length == 0 )
  {
     var saveImg = $(this).parents('.img_listing_long').find('img').clone();
     $(list).append(saveImg);
  }
});
</code>
Or put the class on img tag like class name "myimage" then:
<code>$('.negative').on('click',function() {
      if( $(list).find('.myimage').length == 0 )
      {
         var saveImg = $(this).parents('.img_listing_long').find('img').clone();
         $(list).append(saveImg);
      }
    });
</code>


The relation between making a note from "pitch & duration" and "name & octave"

Question: This question might need some computer science information as well, but I'm stuck in the music theory side of it: I'm trying to use a library in Python (the programming language) called Mingus that makes a Note object given the name and octave of a note, and there is also another library called JythonMusic  which makes a Note object from pitch and duration. Because the second one is very outdated, I cannot use it for my purpose, so I'm trying to figure out from a music theory perspective if it is possible to convert between these. And if yes, how.
In case you have some computer science background, it would probably help you to check the documentation of these libraries (hyperlinked on their names above) in order to answer me.
I need to mention that I have no background in music theory so I don't know how meaningful my question is, but hopefully someone can help me. Please let me know if you need more details.
Thanks in advance!
Comment: Mingus doesn't store duration in the note object, instead it stores it in the bar - so a mingus note can only encode the pitch from jythonmusic, the duration has to be converted when you add the notes to a bar
Comment: Depends on how much different temperaments or microtonality mean to you I think, I found a cool page called xen-calc that given a pitch ratio gives a name for it, it is the most detailed one I have ever found.
Answer: In music theory terms, pitch and duration are independent elements. Knowing one gives no information about the other.
In Mingus, note names and octaves are considered as separate elements defining a single pitch; whereas JythonMusic just uses a single number for the same purpose. The correspondence can be seen by using Mingus's int() function on a note.
But duration is entirely separate.
JythonMusic specifies duration as part of the note object, while Mingus places it in the bar object.
Answer: Mingus must have a way of indicating duration.   Note name and octave are a way of specifying pitch.
JythonMusic specifies pitch as a numeric quantity corresponding to a MIDI key identifier.  Tables mapping these to name-and-octave values should be easy to come by, for example at https://en.wikipedia.org/wiki/Musical_note#Note_designation_in_accordance_with_octave_name
To convert fully from JythonMusic's pitch-and-duration, you'll need to find out how Mingus handles duration.
Comment: Mingus durations are assigned in the "bar" object.
Comment: @Aaron thanks.  I'm way too busy to do any research for the next few days.  Why isn't this helpful information in your answer?  If you add it, you will surely get some upvotes (I have already upvoted for the mention of `int()`).
Answer: As far as I understand this Mingus does identify a note with the pitch, but not with the duration. You can then add notes, rests and chords along with some duration at some time to a bar, as given in Page 3 of the Tutorials. So it is not exactly possible to convert between these two note objects as they store a different amount of information, with JythonMusic also storing the duration, while Mingus does not and infers the duration externally.
Comment: "infers the duration externally": how?
Comment: @phoog I have not studied how exactly Mingus stores the Music, but it seems like a bar is basically filled by triplets `(time, duration, note(s))`.
Answer: Just to state the absolutely obvious.
Pitch: The frequency of the sound wave. Same letter pitches imply a power of 2 relation between them. So to compute the physical frequency f you'd calculate:
f = base_frenquency* 2^(Octave).
So the A above middle C, on a piano, is 440Hz and if you'd want to have 2 octaves above that then it's
440Hz*2²=440Hz*4= 1760Hz.
Or if you want the 3 octaves below that than it's
440Hz*2^(-3)= 440Hz *1/(2³) = 440Hz *1/8 55Hz.
So if you have a frequency value for one of the note names (those can be looked up) and can figure out how man octaves are between that and your note, then you can compute the physical frequency or vice versa.
Though that is the physics point of view, a musician is usually fine with frequencies being obfuscated by letters. They are  mostly interested in the note names as their relative distance creates melody (played sequentially) or harmony (played parallel). And the octave is relevant for a musician in terms of whether it's within the range of their instrument and how the fingers and/or air stream have to be manipulated to achieve that sound.
The duration: Is ... well the duration of how long you hold the note. It's usually indicated by a combination of the a relative time scale like the note length idk quarter, half, full, eights and so on. AND with an absolute descriptor telling you idk that you play idk 120 quater notes per minute or something like that, could also be that it's just implied with a vague word like "vivid" or "grave" or whatnot indicated it should be played fast or slow but left to you what exactly that means (there are also tables that give a rough estimate). Or if your program is more technical it could be a literal time duration in seconds or milliseconds.
So you can use the name+octave to infer the frequency from it but you'd need to find a different place to make use of the duration information as that is apparently not handled at the note object.


Finding the color at coordinates in a PNG image in Java

Question: With a URL of a PNG image (or the data at that url, in String form), how could one use Java to find the RGB (or similar) value at a set of coordinates?
Thanks in advance!
Answer: This example should have all you need:

http://www.daniweb.com/software-development/java/threads/114513

To cite the relevant part of the thread:
File inputFile = new File("image.png");
BufferedImage bufferedImage = ImageIO.read(inputFile);
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight(null);

//Get Pixels
int [] rgbs = new int[w*h];
bufferedImage.getRGB(0, 0, w, h, rgbs, 0, w); //Get all pixels

and then to get a particular pixel, see the docs:

http://docs.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html#getRGB(int,%20int,%20int,%20int,%20int%91%93,%20int,%20int)

i.e.:
int pixel = rgbs[offset + (y-startY)*scansize + (x-startX)];

If you just want one pixel, you can use getRGB(x, y):

http://docs.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html#getRGB(int,%20int)

i.e.:
int pixel = bufferedImage.getRGB(x, y);


Como permitir que um evento atinja outros elementos de UI?

Question: Eu possuo um xaml que aplico um retângulo sobre várias imagens, com o intuito de poder manipula-las após um holding nelas. O problema é que, caso eu coloque o IsHitTestVisible em estado false no retângulo e, quando uma das imagens disparar o Holding, eu atualize o estado do IsHitTestVisible para true, o retângulo na dispara eventos, como ManipulationDelta, sendo necessário retirar o dedo da  touchscreen e colocá-lo de novo para disparar os eventos no meu retângulo.
O que eu tenho de problema é semelhante a essa pergunta do SOen, apesar de não ter resposta, eles citam técnicas de reflexão e o uso de routed events, no entanto não resolveu o meu problema por eu não saber usar corretamente ou por realmente não ser a solução adequada. Poderiam me dar exemplo de como fazer para resolver esse problema?
Comment: Poste o `XAML` para facilitar o entendimento. @felipe-avelar
Answer: Depois de pesquisar muito, a solução encontrada foi utilizar o VisualTreeHelper.FindElementsInHostCoordinates. Daí o que foi feito foi o seguinte: Primeiro deixamos ativo o retângulo que está sobre as imagens e adicionei o evento de Holding nele, depois utilizo o FindElementsInHostCoordinates pra encontrar as imagens debaixo dele e disparar o evento de Holding para o "filho" correto, já que eu consigo pegar todos os elementos de interface que estão sob o meu dedo. Acredito que essa seja a melhor maneira, mas, caso alguém tenha uma melhor, por favor, compartilhe.