text:
Q: Failed to Autowire @Repository annotated interface after upgrading Spring Boot The below implementation is working with SpringBoot version 2.0.2.RELEASE.
After some dependencies upgrade the code fails to autowire DataRecordDBItemRepository.
The upgrades were:
spring-boot-dependencies 2.2.6.RELEASE
io.github.boostchicken:spring-data-dynamodb 5.2.5 (instead of com.github.derjust)
aws-java-sdk 1.11.807
jsk-bom 2.8.0

I also tried to add @Entity annotation but then I received multiple other errors.
As this implementation is working with older Spring version, I would like to understand why the upgrade in SpringBoot triggered the failure.
The class MyApplication.java looks like this:
package com.company.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication(scanBasePackages = "com.company.app", exclude = {RedisAutoConfiguration.class, ValidationAutoConfiguration.class, CassandraAutoConfiguration.class, DataSourceAutoConfiguration.class})
@ComponentScan(basePackages={"com.company.app"})
@EntityScan(basePackages={"com.company.app.entities"})
@EnableJpaRepositories(basePackages={"com.company.app.repositories"})
public class MyApplication {

    public static void main(String[] args) {
        try {
            SpringApplication.run(MyApplication.class, args);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

The class DataRecordController.java looks like this:
package com.company.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;

@RestController
@RequestMapping("/v1/dataRecord")
public class DataRecordController {

    private DataRecordService dataRecordService;

    @Autowired
    public void setDataRecordService(DataRecordService dataRecordService){
        this.dataRecordService = dataRecordService;
    }

    @RequestMapping(value = "/{tid}", method = RequestMethod.GET)
    public List<DataRecordDbItem> retrieveDataRecord(final @NotBlank @PathVariable String tid){

        List<DataRecordDbItem> dataRecordDbItems = dataRecordService.retrieveDataRecord(tid);

        return dataRecordDbItems;
    }
}

The interface DataRecordService.java looks like this:
package com.company.app.service;

import com.company.app.entities.DataRecordDbItem;
import java.util.List;

public interface DataRecordService {
    List<DataRecordDbItem> retrieveDataRecord(String tid);
}

The class DataRecordServiceImpl.java looks like this:
package com.company.app.service;

import com.company.app.entities.DataRecordDbItem;
import com.company.app.repositories.DataRecordDBItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DataRecordServiceImpl implements DataRecordService {

    private DataRecordDBItemRepository dataRecordDBItemRepository;

    @Autowired
    public void setDataRecordDBItemRepo(DataRecordDBItemRepository dataRecordDBItemRepo){
        this.dataRecordDBItemRepository = dataRecordDBItemRepo;
    }

    @Override
    public List<DataRecordDbItem> retrieveDataRecord(String tid) {
        List<DataRecordDbItem> dataRecordDbItems = dataRecordDBItemRepository.findDataRecordDbItemsByTid(tid);
        return dataRecordDbItems;
    }
}

The repository DataRecordDBItemRepository.java looks like this:
package com.company.app.repositories;

import com.company.app.entities.DataRecordDbItem;
import com.company.app.entities.DataRecordId;
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@EnableScan
@Repository
public interface DataRecordDBItemRepository extends CrudRepository<DataRecordDbItem, DataRecordId> {

    List<DataRecordDbItem> findDataRecordDbItemsByTid(String tid);
}

The Entity DataRecordDbItem.java looks like this:
package com.company.app.entities;

import com.amazonaws.services.dynamodbv2.datamodeling.*;
import org.springframework.data.annotation.Id;
import java.io.Serializable;

@DynamoDBTable(tableName = "DataRecord")
public class DataRecordDbItem  implements Serializable {

    @Id
    private DataRecordId dataRecordId;
    private String originalRequestTime;
    private String tid;

    @DynamoDBRangeKey(attributeName = "originalRequestTime")
    public String getOriginalRequestTime() { return originalRequestTime; }

    public void setOriginalRequestTime(String originalRequestTime) {
        this.originalRequestTime = originalRequestTime;
        if (dataRecordId == null) {
            dataRecordId = new DataRecordId();
        }
        dataRecordId.setOriginalRequestTime(originalRequestTime);
    }

    @DynamoDBHashKey
    public String getTid() { return tid; }

    public void setTid(String tid) {
        this.tid = tid;
        if (dataRecordId == null) {
            dataRecordId = new DataRecordId();
        }
        dataRecordId.setTid(tid);
    }

}

The Entity DataRecordId.java looks like this:
package com.company.app.entities;

import com.amazonaws.services.dynamodbv2.datamodeling.*;
import java.io.Serializable;

public class DataRecordId implements Serializable {

    private static final long serialVersionUID = 1L;
    private String tid;
    private String originalRequestTime;

    @DynamoDBRangeKey
    public String getOriginalRequestTime() {
        return originalRequestTime;
    }

    public void setOriginalRequestTime(String originalRequestTime) {
        this.originalRequestTime = originalRequestTime;
    }

    @DynamoDBHashKey
    public String getTid() {
        return tid;
    }

    public void setTid(String tid) {
        this.tid = tid;
    }
}

The exception is:
{"level":"ERROR","thread":"main","msg":""
***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataRecordDBItemRepository in com.company.app.service.DataRecordServiceImpl required a bean of type 'com.company.app.repositories.DataRecordDBItemRepository' that could not be found.

Action:

Consider defining a bean of type 'com.company.app.repositories.DataRecordDBItemRepository' in your configuration.
"}
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataRecordController': Unsatisfied dependency expressed through method 'setDataRecordService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataRecordServiceImpl': Unsatisfied dependency expressed through field 'dataRecordDBItemRepository'; nested exception is

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.company.app.repositories.DataRecordDBItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataRecordController': Unsatisfied dependency expressed through method 'setDataRecordService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataRecordServiceImpl' defined in file [/Users/myuser/workspace /app/target/classes/com/company/app/service/DataRecordServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.company.app.repositories.sDataRecordDBItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
    at com.company.app.MyApplication.main(MyApplication.java:89)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataRecordServiceImpl' defined in file [/Users/myuser/workspace /app/target/classes/com/company/app/service/DataRecordServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.company.app.repositories.DataRecordDBItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:228)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1290)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1210)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:715)
    ... 19 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com. company.app.repositories.DataRecordDBItemRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1700)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1256)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
    ... 32 more

Process finished with exit code 0

A: One of the pom.xml upgrades were
io.github.boostchicken:spring-data-dynamodb version 5.2.5
which replaced com.github.derjust:spring-data-dynamodb version 5.0.4
I had another dependency that also imported the com.github.derjust.
The impact was that I actually had dependencies to both io.github.boostchicken and com.github.derjust. Spring didn't know which lib to use for the required @Bean.
Excluding the com.github.derjust lib from the other dependency solved the issue.

A: For setter injection to work, the setter method needs to follow Java bean conventions i.e., there should be setter method called set, here it should be setDataRecordDBItemRepository. Corrected the code and please have a try?
package com.company.app.service;

import com.company.app.entities.DataRecordDbItem;
import com.company.app.repositories.DataRecordDBItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class DataRecordServiceImpl implements DataRecordService {

    private DataRecordDBItemRepository dataRecordDBItemRepository;

    @Autowired
    public void setDataRecordDBItemRepository(DataRecordDBItemRepository dataRecordDBItemRepo){
        this.dataRecordDBItemRepository = dataRecordDBItemRepo;
    }

    @Override
    public List<DataRecordDbItem> retrieveDataRecord(String tid) {
        List<DataRecordDbItem> dataRecordDbItems = dataRecordDBItemRepository.findDataRecordDbItemsByTid(tid);
        return dataRecordDbItems;
    }
}


text:
Q: Is there a way to reuse an XML declaration of a UI component in Android? I've done some snooping around for what I feel is relatively simple, however, I guess I wasn't quite sure how to phrase this question because I wasn't getting many results. I apologize if this is a duplicate question. What I want to do is define an EditText with some attributes like so:
<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:background="#00000000"
    android:digits="0123456789.,"
    android:ellipsize="start"
    android:maxLines="1"
    android:gravity="center"
    android:hint="    "/>

And from there, I wish to simply declare MyEditText (Assuming my above definition is called MyEditText), and not have to worry about defining these 9 attributes every time I wish to use an EditText of this style. Is this possible? I have read through Android's guide to Custom components, however, it seems to be overkill for what I am trying to accomplish. (I do not wish to do anything custom persay, I'm just looking to package some already existing functionality into a single component.) Could somebody point me in the right direction?
Thank you!!

A: Use the style for this.
You can create a style as-
   <style name="editText">
        <item name="android:layout_width">@dimen/text_box_width</item>
        <item name="android:maxLines">2</item>
        <item name="android:textColor">#000000</item>
        <item name="android:textSize">15sp</item>
        <item name="android:layout_marginLeft">40dp</item>
        <item name="android:gravity">left</item>
    </style>

And you can set this style in the layout file as
<EditText
 style="@style/editText" />

A: Google ViewStub and see if that will work for your needs.
or I believe you could inflate a new View from the same XML:
 EditText anotherOne = getLayoutInflater().inflate(R.layout.yourLayoutXmlNameHere, null);

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS: Why is vertical-align: baseline stop working on Firefox when using overflow: hidden? You can reproduce this by running this test case. The results are shown in the screenshot below. The issue is that on Firefox, when adding a overflow: hidden on the "block" (with grey background in the screenshot), the block stop being aligned as I'd like it to be: instead of the baseline of the text in the block being align to the the baseline of the parent box, it is as if the bottom of the block was aligned on the baseline of the parent box. As you can see in the screenshot, this doesn't happen with Chrome.

*

*Is this a Firefox bug?

*How to get the expected result on Firefox (baseline alignment with overflow: hidden)?

Note: Using vertical-align: middle on "block" doesn't cut it, as what I really want is baseline alignment. You can see more clearly that vertical-align: middle doesn't do baseline alignment by setting padding: 1em 0 .1em 0 (more padding at the top of the box), which give you:

A: It does look like overflow:hidden is buggy in that it removes the baseline from an inline-block element. Fortunately, there's a seemingly redundant Mozilla CSS extension value for overflow that prevents overflow but doesn't exhibit this buggy behaviour.
Try this:
.block {
    width: 10em; padding: .3em 0 .1em 0;
    overflow: hidden;
    overflow: -moz-hidden-unscrollable;
    white-space: nowrap;
    display: inline-block;
    border: 1px solid #666; background-color: #eee;
}

It looks like it corrects the problem in Firefox and doesn't mess with Safari.
Update:
It looks like Firefox and Opera are rendering overflow:hidden inline blocks correctly and Webkit browsers are not.
According to the W3C CSS2 Working Draft's Visual Formatting Model Details,

The baseline of an 'inline-block' is
  the baseline of its last line box in
  the normal flow, unless it has either
  no in-flow line boxes or if its
  'overflow' property has a computed
  value other than 'visible', in which
  case the baseline is the bottom margin
  edge.

A: try adding vertical-align: text-bottom; to .block
you can also try to set equal line-heights for .label and .block

A: try
.label {
        float: left;
        line-height: 30px;
        margin-right: 5px;
        }

this will get the desired result in both FF and Chrome/Safari.  Did not test in IE however.


text:
Q: Bash newline in string grep $ cat ansible/file | grep "Other users"
Other users

How can i add a new string on a new line after my grep as above?
$ cat ansible/file | grep "Other users"
Other users
NewString  # New line with new string appended to file

A: sed is for doing s/old/new/ on individual lines, that is all. For anything else you should use awk:
awk '{print} /Other users/{print "New Line"}' file

The above will work robustly and efficiently with any awk in any shell on any UNIX box and will be trivial to enhance/maintain if/when your requirements change later.

A: You can use sed to find the string you're looking for, and replace it with itself + the new line:
sed "s/Other users/Other users\nNew Line/g"

We're replacing "Other users" with "Other users\nNew String" (which is the string itself, and a new line appended to it with the content you want to insert).


text:
Q: Will gradient descent be stuck in non-minima point? How can we prove its correctness? For stuck example, let our cost function be J(x,y) = x * y and we are currently at point (0,0)
Then the gradient vector will be (0,0). That means we will not move to any other point with the gradient descent algorithm.
For the later question, let's consider another example: the derivative by x of function F(x,y) (let's call it Fx(x,y)) is negative, and the derivative by y of function F(x,y) (let's call it Fy(x,y)) is also negative. Then, what we will do with gradient descent is moving along the vector alpha * (Fx(x,y), Fy(x,y)). How can we guaranteed that F(x + alpha * Fx(x,y),y + alpha * Fy(x,y)) < F(x,y) for any sufficiently small alpha??

A: There is no guarantee for gradient descent algorithms to find the global minimum or even a local minimum.
Yes, the algorithm would be stuck at (0,0) as you described. However you will most likely never be exactly at (0,0).
Also there are a lot of techniques that prevent this from happening.


text:
Q: How to reference unrendered dom node using useRef? So basically I am using a material ui component (Dialog) and whenever I click to open it, the error of:
"Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside StrictMode. Instead, add a ref directly to the element you want to reference"

I narrowed the issue down to the fact that there is no reference to the node because well it hasn't been rendered yet so the reference is null. The error only occurs once when dialog is first opened so I can be sure thats the reason for the error because after it renders for the first time, there is a reference. Dialog is a modal so of course its null because it won't be rendered until prompted. So how can I get rid of this issue? I am using function based components so I was thinking of using useRef but so far it hasn't solved the issue for me. Here is the Dialog.
         <Dialog maxWidth='sm' fullWidth onClose={handleClose} open={commentsOpen}>
            <MuiDialogTitle disableTypography className='modalTitle'>
                <Typography align='center' variant="h6">Modal</Typography>
                {handleClose ? (
                <IconButton aria-label="close" className='closeBtn' onClick={handleClose} style={{ color: 'red' }}>
                    <CloseIcon />
                </IconButton>
                ) : null}
            </MuiDialogTitle>
            <MuiDialogContent dividers className='modal'>
                {isLoading ? (

                        <CircularProgress style={{ color: 'red' }} />

                ) : (

Testing

                )}

            </MuiDialogContent>
            <MuiDialogActions className='modalAction' />
        </Dialog>

Thank You!


text:
Q: How to deploy a machine learning model on EC2 and connect to API Gateway without Lambda? I have trained a classifier using scikit.learn. I want to set up an API Gateway, so a user can submit the data using this API. After data run through the trained model, return the result using the API as well.
Since my model requires spacy.io's big trained model as the backend, I CANNOT use Lambda due to Lambda's limitation on file size (512 MB). But all I Googled is related to Lambda.
I am thinking, in my EC2 instance, I setup a Flask or Django app to receive the data from API Gateway and then run the model, return the result back to API Gateway.
But I don't know how to do it, could any one point out some resources?
Or is there any better solution out there?

A: It sounds like you've only discovered documentation for the Lambda integration method. You need to look at either the HTTP or HTTP_PROXY integration methods. I would start by reading this page in the documentation, and then proceed to this page.
If you also want to prevent anything but API gateway from directly accessing your back-end system, then you will also need to setup client-side SSL certificate verification on your back-end.


text:
Q: Equations of state for white dwarf stars I am dealing with some model describing the given composition of a white dwarf made with photons, degenerate electrons, positrons and ions. From that, I can get tabulated values of densities ranging from small to large numbers and corresponding to it the total pressure and total energy. Now I'm interested in getting the parameters like density, mass and pressure with respect to the radius at some given initial conditions. I can do it using two coupled ordinary differential equations, i.e.:
$$
\frac{\partial m}{\partial r}=4\pi r^2\rho(r)\\
\frac{\partial P}{\partial r}=-\frac{Gm(r)\rho(r)}{r^2}
$$
This can be solved, for example, using the forward Euler method which will give us as follows:
$$
m(i)=m(i-1)+4\pi r^2 \rho(i-1)\Delta r\\
P(i)=P(i-1)-\frac{Gm(i-1)\rho(i-1)}{r^2}\Delta r
$$
Firstly, I want to implement the following initial conditions i.e.
$$
m(0)=0 \ \ ; \ \ \rho(0)=\rho_{central}
$$
I'm going outward with my calculations. Using my tabulated values of pressure and density I can easily calculate for small $\Delta r$ how the mass and pressure change with respect to the radius breaking the computations when the density reaches a very small value (the surface of the WD). Having all of these I can determine what is the mass of the WD for a given central density.
Secondly, I want to use different initial conditions to get, in the end, the central density for a given mass, i.e.
$$
m(R)=M \ \ ; \ \ \rho(R)=0 \ \ or/and \ \ P(R)=0
$$
It means that I have to do my calculations inward. In that case, I have to modify the above result of the Euler method to get:
$$
m(i-1)=m(i)-4\pi r^2 \rho(i)\Delta r\\
P(i-1)=P(i)+\frac{Gm(i)\rho(i)}{r^2}\Delta r
$$
And this is the moment I got stuck for several weeks. If I take my initial conditions which are the total mass, density and pressure are equal to zero at the surface then the only parameter that stops me from proceeding with these computations is the total radius. And here I need some help or hint. How can I perform these calculations inward when I don't know this radius? Is there maybe some way of transformation of getting rid of this unknown? Or perhaps I can do computations outward even though I've got surface boundary conditions?

A: You've described a boundary value problem: you're trying to solve a differential equation where different conditions apply at different boundaries. These are distinguished from initial value problems, where you're given all the conditions you need at some point (usually in time), from which you can solve the equations. The method you describe of starting from, say, the centre and integrating outwards would solve an initial value problem but, as you've realised, you need something else to solve a boundary value problem.
The simplest approach I'm aware of is the shooting method. Conceptually, what you do is

*

*guess the missing condition at one end (e.g. the central density),

*solve the equations outwards using whatever method¹ until you reach the surface condition (e.g. P(R)=0) and

*then compare your result with the condition you haven't considered yet (the total mass M(R)).

You can then iterate on central density by using a root-finding algorithm on the total mass less the target mass to find the value of the central density that works.
Put differently, the outward integration gives you a function that looks something like $M(\rho_c)$ and you do a root-find on $M(\rho_c)-M_\mathrm{target}$.
¹ You mentioned Euler, which is a fine place to start.


text:
Q: ¿Como puedo agregar datos de entrada desde un archivo .txt a un array en C? Tengo el siguiente programa para poder leer datos desde un archivo.txt y pasarlos a un array, quiero hacerlo utilizando CMD de windows de la siguiente forma: lee_datos < datos_entrada.txt.
y el codigo es el siguiente:
#include<stdio.h>
#include<stdlib.h>

void lee_datos(int *array,int N);
void imprime_datos(int *array,int N);

int main(){
    int N = 5;
    int array[N];

    //llenamos el array con los datos de entrada
    lee_datos(array,N);

    //comprobacion

    printf("El array es: ");
    imprime_datos(array,N);

    return 0;
}

void lee_datos(int *array,int N){
    int i;
    int dato;
    for(i=0; i<N;i++){
        scanf("%d",&dato);
        array[i] = dato;
    }
}

void imprime_datos(int *array,int N){
    int i;
    printf("Total de datos: %d\n",N);
    for(i=0;i<N;i++){
        printf("%d ",array[i]);
     }
}

destaco que el archivo txt tiene formato:
1
2
3
4
...

¿Es correcto utilizar cmd de windows?, he visto que en mac utlizan ./lee_datos<datos_entrada.txt y el array se llena con los números dentro del archivo pero cuando hago ese mismo comando en CMD al parecer llena con números aleatorios y no es lo que busco (supongo que es por que C llena con datos al azar en memoria cuando no hay nada) y en powerShell tampoco funciona.

A: Si estás usando c que ya veo que si te recomiendo que no lo hagas con el cmd sino con la función fgets(); y un puntero FILE* es más facil. Este sería el codigo para meter cada línea del archivo en un string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

void limpiar(char[]);

int main (){

setlocale(LC_ALL,"spanish");//cambio la lengua a español para poder poner tildes.

int i;
char lectura[30][30]; //crea 30 strings que pueden almacenar 30 letras parav poner en cada uno una linea del archivo.
int contador = 0; //va a ir contando cuantas lineas se han leido y al final va a decir el total de letras leidas.
FILE *f; //creo un puntero hacia un archvo

f=fopen("archivo.txt","rt"); //El primer dato que pasas es el nombre del archivo que tiene que estar en la misma carpeta que el programa.
                             //El segundo dato que pasas es rt que significa leer texto (no puedes escribir) para escribir texto usa WT.

if(f != NULL) //si el archivo no existe f va a ser == NULL si existe leemos el programa
{

while( fgets(lectura[contador],30,f)) //Siempre y cuando no haya llegado al final del archivo sigue lellendo más lineas.
{                                     //fgets lee una linea del archivo y luego la siguiente vez que llamas la función lee la siguiente linea.

limpiar(lectura[contador]);//fgets siempre debuelve la variable con un '\n' al final con esta función lo quitamos.
contador=contador+1; //cada vez que lee una linea se suma uno a contador así la proxima kinea se guarda en otra variable que la anterior.
}

fclose(f);//cierro el archivo porque ya he acabado de leerlo.

for(i=0;i<contador;i++)
{
    printf("%s\n",lectura[i]);
}

}
else //Si el archivo no exste da un aviso de error antes de cerrar el programa
{
    printf("El archivo no existe comprueba si está en la misma carpeta que el proograma.\n\n");
}
printf("\n\n");
system("pause");

return 0;
}

void limpiar(char frase[])
{
    int i;
    for(i=0;i<strlen(frase);i++)//comprueba una por una todas las letras hasta que encuentra el \n
    {
        if(frase[i]=='\n')//si la letra por la que va es un \n lo cambia po \0 para así eliminarlo.
        {
            frase[i]='\0';
            return; //una vez que ha encontrado el \n no sigue buscando más se acaba la función.
        }
    }
}

si lo que quieres es meter números puedes usar la funcion itoa que sirve para cambiar de char a int y viene con la librería string.h. O también si quieres un solo número o solo una palabra puedes usar la función fscanf();.


text:
Q: Redirect two levels out I'm looking for a way to redirect out to my root page. Want to redirect
RewriteRule ^folder1/folder2.*$ index.php?page=folder1_folder2 [NC]

In the web browser this looks something like
http://www.example.com/folder1/folder2

UPDATE:
Forgot to add that I tried this:
RewriteRule ^([folder1/]+)/([folder2/]+)/?$ index.php?page=$1_$2 [NC,R=301]

but for some reason it alters the url to
http://www.example.com/index.php?page=folder1_folder2

A: In the end this worked for me:
RewriteRule ^([folder1/]+)/([folder2/]+)/?$ index.php?page=$1_$2 [NC,QSA]


text:
Q: SQL Azure Request Limits and a possible connection leak I have an interesting problem going on.  I recently moved 2 SQL databases to SQL Azure for a client and all seemed to be going well...at first.  Mid-morning I get a spike of error emails for various things, but a few common ones:
-The request limit for the database is 90 and has been reached.
-Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
-A transport-level error has occurred when receiving results from the server.
There's obviously some database related issues going on with the move to Azure, or the existing code in general.  The errors that seemed to happen the most were request limit and timeouts. Once they started, they never seemed to stop.  And I don't think there were many users using the site today.  It almost seemed like the connection continued to try to connect on a different thread in the background if this makes any sense. This is in reference to the "The timeout period elapsed prior to completion of the operation or the server is not responding."  I would get an error email, I'd check the page it referenced myself, and it would load immediately.  I checked with the user who threw the error and they reported everything was fine.  Strange.  Yet I continued every few minutes to get the same error email.
I currently have them on the S1 Tier which limits the requests to 90 concurrently.  I did some digging and found the following SQL query:
select * from sys.dm_exec_connections

I ran this, and it showed I had over 90 active connections, some of which were opened some time ago.  This was strange to me as the site was currently not being used (it's really late at night and I know no one is using the site).  I wanted to end all the connections so I came up with the following query:
DECLARE @sessionId int
DECLARE @SQL nvarchar(1000)
DECLARE @clientIP nvarchar(50)

set @clientIP = 'XX.XX.XX.XX'

select @sessionId = min( session_id ) from sys.dm_exec_connections where   client_net_address = @clientIP

while @sessionId is not null
begin
    SET @SQL = 'KILL ' + CAST(@sessionId as varchar(4))
    EXEC (@SQL)
    select @sessionId = min( session_id ) from sys.dm_exec_connections where session_id > @sessionId and client_net_address = @clientIP
end

I tried running this command, but the connections came right back.  I went on the web server and manually stopped the site in IIS, ran the KILL command again but the connections remained.  I put up the app_offline file and took the site down for about a half hour to see if any lingering connections would drop, but they didn't.  And I still continued to get error emails for pages I KNEW were not accessible because I stopped the Site AND app pool.  I went on the server and manually stopped the w3wp process and ran SQL KILL statements to kill the connections.  They finally went away! I put the app back online and hit a single page.  I kept running the above query to see the active connections and sure enough every time I ran the query the active connection count kept creeping up.  It stops around 102 as of right now.  And that's me as a user hitting a single page.  I'm guessing this isn't normal?  Does this indicate connections are lingering out there and not being dropped or closed?
I just made code changes recently adding Entity Framework.  Wherever I'm grabbing data through EF, im using so with a using statement on the context.  The rest of the app is sort of old and is using TableAdapters.  I see in some places it's following the same pattern with using statements, other places Dispose is being called.  I haven't had a chance to track down all the usages yet.  Is this a good place to start looking?   Anyone have any suggestions on how to track this 'leak' down?  I'm not super knowledgeable with SQL so any help would be greatly appreciated!


text:
Q: Encrypt/Decrypt property while writing/reading to c# mongo db Just going to lay out all the info i have:
In short, I am looking for something exactly (literally) like this but compatible with ASP Core (2.2) and the C# MongoDB Driver (2.7).
This seems like such a common requirement, I am very surprised i can't find anything already built.
Here is what i have so far:
Model:
public class Patient
{
    //comes from the client as XXXXXXXXX, RegEx: "([0-9]{9})"
    //[MongoEncrypt]
    public EncryptedString SocialSecurityNumber { get; set; }
}

Attribute:
[AttributeUsage(AttributeTargets.Property)]
public class MongoEncryptAttribute : BsonSerializerAttribute
{
    public MongoEncryptAttribute()
    {
        SerializerType = typeof(MongoEncryptSerializer);
    }
}

Custom Serializer:
public interface IMongoEncryptSerializer : IBsonSerializer<EncryptedString>{ }

public class MongoEncryptSerializer : SerializerBase<EncryptedString>, IMongoEncryptSerializer
{
    private readonly string _encryptionKey;

    public MongoEncryptSerializer(IConfiguration configuration)
    {
        _encryptionKey = configuration.GetSection("MongoDb")["EncryptionKey"];
    }

    public override EncryptedString Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var encryptedString = context.Reader.ReadString();
        return AesThenHmac.SimpleDecryptWithPassword(encryptedString, _encryptionKey);
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, EncryptedString value)
    {
        var encryptedString = AesThenHmac.SimpleEncryptWithPassword(value, _encryptionKey);
        context.Writer.WriteString(encryptedString);
    }
}

Open Items:

*

*Use DI (vanilla .net core DI) to get the Serializer. thinking of something like BsonSerializer.RegisterSerializer(type,serializer) in a bootstrap method where i can access the service collection and do a GetInstance but then i would need string SocialSecurityNumber to use a custom type (maybe SecureString?)

*

*Went with a custom type,EncryptedString, with implicit string conversion

*Use DI in the serializer to get the key (initially from IConfiguration/appsettings.json  and then ultimately from Azure KeyVault (whole new can of worms for me)) and the EncryptionProvider

*deterministic encryption for searching. AesThenHmac comes from this popular post.  I can store and retrieve data back fine in its current implementation.  But in order to search for SSNs, I need deterministic encryption which this lib does not provide.

A: My Solution:
Model:
public class Patient
{
    //comes from the client as XXXXXXXXX, RegEx: "([0-9]{9})"
    public EncryptedString SocialSecurityNumber { get; set; }
}

Custom Type:
public class EncryptedString
{
    private readonly string _value;

    public EncryptedString(string value)
    {
        _value = value;
    }

    public static implicit operator string(EncryptedString s)
    {
        return s._value;
    }

    public static implicit operator EncryptedString(string value)
    {
        if (value == null)
            return null;

        return new EncryptedString(value);
    }
}

Serializer(using Deterministic Encryption):
public interface IEncryptedStringSerializer : IBsonSerializer<EncryptedString> {}

public class EncryptedStringSerializer : SerializerBase<EncryptedString>, IEncryptedStringSerializer
{
    private readonly IDeterministicEncrypter _encrypter;
    private readonly string _encryptionKey;

    public EncryptedStringSerializer(IConfiguration configuration, IDeterministicEncrypter encrypter)
    {
        _encrypter = encrypter;
        _encryptionKey = configuration.GetSection("MongoDb")["EncryptionKey"];
    }

    public override EncryptedString Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var encryptedString = context.Reader.ReadString();
        return _encrypter.DecryptStringWithPassword(encryptedString, _encryptionKey);
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, EncryptedString value)
    {
        var encryptedString = _encrypter.EncryptStringWithPassword(value, _encryptionKey);
        context.Writer.WriteString(encryptedString);
    }
}

Registering the serializer:
collection.AddScoped<IEncryptedStringSerializer, EncryptedStringSerializer>();
//then later...
BsonSerializer.RegisterSerializer<EncryptedString>(sp.GetService<IEncryptedStringSerializer>());


text:
Q: Android get data from the parse table (json file) (imported in parse.com-data browser) I have one json file, that I imported in parse.com->data browser->import partition. I can get the String and image value from the table but I have no idea about how to get following values. First column have name chapters of type array look like one field following,
[{"__type":"Pointer","className":"Chapter","objectId":"BCr3uAnapV"}]

how to get above value and second column have, name user of type object look like following,
{"password":"xxx"}

Please any one help me for above, I have tried Googling but it did not help.
EDIT:
See following screen shot: arrow display column 1) chapter and have another column 2) user I want to fetch (get ) that for e.g. if we want to get data of String type like: String provider = (String) objectList.get(i).get("provider"); this manner this way I want to above data, below my screen shot:

A: This line is a relation (of type Pointer) to another Class in Parse:
[{"__type":"Pointer","className":"Chapter","objectId":"BCr3uAnapV"}]

The class being Chapter. You can make sure this object is fetched together with the object pointing to it using "include":
query.include("chapter");

When you query for the other object, using query.include on pointer relations will ensure these related objects are fetched as well.


text:
Q: DocumentFragment elements not visible for WebDriver I have page to test

        Login

    Date: 28/02/2019
    Time: 12:20

    No additional information

When i try to click on //*[@class="activity-action"][1] with webdriver i get 'Element not visible exception'.
Next step, check why element not visible for selenium:
document.getElementsByClassName('activity-action')[0].getBoundingClientRect()

response:
DOMRect {x: 359.3125, y: 343, width: 900, height: 59, top: 343, …}
Element visible, now check parent:
document.getElementsByClassName('activity-action')[0].parentNode.getBoundingClientRect() and get DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …}
Parent element not visible so child is not visible too. But parent element is something weird:
document.getElementsByClassName('activity-action')[0].parentNode
returns:

 and i dont understand how it could be. I cant see this element in chrome inspector. What is this?
document.getElementsByClassName('activity-action')[0].parentNode.parentNode

returns
...
 this element must be returned in previous step.
Could i make element //*[@class="activity-action"][1] visible by modify it with JavascriptExecutor?

A: based on provided Exception:

Completed command waitForElementVisible (15235 ms) and Timed out while waiting for element <//div[@class="activity-container"]/div[1]> to be visible for 15000 milliseconds. - Expected "visible" but got: "not visible

your xpath given to Selenium is wrong. Selenium try click child div of activity-container div which is activity-description div having style="display: none;
Please verify your xpath, for example in Chrome dev tools before passing it to Selenium test


text:
Q: Connection alive to a removed pod on k8s We repeatedly have a situation that a client pod (http, zeromq) doesn't notice a server pod was restarted and somehow keeps the connection to the removed server pod, instead of reconnecting to the new one.
Restarting client pod helps of course, but this is rather a workaround.
Is there any explanation why does it happen and how to properly handle it?


text:
Q: Creating service area using both streets and buslines in same ArcGIS network? I want to create a network analysis more difficult. Therefore, I want to calculate a Service Area around hospitals next to bus stops. But: The network does not only consist of roads and pedestrians (time) but also of bus lines and bus stops. In best case the result should be a augmented service area, which includes bus drives to the hospital in a certain time! I nearly have the solution, but here is the problem. Trying to solve the analyse I realized that several bus stops are not within the calculation. I have checked the topology of the stops and lines and there are no errors (as ArcGIS says). Also the attribute table seems to be correct. I tried to planarize the bus lines but I can't use the tool, as it is not possible to click on it (grey color).
Maybe you have a idea to help me?
Problem picture:

(Source)

A: The asker "put the busstations on street junctions and that worked".
Although this is a very short Answer I have transferred it from a comment by the asker to assist removal of this resolved issue from our Unanswered questions.


text:
Q: Como usar PDO bindParam no IN() da query? Tenho uma query similar a esta:
$modelos = "1,2,3,4";
$sql = "Select codigo_modelo, nome From modelos Where codigo_modelo in (:codigo_modelo)"
$sql->bindParam(":codigo_modelo",$modelos,PDO::PARAM_INT); //TAMBEM JA TENTEI COM PARAM_STR

Porém continua me retornando 0 rows.
Fazendo desta outra forma tudo ocorre normalmente:
$modelos = "1,2,3,4";
$sql = "Select codigo_modelo, nome From modelos Where codigo_modelo in (".$modelos.")"

Alguma idéia? Gostaria de seguir utilizando o bindParam por motivos obvios...

A: Uma sugestão seria formatar sua string de consulta e depois fazer o bindParam para cada parâmetro, exemplo:
    $modelos = explode(",","1,2,3,4"); // transforma string em array
    $query = sprintf("Select codigo_modelo, nome From modelos Where codigo_modelo in (%s)",
            implode(
            ',',
            array_map(
                function() {
                   static $x = 0;
                   return ':cod_'.$x++;
                },$modelos
            )
        )
    );

Isto irá formatar sua string de consulta da seguinte forma:
Select codigo_modelo, nome From modelos Where codigo_modelo in (:cod_0,:cod_1,:cod_2,:cod_3)

Assim você poderá percorrer o array e fazer bindParam dos parâmetros
    $sql = $conexao->prepare($query);
    for ($i = 0; $i < sizeof($modelos); $i++){
        $sql->bindParam(":cod_".$i,$modelos[$i]); //$sql->bindParam(":cod_0",1) ...;
    }
    $sql->execute();

A: Para cada valor na consulta é necessario informar o respectivo named/placholder, a forma como você passou o valor(1,2,3,4) o PDO entendeu isso como um unico valor representado por :cod_modelo.
Uma forma de realizar bind dinamico é saber o número do parametros, criar uma string com n interrogações e concatenar elas na consulta dentro da clásula IN.
Os valores devem ser passados no execute() como um array e não mais de forma individual com bindParam()
$dados = array(1,2,3,4);
$totalInterrogacoes = count($dados);

$interrogacoes = str_repeat('?,', $totalInterrogacoes);
$interrogacoes = substr($interrogacoes, 0, -1); // remove a última virgula

$cmd = "SELECT * FROM modelos WHERE codigo_modelo in($interrogacoes)";
$stmt = $sql->prepare($cmd);
$stmt->execute($dados);

$operacao->execute($values);


text:
Q: Express middleware not firing when using postman but works when connecting with browser I have a simple express application boiler plated with Express Generator.
I am trying to run middleware to verify a JWT but none of my middleware seems to get run when testing with postman.
If I make a request from my browser, I can see the logs in the middleware run fine.
My app.js has a simple logger function which should run on all requests.
import token_verification from './middleware/token_verification';
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var api = require('./routes/api');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/api', api);

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)
app.use(token_verification);

const LOCALHOST = process.env.PORT || 3037;
app.listen(LOCALHOST, () => {
  console.log(`Listening on ${LOCALHOST}`);
});

module.exports = app;

I have my routes/index.js with a simple GET route
import express from 'express';
const router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

As I said, when I got to http://localhost:3037/ in my browser, I can see my terminal logs "LOGGED" but when I make a GET request via post to the same URI, nothing is logged and appears no middleware runs.
EDIT:
Postman screenshot

A: I don't know why it's working from the browser but not from Postman (there's likely some headers that are being set by the browser and not by postman, but I don't see why that would matter).
What does matter, though, is that you're defining your logger after your routes, and since your GET route ends the response with res.render the middleware will not fire.
Remember, in the latest versions of Express, middleware fires in the order they're mounted on the app.
If you want the logger to always fire, reorder things:
var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)
app.use(token_verification);
app.use('/', index);
app.use('/api', api);


text:
Q: Eclipse keyboard command to add import statement I am a C# developer who is doing some Android development in Eclipse. One of my favorite keyboard shortcuts in Visual Studio is CTRL + . which brings up the SmartTag menu. This is incredibly useful for adding using statements on the fly.
As an example if I don't have an import statement for System.Xml.Linq but create a variable of type XDocument I can quickly add the appropriate using with the keyboard command.
Is there a similar keyboard command available in Eclipse?

A: For Mac users the shortcut is:
CMD + Shift + O

A: some useful Eclipse shortcuts, you need first one
1. Ctrl + Shift + O : Organize imports

*Ctrl + D : Delete row

*Ctrl + 1 : Activate quick fix

*Ctrl + O : Open declarations

*Ctrl + / : Line Comment

*Alt + Shift + R : Rename selected element

*Ctrl + Shift + L : Shortcut for shortcuts
if you need more refer here

A: I'm pretty sure he has Ctrl + Shift + O in mind, but I may be wrong.

A: The easiest thing to do is to start typing the type name, then press Ctrl + Space to get the completions. Selecting the completion will complete the type name that you are typing and will also add the import statement. Short of that, there is Ctrl + 1, which will bring up quick fixes when you are over a piece of code with problem. There is typically a quick fix to import type.

A: You can use Ctrl + Shift + O to "O"rganize Imports (like Crembo mentions).  Another neat trick is to go to Windows > Preferences, search for "Save Actions", and check "Organize Imports".  Now whenever you save (Ctrl + S), Eclipse will automatically run the "organize imports" feature.  I find this quicker, since it's quicker for me to hit Ctrl + S than Ctrl + Shift + O (one-hand shortcut versus two-hand shortcut).

A: In Preferences->General->Key, you can have your bindings for shortcut key. This article: Eclipse Short Cut Keys lists some useful shortcuts.


text:
Q: Series solution to a second-order linear ordinary differential equation Problem:
Let $n\in\mathbb{N}$. Find a solution to
$$x^2y''+xy'+(x^2-n^2)y=0$$
given
$$y(x)=\sum_{j=0}^\infty a_jx^{k+j},\qquad k>0.$$
A brief progress:
By differentiating the series we get
$$y'=\sum_{j=0}^\infty (k+j)a_jx^{k+j-1}\\
y''=\sum_{j=0}^\infty (k+j-1)(k+j)a_jx^{k+j-2}$$
Substituting this back in our equation we get
$$\sum_{j=0}^\infty (k+j-1)(k+j)a_jx^{k+j}+\sum_{j=0}^\infty (k+j)a_jx^{k+j}+\sum_{j=0}^\infty a_jx^{k+j+2}-\sum_{j=0}^\infty n^2a_jx^{k+j}=0$$
which simplifies to
$$\sum_{j=0}^\infty[(k+j)^2-n^2]a_jx^{k+j}+\sum_{j=0}^\infty a_jx^{k+j+2}=0$$
Status:
This is where i'm stuck!

*

*Am I on the right track?

*How do I add the series in the last equation with $x^{k+j}$ and $x^{k+j+2}$?

*How do I find $k$ and $a_j$?

A: Your last formula
$$\sum_{j=0}^\infty[(k+j)^2-n^2]a_jx^{k+j}+\sum_{j=0}^\infty a_jx^{k+j+2}=0$$
can be written equivalently as
$$\sum_{j=0}^\infty[(k+j)^2-n^2]a_jx^{k+j}+\sum_{j=2}^\infty a_{j-2}x^{k+j}=0$$
or
$$
(k^2-n^2)a_0x^k+((k+1)^2-n^2)a_1x^{k+1}+
\sum_{j=2}^\infty\big[[(k+j)^2-n^2]a_j+a_{j-2}\big]x^{k+j}=0$$
Hence, you obtain two solutions, one for $a_0=1,a_1=0$ and another for $a_0=0,a_1=1$. Then continue recursively in each case.
For the first solution, $a_0=1$, $a_1=0$, implies that $k=\pm n$, and
$$
a_{2j+1}=0,\quad a_{2j+2}=\big(n^2-(k+2j)^2\big)a_{2j}.
$$


text:
Q: Using unique id's in div's to show/hide in jQuery I'm having some difficulties writing code to catch the 'id' name from the  to open the requested .
I have three boxes:

Box 1

Show Box 2

Box 2

Show Box 3

Box 3

TBD

And I am trying to catch the 'id' from the  tag to open the respected  with that 'id'. For example, a id="box2" will open div id="box2".
$(document).ready(function() {
$("div#" + getName).hide();
$('a#' + getName).click(function() {
    $('div#' + getName).show();
    return false;
  });
});

I'm not sure if jQuery is sensitive to single or double quotes, or if I am approaching this incorrectly. Any help is appreciated. Have an outstanding day!

A: You can't use the same "id" value for more than one element on a page, period. That's what "id" means.
One way to relate one element to another is to use a "data-" attribute:
<button data-friend="something">Click Me</button>

 ...

The jQuery library will give you the value of a "data-" attribute via the ".data()" API:
var friend = $('button').data('something');
var friendDiv = $('#' + friend);

You can also use class values to relate elements together.

A: Id must be unique. Try using a class as a selector.
$("div." + getClass).hide();


text:
Q: How to use ggplot2's geom_dotplot() with symmetrically spaced and separated dots I am having a problem symmetrically placing the dots in geom_dotplot when stackratio is greater than 1.  With stackratio = 1, the dots are symmetrically placed above the ticks marks.  With stackratio > 1, the dots are shifted left.  Is there a way to keep the dots symmetrically placed while creating space between the dots?
library(ggplot2)

data <- data.frame(x = rep(seq(2018, 2021, 1), 15),
                   y = sample(seq(3, 5, .125), 60,
                   replace = T))

ggplot(data, aes(factor(x), y)) +
  geom_dotplot(binaxis = "y", stackdir = "center", stackratio = 1)

ggplot(data, aes(factor(x), y)) +
  geom_dotplot(binaxis = "y", stackdir = "center", stackratio = 2)

A: The problem seems to be in the makeContext.dotstackGrob function. It calculates the offsets for each point with
xpos <- xmm + dotdiamm * (x$stackposition * x$stackratio + (1 - x$stackratio) / 2)

but for the life of me, I cannot see why the (1 - x$stackratio) / 2 part is there. Without it, everyything seems to lineup OK. If I change that line to
xpos <- xmm + dotdiamm * x$stackposition * x$stackratio

and test with the sample data, I get
ggplot(data, aes(factor(x), y)) +
  geom_dotplot(binaxis = "y", stackdir = "center", stackratio = 1)

ggplot(data, aes(factor(x), y)) +
  geom_dotplot(binaxis = "y", stackdir = "center", stackratio = .5)

ggplot(data, aes(factor(x), y)) +
  geom_dotplot(binaxis = "y", stackdir = "center", stackratio = 2)

So maybe this counts a a bug report? Not sure what else to test


text:
Q: I am trying to make a half circle in sketchup I'm trying to create essentially a half pipe shape in sketchup but having trouble. I can get an arc and build the shape, but it won't extrude.

Thanks,
Dirk

A: create a vertical rectangle then create your half circle on it.
Or using the tape measure, make sure all geometry is coplanar.
GIF explanation


text:
Q: two docker-compose .yml in the same network with COMPOSE_PROJECT_NAME I am trying to have my own network name for my docker-compose files (server.yml and test.yml), as test.yml gets only started from time to time, but needs access to some services in the server.yml. I can make it work with docker-compose -p nameofproject up, but not with COMPOSE_PROJECT_NAME.
server.yml
version: '2'

networks:
  mynetwork:
    driver: bridge

services:
  app1:
    networks:
      - mynetwork
    environment:
      POSTGRES_PASSWORD: somepassword
      COMPOSE_PROJECT_NAME: serverstack

  app2:
    networks:
      - mynetwork
    environment:
      COMPOSE_PROJECT_NAME: serverstack
    depends_on:
      - app1

My expectation is that when the container is starting I should see
Creating serverstackmynetwork_app_1
Creating serverstackmynetwork_app_2

the network should be named (docker network ls)
serverstack_mynetwork

just like when I do the following, which actually works
docker-compose -p serverstack up

And then I can connect just by using docker-compose up with the second file (which works just fine when using the -p option on the server.yml)
testing.yml
version: '2'

networks:
  testapp_network:
    external:
      name: serverstack_mynetwork

services:
  testapp:
    networks:
      - testapp_network

But using it without -p serverstack on the server.yml I see directories as names
Creating directoryofapp1_app1_1
Creating directoryofapp2_app2_1

so COMPOSE_PROJECT_NAME is being omitted and I also cannot connect to the server service though serverstack_mynetwork
I did add the COMPOSE_PROJECT_NAME: serverstack after building the image, but I would expect it should work anyhow. What am I missing?

A: I solved this by creating the ".env" file containing
COMPOSE_PROJECT_NAME=myprojectname


text:
Q: $M/M/2/3$ Queuing Theory Word-Problem A service center consists of two servers, each working at an exponential rate of two services per hour. If customers arrive at a Poisson rate of three per hour, then, assuming a system capacity
of at most three customers.

*

*What fraction of potential customers enter the system?

*What would the value of part (1) be if there were only a single server and his rate were twice as fast ($\mu = 4$)?

I understand there are four states in the system : $0$, $1$, $2$ and $3$. The transition rates for the system are $\lambda _0=\lambda _1=\lambda _2=3$ and $\mu _1=2$, $\mu _2=\mu _3=4$. I am struggling to model this and find transition table to aid the questions.

A: This is popularly known as the Erlang-B model. You can use time reversibility of ctmcs(see corollary 1.5 of this) to get the transitional probabilities. As you pointed out the $\lambda$ and $\mu$ correctly, in general for any $i$ we have
$$ \pi_i \lambda = \pi_{i+1}(i+1)\mu$$
You can easily solve this recursion to get $\pi_i$ from here.
Hint: It would come out to be something like $\pi_i \propto \frac{\lambda}{\mu}\frac{1}{i!}, i\geq1$, if done correctly.
The final step is a bit more subtle: let us find the long-run fraction of time a customer coming in sees the queue full(so they will not enter the system). Conveniently, by PASTA(which I hope you must have studied by now. If not, see this), it is just $\pi_3$. So the fraction of people who enter the system is $1-\pi_3$.
The final answer should come out to be $$1-\frac{\frac{\rho^m}{m!}} { \sum_{i=0}^m \frac{\rho^i}{i!}}$$
where $\rho$ is $\frac{\lambda}{\mu}$. $m$ and $\rho$ you can define appropriately for parts a and b resp.

A: We can model this as a continuous-time Markov chain with generator matrix
$$
Q = \begin{pmatrix}
-3 & 3 & 0 & 0\\
2 & -5 & 3 & 0\\
0 & 4 & -7 & 3\\
0 & 0 & 4 & -4
\end{pmatrix}.
$$
The stationary distribution $\pi$ satisfies $\pi Q=0$ and $\sum_{i=0}^3 \pi_i=1$, from which we find
$$
\pi = \begin{pmatrix}\frac{32}{159}&\frac{16}{53}&\frac{12}{53}&\frac 9{53}\end{pmatrix}.
$$
It follows that the fraction of potential customers that enter the system is $1-\pi_3=\frac{44}{53}$.
If there were one server with a rate of $\mu=4$ then the generator matrix would be
$$
Q= \begin{pmatrix}-3&3&0&0\\4&-7&3&0\\0&4&-7&3\\0&0&4&-4
\end{pmatrix},
$$
with
$$
\pi = \begin{pmatrix}\frac{64}{175}&\frac{48}{175}&\frac{36}{175}&\frac{27}{175}\end{pmatrix}
$$
and the fraction of potential customers that enter the system $\frac{148}{175}$.


text:
Q: Access properties of referenced object User schema:
const UserSchema = mongoose.Schema(
    {
        username: {
            type: String,
        },
        following: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
    },
);

module.exports = mongoose.model("User", UserSchema);

Me:
"following": [
        "5f0fd1874f2f4556f00c1f14", //in MongoDB it's ObjectId("5f0fd1874f2f4556f00c1f14")
        "5f0fe1e182878023cc54eb0a"  //in MongoDB it's ObjectId("5f0fe1e182878023cc54eb0a")
],
"_id": "5f0fd1470c39e43cf8a843ad",
"username": "David",

And there are other users with username property (e.g. "username": "Jeff").
In React I can access my username like this:
<p> {user.user.username} </p>

However when I want to access the following users then I just get their id in string.
<p> {user.user.following} </p>

If I want to access their username then I get undefined error.
<p> {user.user.following.username} </p>

Is it because following array contains strings? I specifically did this in the User schema:
following: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],

I thought I will get back the users with properties and all.
How do I access the properties of these users in the following array? I would like to map through them and output their username in my React app.

A: Chris helped.
Need to populate the references.
On the backend:
const user = await User.findById(req.user.id).populate("following");

And then map through it on the client side:
{user.user.following.map((a) => {
  return <p>{a.username}</p>;
})}


text:
Q: How is a T-SQL transaction not thread-safe? The following (sanitized) code sometimes produces these errors:

Cannot drop the table 'database.dbo.Table', because it does not exist or you do not have permission.
  There is already an object named 'Table' in the database.

begin transaction
    if exists (select 1 from database.Sys.Tables where name ='Table')
        begin drop table database.dbo.Table end

    Select top 3000 *
    into database.dbo.Table
    from OtherTable
commit

select * from database.dbo.Table

The code can be run multiple times simultaneously.  Anyone know why it breaks?

A: Can I ask why your doing this first? You should really consider using temporary tables or come up with another solution.
I'm not positive that DDL statments behave the sameway in transactions as DML statements and have seen a blog post with a weird behavior and creating stored procedures within a DDL.
Asside from that you might want to verify your transaction isolation level and set it to Serialized.
Edit
Based on a quick test, I ran the same sql in two different connections, and when I created the table but didn't commit the transaction, the second transaction blocked. So it looks like this should work. I would still caution against this type of design.

A: In what part of the code are you preventing multiple accesses to this resource?
begin transaction
    if exists (select 1 from database.Sys.Tables where name ='Table')
        begin drop table database.dbo.Table end

    Select top 3000 *
    into database.dbo.Table
    from OtherTable
commit

Begin transaction isn't doing it.  It's only setting up for a commit/rollback scenario on any rows added to tables.
The (if exists, drop) is a race condition, along with the re-creation of the table with (select..into).  Mutiliple people dropping into that code all at once will most certainly cause all kinds of errors.  Some creating tables that others have just destroyed, others dropping tables that don't exist anymore, and others dropping tables that some are busy inserting into.  UGH!
Consider the temp table suggestions of others, or using an application lock to block others from entering this code at all if the critical resource is busy.  Transactions on drop/create are not what you want.

A: If you are just using this table during this process I would suggest using a temp table or , depending on how much data , a ram table. I use ram tables frequently to avoid any transaction costs and save on disk activity.


text:
Q: Mean.js - How to inject a 3rd party dependency (draw2d)? I'm beginning with the MEAN Stack and I'm struggling to do something I'm sure it's pretty basic.
I'm trying to inject a new instance of draw2d provided by their downloadable library.
I keep having :
"ncaught Error: [$injector:modulerr] Failed to instantiate module mean due to:
Error: [$injector:modulerr] Failed to instantiate module draw2d due to:
Error: [$injector:nomod] Module 'draw2d' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument."
Comming from :

modules/core/client/app/config.js
  var applicationModuleVendorDependencies = ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'ui.bootstrap', 'ui.utils', 'angularFileUpload', 'draw2d'];

Here are the other files :

modules/mymodule/client/controllers/projects.client.controller.js
...
ProjectsController.$inject = ['$scope', '$state', 'Authentication', 'projectResolve', 'draw2d'];

function ProjectsController ($scope, $state, Authentication, project, draw2d) {
    $scope.$on('$viewContentLoaded', function(event){
        var canvas = new draw2d.create('canvas');
    }
);
...

modules/mymodule/client/services/draw2d.client.service.js
(function () {
  'use strict';

  angular
    .module('mymodule')
    .factory('draw2d', draw2d);

  function draw2d() {
    return {
      create: function (divName) {
        var Draw2d = draw2d;
        return new Draw2d().Canvas('canvas');
      }
    };
  }
})();

The module's package is in "public/lib/vendors/draw2d"
config/assets/default.js
'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.css'
      ],
      js: [
        'public/lib/vendors/draw2d/lib/canvg.js',
        'public/lib/vendors/draw2d/lib/Class.js',
        'public/lib/vendors/draw2d/lib/jquery-1.10.2.min.js',
        'public/lib/vendors/draw2d/lib/jquery-touch_punch.js',
        'public/lib/vendors/draw2d/lib/jquery.autoresize.js',
        'public/lib/vendors/draw2d/lib/jquery.contextmenu.js',
        'public/lib/vendors/draw2d/lib/json2.js',
        'public/lib/vendors/draw2d/lib/pathfinding-browser.min.js',
        'public/lib/vendors/draw2d/lib/raphael.js',
        'public/lib/vendors/draw2d/lib/rgbcolor.js',
        'public/lib/vendors/draw2d/lib/shifty.js',
        'public/lib/vendors/draw2d/lib/StackBlur.js',
        'public/lib/vendors/draw2d/src/draw2d.js',

        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js'
      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css',
      'public/lib/vendors/draw2d/css/contextmenu.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js'
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: 'gruntfile.js',
    gulpConfig: 'gulpfile.js',
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: 'modules/*/server/config/*.js',
    policies: 'modules/*/server/policies/*.js',
    views: 'modules/*/server/views/*.html'
  }
};

modules/mymodule/core.client.module.js
(function (app) {
    'use strict';

    app.registerModule('mymodule', ['core']);// The core module is required for special route handling; see /core/client/config/core.client.routes
    app.registerModule('mymodule.services');
    app.registerModule('kmymodule.routes', ['ui.router', 'mymodule.services']);
})(ApplicationConfiguration);

Can you please help me in explaining me what I did miss ?
Thanks a lot for your precious help ! :)

A: Oh boy, I found what was providing this error.
I didn't have to declare it in the project dependency.
Works now...


text:
Q: Debug Tomcat server taking long to start on Eclipse I created a debug configuration for my tomcat 8.5 server, but when I start it, it takes long and does not start.
I supplied -Xmx2048m and -Xms2048m and the arguments, and I added the webapps and directory of my workspace. The server works fine when it is not in debug mode.
Any help is appreciated greatly. I have tried importing the workspace again, refreshing, and cleaning but to no avail.
It is hung up on this line 2021-03-22 16:05:44.826 INFO 280658 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/demoau] : Initializing Spring root WebApplicatioNContext


text:
Q: Why is an object's method not available for another object? function Vector(i, j, k){
    this.i = i;
    this.j = j;
    this.k = k;
};

Vector.prototype = {
    addition: function(vec){
        return new Vector(vec.i+this.i, vec.j+this.j, vec.k+this.k);
    },
    magnitude: function(){
        return Math.sqrt(this.i*this.i + this.j*this.j + this.k*this.k);
    },
};

function Orbit(rp, ra, ecc){
    this.rp = new Vector(rp, 0, 0);
    this.ra = new Vector(ra, 0, 0);
    this.a = this.rp.addition(this.ra).magnitude(); //The error is in this line
};

var orbit = new Orbit(6563, 42165);

So what I'm trying to do here is create Vector objects for rp, ra in the Orbit object. a is supposed to utilize the prototype methods of the vectors rp and ra, but when I run the script, the prototype methods of rp are not available and I get an error saying:
TypeError: 'undefined' is not a function (evaluating 'this.rp.addition(this.ra)')

I hope this isn't a dumb mistake that I'm missing somewhere, because this has been giving me some trouble for a while. This is my first time ever using prototypes in JS, so I don't see what I'm doing wrong here. I just need to know why this.rp does not have the Vector methods and what I could do to fix my code.

A: The problem isn't where you think it is.
this.a is built as :
this.a = this.rp.addition(this.ra).magnitude();

which means it's a number, so you can't take this.a.magnitude()
I suppose this.a wasn't supposed to be the magnitude (or you're changed your mind). A fix would be to change it's construction to
this.a = this.rp.addition(this.ra);


text:
Q: Ajaxify hyperlink so on success will load content otherwise redirect as default I have a <a href> hyperlink. I used JQuery so clicking the link will load contents into a div in the current page (i.e. stay in the same page), and it works now.
However I also want that, if the request fails, the link act normally and go to the href url.
I tried e.preventDefault(); and return false; in the success: callback function, but they are not in the correct scope. If I place e.preventDefault() in the calling function, I can't reverse that effect later.
Here is my code:
$('a.more-link').click(function(e){
    var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
    var postContent=$(this).parent();
    $.ajax({
        url:"?action=ajax_load_post&id="+postId,
        success:function(data){
            postContent.html(data);
            // Can't access e.preventDefault, nor return false;
        },
        error:function(data){

        }
    });
    e.preventDefault();
});

A: Don't worry about the preventDefault(), just redirect the user in the error function like this:
$('a.more-link').click(function(e){
    var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
    var postContent=$(this).parent();
    var _this = $(this);
    $.ajax({
        url:"?action=ajax_load_post&id="+postId,
        success:function(data){
            postContent.html(data);
        },
        error:function(data){
            window.location = _this.attr('href');
            return false;
        }
    });
});


text:
Q: How to store custom ggplot aliases as `list` objects in .R script and source them along required label vectors I want to streamline my work with ggplot2 given certain settings I repeat across plots. To this end, I want to:

*

*set aliases for those ggplot2 settings (assigned to individual list objects)

*store them all in an .R script

*source() the .R script

*call the aliases when creating a plot with ggplot
However, this workflow fails when I set aliases for ggplot functions that call vectors. For example, scale_x_discrete() has an argument called labels, which takes a character vector of strings. This vector can be set in-place (e.g., scale_x_discrete(labels = c("a", "b", "c"))) or otherwise call a vector object stored in the environment:
labels_for_x <- c("a", "b", "c")

scale_x_discrete(labels = labels_for_x)

Therefore, my problem happens when I want to set an "alias" for a ggplot function that relies on an additional, separate vector.
Demonstrating the problem with example
Step 1 -- set alias for scale_x_discrete in a new .R script
library(tidyverse)

mygg_scale_x_relabel <-
  scale_x_discrete() %>%
  list

Works!
But what if:
mygg_scale_x_relabel <-
  scale_x_discrete(labels = labels_for_barplot) %>%
  list

Error in check_breaks_labels(breaks, labels) :    object
'labels_for_barplot' not found

So I can do:
labels_for_barplot <- c()

mygg_scale_x_relabel <-
  scale_x_discrete(labels = labels_for_barplot) %>%
  list

And this runs OK.

Step 2 -- open a new .R/.Rmd script and source the previous .R script with alias
source(file = ...)

Step 3 -- in the new script, generate a bar plot
library(ggplot2)

df <- data.frame(trt = c("col_1", "col_2", "col_3"), outcome = c(2.3, 1.9, 3.2))

p <-
  ggplot(df, aes(trt, outcome)) +
  geom_col()

p

Step 4 -- (PROBLEM HAPPENS HERE) -- call the scale_x_discrete alias
labels_for_barplot <- c(col_1 = "new_lab_col_1",
                        col_2 = "new_lab_col_2",
                        col_3 = "new_lab_col_3")

p +
  mygg_scale_x_relabel

<----- You can see here that all x labels are now gone!   This is because I've set labels_for_barplot <- c() (meaning, an empty vector) in my aliases script. But why this cannot be overridden with an updated vector assignment after script is sourced?

A: When you assign a value to mygg_scale_x_relabel, it gets set straight away with the values it has. It won't change when labels_for_barplot changes.
The best way to do what you want is with a function. The function won't evaluate until you call it.
mygg_scale_x_relabel <- function(labels_for_barplot) {
  scale_x_discrete(labels = labels_for_barplot) %>%
  list()
}

labels_for_barplot <- c(col_1 = "new_lab_col_1",
                        col_2 = "new_lab_col_2",
                        col_3 = "new_lab_col_3")

p +
  mygg_scale_x_relabel(labels_for_barplot)

However, if you really wanted the syntax you've described, you can use active bindings. This is not the way things should be done generally, though.
rlang::env_bind_active(
  rlang::global_env(),
  mygg_scale_x_relabel = function() scale_x_discrete(labels = labels_for_barplot) %>% list()
)

labels_for_barplot <- c(col_1 = "new_lab_col_1",
                        col_2 = "new_lab_col_2",
                        col_3 = "new_lab_col_3")

p + mygg_scale_x_relabel

labels_for_barplot <- c(col_1 = "a",
                        col_2 = "b",
                        col_3 = "c")

p + mygg_scale_x_relabel


text:
Q: WordPress Index Page As I attempted to convert an HTML page to WordPress which is supposed to display the most recent post in big and the other ones in small, but now the small ones are not clickable at all.
Also, I don't know how to avoid calling the latest one on the second function, therefore it is displayed twice (both in big and first small one as well).
Would anyone know how to correct these please?
Thank you all in advance for your time and attention.
Index:

sharing is caring

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

                        <?php query_posts('posts_per_page=1');
                        if(have_posts()) :
                    while (have_posts()) : the_post();
                            $latest_posts = wp_get_recent_posts($args); ?>

                                    <?php get_template_part('template-parts/content', get_post_format()); ?>

                    <?php endwhile; ?>
                <?php else : ?>
                    <?php get_template_part('template-parts/content', 'none'); ?>
                <?php endif;  wp_reset_query(); ?>

                        <?php if(have_posts()) :
                    while (have_posts()) : the_post(); ?>

                                <?php get_template_part('template-parts/content', get_post_format()); ?>

                    <?php endwhile; ?>

                            <?php the_posts_pagination(
                array(
                    'prev_text' => __('', 'textdomain'),
                    'next_text' => __('', 'textdomain'),
              )); ?>

                <?php else : ?>
                    <?php get_template_part('template-parts/content', 'none'); ?>
                <?php endif; ?>

Content-part:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

        <?php if(has_post_thumbnail()) { ?>
            <a href="<?php the_permalink(); ?>">
                <?php if ( 'post' === get_post_type() ) : ?>

                        <?php the_title( '
', '
' ); ?>
                         <?php the_time(); ?>    <?php the_date(); ?>

                <?php endif; ?>

                <?php the_post_thumbnail(); ?>

      <?php } ?>


text:
Q: Can I get the CSS counter value of the parent? I need to implement the following list style:

01 Item 1
02 Item 2
    02a Item 2a
    02b Item 2b
03 Item 3

How can I get the counter value of the parent to use in the :before content of my sub item? (02 in my above example)

A: You use two different counters: one for the li parents and one for the li subitems. Then, in each li subitem, concatenate multiple counter() functions using each counter, like this:
ol {
    counter-reset: item;
}

ol ol {
    counter-reset: subitem;
}

li {
    display: block;
}

/* First level of parent items */
li:before {
    content: counter(item, decimal-leading-zero) ' ';
    counter-increment: item;
}

/* Second level of subitems */
li li:before {
    /* counter(item) for the parents, counter(subitem) for the subitems */
    content: counter(item, decimal-leading-zero) counter(subitem, lower-alpha) ' ';
    counter-increment: subitem;
}

jsFiddle demo, tested in all browsers that support :before and CSS2.1 counters including IE8+
Useful reading: W3C CSS2.1 generated content spec, §12.4.1 Nested counters and scope

A: See this: there is no way to do such things in CSS, obviously you would need to use JavaScript for it but pseudo-elements are not in the DOM afaik.
As for the other answers: he wants the value of the counter that appears before the list items.

A: No, CSS doesn't support such "variable" things.
All you can do is set the same style as parent.


text:
Q: When using a path string in a shell script, it would be trans to a string containing children Here is some bash code
path='*'
echo $path

If I execute the code in terminal directly, the output is
*

But if I put it in a shell script e.g., test.sh. Then I execute the test.sh, the output will be like this
test.sh file1 file2 file3

I got a string contains all items under the path.
Why the two outputs is different? If I want the second output to be the first one, which means do not trans a path string when I use it, what should I do?

A: I tested a little. You could change your script to this:
path='*'
echo "$path"

and it will print * instead of files if you run it as a bash script.
Seems echo can be used as a alternative of ls command:
echo * means list all files under current folder.
echo *.jpg will list all files with jpg as suffix, and if there is no such file in current folder, echo *.jpg will just print "*.jpg".
I think this answer should be posted as a comment, since I don't really know why echo command behave like this. But I do not have enough reputation to add comment, so...


text:
Q: GKE Pod download speed of BigQuery API is very slow I have an image that performs a query on BigQuery and then downloads the result (about 8GB) with the following code:
query_job = client.query(my_sql_query)
query_result = query_job.result()
data_table = query_result.to_arrow(progress_bar_type='tqdm')

When I run the code locally the download speed is OK (100 mbs, basically my computer actual  bandwidth). The problem is that when I run It on GKE cluster the download is very slow (With tqdm I can see that it will be about 2 hours).
I checked the  bandwidth of my pod with the python package speedtest-cli and it is near 500 mbs.

A: The problem was that I wasn't installed the package google-cloud-bigquery-storage inside the pod so I was using the google-cloud-bigquery package to perform the download.


text:
Q: Use Regex to make separate lists Let's say we've 6 files:
scTest_model1.zip
scTest_model2.zip
scTest_unfiltred_model1.zip
scTest_unfiltred_model2.zip
scStr_model1.zip
scStr_model2.zip

I need optimised regex to create 3 separate lists:

*

*Filtered :

scTest_model1.zip
scTest_model2.zip

*Unfiltered:

scTest_unfiltred_model1.zip
scTest_unfiltred_model2.zip

*STR:

scStr_model1.zip
scStr_model2.zip

What's the most optimised regex I can use here? Thanks in advance for all the help

A: link to regex description
import re

s = """scTest_model1.zip
scTest_model2.zip
scTest_unfiltred_model1.zip
scTest_unfiltred_model2.zip
scStr_model1.zip
scStr_model2.zip"""

filtered = re.findall(r'(scTest_model\d+\.zip)', s, re.MULTILINE)
unfiltered = re.findall(r'(scTest_unfiltred_model\d+\.zip)', s, re.MULTILINE)
str_ = re.findall(r'(scStr_model\d+.zip)', s, re.MULTILINE)

print(filtered, unfiltered, str_)


text:
Q: How to modify "/etc/bash.bashrc"? It is read only? Trying to modify /etc/bash.bashrc I get an error:
$ echo "my edit" >> /etc/bash.bashrc
bash: /etc/bash.bashrc: Permission denied

ls -ll /etc/bash.bashrc shows:
-rw-r--r-- 1 root root 1975 2011-05-18 19:54 /etc/bash.bashrc

How could I modify /etc/bash.bashrc ?

A: sudo bash -c "echo 'text' >> /etc/bashrc"

Don't change the owner. Don't chmod it. Just use sudo. Open it with sudoedit if you need to do complicated things.
By the way, you can make changes for one user by just editing ~/.bashrc without requiring any special permissions.

A: You need superuser permissions to edit the file.
To become the superuser, type in sudo -s then enter your password. After you log in, then try your command, and it will work.

A: You've probably discovered by now that there are many ways to do this. But I think this one is the most elegant of all. (It often involves the least typing, too, when everything is said and done.)
echo "my edit" | sudo tee -a /etc/bash.bashrc

See man tee if you're interested in the technical details of how this works.
In general:

*

*To do the work of echo some-text > some-file as root, run:
echo some-text | sudo tee some-file

*To do the work of echo some-text >> some-file as root, run:
echo some-text | sudo tee -a some-file

A: sudo nano /etc/bash.bashrc

Do the changes you want. Save it (Ctrl+X) and confirm with y and Enter.

A: sudo echo "my edit" >> /etc/bash.bashrc


text:
Q: appsettings.json copied, passed or published to Azure App Service configuration? I have been trying to understand the appsettings.json method of use for some time now as I am building an ASP.NET Core 3.1 API that is to be published to Azure.
When I'm publishing the project to my web app my settings don't seem to get copied to the App Service configurations list in the Azure App Service resource.
Is this how it is supposed to work or am I missing something here?
I've read about appconfigurationbuilder and such, but as I understand it it's for telling the application which appsettings.json file to use depending on what environment is defined in the environment variable (ASPNETCORE_ENVIRONMENT) for example.
Though having a bunch of Key Vault references in my config, this doesn't work as my references of type:
@Microsoft.Keyvault(SecretUri=[KEY VAULT SECRET URL])

Can't fetch the secret from keyvault by only being the the appsettings.env.json file and not being copied to the app service configurations where they connect to keyvault through identity principal.
What am I missing or have I misunderstood the whole thing with appsettings.json?
So short recap: what I'm trying to do is understand if app settings can work like this:
appSettings.Env.json --> publish project to Azure app service --> settings are set automatically in app service configuration.

A: As mentioned in the comment, the app settings will not be copied to the azure app service when published, you need to specify the values in it manually.
Follow this doc - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-5.0#azure-app-service


text:
Q: Convert a list to a string and back I have a virtual machine which reads instructions from tuples nested within a list like so:
[(0,4738),(0,36),
 (0,6376),(0,0)]

When storing this kind of machine code program, a text file is easiest, and has to be written as a string. Which is obviously quite hard to convert back.
Is there any module which can read a string into a list/store the list in a readable way?
requirements:

*

*Must be human readable in stored form (hence "pickle" is not suitable)

*Must be relatively easy to implement

A: Use  the json module:
string = json.dumps(lst)
lst = json.loads(string)

Demo:
>>> import json
>>> lst = [(0,4738),(0,36),
...  (0,6376),(0,0)]
>>> string = json.dumps(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = json.loads(string)
>>> lst
[[0, 4738], [0, 36], [0, 6376], [0, 0]]

An alternative could be to use repr() and ast.literal_eval(); for just lists, tuples and integers that also allows you to round-trip:
>>> from ast import literal_eval
>>> string = repr(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = literal_eval(string)
>>> lst
[[0, 4738], [0, 36], [0, 6376], [0, 0]]

JSON has the added advantage that it is a standard format, with support from tools outside of Python support serialising, parsing and validation. The json library is also a lot faster than the ast.literal_eval() function.

A: Just use ast.literal_eval
>>> from ast import literal_eval
>>> a = literal_eval('[(1, 2)]')
>>> a
[(1, 2)]

You can convert it into a string using repr().
>>> repr(a)
'[(1, 2)]'

A: JSON!
import json

with open(data_file, 'wb') as dump:
    dump.write(json.dumps(arbitrary_data))

and similarly:
source = open(data_file, 'rb').read()
data = json.loads(source)

A: eval should do it in a simple way:
>>> str([(0,4738),(0,36),(0,6376),(0,0)])
'[(0, 4738), (0, 36), (0, 6376), (0, 0)]'

>>> eval(str([(0,4738),(0,36),(0,6376),(0,0)]))
[(0, 4738), (0, 36), (0, 6376), (0, 0)]

A: If you're just dealing with primitive Python types, you can just use the built-in repr():
Help on built-in function repr in module __builtin__:

repr(...)
    repr(object) -> string

    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.

A: If these are just two-tuples, you could store them in a CVS file using the csv module. No need for any brackets/parentheses.

A: with open('path/to/file', 'w') as outfile:
     for tup in L:
         outfile.write("%s\n" %' '.join(str(i) for i in tup))

with open('path/to/file) as infile:
    L = [tuple(int(i) for i in line.strip().split()) for line in infile]


text:
Q: Can't Move-Item Modified file I was trying to follow the solution given by @StephenP in this post:
Renaming and Moving Files Powershell
I am trying to Move a renamed file to the Output Folder, but it didn't move.
What could go wrong?
Here's my code:
$Files = GCI "$ParentFolder" | ?{$_.Extension -Match "png?"}
$Date = Get-Date -Format "yyyymmddhhmmss"
$Dest = ".\Output"

$Files | ForEach-Object {

    # Get the File BaseName and Select the Screen Title only
    $FileName = $_.BaseName
    $NameCount = $FileName.length
    $ScreenTitle = $FileName.substring(0,$NameCount -21)

    # Set the New File Name as Variable
    $NewFileName = "$($Date)_[$($ScreenTitle)]"

    # Start Renaming
    $GetName = $_.FullName -replace "$FileName","$NewFileName"
    Rename-Item $_ $GetName

    # Move the renamed file
    Move-Item $GetName -Destination $Dest
}

Thank you for helping :)

A: First of all, you don't need to rename the file first and then move, because you can do this using Move-Item at the same time.
Use -Filter '*.png' instead of a Where-Object afterwards. The Filter is much more efficient.
Your code does not check if the length of the file BaseName is actually more than 21 characters long, so this $FileName.Substring(0, $NameCount -21) can throw exceptions. However, since you didn't provide any filename examples, I left that in.
Try
$Files = Get-ChildItem -Path $ParentFolder -Filter '*.png' -File
$Date  = Get-Date -Format "yyyymmddhhmmss"
$Dest = ".\Output"

$Files | ForEach-Object {
    # Get the File BaseName and Select the Screen Title only
    $FileName    = $_.BaseName
    $NameCount   = $FileName.Length
    # very tricky this.. could throw error if $FileName is less than 21 characters..
    $ScreenTitle = $FileName.Substring(0, $NameCount -21)

    # Set the New File Name as Variable
    $NewFileName = '{0}_[{1}]{2}' -f  $Date, $ScreenTitle, $_.Extension

    # Move the file with a new name to the destination
    $_ | Move-Item -Destination (Join-Path -Path $Dest -ChildPath $NewFileName)
}

As aside, using square brackets in filenames could cause you problems and to do more PowerShell on these files, you need to always remember to use -LiteralPath instead of -Path on cmdlets that support it like Get-ChildItem


text:
Q: '^' in func pointer declaration In <stdlib.h> in Mac OS, I saw something like this:
int atexit_b(void (^)(void)) __attribute__((availability(macosx,introduced=10.6)));
void *bsearch_b(const void *, const void *, size_t,
 size_t, int (^)(const void *, const void *)) __attribute__((availability(macosx,introduced=10.6)));

So what does '^' in these declaration mean? Really appreciate if some one can help me here.


text:
Q: Error: filter:notarray when using filters with Lodash Groupby This is how I am getting listing.
    $scope.events = [];
    $scope.groupevent = [];

    Event.getList().then(function(data){
        $scope.events = data.events;
        $rootScope.events = data.events;

        angular.forEach($scope.events,function(value,key){
            value.groupdate = value.startDate.substring(0,7)+'-01';
            console.log(value.groupdate);
        });

        $scope.events = _.orderBy($scope.events, ['startDate'], ['asc']);
        $scope.groupevent = _.groupBy($scope.events,'groupdate');
        console.log($scope.groupevent);
    });

I have another function which I want to use for filter: it looks like below.
$scope.greaterThan = function(){
    var prop='endDate';
    var val=Date.now();
    return function(item){
        return new Date(item[prop]) > val;
    }
};

But when I am ng-repeat:
ng-repeat="(key,x) in groupevent | filter:greaterThan()"

it says: Error: filter:notarray


text:
Q: Connecting Buttons which are added using interface Builder using code - Beginner I have created 4 buttons via Interface Builder. I have an array which has the following content stored in it
"A"
"B"
"B"
"A"

Now what i need to do is to read the array of strings and paint the button Yellow or Red. If the String is A then the button should be Yellow, and if the String character is B the button should be Red.
My code so far;
for (NSString* content in arr) {
           if ([content isEqualToString:@"A"]){
               // Make the (1st/there after) button in the interface builder to Yellow and etc
           }else {
// Make the 1st button in the interface builder to Redand etc
}
       }

A: First, in Interface Builder (IB) you need to assign tag's to each button that you want to change so that you can retrieve them later.  Set the first button tag to 0, second to 1, etc.
Then your code would look something like this:
for (NSUInteger i = 0; i < 4; i++) {
    UIButton *button = (UIButton *)[self.view viewWithTag:i];
    if ([(NSString *)[arr objectAtIndex:i] isEqualToString:@"A"]) {
        [button setBackgroundColor:[UIColor yellowColor]];
    } else {
        [button setBackgroundColor:[UIColor redColor]];
    }
}

A: You should tag the buttons in IB, or create Outlets for them in the subclass. Then you can reference them by these tags or outlets.
Once you have created all of the outlets, you could store the references in a member variable containing the outlets. Then it is a simple matter of setting the background color to the correct value based on the string.

A: Actually, you can use tag property of UIButton. Suppose, your button tags will be 1, 2, 3, 4. So:
NSArray *array = [NSArray arrayWithObjects:@"A", @"B", @"B", @"A", nil];
for (int i = 0; i < 4; i++) {
    UIView *view = [self.view viewWithTag:i + 1];
    if ([[array objectAtIndex:i] isEqualToString:@"A"])
        view.backgroundColor = [UIColor yellowColor];
    else if ([[array objectAtIndex:i] isEqualToString:@"B"])
        view.backgroundColor = [UIColor redColor];
}

Besides, I wouldn't recommend you to use IB, especially at the beginning. Write the code by yourself.
This code may contain syntax or logic errors (I wrote it in notepad):
@interface ViewController : UIViewController
@end

//
@implementation ViewController

- (void)loadView {
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    self.view.backgroundColor = [UIColor whiteColor];

    NSArray *array = [NSArray arrayWithObjects:@"A", @"B", @"B", @"A", nil];
    CGFloat offset = 5.0f, step = self.view.frame.size.width / [array count];
    for (NSString *string in array) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(offset, 5, step - 10, 50);
        offset += step;

        if ([string isEqualToString:@"A"])
            button.backgroundColor = [UIColor yellowColor];
        else if ([string isEqualToString:@"B"])
            button.backgroundColor = [UIColor redColor];

        [self.view addSubview:button];
    }
}

@end


text:
Q: React JS - ESLint - Rules for ignoring components with UNSAFE_componentWillMount, UNSAFE_componentWillUpdate, and UNSAFE_componentWillReceiveProps Currently, I'm getting these linting errors:
ESLint: UNSAFE_componentWillUpdate should be placed after someFunction (react/sort-comp)
and
ESLint: Identifier 'UNSAFE_componentWillUpdate' is not in camel case. (camelcase)
Currently, I'm not able to find the correct rules to add to .eslintrc to apply to the prepended UNSAFE_ component lifecycles. I'm trying to make it apply to both react/sort-comp and camelcase rules, any clues/help would be appreciated

A: You can add this to your eslint
"camelcase": [
  "error", {
    "ignoreDestructuring": true,
    "allow": [ "^UNSAFE_" ]
  }
],

This basically just allows all the renamed UNSAFE_ lifecycle methods.