text:
Q: How to add mysql-8.0 repository from archive.ubuntu.com/ubuntu/pool/main/m/mysql-8.0/ Official repo for MySQL8 https://repo.mysql.com/apt/ not working.
How to add archive.ubuntu.com/ubuntu/pool/main/m/mysql-8.0/ to source list for Ubuntu 18.04 Bionic for setup MySQL8?
I'm trying to add next list to /etc/apt/sources.list.d/mysql.list
deb http://ua.archive.ubuntu.com/ubuntu/pool/main  bionic main
deb-src http://ua.archive.ubuntu.com/ubuntu/pool/main bionic main

but it's not working

A: The first method:
wget https://repo.mysql.com/mysql-apt-config_0.8.9-1_all.deb
sudo dpkg -i mysql-apt-config_0.8.9-1_all.deb

Text window will appear:

*

*Select Xenial as most recent and hit Enter

*Select MySQL Server & Cluster (Currently selected: mysql-5.7) and hit Enter

*Select mysql-8.0 preview and hit Enter

*Select OK and press

But you could get the following errors during sudo apt update:
Err:3 http://repo.mysql.com/apt/ubuntu xenial InRelease
  The following signatures were invalid: EXPKEYSIG 8C718D3B5072E1F5 MySQL Release Engineering <mysql-build@oss.oracle.com>
Reading package lists... Done
W: GPG error: http://repo.mysql.com/apt/ubuntu xenial InRelease: The following signatures were invalid: EXPKEYSIG 8C718D3B5072E1F5 MySQL Release Engineering <mysql-build@oss.oracle.com>
E: The repository 'http://repo.mysql.com/apt/ubuntu xenial InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

To get rid of those errors, remove newly added repository file:
sudo rm /etc/apt/sources.list.d/mysql.list

So try the second method.
The second method if the first did not go:
Your /etc/apt/sources.list should look like this for that:
deb http://us.archive.ubuntu.com/ubuntu/ bionic main restricted
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates main restricted
deb http://us.archive.ubuntu.com/ubuntu/ bionic universe
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates universe
deb http://us.archive.ubuntu.com/ubuntu/ bionic multiverse
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates multiverse
deb http://security.ubuntu.com/ubuntu bionic-security main restricted
deb http://security.ubuntu.com/ubuntu bionic-security universe
deb http://security.ubuntu.com/ubuntu bionic-security multiverse

If your server is used for learning and testing purposes, OS dependencies issues and system breaking are accessible, then you could try to add the next to your sources.list:
deb http://ru.archive.ubuntu.com/ubuntu/ eoan main restricted

Then sudo apt update && sudo apt install mysql-server-8.0
During mysql-server-8.0 package installation copy installed packages information somewhere to have the ability to remove them and install supported versions instead after eoan's repository commenting. It could remove other packages, required for stable system processing. So be prepared to recover or reinstall your system.
After mysql-server installation

*

*Comment out eoan repository record

*sudo apt clean && sudo apt update
To roll back to normal configuration:

*

*sudo apt purge mysql-server-8.0 && sudo apt autoremove

*Comment or remove eoan record in sources.list

*sudo apt update && sudo apt install -f && sudo apt upgrade


text:
Q: M/Monit how to see current disk space? In the admin interface of M/Monit under Reports -> Analytics I can chose to show Space %.

*

*How can I make the Monit clients submit this info?

*Is there a way to display Disk Space percentage on the Status page besides %Cpu and %Mem?

I have found that I can set alerts if disk space is running out (will do that, but would like to have an overview as well).

A: You can see this information on the Reports -> Analytics page.

Your Monit config needs to have disk checks for the filesystems you require:
check device root with path /
    if SPACE usage > 80% then alert

check device var with path /var
    if SPACE usage > 80% then alert

check device usr with path /usr
    if SPACE usage > 80% then alert

check device tmp with path /tmp
    if SPACE usage > 80% then alert

There's no way to add disk space to the overview graph. It wouldn't make sense from a design or UI perspective.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linking with OpenSSL, libcurl, and zlb in AWS CPP SDK I am trying to build AWS-CPP SDK on Linux and Windows. It has dependency of OpenSSL, zlib, and libucurl.  Although these packages are available on Linux, they are not on Windows. How do I specify the locations of these packages' header files and libraries?
I also have more recently versions of these packages on Linux.  How do I override the default paths?

A: There isn't any special requirements for Windows. As you can see from this: http://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup.html
Only Linux requires those extra libraries. On Windows, it will use whatever is provided by platform/Visual Studio.

A: All 3 dependencies are found for Windows  - both x32 and x64 bit architectures.
You may also build them from source.

*

*OpenSSL can be found here (and on other sites too):
https://wiki.openssl.org/index.php/Binaries

*Zlib is found at :
https://github.com/kiyolee/zlib-win-build

*libCurl can be built from source too:
https://curl.se/docs/install.html
Building from source code is necessary, if you want the resulting .LIBs(static)  and/or DLLs, to be compatible with your version of Visual C++/Studio(2005-2022).


text:
Q: looping through variable from rest api and ading it to a v-list I am having some difficulties with the vue.js. The main problem is that I am getting this error :
Property or method `response` is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for `class-based` components, by initializing the property.

My main idea is to loop through the response (which is just an array) and add it to my v-list to have it in shape of something like this :

Instead of having create, read etc. to have my elements of array, and I am wondering how to even start with this problem.
like this is the part with my list in vue.js, I know that I think I need to use v-for method but I cant even start it without solving the error.
            <v-list-group>
              <v-list-item @click="getHosts()">
              {{response}}
              </v-list-item>
              <v-list-item-group>
              </v-list-item-group>
            </v-list-group>
          </v-list>

and this is the function that gets the array.
getHosts(){
      axios.get('http://127.0.0.1:8000/something')
      .then((response)=>{
      console.log(response.data)
      return response
      })
    }

I've added this function in export default in section methods, I've read about other sections and thought maybe beforeMount but I still got an error.
Thanks for any clues/help/solutions!

A: Instead of returning the response directly. You can bind the response in the data property.
Working Demo (For demo purpose I am using v-for instead of v-list) :

var vm = new Vue({
  el: '#vue-instance',
  data() {
    return {
      hostList: []
    }
  },
  methods: {
    getHosts() {
        axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
        this.hostList = response.data;
        }).catch((error) => {
        console.warn('API error');
      });
    }
  }
});

  <button v-on:click="getHosts">Get Hosts!</button>

      {{ host.name }}


text:
Q: How to acces sql server database that is on my desktop computer over the internet? I have a SQL server database,and I want to access it via my application over other device,like my laptop.If I am at home,and I am connected to my WIFI,all I have to do is change my connection string to the ip address of my computer where the sql server is and it works.
Can I somehow manage to connect to that database when I am not on my wifi?When I am somewhere else?
I have a free dns,I tried entering it in the connection string,under data source,but it is not working..
The app I am developing is a wpf desktop application
EDIT: This can't be done as easily is I thought,so this question isn't helpfull.

A: Your questions is very tricky, that is not simple that you think, here i answer a similar question for another stackoverflow member:
How to run a live server win winsock?
Maybe in the best and simple case, your router support virtual servers (and that router module works), you can setup a virtual server pointing to your private/internal sql service.
If you have a dynamic ip from your ISP, thats works meanwhile that ip is valid

A: Do you have a secure corporate login?  If you have a FOB key, or something along those lines, you can definitely do it.  I used to do this all the time at my previous job.


text:
Q: Sceneform SDK can access all features of ARCore SDK? I run through all sample provided in both ARCore SDK and Sceneform SDK. But in Sceneform samples, it detect only plane surfaces not Walls. But it works in samples provided in ARCore SDK.
So there is no wall detection available in Sceneform? And Is there any ARCore feature which is not accessible using Sceneform ?

A: All the features of ARCore on Android are available when using Sceneform.  The most common use cases are very easy, such as working with objects on a floor plane.
To access the ARCore session you can call ArSceneView.getSession()
You can perform per-frame operations by setting the Scene listener by calling Scene.setOnUpdateListener() then in the listener call ArSceneView.getArFrame().
For example
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.sceneView = (ArSceneView) findViewById(R.id.scene_view);
    sceneView.getScene().setOnUpdateListener((this::onSceneUpdate));
}

private void onSceneUpdate(FrameTime updatedTime) {
    Frame frame = sceneView.getArFrame();
    Collection<Anchor> updatedAnchors = frame.getUpdatedAnchors();
    for (Anchor anchor : updatedAnchors) {
        // Handle updated anchors...
    }
}

For ARCore features that require session configuration, you can create the session in your own code and call ArSceneView.setupSession() or if you use ArFragment, you can extend ArFragment can implement getSessionConfiguration() which is called immediately after creating the session.
Just remember if you configure the session directly to set the update mode to LATEST_CAMERA_IMAGE.


text:
Q: How to get null values in textboxes in JQuery? Actually I am having one registration form & one settings page. After entering some values in registration form when i change my page to settings page & if I come back to registration page I want all those values entered previously needs to be empty, but they are displayed as per the values entered by me.
The following code shows the full description of my code:
index.html

              Register
              Settings

          Name <input type="text" id="name" name="name"> </input>
          Age <input type="number" id="age" name="age"></input>
          Mobile Number <input type="number" id="mobile" name="mobile"> </input>
          Email Id <input type="email" id="email" name="email"> </input>
          <input type="submit" id="register" name="register" value="Register"> </input>

.....

As per the following code after entering some values in registration form when I change my page to settings page & if I come back to registration form all the values need to be empty. Can anyone please help me with this...
Waiting for your reply...

A: $(document).ready(function() {
  $("input[type='text']").val('');  //sets blank to all textboxes of type input
});

Or if you want inputs of specific divs to be cleared then:
$(".registrationScreen :input:not(input[type='submit'])") { //except for submit
  $(this).val('');
});

A: The following jQuery will clear all form elements that are children of the class registrationScreen:
$(".registrationScreen").children().each(function() {
    $(this).val("");
});


text:
Q: iOS gamekit/bluetooth data streaming I have a written a program using gamekit/bluetooth to transfer low quality video using compressed jpegs from one iOS device to another.  I do already realize that gamekit/bluetooth should not be used for this purpose (for small chunks of data) but it does indeed work well streaming 15 low quality compressed jpegs/second with little to no latency.
The question I have is once I increase either the quality or frame rate from the iOS device sender to the iOS receiver, a lag or delay will occur and will no longer be real time.  If there is a delay, I'd like somehow for the sending iOS device to discard frames so that the receiver can catchup or for the receiver to ignore the backlog queue.
In GameKit I have set the session mode to use GKSendDataUnreliable to see if it could help, but to no avail.
If delays occur, what is the best solution and correct approach to discard the frames (jpegs) so that the iOS receiver can then catch up back to real time?  Would the sender need to stop transmission for a period of time or is there something that receiving client can do to discard the accumulating queue.
I've used NSStream before as well, and while using wifi allows for greater bandwidth, the same problem will still occur in terms of delays if too much data is being transmitted.
Thank you in advance for your help.

A: Could you not attach a timestamp to each jpg (time since epoch perhaps) so the receiving client will ignore all images that are not within a given timeframe.
Also you could have the receiving client respond back with simple acknowledgement packets indicating that a jpg has been received. If the sending client hasn't received an acknowledge packet within a given timeframe it discards all images it was going to send and starts from scratch.
With this solution if the receiving client falls X seconds behind the sender it will stop sending acknowledgement packets and discard all incoming data until the sender throws out everything in its queue and starts sending "live" frames again.


text:
Q: Test connection with MongoDb using Spring Boot 2 with MongoTamplete I need to test periodically my connection with MongoDB, to do this I would like to use MongoTemplate.
How can I do this?
tks.

A: You can use Spring Boot Actuator for that. Include the Actuator dependency. In application.properties include  management.endpoint.health.show-details=ALWAYS. Now you should be able to see status of your Mongo Connection.


text:
Q: Position React Native alert at bottom of screen React Native alert defaults to showing up at the center of the screen. I've been trying to style it so that it shows up at the bottom of the screen - with no success. Does anyone know how I would go about this? I tried position: absolute and bottom: 0 but it still shows up in the center.

A: I have tried this out let me know if it helps also have designed according to the image.
Copy Paste the code and try.
import React, { useState } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TextInput,
  Pressable,
  Modal,
  Dimensions,
  Button,
} from 'react-native';

const App = () => {
  const [showWarning, SetshowWarning] = useState(false);
  const onPressHandler = () => {
      SetshowWarning(true);
  }

  return (
    <View style={styles.body}>
      <Modal
        visible={showWarning}
        transparent
        onRequestClose={() =>
          SetshowWarning(false)
        }
        animationType='slide'
        hardwareAccelerated
      >
        <View style={styles.centered_view}>
          <View style={styles.warning_modal}>
            <View style={styles.warning_title}>
              <Text style={{
                color: '#000000',
                fontSize: 25,
                fontWeight:'700',
                textAlign: 'center',
              }}>Unsaved Changes</Text>
              <Text style={styles.text}>Are you sure you want to continue?</Text>
            </View>
            <Pressable
              onPress={() => SetshowWarning(false)}
              style={styles.warning_button1}
              android_ripple={{ color: '#fff' }}
            >
              <Text style={styles.textKE}>Keep Editing</Text>
            </Pressable>
            <Pressable
              onPress={() => SetshowWarning(false)}
              style={styles.warning_button}
              android_ripple={{ color: '#fff' }}
            >
              <Text style={styles.textDC}>Discard Changes</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
      <Button onPress={() =>onPressHandler()} title="Text This"></Button>
      {/* Add Here full code */}
    </View >
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    backgroundColor: '#ffffff',
    alignItems: 'center',
  },

  centered_view: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#00000099',
  },
  warning_modal: {
    width: Dimensions.get('window').width,
    height: 200,
    backgroundColor: '#eeff0f0',
    borderRadius: 20,
    top:"31%"
  },
  warning_title: {
    height: 100,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#eff0f0',
    borderTopRightRadius: 20,
    borderTopLeftRadius: 20,
    borderBottomWidth:1,
    borderColor:'grey'
  },
  warning_body: {
    height: 100,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textKE: {
    marginTop:20,
    color: '#1485fe',
    fontSize: 20,
    margin: 5,
    textAlign: 'center',
  },
  textDC: {
    marginTop:20,
    color: 'red',
    fontSize: 20,
    margin: 5,
    textAlign: 'center',
  },
  warning_button1: {
    height:70,
    backgroundColor: '#efeff0',
    borderBottomWidth:1,
    borderColor:'grey'
  },
  warning_button: {
    height:70,
    backgroundColor: '#efeff0',
    borderBottomLeftRadius: 20,
    borderBottomRightRadius: 20,
  }
});

export default App;


text:
Q: Is it possible to set pthread_sigmask on all threads in a process? This is a follow-up to this question and I have looked at the related questions.
I am still attempting to do some cleanup when SIGTERM is received, and then achieve the effect of TERM which is the default behavior when no thread in a process is waiting for a signal, and and no signal handler is defined.
In the earlier question, I had assumed that signals had deterministic behavior in a multithreaded application, but after some non-deterministic results and some research, I realized that this is not a safe assumption.
My application is multithreaded and using a normal signal handler via sigaction or signal has non-deterministic results because the arbitrary choice of which thread is actually interrupted to run the signal handler matters to the signal handler's operation (it is cleaning up some threads which might deadlock if the wrong thread is interrupted).
Therefore, I switched to doing synchronous signal handling. In particular, I am blocking SIGTERM using pthread_sigmask in the starting thread, and then calling sigwait() in the thread that will actually perform the cleanup. However, after sigwait() returns in the thread, and I finish my cleanup, I then try the following:
kill(getpid(), SIGTERM);

However, this signal is obviously ignored, because all the other active threads are blocking SIGTERM. Thus, I need to unblock signals in all other threads, before returning from the function that my cleanup thread is running. Is there a function call that can be used to set pthread_sigmask on other threads?

A: There is no call that can be used to set signal mask on other threads. Received signal is a trigger and no sense to resend that signal for itself. Try to use pthreads condition variables instead.


text:
Q: Is there any way to find who define / where a particular Spring Bean is defined? We have a large Spring project with dependencies coming from many different internal libraries.  We have a number of conflicts with the same bean being defined more than once.
We don't want to enable beans override configuration property.  So, need to know who define these beans and where they are defined?

A: If you are using IntelliJ IDEA you can search for beans with Ctrl+Alt+Shift+N.


text:
Q: Isomorphic semidirect products? Let $N\rtimes_\varphi H$ and $N\rtimes_\psi H$ be semidirect products such that $\psi$, for $h\in H$, is given by the formula
$$
\psi(h)=\sigma\circ\varphi(h)\circ\sigma^{-1}
$$
for some $\sigma\in\text{Aut}(N)$.
Is it true that
$$
N\rtimes_\psi H\cong N\rtimes_\varphi H?
$$

A: Define a function
$$\alpha :N\rtimes_\varphi H\to N\rtimes_\psi H:(n,h)\mapsto (\sigma (n),h).$$
You can easily check, using the fact that $\sigma\in Aut(N)$ and that $\sigma \circ \varphi(h)=\psi(h)\circ \sigma$ for all $h\in H$, that this is a group homomorphism. By a similar reasoning,
$$\beta:N\rtimes_\psi H\to N\rtimes_\varphi H:(n,h)\mapsto (\sigma^{-1}(n),h)$$
is a group homomorphism, and it is easily seen to be an inverse for $\alpha$, which is thus an isomorphism.


text:
Q: Shiny R: how to evaluate data set name to print the dataset I want to print data set values in R shiny web app. But below code is printing the name of dataset in UI output. How can I print values of dataset?
library(MASS)
library(shinythemes)
library(shiny)
library(ggplot2)

mass.tmp <- data(package = "MASS")[3]
mass.datasets <- as.vector(mass.tmp$results[,3])

ui <- fluidPage(

  theme = shinytheme("superhero"),
  titlePanel("Linear Regression Modelling"),
  sidebarLayout(
    sidebarPanel(
      selectInput("dsname", "Dataset:",choices = c(mass.datasets))
      ,
       uiOutput("x_axis")
      ,
       tableOutput("tab")
    ),
    mainPanel(
      tags$br(),
      tags$br()
  )
)
)

server <- function(input, output) {

  num_ds <- function(ds)
  {
    nums <- sapply(ds,is.numeric)
    num_ds <- ds[,nums]
    return(num_ds)
  }

  ds_ext <- reactive({  num_ds(input$dsname) })

  output$tab <- renderTable({  eval(input$dsname) })

    # output$x_axis <- renderUI({
    #    col_opts <- get(ds_ext())
    #    selectInput("x_axis2", "Independent Variable:", choices = names(col_opts))
    # })

}

shinyApp(ui = ui, server = server)

This is full code. I am trying to display data set from MASS package as you see in the code above.


text:
Q: Problem minimizing a constrained function in Python with scipy.optimize.minimize I'm trying to minimize a constrained function of several variables adopting the algorithm scipy.optimize.minimize. The function concerns the minimization of 3*N parameters, where Nis an input. More specifically, my minimization parameters are given in three arrays H = H[0],H[1],...,H[N-1], a = a[0],a[1],...,a[N-1] and b = b[0],b[1],...,b[N-1] which I concatenated in only one array named mins, with len(mins)=3*N.
Those parameters are also subjected to constraints as follows:
0 <= H  and  sum(H) = 0.5
0 <= a <= Pi/2
0 <= b <= Pi/2

So, my code for the constraints read as:
import numpy as np

# constraints on x:
def Hlhs(mins):    # left hand side
    return np.diag(np.ones(N)) @ mins.reshape(3,N)[0]
def Hrhs(mins):    # right hand side
    return np.sum(mins.reshape(3,N)[0]) - 0.5
con1H = {'type': 'ineq', 'fun': lambda H: Hlhs(H)}
con2H = {'type': 'eq', 'fun': lambda H: Hrhs(H)}

# constraints on a:
def alhs(mins):
    return np.diag(np.ones(N)) @ mins.reshape(3,N)[1]
def arhs(mins):
    return -np.diag(np.ones(N)) @ mins.reshape(3,N)[1] + (np.ones(N))*np.pi/2
con1a = {'type': 'ineq', 'fun': lambda a: alhs(a)}
con2a = {'type': 'ineq', 'fun': lambda a: arhs(a)}

# constraints on b:
def blhs(mins):
    return np.diag(np.ones(N)) @ mins.reshape(3,N)[2]
def brhs(mins):
    return -np.diag(np.ones(N)) @ mins.reshape(3,N)[2] + (np.ones(N))*np.pi/2
con1b = {'type': 'ineq', 'fun': lambda b: blhs(b)}
con2b = {'type': 'ineq', 'fun': lambda b: brhs(b)}

My function, with the other parameters (and adopting N=3) to be minimized, is given by  (I'm sorry if it is too long):
gamma = 17
C = 85
T = 0
Hf = 0.5
Li = 2
Bi = 1

N = 3

def FUN(mins):
    H, a, b = mins.reshape(3,N)
    S1 = 0; S2 = 0
    B = np.zeros(N); L = np.zeros(N);
    for i in range(N):
        sbi=Bi; sli=Li
        for j in range(i+1):
            sbi += 2*H[j]*np.tan(b[j])
            sli += 2*H[j]*np.tan(a[j])
        B[i]=sbi
        L[i]=sli
    for i in range(N):
        S1 += (C*(1-np.sin(a[i])) + T*np.sin(a[i])) * (Bi*H[i]+H[i]**2*np.tan(b[i]))/np.cos(a[i]) + \
        (C*(1-np.sin(b[i])) + T*np.sin(b[i])) * (Li*H[i]+H[i]**2*np.tan(a[i]))/np.cos(b[i])
    S2 += (gamma*H[0]/12)*(Bi*Li + 4*(B[0]-H[0]*np.tan(b[0]))*(L[0]-H[0]*np.tan(a[0])) + B[0]*L[0])
    j=1
    while j<(N):
        S2 += (gamma*H[j]/12)*(B[j-1]*L[j-1] + 4*(B[j]-H[j]*np.tan(b[j]))*(L[j]-H[j]*np.tan(a[j])) + B[j]*L[j])
        j += 1
    F = 2*(S1+S2)
    return F

And, finally, adopting an initial guess for the values as 0, the minimization is given by:
x0 = np.zeros(3*N)
res = scipy.optimize.minimize(FUN,x0,constraints=(con1H,con2H,con1a,con2a,con1b,con2b),tol=1e-25)

My problems are:
a) Observing the result res, some values got negative even though I have constraints for them to be positive. The success of the minimization was False, and the message was: Positive directional derivative for linesearch. Also, the result is very far from the minimum expected.
b) Adopting the method='trust-constr' I got a value closer to what I was expecting but with a false success and the message The maximum number of function evaluations is exceeded.. Is there any way to improve this?
I know that there is a minimum very close to these values:
H = [0.2,0.15,0.15]
a = [1.0053,1.0053,1.2566]
b = [1.0681,1.1310,1.3195]

where the value for the function is 123,45. I've checked the function several times and it seems to be working properly. Can anyone help me to find where my problem is? I've tried to change xtol and maxiter but with no success.

A: Here are a few hints:

*

*Your initial point x0 is not feasible since it doesn't satisfy the constraint sum(H) = 0.5. Providing a feasible initial point should fix your first problem.

*Except for the constraint sum(H) = 0.5, all constraints are simple bounds on the variables. In general, it's recommended to pass variable bounds via the bounds parameter of minimize. You can simply define and pass all the bounds like this
from scipy.optimize import minimize
import numpy as np

# ..your variables and functions ..

bounds = [(0, None)]*N + [(0, np.pi/2)]*2*N

x0 = np.zeros(3*N)
x0[0] = 0.5

res = minimize(FUN, x0, constraints=(con2H,), bounds=bounds,
               method="trust-constr", options={'maxiter': 20000})

where each tuple contains the lower and upper bound for each variable.

*

*Unfortunately, 'trust-constr' has still trouble to converge to a local minimizer. In this case, you can either try other initial points or you can use the state-of-the-art open source solver Ipopt instead. The Cython wrapper cyipopt provides a interface similar to scipy:

from cyipopt import minimize_ipopt

# rest as above

res = minimize_ipopt(FUN, x0, constraints=(con2H,), bounds=bounds)

this gives me a solution with objective value 122.9.

*

*Last but not least, it's always a good idea to provide exact gradients, jacobians and hessians.


text:
Q: Fill between many pairs of points If I run the following code:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'start': [0, 3, 7], 'end': [1, 4, 8]})

fig, ax = plt.subplots()
for i in df.index:
    ax.fill_betweenx([0, 1], df.loc[i, 'start'], df.loc[i, 'end'], color='red')

I get this output, as expected:

The problem with the code I've written is that, if I have a huge dataframe, then looping through all the rows takes a long time.
Is there a faster way of achieving the same output?
matplotlib or plotly solutions welcome.

A: If you use fill_between instead of fill_betweenx, you can do
boundaries = df[['start', 'end', 'end']].to_numpy().ravel()

ax.fill_between(
    boundaries,
    np.zeros(len(boundaries)),
    np.ones(len(boundaries)),
    where=np.tile([True, True, False], len(df)),
    color='red'
)


text:
Q: Convert a non hex string to byte C# I need to convert a non hex string to byte in c#
var string1 = "xs";
byte result = byte.parse(string1);

But this throws  format exception.
Anything that I am missing.

A: try this...
        var string1 = "xs";
        byte[] result = System.Text.Encoding.ASCII.GetBytes(string1);


text:
Q: Completely lock user account on server, including ssh I need to lock some user accounts, without messing with their HOME, if at all possible.
Normal way would be usermod -L user but it seems to leave open ssh login with public key authentication (routinely used on this server).
I know I could just mv /home/user/.ssh /home/user/_ssh or something similar, but is that the right way of doing this?
What am I missing?

A: Your should be able to disable ssh-logins for users by adding their usernames or groups in
/etc/ssh/sshd_config

under the setting DenyUsers and/or DenyGroup.
See man 5 sshd_config.
Don't forget to HUP the sshd.

A: To properly prevent access for a user on an SSH server, the correct solution is to modify the SSHD config so that they are explicitly denied access using the DenyUsers and/or DenyGroups settings. I would normally suggest using DenyGroups and creating a dedicated group for this purpose that you add anyone who is not supposed to have SSH access to.
To fully lock the account you also need to lock their password, set it expired (both using either usermod), and change their login shell to /sbin/nologin so that other login mechanisms do not let them in. You may need to do even more than that in some cases as well (for example, if the server runs Samba and the user had access to file shares through SMB, you probably need to lock their Samba account as well using smbpasswd).

Why is just locking the account with usermod not sufficient?
This comes down to the fact that an account is 'locked' in the traditional UNIX sense by making it such that no matter what password the user tries to use, it will never match what is in the password database. This means, rather importantly, that locking the account with usermod only affects those services which are authenticating against the system password database (on a modern Linux system this would mean those services which are configured to use the pam_unix PAM module for authentication).
However, SSHD only actually authenticates against the system password database if the password or challenge-response authentication mechanism is being used. Public key authentication, as well as any other authentication mechanisms (such as GSSAPI or s/key) only involve the system password database to check that the account exists, so they will generally work just fine with a locked account.
Why is setting the login shell to /sbin/nologin not sufficient?
This has to do with the fact that there are a number of ways to access a system as a specific user account that have nothing to do with a login shell.
The most relevant one here is that SFTP, SCP, and SSH with an explicitly specified command do not invoke a login shell at all. That means that even with the login shell set to /sbin/nologin, you can usually get a working shell on a system as a user by running ssh -t user@host /bin/sh (the -t is needed to explicitly request pseudoterminal allocation, which is in turn required to get some things, such as sudo or vim to work correctly from the resulting shell), and you can almost always still use SFTP and SCP to move files around.
Another example of this would be using sudo -u user /bin/sh to get a working shell as a given user from an existing session on the system as a different user. That will work even if the target user's login shell is set to /sbin/nologin, though if the account is also locked using usermod you will have to run it as the root user (at least, in any standard sudo configuration).

A: The documentation, man usermod, gives you the recommended solution:

-L, --lock Lock a user's password. This puts a ! in front of the encrypted password, effectively disabling the password. You can't use this option with -p or -U.
Note: if you wish to lock the account (not only access with a password), you should also set the EXPIRE_DATE to 1.

And then

-e, --expiredate EXPIRE_DATE The date on which the user account will be disabled. The date is specified in the format YYYY-MM-DD.
An empty EXPIRE_DATE argument will disable the expiration of the account.

So, turning this into a real example
usermod -L -e 1 someuser     # Lock
usermod -L -e '' someuser    # Unlock

If you might have a default expiry date set up in /etc/default/useradd you can include its value - if any - as part of the unlocking process:
usermod -U -e "$( . /etc/default/useradd; echo "$EXPIRE")" someuser

Jobs scheduled through cron are also disabled for a user with an expired account but not for just a locked account. Error messages from journalctl -u cron show the expired user's account name (in this instance test2):
Apr 30 11:47:01 pi CRON[26872]: pam_unix(cron:account): account test2 has expired (account expired)
Apr 30 11:47:01 pi cron[472]: Authentication failure
Apr 30 11:47:01 pi CRON[26872]: Authentication failure

Jobs scheduled with at remain unattempted. (It's not clear to me if they will ever be run once they are past their due date; empirically it seems not.)
Other processes already running under the locked and expired account remain unaffected and continue to run.

A: After issuing "usermod -L user" you can deny ssh access by adding this line to the end of the /etc/ssh/sshd_config file:
DenyUsers user

Or you could create a group for this purpose so you can deny ssh login by adding users to the group:
groupadd deny-ssh
usermod -a -G deny-ssh user

And add the group to the end of the /etc/ssh/sshd_config file:
DenyGroups deny-ssh

After every change to the /etc/ssh/sshd_config file make sure to reload the sshd daemon in order to apply the changes:
systemctl reload sshd

The reload command will load the new settings and keep any existing ssh sessions open.

Alternatively, you could change the users shell so even if he logins he won't get a shell:
usermod --shell /usr/sbin/nologin user

I could recommend to create a simple bash script that will do all of the above with just one command.
deny-logon.sh:
#!/bin/bash

#Lock user account
usermod -L $1

#Deny SSH connections
usermod -a -G deny-ssh $1

#Remove user Shell
usermod --shell /usr/sbin/nologin $1

#Reload sshd
systemctl reload sshd

Now you simply have to execute the script like that:
./deny-logon.sh user

And it will automatically make all the above changes for the "user".
EDIT: @roaima solution is the most correct one, expiring an account disables every access to it and should be done if you want to stop a user from loging in.

A: Locking the account is the correct way.
You may also want to remove the authorised_keys file to defeat SSH.
Remember there are other ways besides SSH to logon.
Doing anything with "*rc" routines is clumsy, but commonly used for "sftp only" accounts if it is a utility account foe sftp or SCP say.
But !password is better that changing their password if restoration is required.
As always, keep backups, and securely.

A: If you don't want to rely on assumptions about how different software will treat locked or expired state in the shadow file, a big hammer to completely lock out as user account is to remove its line from the passwd file (keeping a backup somewhere else). With this change, there is no longer any mapping from the user name to the uid or home directory, so nothing (sshd or otherwise) can look up the username, find the homedir and authorized_keys file (or similar) and act on it.


text:
Q: Selectfield stuck in Sencha Touch & events not firing on selection I have a selectfield that works perfectly on desktop (scrolls, selects, fires the right events, updates the appropriate field, etc.), but will not disappear after selection when running on mobile (iPhone).
Upon making a selection, the selectfield "wheel" does not disappear and will not even disappear when tapping in the mask (outside of the scrolling picker area). Again, this only happens on mobile and is perfectly fine on desktop.
Sounds like a framework bug? Read on for more clues...
{
    xtype: 'selectfield',
    id: 'editor-page',
    name: 'page',
    label: 'Page',
    labelWidth: 70,
    options: [
        {text: 'N/A',  value: 'N/A'},
        {text: '1',  value: '1'},
        {text: '2',  value: '2'},
        {text: '3',  value: '3'}
        // ...
    ]
}

Things I've tried (without luck)

*

*From what I've seen of similar issues around the web, I've tried messing with setting showAnimation: 'false'.

*Forcing hideOnMaskTap: 'true' (even though it should be by default)

*Setting modal: 'true'

*Setting stopMaskTapEvent: 'false' (to allow taps outside the picker to be made)
(AND... every combination of the above, just in case of framework quirk or a misunderstanding of their interdependence on my part.)

Selectfield events firing on desktop but not on mobile (iPhone)?
On the selectfield, I put listeners on the following events as a means to trap a selection change and force a hide or blur, but as it turns out, they're only firing on desktop (Chrome) and not in mobile Safari.
listeners: {
    'render': function (thisComponent) {
        alert("select!");
        thisComponent.blur();
    },
    'action': function (thisComponent) {
        alert("action!");
        thisComponent.blur();
    },
    'select': function (thisComponent) {
        alert("select!");
        thisComponent.blur();
    }
}

And lastly, I hate to admit it, but yes, I'm using Sencha Touch 1.1.0
*Gasps! Oh the Horror!*
At this point, the project may not have time enough to consider all the ramifications of migrating to 2.x. Thus, this is my last ditch effort before diving into the migration if I absolutely must to fix this.

A: Egad. So it turns out that although not rendered in the desktop browser, the mobile rendering of selectfield displays a set of "done" and "cancel" buttons.
Since the desktop version works upon selection without displaying these confirmation buttons, I had forgotten the mobile render of selectfield displays the confirmation buttons instead of being able to tap/click outside the picker or clear the mask upon making a selection.
In my particular case, I had some CSS toolbar rules that were obscuring the buttons within the selectfield picker.
Thus, it was only a matter of finding the right CSS selectors to reveal the buttons that (although not necessary or visible on desktop) were being hidden on mobile.
/* Override toolbar padding for selectfield confirmation toolbar */
.x-picker .x-toolbar .x-layout-box-inner {
    margin-top: -35px;
}


text:
Q: How to format External Western Digital hard disk when all NTFS boot sectors cannot be written to I want to format my external hard drive which is a Western Digital 500GB, through cmd dos command. But it fails because all NTFS boot sectors are not writable. Here are the commands I gave and what I got in return!
C:\Users\Stefanos&Fratzeskos>FORMAT F: /Q

The type of the file system is RAW.
The new file system is NTFS.
WARNING, ALL DATA ON NON-REMOVABLE DISK
DRIVE F: WILL BE LOST!
Proceed with Format (Y/N)? Y
QuickFormatting 476269M
Volume label (32 characters, ENTER for none)?
Creating file system structures.
The first NTFS boot sector is unwriteable.
All NTFS boot sectors are unwriteable.  Cannot continue.
Format failed.

Is there something I can do to format my disc?


text:
Q: VBA script ignores some cells I've cobbled together the following script to sort each column so that empty cells/cells with errors in them are at the bottom. The problem is that it does not properly sort if there is only a single empty cell at the top of the column of data (Rows 4-1000) (leaves the empty cell there, but otherwise sorts correctly).
Sub toTop()
'
' toTop Macro
'
' Keyboard Shortcut: Option+Cmd+t
'
Dim sheetName As String
Dim column As Integer

sheetName = ActiveSheet.Name
column = 1

Do Until IsEmpty(Cells(3, column))
    Range(Cells(4, column), Cells(1000, column)).Select
    ActiveWorkbook.Worksheets(sheetName).Sort.SortFields. _
        Clear
    ActiveWorkbook.Worksheets(sheetName).Sort.SortFields.Add _
        Key:=Range(Cells(4, column), Cells(4, column)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
        :=xlSortNormal
    With ActiveWorkbook.Worksheets(sheetName).Sort
        .SetRange Range(Cells(4, column), Cells(1000, column))
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    column = column + 1
Loop
End Sub

Thanks for any help,
Scott
EDIT: Google Sheet Mock-up of Problem. This is post sorting, note that E4 is still empty.

A: Due to my low rep, I have to answer and not comment. Please try changing this line of in your VBA:
    .Header = xlGuess
to this:
    .Header = xlNo
Excel tends to make mistakes when order to decide when to determine whether to use your first row as headers or not. The supplied code will force Excel to not use the first row as a header, but rather as sortable data.


text:
Q: How to plot hour:min time in ISO 8601 time format? I am trying to plot temperature data points according to their time recording.
t = ['2021-12-11T0:6:15', '2021-12-11T7:15', '2021-12-11T8:15', '2021-12-11T9:15', '2021-12-11T10:15']

temp = [33.6, 33.6, 33.6, 33.6, 33.6]

Note: as you have mentioned t is represented without hour, the reason is that temp been collected in hour:second.
t is a string representing the date and time in ISO 8601 format (ref: datetime.datetime.isoformat()) and temp is a floating number. The plot should be in a way that t in x-axis (represented as hour:min) and temp in y-axis (represented in celcius). I want to keep the variables as lists and plot a graph without using Pandas but PyQtGraph library.
I tried the following:
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow
    )
import pyqtgraph as pg # import PyQtGraph after Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        t    = # declared above
        temp = # declared above

        # plot data: time, temp values
        self.graphWidget.plot(time, temp)

# Always start by initializing Qt (only once per application)
app = QApplication([])
window = MainWindow()
## Display the widget as a new window
window.show()
## Start the Qt event loop
app.exec_()

After running the above code, I got a traceback:
numpy.core._exceptions._UFuncNoLoopError: ufunc 'fmin' did not contain a loop with signature matching types (dtype('<U18'), dtype('<U18')) -> None
I know that there is a problem with t since its values are str which they should be same type as of temp (note: temp values should always stay float). I am not sure how to fix it.
I am using PySide6 and PyQtGraph, where Python is the language used. For this, I also tried to just plot the two variables using matplotlib library. I did the following:
import numpy as np
import matplotlib.pyplot as plt

x, y = t, temp

plt.plot(x, y, label='temperature fluctuation')
plt.xlabel('time (hour:min)')
plt.ylabel('temperature (C)')
plt.legend(loc='lower right')

A: A few assumptions:

*

*You mean hour:minutes and not hour:seconds as written. If differently, please clarify your point

*The time string is wrong: according to ISO 8601 hours and minutes should be two-character string chunks. You have to first clean the string list. I've done it manually since a Python script for that is out-of-scope

*I've used a slight different temp array just for displaying some variability in the graph. Completely negligible

That said, the proposed way is:

*

*Convert the iso strings into timestamp (float) values. This will be handled by pyqtgraph to plot numbers.

*Convert the full ISO strings into strings with format HH:MM as you require and that you'll use as axis ticks. You have two choices that are in-code explained (please, read comments)

*Get the x-axis from the PlotWidget and use the setTick property to set your custom ticks. To do so, you have to create a list of tuple with two values, the underlying numeric data and the custom string data

Here is the code:
from datetime import datetime

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow
    )
import pyqtgraph as pg # import PyQtGraph after Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        t_string_list = ['2021-12-11T06:15', '2021-12-11T07:15', '2021-12-11T08:15', '2021-12-11T09:15', '2021-12-11T10:15']

        # Get the timestamp value. A numeric value is needed for the underlying x-axis data
        t_time_value = [datetime.fromisoformat(t_string).timestamp() for t_string in t_string_list]

        # Get the x-axis ticks string values as HH:MM. Two ways
        # ---- straight and unsafe way - It only works if the ISO Format will end with minutes! [...THH:MM]
        t_ticks_values = [val[-5:] for val in t_string_list]

        # --- Safe and general way: create a datetime object from isoformat and then convert to string
        t_ticks_values = [datetime.fromisoformat(val).strftime('%H:%M') for val in t_string_list]

        temp = [33.6, 31.6, 35.6, 32.6, 37.6]

        # plot data: time, temp values
        self.graphWidget.plot(t_time_value, temp)

        # Get the x-axis
        x_axis = self.graphWidget.getAxis('bottom')
        # Check https://stackoverflow.com/questions/31775468/show-string-values-on-x-axis-in-pyqtgraph
        ticks = [list(zip(t_time_value, t_ticks_values))]
        x_axis.setTicks(ticks)

# Always start by initializing Qt (only once per application)
app = QApplication([])
window = MainWindow()
## Display the widget as a new window
window.show()
## Start the Qt event loop
app.exec_()

And here is the result:

For more advanced strategies, such as sub-classing AxisItem for custom tickStrings generator, please refer to this answer
Edit 1: Ticks downsamples
Note that you can downsample the ticks tuple in order to show less major/minor (in the example major only are present) ticks.
As for instance, if you want to show one tick every 2 timestamps:
ticks = [list(zip(t_time_value, t_ticks_values))[::2]]

The result:


text:
Q: iTextSharp self-expanding page width I'm writing a web application to generate labels. The label printer that I'm targeting utilizes 12mm tape and the customer specified that they want to limit the labels to 3.25". I know that with iTextSharp I can specify the size of the document I want to create, however it appears that I have to specify both a width and height.
Document document = new Document(new iTextSharp.text.Rectangle(234f, 33.84f));

234 is 3.25" converted to points, and 33.84 is 12mm converted to points, so this sets the document to the maximum size allowed. Is there any way to set just the height and let the document auto-expand to the amount of content? With that, is there a way to determine if the expanded width of the document exceeds to maximum allowed by the customer? Thanks in advance for any help you can offer.

A: As far as I know, because PDF is a print format, the document width and height must be set.
This is why reporting tools generally default page sizes to the default printer page size.
You best bet to try and calculate the size of the content and create the PDF accordingly.
Depending on the volume and nature of the workflow, you could provide a preview for the customer to check before printing.

A: No, that is not possible in iText.  It's not a particularly good idea anywhere else either.  As Redman said, PDF is a print-based format.  It's not HTML.
There are some tricks you can do to get around this to some extent:

*

*Create your page with the maximum legal height.  200" * 72dpi = 14400 points.

*Add a "generic tag" to your paragraphs.

*create a tag event handler that tracks where the bottom of your last paragraph was drawn.

*Save the PDF.

*Open it again with a PDFStamper

*Set the bottom of the page to match the location of that last paragraph.  Remember that the bottom left starts off at 0,0, and the top right will be

*Save the final PDF

This trick will only work if your total output is less that 200" high.  If you go over that, you'll still get a second page, and your "where the bottom is" code had better be prepared for it.
PS: I don't see what's wrong with having a number of 12mm x 3.25" pages... won't that perfectly fit the labels they want printed?


text:
Q: Security for user-generated content in Phonegap app using access origin My app displays some user-generated content and I also need to allow HTML tags. What I was wondering: When setting the config.xml file to only allow my own server - is there sill a way a user/hacker could somehow steal data? On a normal webpage you could insert a script to send some data to another server. But in my case, it is impossible to get this user's data to a 3rd party server. Or am I missing something? (And yes, I will still use a php script to remove some html entities. So this is just a question about if it is possible and not about if it is a good idea to trust other users)

A: Any attacker in the world can send any data imaginable, valid or invalid, to your app, regardless of what controls you believe are in place, and there is nothing you can do to prevent them from sending anything.
As soon as you believe you've found a way to stop them, they can simply reverse engineer your client (step 1: download the .apk, step 2: JD-GUI, step 3: ???? step 4: pwnage) to allow them whatever capabilities they desire.
If you need to allow some HTML, but don't want to be vulnerable to XSS attacks, the traditional solution is to use HTML Purifier on output when serving data to the end user.
If HTML Purifier is too slow, check out Stauros. Stauros is narrowly focused on XSS prevention, while HTML Purifier has a broader goal of outputting standards-compliant HTML.


text:
Q: Lazy load expensive operations using python __get__ I have a huge config file that I need to parse to get different configuration parameters at several classes/modules. I have created a separate module with function to do the parsing and other modules can call this to get the parsed file output.
I have come across this post Understanding __get__ and __set__ and Python descriptors which says property descriptors get can be used to cache expensive operations.
Here is what I am trying to do:
class Lazy(object):
"""Lazy attribute evaluation decorator class"""
    def __init__(self, f):
        self.f = f
        self.cache = {}
    def __get__(self, instance, owner):
        if instance not in self.cache:
            self.cache[instance] = self.f(instance)
        return self.cache[instance]

then in another class I am doing this:
def load_config_file(self):
    """
    """
    with open('/etc/test.json') as json_file:
        return json.loads(json_file)

How can I decorate the load_config_file such that the actual load from json file is called only once no matter how many modules/classes call this?
If I do
@Lazy
def load_config_file(self, file):

how would I pass the instance parameter? Can someone explain me how to achieve this?


text:
Q: tvOS - strange touchesCancelled received I am having a user input issue in my tvOS SpriteKit project - if I try to move the finger quickly after touching the touchpad on the tv remote I do have touchesCancelled called while if I wait a little while (1s) after first touch (wihout releasing my finger) all works like charm and I can use this tiny interface for steering in my game.
Unfortunately there is no specific code I can paste.
this guy:
 override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { ... }

is being called by the system in case a quick finger move but not called if I wait for 1-2 seconds before I start moving my finger.
Any idea what I could have done wrong?

A: ah .... UISwipeGestureRecognizer from previous Scene was hanging around :(
func removeAllGestureRecognizers(){
    for recognizer in self.view!.gestureRecognizers!{
        self.view!.removeGestureRecognizer(recognizer);
    }
}

fixed my issue ...


text:
Q: sending qimage over qtcpsocket: received only part of the data i am creating an application where i need to send some images over tcp.
the sending part is
QImage image;
image.load("image.png", "PNG");
image.setText("name", "color");
QByteArray ba;
QBuffer buffer(&ba);
image.save(&buffer, "PNG");
int bsize = ba.size();
sendData(MESSAGE_BACKGROUND_COLOR, QString::number(ba.size()).toStdString());
int bsent = m_tcpSocket->write(ba, ba.size());
if(!m_tcpSocket->waitForBytesWritten(-1))
{
    qDebug() << "written Bytes error " << m_tcpSocket->errorString();
}
m_tcpSocket->flush();

and the client:
 QByteArray buffer;
 buffer = m_ConnectedClients[i]->read(messageSize);
 int bytesS = buffer.size();
 QImage image;
 image.loadFromData(buffer.data());
 if (image.isNull())
 {
    qDebug("The image is null. Something failed.");
 }

The problem is that where the server seems to be sending all the data,
the client receives only the header...
(and of-course the program crashes in line

image.loadFromData(buffer.data());

The tcp communication works ok, since other messages containing only text go through ok...
Any ideas?
Thanks in advance!

A: ...and answering my own question, in case anyone else has the same problem...
i needed to set the receiving end to read from the socket until i got all the data...
something like:
int bytesS = 0;
while(byteS < messageSize)
{
   buffer->append(m_ConnectedClients[i]->readAll());
   bytesS = buffer->size();
   if (bytesS == messageSize)
   {
      QImage image;
      image.loadFromData(*m_ConnectedClients[i]->buffer, "PNG");
      if (image.isNull())
      {
         qDebug("The image is null. Something failed.");
      }
   }
}


text:
Q: How would I cross-reference a function generated by autodoc in Sphinx? I am using the Sphinx autodoc feature to generate documentation based on the docstrings of my Python library.
The syntax for cross referencing is found here
A label must precede the section in order to allow that section to be referenced from other areas of the documentation.
What I have is a .rst (ReStructeredText) file for one of my classes. It uses
.. autoclass:: classname
    :members:

To generate documentation for the class.
My question is, how would I reference the auto-generated methods of the class from another .rst document in the documentation? If I try to place a label within the method's docstring, Sphinx complains. If I try to place a label before the method heading, Sphinx doesn't recognize it.
Is there a simple way to do this, or will I have to explicitly write in my class file the method name and precede that with a label?
Here is an example a reference within the [Python documentation2 doing what I need (I am assuming it used the autodoc feature, though I don't know for sure)

A: In addition to the excellent answer already provided:
To add an alias to the referenced module (method, function, attribute, etc.), the following syntax is used:
:mod:`Alias Name <package.module>`

This will appear as a reference to Alias Name in the docs, and link to the module provided.

A: You don't need to add labels. In order to refer to a Python class, method, or other documented object, use the markup provided by the Python domain.
For example, the following defines a cross-reference to the mymethod method:
:py:meth:`mymodule.MyClass.mymethod`

Or even simpler (since the Python domain is the default):
:meth:`mymodule.MyClass.mymethod`

The documentation of TextWrapper.wrap that you link to in the question includes two cross-references of this kind (click on "Show Source" to see the reST markup).


text:
Q: Prometheus setting for scrape_interval I'm trying to use Prometheus and VictoriaMetrics to collect data and when configuring my server prometheus.yml there is one line:
scrape_interval: 15s  # How frequently to scrape targets by default.

Does this mean my search result might be delayed by 15s?

A: Yes, this means that at worst, your metrics will arrive 15 seconds later. You can configure it to be faster.
<duration>: a duration matching the regular expression [0-9]+(ms|[smhdwy])
The above is from the Prometheus docs at: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#duration
Typically, think of it as Prometheus taking snapshots of what your (continuous) metrics look like (CPU used, no. of threads running etc.) instead of thinking of Prometheus as a place to collect discrete events.
When you are thinking of how long your alert will take to fire, or for the data to be visible, the scrape interval is a factor to keep in mind.
In the context of alerting, a good resource is this article: https://pracucci.com/prometheus-understanding-the-delays-on-alerting.html
It basically says that if your scrape interval is x time unit, and you only fire an alert if an expression is true for y time unit, then the delay could at worst be (x + y) time units.


text:
Q: linq query for update more than one record I have a table named industries. In this my fields are

*

*workfor_id,

*workfor_usr_id,

*workfor_industry_id.

With the same values of workfor_id, I have different workfor_industry_id's.
foreach (var k in us){
    var ind = dbContext.industries.Where(i => i.workfor_id ==
        k.id).Select(i => i).FirstOrDefault();
    string ind2 = k.industry;
    var industryParts =   ind2.Split(',');
    var o = (industryParts.Length);
    for (c = 0; c < o; c++){
    ind.workfor_id = Convert.ToInt16(k.id);
    ind.workfor_industry_id = Convert.ToInt16(k.industryid); }
     }

To update workfor_industry_id field I have implemented inner loop inside the foreach loop to get the values of workfor_industry_id's.here same record is over loading with  different workfor_industry_id's.
can you tell me how to implement this.

A: UPDATED
This update adds a little more error checking and assumes that -1 is never a valid value for industry_id
short GetShort(string value) {
  short returnValue;
  value = (value ?? string.Empty).Replace("\"",null);
  return short.TryParse(value, out returnValue) ? returnValue : (short)-1;
}

foreach (var k in us){
  var id=Convert.ToInt16(k.id);
  var toRemove=from i in dbContext.industries
               where i.workfor_id == k.id
               select i;
  var toAdd = from x in (k.industry ?? string.Empty).Split(',')
              select new Industry {
                      workfor_id=id,
                      workfor_industry_id=GetShort(x)
                    };

  dbContext.industries.DeleteAllOnSubmit(toRemove);
  dbContext.industries.InsertAllOnSubmit(toAdd.Where(x=>x.workfor_industry_id != -1));

}
dbContext.SubmitChanges();


text:
Q: changing DNS setting doesn't seem to have any effect I am currently on Windows 10, and trying to use dnscrypt to proxy my DNS lookup from port 53 to some other port so it will bypass transparent DNS.
however, when I change my windows DNS setting to 127.0.0.1 (so dnscrypt will procy it somewhere else) the DNS seems to just ignore my setting and do some dnsquerying to my ISP DNS. Even when I deliberately put some IP that has no computer on it(192.168.1.230), the DNS just works on the ISP setting. I have turned off DHCP setting on my wireless router and modem. Can someone explain to me why this is happening? and how to make my computer recognize the setting i put in the DNS field?
Thanks

A: Turned out I have an IPV6 address as my DNS, and it perform the lookup for me. after disabling it, all went as expected


text:
Q: How to tell Sonar to use my LCOV file for Code Coverage for GOLANG GO Team,
I am generating go coverage and converting them to html to view in Jenkins. but I want to ship the LCOV file .dat to sonarqube. is there a way? like set a key value in sonar-project.properties
./bazel $BAZEL_STARTUP_OPTS coverage $BAZEL_OPTS $BAZEL_EXTRA_OPTS //src/services/discovery/... \
    --combined_report=lcov \
    --test_output=errors --test_verbose_timeout_warnings | tee /tmp/test_results.txt

for view on Jenkins I am converting LCOV _coverage_report.dat to html. But what I want to know if I can specify this in sonarqube.properties file either html or .dat lcov? to pick it up after scanning is done?
I see this for java but not for GO
./bazel run @lcov//:bin/genhtml -- -o \coverage/discovery --ignore-errors source --no-source --function-coverage --branch-coverage --no-sort bazel-out/_coverage/_coverage_report.dat || true


text:
Q: mongodb: query for values (not objects) in list I have a database with documents like
{_id: 5,
 fruit: 'apple',
 vitamins: ['B1', 'B12', 'A1']
}
{_id: 7,
 fruit: 'appricot',
 vitamins: ['B6', 'D12', 'A1']
}

Is there a way to query for all the records which have e.g. vitamin 'A1'?
I am looking for a mongo shell query and a pymongo equivalent.
I know that I can put a for loop to iterate over records and check whether the list contains an element or no, but I prefer a query if there is one.
As it is a list and not a list of objects so seems I can't use $elemMatch...
Thanks

A: You have a couple of options:
Option 1: If you want to match just one element, you could use the index in projection
db.collection.find({"vitamins":"A1"}, {"fruit":1, "vitamins.$":1})

Option 2: If you want to able to match multiple elements in the array, you can look at the aggregation framework:
db.collection.aggregate([{$unwind:"$vitamins"}, {$match:{"vitamins":"A1"}}])


text:
Q: A decimal variable in data of vuejs component We don't have the decimal type between the possible types to use in the data of a vuejs component (String, Number, Boolean, Array, Object, Date, Function, Symbol), so how to define a variable of this type ?

A: A decimal variable is of type Number, you could define it as number then use a validator to check if it's  decimal :
props:{
 price:{
   type:Number,
   validator(value){
     return value%1!==0
  }
 }
}


text:
Q: Sorting Floating Point Numbers In MIPS We are given a project in which we have to find the min, max, and median of entered floating point numbers in MIPS. I'm currently trying to sort the numbers in ascending order but am not having much luck. I'm stuck on an error that says address out of range. Here is my code, can anyone help?
.data
 arr: .word 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0
 end: .float 0.0
 low: .float 0

pro:  .asciiz "This Program will show the max, min,\nand median of the entered values.\nType 0.0 to end the program."
pro1: .asciiz "\nEnter a floating point value.\n"

.text
li $v0, 4
la $a0, pro
syscall

index:
li   $s0,  0
li   $t0,  0
lwc1 $f11, end

main:
li $v0, 4
la $a0, pro1
syscall
li $v0, 6
syscall
la     $s0, arr
sw     $v0, arr
add    $s0, $s0, 4
c.eq.s $f0, $f11

loop1:
swc1   $f0, arr($s0)
addi   $s0, $s0, 4
swc1   $f1, arr($s0)
c.lt.s $f0, $f1
bc1t   min
j      main

min:
swc1 $f0, low
j    main

li $v0, 2
syscall

exit:
lwc1 $f12, low
li   $v0,  2
syscall
li   $v0, 10
syscall

A: You are loading the address of arr into $s0, but then using $s0 as an offset from arr (arr($s0)).  If $s0 has the address of the data you want, just use ($s0).


text:
Q: what is the difference between Hadoop batch analytics and hadoop real time analytics I want to know the difference between Hadoop batch analytics and Hadoop real time analytics.
E.g Hadoop real time analytics can be done using Apache Spark while Hadoop batch analytics can be done using Map reduce programming.
Also if real time analytics is the more preferred one then what is batch analytics required for?
thanks

A: Batch means you process aaaaaaall data you have collected so far. Real-time means you process data as it enters the system. Neither one is "preferred".

A: Let me explain use cases for Batch processing & Real processing.
Batch processing:
In stock market application, you have requirement to provide below summary data on daily basis

*

*For each stock, total number of buy orders and sum of all buy orders

*For each stock, total number of sell order and sum of all sell orders

*For each stock, total number of successful orders & failed orders
etc.
Here need 24 hours of stock market data to generate these reports.
** Weather application: **
Save weather reports of all places in the world for all countries. For a given place like Newyork or Country like America, find hottest and coldest day since 1900. This query requires huge input data sets which requires processing on thousands of noudes.
You can use Hadoop Map Reduce job to provide above summary. You may have to process Peta bytes of data, which is stored in 4000+ servers in Hadoop cluster.
Real time analytics:
Another use case, you logged into social networking site like facebook or twitter. Your friends posted a message on your wall or tweeted in twitter. You have to get these notification in real time.
When you visit sites like Booking.com to book a hotel, You will get real time notifications like X users are currently viewing this hotel etc. These notifications are generated in real time.
In above use cases, system should process streams of data and generate real time notifications to users instead of waiting for one day data. Spark streaming provides excellent support to handle these type of scenarios.
Spark uses in - memory processing for faster query execution but it's not possible to always use in - memory for peta bytes of  data. Spark can process terabytes of data and Hadoop can process Peta bytes of data.

A: Hadoop batch analytics and real time analytics both are totally different, It depends on your use case what you want, example - you have a large volume of row dataset and you want to extract only few information from that dataset, information may be based on some calculation/trending etc. than this can be done with batch processing like finding a minimum temperature since last 50 years.
Whereas real time analytics, means you need the expected output ASAP like your friend tweeted on twitter and you get the tweets as soon as tweeted by your friend.

A: Batch data processing is an efficient way of processing high volumes of data is where a group of transactions is collected over a period of time. Data is collected, entered, processed and then the batch results are produced (Hadoop focused on batch data processing). Batch processing requires separate programs for input, process and output. An example is payroll and billing systems.
In contrast, real time data processing involves a continual input, process and output of data. Data must be processed in a small time period (or near real time). Radar systems, customer services and bank ATMs are examples.


text:
Q: VS Code setting to collapse activity bar on focus change Couldn't find an answer on here or elsewhere.
It's just a convenience feature that I would use. I prefer to use the screen space on split editors, and it would save me the effort of manually closing the activity bar.

A: I don't believe that is a feature that VS Code has implemented. Feel free to reach out to the developers on GitHub here: https://github.com/Microsoft/vscode
In the meantime, you can create a hotkey that will hide the activity bar.
{
  "key": "ctrl+shift+b",
  "command": "workbench.action.toggleActivityBarVisibility"
},


text:
Q: How to share my IPv6 Internet connection via Wi-Fi from my Windows PC to my Android devices? According to Using Wireless Hosted Network and Internet Connection Sharing, our Internet connection can be shared to other devices via Internet Connection Sharing and wireless Hosted Networks. However these techniques support IPv4 only seemingly, and the IPv4 addresses of some sites, namely Google, is blocked in my location, namely Mainland China. Thence I may only update my Android SDK on my PC but may not update my apps from Play Store.
Therefore it would be very nice to let it work for IPv6 as well as IPv4. Thank you very much!

PS:
It can be shared with the help of a router and OpenWrt, but it is broken
I'm not looking for a method to access Play Store on my phones, but a more specified and perhaps more interesting one to access it via my PC and the direct connection to Google's servers
Any answers are welcomed, but those without the help of any third-party software or those with the help only from Free Software or Open Source Software are preferred, just by me

A: Same problems as you, my solution is to use a router with openwrt installed. See https://github.com/tuna/ipv6.tsinghua.edu.cn/blob/master/openwrt.md for detailed configuration(Since you are in mainland China I think it is not a problem for you to read Simplified Chinese).


text:
Q: JUnit exception "Object is not an instance of declaring method" I have the next JUnit test, but when I execute it throws "Object is not an instance of declaring method".
What could it be?
@Test
    public void testCopiarByteArray() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException, UnsupportedEncodingException{
        String expected = "prueba";
        String mensaje = "prueba";

        DataReader datareader = new DataReader(null, null, 100, "=");

        Method copiarByteArray = datareader.getClass().getDeclaredMethod("copiarByteArray", byte[].class, int.class);
        copiarByteArray.setAccessible(true);

        byte[] copia = (byte[]) copiarByteArray.invoke(mensaje.getBytes(), mensaje.getBytes().length);

        String actual = new String(copia, "UTF-8");

        assertEquals("failure - encription not correctly encript", expected, actual);
    }

A: The first parameter of .invoke should be an instance of the object to invoke the method on.
So instead of:

    byte[] copia = (byte[]) copiarByteArray.invoke(mensaje.getBytes(), mensaje.getBytes().length);

You need to add datareader as first parameter:
    byte[] copia = (byte[]) copiarByteArray.invoke(datareader, mensaje.getBytes(), mensaje.getBytes().length);

A: Check the javadoc on reflection APIs.
You have to pass the object to call your method on as first parameter; and then followed by the "actual" method parameters.
Your code tries to execute a method on mensaje.getBytes(); which of course will not work.


text:
Q: Python - Download files from SharePoint site I have a requirement of downloading and uploading the files to Sharepoint sites. This has to be done using python.
My site will be as https://ourOrganizationName.sharepoint.com/Followed by Further links
Initially I thought I could do this using Request, BeautifulSoup etc., But I am not at all able to go to "Inspect Element" on the body of the site.
I have tried libraries such as Sharepoint,HttpNtlmAuth,office365 etc., but I am not successful. It always returning 403.
I tried google as much I can but again not successful. Even Youtube hasn't helped me.
Could anyone help me how to do that? Suggestion on Libraries with documentation link is really appreciated.
Thanks

A: Have you tried Office365-REST-Python-Client library, it supports SharePoint Online authentication and allows to download/upload a file as demonstrated below:
Download a file
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File

ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user(username, password)
ctx = ClientContext(url, ctx_auth)
response = File.open_binary(ctx, "/Shared Documents/User Guide.docx")
with open("./User Guide.docx", "wb") as local_file:
    local_file.write(response.content)

Upload a file
ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user(username, password)
ctx = ClientContext(url, ctx_auth)

path = "./User Guide.docx" #local path
with open(path, 'rb') as content_file:
   file_content = content_file.read()
target_url = "/Shared Documents/{0}".format(os.path.basename(path))  # target url of a file
File.save_binary(ctx, target_url, file_content) # upload a file

Usage
Install the latest version (from GitHub):
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git

Refer /examples/shrepoint/files/* for a more details

A: You can also try this solution to upload file. For me, first solution to upload doesn't work.
First step: pip3 install Office365-REST-Python-Client==2.3.11
import os
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

def print_upload_progress(offset):
    print("Uploaded '{0}' bytes from '{1}'...[{2}%]".format(offset, file_size, round(offset / file_size * 100, 2)))

# Load file to upload:
path = './' + filename # if file to upload is in the same directory
try:
    with open(path, 'rb') as content_file:
        file_content = content_file.read()
except Exception as e:
    print(e)

file_size = os.path.getsize(path)

site_url = "https://YOURDOMAIN.sharepoint.com"
user_credentials = UserCredential('user_login', 'user_password') # this user must login to space

ctx = ClientContext(site_url).with_credentials(user_credentials)

size_chunk = 1000000
target_url = "/sites/folder1/folder2/folder3/"
target_folder = ctx.web.get_folder_by_server_relative_url(target_url)

# Upload file to SharePoint:
try:
    uploaded_file = target_folder.files.create_upload_session(path, size_chunk, print_upload_progress).execute_query()
    print('File {0} has been uploaded successfully'.format(uploaded_file.serverRelativeUrl))
except Exception as e:
    print("Error while uploading to SharePoint:\n", e)

Based on: https://github.com/vgrem/Office365-REST-Python-Client/blob/e2b089e7a9cf9a288204ce152cd3565497f77215/examples/sharepoint/files/upload_large_file.py


text:
Q: How to get multiple random values from a specified area in a dictionary I am trying to create a workout simulator. If the user wants to target two areas, I want to be able to take 3 exercises from each section and then combine them into their own set. How would I take 3 random exercises? I have tried using random.sample with no luck
musclegroup_exercises = {
    'legs': {"squat", "calf raises", "hamstring curls", "deadlifts", "walking lunges"},
    'chest': {"barbell bench", "pushups", "cable fly", "dumbbell fly", "dumbbell incline bench press"},
    'arms': {"bicep curls", "kickbacks", "tricep pushdown", "reverse curls", "hammer curl"},
    'shoulders':{"shoulder press", "lateral raise", "barbell shrug", "bent over reverse flys", "push press"},
    'back':{"dumbbell rows", "back extension", "pull ups", "lat pull downs", "machine seated row"},
    'core':{"sit ups", "crunches", "russian twists", "bicycles", "planks"},
}

print('Here are the possible muscle groups you can target: Legs, Chest, Arms, Shoulders, Back, Core')
print('Here are the possible intensity levels: Easy, Medium, Hard')

num = int(input('Would you like to target one or two muscle groups? '))
if num == 1:
    musclegroup = input('What muscle group would you like to target?  ')
if num == 2:
    musclegroup1 = input('What is the first musclegroup you would like to target? ')
    musclegroup2 = input('What is the second musclegroup you would like to target? ')
intensity = input('What intensity level would you like? ')
if intensity == 'Easy':
    rate = '65%'
if intensity == 'Medium':
    rate = '80%'
if intensity == 'Hard':
    rate = '90%'
def createworkout1(y):
    for exercise in musclegroup_exercises[musclegroup.lower()]:
        print(exercise)
def createworkout2(j,k):
    import random
    half1 = random.sample(musclegroup_exercises[musclegroup1.lower()].items(),3)

A: You can use shuffle:
from itertools import chain
from random import shuffle

musclegroup_exercises = {
    'legs': {"squat", "calf raises", "hamstring curls", "deadlifts", "walking lunges"},
    'chest': {"barbell bench", "pushups", "cable fly", "dumbbell fly", "dumbbell incline bench press"},
    'arms': {"bicep curls", "kickbacks", "tricep pushdown", "reverse curls", "hammer curl"},
    'shoulders':{"shoulder press", "lateral raise", "barbell shrug", "bent over reverse flys", "push press"},
    'back':{"dumbbell rows", "back extension", "pull ups", "lat pull downs", "machine seated row"},
    'core':{"sit ups", "crunches", "russian twists", "bicycles", "planks"},
}

def shuffled_group(group):
    group = [i for i in group]
    shuffle(group)
    return group

selected_groups = ["back", "core"]  # This should come from your input, though, not be hardcoded.

targets = list(chain(*(shuffled_group(v)[:3] for k, v in musclegroup_exercises.items()) if k in selected_groups))

This could also work, though sample is being deprecated for sets so you have to do some more work:
list(chain(*(sample(list(v), 3) for k, v in musclegroup_exercises.items() if k in selected_groups)))

A: You can use random.sample(). Pass as parameters the list from which to get the elements and the length of the new list.
import random

musclegroup_exercises = {
    "legs":["squat", "calf raises", "hamstring curls", "deadlifts", "walking lunges"],
    "chest":["barbell bench", "pushups", "cable fly", "dumbbell fly", "dumbbell incline bench press"],
    "arms":["bicep curls", "kickbacks", "tricep pushdown", "reverse curls", "hammer curl"],
    "shoulders":["shoulder press", "lateral raise", "barbell shrug", "bent over reverse flys", "push press"],
    "back":["dumbbell rows", "back extension", "pull ups", "lat pull downs", "machine seated row"],
    "core":["sit ups", "crunches", "russian twists", "bicycles", "planks"],
}

random_exercises = {}
exercises_per_group = 3
for exercise_type in musclegroup_exercises:
    exercises = exercise = random.sample(musclegroup_exercises[exercise_type], exercises_per_group)
    random_exercises[exercise_type] = exercises

NOTE: Always import the packages you need at the beginning of the program, do not import them in the meantime inside an if or functions.
To take the exercises from only one area, you can simply change the key you use to access to musclegroup_exercises:
import random

musclegroup_exercises = {
    "legs":["squat", "calf raises", "hamstring curls", "deadlifts", "walking lunges"],
    "chest":["barbell bench", "pushups", "cable fly", "dumbbell fly", "dumbbell incline bench press"],
    "arms":["bicep curls", "kickbacks", "tricep pushdown", "reverse curls", "hammer curl"],
    "shoulders":["shoulder press", "lateral raise", "barbell shrug", "bent over reverse flys", "push press"],
    "back":["dumbbell rows", "back extension", "pull ups", "lat pull downs", "machine seated row"],
    "core":["sit ups", "crunches", "russian twists", "bicycles", "planks"],
}

exercises_per_group = 3
exercise_type = "legs"
exercises = random.sample(musclegroup_exercises[exercise_type], exercises_per_group)

A: Maybe use random.choices since sample is deprecated:
exercices = [j for z in [random.choices(tuple(musclegroup_exercises[i]),k=3) for i in (musclegroup1, musclegroup2)] for j in z]

Or in more understandable form:
exercices = []
for i in (musclegroup1, musclegroup2):
    exercices.extend(random.choices(tuple(musclegroup_exercises[i]), k=3))


text:
Q: NSCalendar dateFromComponents returns strange date The NSCalendar dateFromComponents function returns unexpected date.
Here is the use case :
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:timeZone];

Where timezone is: Local Time Zone (Europe/Paris (GMT+1) offset 3600)
NSDateComponents *finalComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday fromDate:now];
[finalComponents setWeekday:weekDay];

At this point, I have the following value for finalComponents :

    Calendar Year: 2018
    Hour: 23
    Minute: 59
    Week of Year: 1
    Weekday: 2
The [calendar dateFromComponents:finalComponents] returns 2018-12-31 22:59:00 +0000 and I expect 2017-12-31 22:59:00 +0000
Any help is welcome

A: May this help you..!
Note: I used value for weekday as 1 (for IST it gives me correct date). You can update it according to your timezone.
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:NSTimeZone.localTimeZone];

NSDate *currentDate = [NSDate date];

NSDateComponents *finalComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday fromDate:currentDate];
[finalComponents setWeekday: 1];
[finalComponents setYearForWeekOfYear:finalComponents.year];  // Update year dynamically here

NSLog(@"Current Date: %@",currentDate);
NSLog(@"Print Date: %@",[calendar dateFromComponents:finalComponents]);

Current Date: Fri Jan  5 20:00:53 2018
Print Date: Sun Dec 31 20:00:00 2017

Ask me, if you need any further help..!

A: The components that you extract seem to be ambiguous, resulting in a weird date. If you include the NSCalendarUnitYearForWeekOfYear in your selected components, you should get the correct year:
NSDateComponents *finalComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitYearForWeekOfYear fromDate:now];

For me adding the extra component makes it so that I get the correct year.


text:
Q: MySQL - count different fields on different conditions in one joined table There is a hypothetical table called Table1, with the columns:

*

*id

*condition 1

*condition 2

*joinable_key

There is another one, Main_Table, whose ID corresponds with the joinable_key in the first one.
I would like to join them in such a fashion that I can count the rows of Table1 according to both condition 1 and condition 2 separately - that is, I would like to be able to perform "count(Table1.condition1) as first_condition, count(Table1.condtion2) as second_condition" on the select query.
The query would presumably look something like this:
SELECT  Main_Table.some_column, COUNT(Table1.condition1) AS first_condition, COUNT(Table1.condtion2) AS second_condition
FROM  Main_Table
LEFT JOIN Table1 AS T1 on (T1.joinable_key = Main_Table.id AND T1.condition1 = 'something')
LEFT JOIN Table1 AS T2 on (T2.joinable_key = Main_Table.id AND T2.condition2 = 'something else')
GROUP BY (Main_Table.id)

When this executes, however, both count results are equal, and actually multiply with each other.
It is imperative that all results be included in the final output - including those that do not have any entries from Table1 - that is, if there is no row in Table1 with a joinable_key equal to Main_Table.id, it too needs to be included.
Before anyone suggest actually doing two separate queries and handling it through PHP - yes, I know why and how it can be done, but my goal is to find out whether or not this multi-count can be done all in one query.
Thank you

A: SELECT some_column,
       (SELECT COUNT(1)
          FROM Table1
         WHERE mt.id = joinable_key
           AND condition1 = 'something'
       ) AS first_condition,
       (SELECT COUNT(1)
          FROM Table1
         WHERE mt.id = joinable_key
           AND condition2 = 'something else'
       ) AS second_condition
  FROM MainTable mt

A: SELECT  Main_Table.some_column,
        SUM(t1.condition1 = 'something') AS first_condition,
        SUM(t1.condition2 = 'something_else') AS second_condition
FROM    Main_Table
LEFT JOIN
        Table1 AS t1
ON      t1.joinable_key = Main_Table.id
        AND
        (
        t1.condition1 = 'something'
        OR
        t1.condition2 = 'something else'
        )
GROUP BY
        Main_Table.id

If both condition1 and condition2 are selective, this syntax may be more efficient:
SELECT  Main_Table.some_column,
        (
        SELECT  COUNT(*)
        FROM    table1 t1
        WHERE   t1.joinable_key = main_table.id
                AND t1.condition1 = 'something'
        ),
        (
        SELECT  COUNT(*)
        FROM    table1 t1
        WHERE   t1.joinable_key = main_table.id
                AND t1.condition2 = 'something_else'
        )
FROM    Main_Table

You should create the following indexes:
table1 (id, condition1)
table1 (id, condition2)

for this to work fast.


text:
Q: Chaining $.Deferred I'm hoping to understand why I'm getting different behavior when attemping to chain a deferred object directly than I do when attempting to chain by saving the object in a variable and invoking one or more deferred methods on that variable.
When saving the object in a variable, the value sent in to each function is the same (in the case of the code snippet below, 5) - i.e. the values don't filter in this case.  When chained directly, the values filter...  so I'm unclear on how get filtering to occur when setting up a Deferred.pipe() in several different statements.  And by my reading of the jquery docs, it should be possible:

The Deferred object is chainable, similar to the way a jQuery object is chainable, but it has its own methods. After creating a Deferred object, you can use any of the methods below by either chaining directly from the object creation or saving the object in a variable and invoking one or more methods on that variable.

What am I doing wrong?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
// This works as expected - alert(20)

var defer = new $.Deferred();
defer.pipe(myFunction).pipe(myFunction).pipe(myAlert);
defer.resolve(5);

// This does not work as expected - alert(5)
var defer2 = new $.Deferred();
defer2.pipe(myFunction);
defer2.pipe(myFunction);
defer2.pipe(myAlert);
defer2.resolve(5);

});

var myFunction = function (value) {
return value * 2;
}

var myAlert = function (value) {
alert('The value is ' + value);
}
</script>

A: The $.Deferred object is indeed chainable, but in your second scenario, you are not chaining anything; you are just assigning multiple pipes to the $.Deferred object to be executed independently, when the $.Deferred is either resolved or rejected. In other words, you are ignoring the returned Promise object which contains the filtered/modified value to be passed to the next .pipe() in the chain.
From the docs:

The deferred.pipe() method returns a new promise that filters the
  status and values of a deferred through a function.

To achieve what you want in your second example, pipe the resulting Promise instead of the original $.Deferred object:
var defer2 = new $.Deferred();
var promise = defer2.pipe(myFunction);
promise = promise.pipe(myFunction); // pipe and update promise
promise.pipe(myAlert);
defer2.resolve(5);

DEMO.

A: Joao, I had the same case - unknown number of pipe to be called.
here is how do that - Asynchronous for cycle in JavaScript


text:
Q: useState([]) returns undefined instead of empty array using context I am quite new to react and i´m tryng to make a wishlist using context. I have done something similar for my cart so I coppied all the code from there, but I cannot figure out why this is not working. When I call the array "wishlist" it returns undefined instead of an empty array despite having used useState([]) in the wishlist Context. (I DID THE SAME WITH THE CART AND WORKS PERFECTLY!) Here I leave the code:
wishlistContext.js
import { createContext, useContext, useState } from "react";

const WishlistContext = createContext([]);

export const useWishlistContext = () => useContext(WishlistContext);

export const WishlistProvider = ({ children }) => {
  const [wishlist, setWishlist] = useState([]); // HERE I SET "wishlist" AS AN EMPTY ARRAY

  const value = {
    wishlist,
  };

  return (
    <WishlistContext.Provider value={value} displayName="wishlistContext">
      {children}
    </WishlistContext.Provider>
  );
};

Wishlist.jsx
import { useEffect, useState } from "react";
import { useWishlistContext } from "../context/wishlistContext";

export const Wishlist = () => {
  const { wishlist } = useWishlistContext();
  console.log(wishlist); // THIS IS WHAT RETURNS UNDEFINED

  return (

      Something

  );
};

NOW I LEAVE THE SAME EXAMPLE WITH CART THAT WORKS FLAWLESSLY
cartContext.js
import { createContext, useContext, useState } from "react";

const CartContext = createContext([]);

export const useCartContext = () => useContext(CartContext);

export const CartProvider = ({ children }) => {
  const [cart, setCart] = useState([]); // HERE I SET "cart" AS AN EMPTY ARRAY

  const removeProduct = (id) => {
    const newCart = cart.filter((product) => product.id !== id);
    setCart(newCart);
  };

  const addProduct = (item, qty) => {
    const element = cart.find((product) => product.id === item.id);

    if (!element) return setCart([...cart, { ...item, qty }]);

    const newCart = cart.map((product) => {
      if (product.id === item.id) {
        return { ...product, qty: product.qty + qty };
      }
      return product;
    });
    setCart(newCart);
  };

  const getTotal = () =>
    cart.reduce((acc, product) => acc + product.valor * product.qty, 0);

  const getCartQty = () => cart.reduce((acc, product) => acc + product.qty, 0);

  const emptyCart = () => setCart([]);

  const value = {
    cart,
    addProduct,
    removeProduct,
    getCartQty,
    getTotal,
    emptyCart,
  };

  return (
    <CartContext.Provider value={value} displayName="cartContext">
      {children}
    </CartContext.Provider>
  );
};

Cart.jsx
import { BsFillCartFill } from "react-icons/bs";
import { useEffect, useState } from "react";
import { addOrder } from "../api/orders";
import { updateManyProducts } from "../api/products";
import { useCartContext } from "../context/cartContext";
import Swal from "sweetalert2";

export const Cart = () => {
  const { getTotal, cart, emptyCart } = useCartContext();

  console.log(cart);

  if (cart.length <= 0)
    return (

          <BsFillCartFill />
 Su carrito esta vacío

    );

  const createOrder = async (e) => {
    e.preventDefault();
    const items = cart.map(({ id, nombre, qty, valor }) => ({
      id,
      nombre,
      qty,
      valor,
    }));

    let itemsAlert = "";

    for (let i = 0; i < items.length; i++) {
      itemsAlert +=
        "Item: " +
        items[i].nombre +
        "
Cantidad: " +
        items[i].qty +
        " Valor Unidad: $" +
        items[i].valor +
        "

";
      console.log(itemsAlert);
    }

    const order = {
      buyer: { name, phone, email },
      items,
      fecha: newdate,
      estado: { orderState },
      total: getTotal(),
    };
    const { buyer, fecha, total } = order;

    const id = await addOrder(order);

    await updateManyProducts(items);
    emptyCart();

    Swal.fire({
      title: "Pedido Realizado",
      html: `El id de su compra es <b>"${id}"</b> <br> Fecha: ${fecha}<br><br> <b>Detalle de compra:</b><br> <br> <b>Comprador:</b> ${buyer.name} <br><br> ${itemsAlert}<br> <b>Total: $${total}</b>`,
      icon: "success",
      confirmButtonText: "OK",
    });
  };

  return (

        <BsFillCartFill /> Carrito <BsFillCartFill />{" "}

      {cart.map((product) => (

            Producto :{" "}

              {product.nombre}

            Valor unitario :{" "}

              ${product.valor}

            Cantidad :{" "}

              {product.qty}

      ))}

        Total :{" "}

          ${getTotal()}

      <form style={{ display: "grid", gap: 10 }} className="mb-5">
        Nombre
        <input
          style={{ border: "1px solid black", height: 40 }}
          onChange={(e) => setName(e.target.value)}
        />
        Telefono
        <input
          type={"phone"}
          style={{ border: "1px solid black", height: 40 }}
          onBlur={(e) => validateInput(e.target.value, "phone")}
        />
        Email
        <input
          type={"email"}
          style={{ border: "1px solid black", marginBottom: 15, height: 40 }}
          onBlur={(e) => validateInput(e.target.value, "email")}
        />
        Confirmar Email
        <input
          style={{ border: "1px solid black", marginBottom: 15, height: 40 }}
          onBlur={(e) => checkEmail(e.target.value)}
        />
        <input type="submit" value="Enviar" onClick={createOrder} />
      </form>

        {mailError}

        {phoneError}

  );
};

I dont know if this has to do with some async property that i´m missing. Truth is I literally replicated the  cart code, and this outcome really surprised me. Thank you all beforehand, this is giving me a big headache.

A: The JSX component must be wrapped by the context provider. Not sure if that is the issue without seeing the parent of your Wishlist component. Here is how I recreated the project and resolved issue:
Create React App 5.0.1

*

*npx create-react-app test

*cd test

*npm start

*Copy wishlistContext.js to src/context/

*Copy wishlist.jsx to src/

*To reproduce the issue, modify App.js to the following:

    import './App.css';
    import { Wishlist } from './wishList';

    function App() {
      return (
        <Wishlist />
      );
    }

    export default App;

*See undefined in the console

*Wrap the JSX element with the context provider

    import './App.css';
    import { Wishlist } from './wishList';
    import { WishlistProvider } from './context/wishlistContext';

    function App() {
      return (
            <WishlistProvider>
              <Wishlist />
            </WishlistProvider>
      );
    }

    export default App;

*See [] in the console


text:
Q: Is ARIMA better in comparision with Neural Networks? After working on Backpropagation Neural Network and ARIMA Time Series Model, I asked myself which one is better, but can't figure out the answer. They both use different approaches on the same problem (future prediction). Please can someone help me stating the obvious.
Backpropagation(C++):
 typedef struct {                     /* A LAYER OF A NET:                     */
    INT           Units;         /* - number of units in this layer       */
    REAL*         Output;        /* - output of ith unit                  */
    REAL*         Error;         /* - error term of ith unit              */
    REAL**        Weight;        /* - connection weights to ith unit      */
    REAL**        WeightSave;    /* - saved weights for stopped training  */
    REAL**        dWeight;       /* - last weight deltas for momentum     */
} LAYER;

typedef struct {                     /* A NET:                                */
    LAYER**       Layer;         /* - layers of this net                  */
    LAYER*        InputLayer;    /* - input layer                         */
    LAYER*        OutputLayer;   /* - output layer                        */
    REAL          Alpha;         /* - momentum factor                     */
    REAL          Eta;           /* - learning rate                       */
    REAL          Gain;          /* - gain of sigmoid function            */
    REAL          Error;         /* - total net error                     */
} NET;

ARIMA(R):
arima(stockadj,order=c(best.model[1],best.model[2],best.model[3]),xreg=1:n)
stockfor<-predict(stockari,h=100,newxreg=(n+1):(n+100))
ts.plot(stockadj,stockfor$pred,ylab="Original+Predicted Values",main="Forecast")

A: It looks like you are using both of these models for time-series forecasts.  I would cross-validate both models and compare their out-of-sample error.

A: NN ignore outliers.  If you ignore outliers, then you are in big trouble.
Your ARIMA model is also ignoring outliers so then you are also in big trouble.
As for cross-validating, that is for those that are fitting models to data instead of actually modeling.  Only the 849 page text book "Principles of Forecasting" agrees with me on this statement, BUT if you have taken care of all the things you need to then you can be so dumb.   See the reference here.
4.6 Obtain the most recent data
See more on outliers here.


text:
Q: SAP UI5 Transition Parameters I am using SAP UI5 for a while and thank you all your answers about ui5, it helped me much.
I want to learn what the transition parameters is, i have two views and app. Using to function for the navigation between them. But i want slow transition, it happening very fast.
In the to function there is oTransitionParameters parameter but i don't know how to set it.
Here is the code i'm using to show second view but it is not slowed the transition :

app.to(izinView,"flip",null,"duration:'slow'")

Hope somebody know it.

A: The answer to your question is in the last sentence of the comment for the sTransitionName parameter:
https://openui5.hana.ondemand.com/#docs/api/symbols/sap.m.NavContainer.html#to

None of the standard transitions is currently making use of any given
  transition parameters.

You can also see in the source code for sap.m.NavContainer it is not being used:
/*, oTransitionParameters is unused */
However, that being said you could monkey patch the the sap.m.NavContainer.transitions object with your own custom animation.
sap.m.NavContainer.transitions["slowFlip"] = {
    // definition here
};

To look at the current implementation of "flip" see here:
https://github.com/SAP/openui5/blob/master/src/sap.m/src/sap/m/NavContainer.js#LC1202