text:
Q: Newton-Côtes closed formula for $\int_{0}^{2n} x^{2n+1}\cos(2{\pi}x) dx$ Given $n \in \mathbb{N}$, I want to determine the value obtained by approximating the integral
$$ \int_{0}^{2n} x^{2n+1}\cos(2{\pi}x) dx $$
using the closed Newton-Côtes formula of $2n + 1$ points.
In other words, I want to find a closed formula for:
$$\int_{0}^{2n} P_{2n}(x) dx$$
where $P_{2n}(x)$ is the Lagrange interpolating polynomial of $f(x) = x^{2n+1}\cos(2{\pi}x)$ through the $2n + 1$ points $\{0, 1, ..., 2n\}$, which has degree less than or equal to $2n$.
For $n = 1, ..., 6$, the values of the integrals are:
$$4, \frac{2048}{3}, 209952, \frac{536870912}{5}, \frac{250000000000}{3}$$
but I don't see a pattern.

Note: I initially considered the problem for $f(x) = x^{2n}\cos(2{\pi}x)$. Since in this case, there are $2n + 1$ points and $f(k) = k^{2n}$ for $k = 1, ..., 2n$, the Lagrange interpolating polynomial of $f(x)$ (which is unique) must be $x^{2n}$, as it has degree less than or equal to $2n$. Then the value of the integral is trivial to compute ($\frac{(2n)^{2n+1}}{2n+1}$).

A: I don't know if this helps, but
$$x^{2n+1}-\prod_{k=0}^{2n}(x-k)=x^{2n+1}-(x)_{2n+1}$$
Is a polynomial of degree $2n$ that goes through all the $2n+1$ points, where $(x)_{2n+1}$ is the falling factorial. The first few integrals:
       0  0.000000000000000000000000000000000E+0000
       1   4.00000000000000000000000000000000
       2   682.666666666666666666666666666667
       3   209952.000000000000000000000000000
       4   107374182.400000000000000000000000
       5   83333333333.3333333333333333333333
       6   91708461753490.2857142857142857145
       7   136122083613085696.000000000000000
       8   262353693492758067427.555555555558
       9   637411810819803908721868.800000012
      10   1906501818181818181818181818.18188

EDIT: Are you trying to form some sort of inductive hypothesis like
$$A_n=\frac{2^{2n-1}(n-1)^{2n}}n$$
EDIT: The situation is so much simpler than this. If we make the substitutions $y=2n-x$ and $j=2n-k$ then
$$\begin{align}\int_0^{2n}\prod_{k=0}^{2n}(x-k)dx&=\int_{2n}^0\prod_{k=0}^{2n}(2n-y-k)(-dy)\\
&=\int_0^{2n}\prod_{k=0}^{2n}(2n-y-k)(dy)\\
&=\int_0^{2n}\prod_{j=0}^{2n}(2n-y-2n+j)(dy)\\
&=(-1)^{2n+1}\int_0^{2n}\prod_{j=0}^{2n}(y-j)(dy)\\
&=-\int_0^{2n}\prod_{k=0}^{2n}(x-k)dx\\
&=0\end{align}$$
Because only zero is its own additive inverse. The $2n+1$-point Newton-Cotes formula also says this integral is $0$ because the integrand is zero at all the sample points. Thus the $2n+1$-point Newton-Cotes formula is exact for all polynomials of degree $2n+1$ because it's exact for all polynomials of degree $2n$ by construction and the difference between and degree $2n+1$ polynomial and some degree $2n$ polynomial is a multiple of $\prod_{k=0}^{2n}(x-k)$, which the $2n+1$-point Newton-Cotes formula evaluates exactly. That's an old theorem.
Thus if $f(x_k)=x_k^{2n+1}$ then a polynomial of degree $2n+1$ that goes through all $2n+1$ points is $f(x)=x^{2n+1}$ and because the $2n+1$-point  Newton-Cotes formula integrates this exactly, it spits out
$$\int_0^{2n}x^{2n+1}dx=\frac{(2n)^{2n+2}}{2n+2}=A_{n+1}$$
which is the same as our numerical results.


text:
Q: Java FileOutputStream Created file Not unlocking Currently am facing a problem with  FileOutputStream in my code used  FileOutputStream for creating file in my disk .Once file created there is no way for opening , deleting or moving file from its location ,getting error message already locked by other user  When stopped web server it working properly .how can i solve this issue.
private void writeToFile(InputStream uploadedInputStream,
            String uploadedFileLocation) {

            try {
                OutputStream out = new FileOutputStream(new File(
                        uploadedFileLocation));
                int read = 0;
                byte[] bytes = new byte[1024];

                out = new FileOutputStream(new File(uploadedFileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();

            } catch (IOException e) {

                e.printStackTrace();
            }

        }

A: You are creating two instances of FileOutputStream and assigning both to out, but only closing one.
Remove the second out = new FileOutputStream(new File(uploadedFileLocation));.
Also, you should consider using a try-with-resources block
private void writeToFile(InputStream uploadedInputStream,
    String uploadedFileLocation) {

    try (OutputStream out = new FileOutputStream(new File(uploadedFileLocation))) {
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

}

or finally block to ensure that the streams are closed
private void writeToFile(InputStream uploadedInputStream,
    String uploadedFileLocation) {

    OutputStream out = null;
    try {
        out = new FileOutputStream(new File(uploadedFileLocation))
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

    } catch (IOException e) {

        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException exp) {
            }
        }
    }

}

See The try-with-resources Statement for more details

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deserialize json.net property as uppercase Given the following POCO:
public class AggV2
{
    [JsonProperty("T")]
    public string Ticker { get; set; }
    [JsonProperty("v")]
    public decimal Volume { get; set; }
    [JsonProperty("o")]
    public decimal Open { get; set; }
    [JsonProperty("c")]
    public decimal Close { get; set; }
    [JsonProperty("h")]
    public decimal High { get; set; }
    [JsonProperty("l")]
    public decimal Low { get; set; }
    [JsonProperty("t")]
    [JsonConverter(typeof(UnixMillisecondsConverter))]
    public DateTimeOffset Timestamp { get; set; }
}

I have seen the 3rd party data provider is sending mixed case for the same ticker, i.e. MsFT and MSFT - the is causing nightmares with MSSQL key constraints!
First step is to filter to a common case, so that the Ticker property value would always be MSFT for the above example.
How can I ensure Ticker is always serialized as uppercase please?

A: I wrote the following converter, would this be the best practice way or have i reinvented the wheel?
public class AggV2
{
    [JsonProperty("T")]
    [JsonConverter(typeof(UppercaseStringConverter))]
    public string Ticker { get; set; }
    [JsonProperty("v")]
    public decimal Volume { get; set; }
    [JsonProperty("o")]
    public decimal Open { get; set; }
    [JsonProperty("c")]
    public decimal Close { get; set; }
    [JsonProperty("h")]
    public decimal High { get; set; }
    [JsonProperty("l")]
    public decimal Low { get; set; }
    [JsonProperty("t")]
    [JsonConverter(typeof(UnixMillisecondsConverter))]
    public DateTimeOffset Timestamp { get; set; }
    [JsonProperty("n")]
    public int Samples { get; set; }
}

public class UppercaseStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is string str)
            writer.WriteValue(str.ToUpper());
        else
            throw new JsonSerializationException("Expected date object value.");
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        bool nullable = Nullable.GetUnderlyingType(objectType) != null;

        if (reader.TokenType == JsonToken.Null)
        {
            if (!nullable)
            {
                throw new JsonSerializationException($"Cannot convert null value to {objectType}.");
            }
            return null;
        }

        if (reader.TokenType == JsonToken.String)
            return ((string)reader.Value).ToUpper();
        else
            throw new JsonSerializationException($"Unexpected token parsing date. Expected String, got {reader.TokenType}.");
    }
}


text:
Q: 396: error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict I am trying to build a face recognition program using Python 2.7.13 and OpenCV 3.3.0.
However, I receive this error when it tries to detect my face:
File "C:\GitProject\face_recognition\detector.py", line 20, in
 <module> Id = recognizer.predict(gray[y:y+h,x:x+w])
error: C:\projects\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:396:
error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict

Here is my code:
import cv2 ,os
import numpy as np
from PIL import Image
import pickle

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/training_data.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

cam = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
    ret, im =cam.read()
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(gray, 1.2,5)
    for(x,y,w,h) in faces:
        cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
        Id = recognizer.predict(gray[y:y+h,x:x+w])
        if(conf<50):
            if(Id==1):
                Id="Anirban"
            elif(Id==2):
                Id="Sam"
        else:
            Id="Unknown"
        cv2.PutText(cv2.fromarray(im),str(Id), (x,y+h),font, 255)
    cv2.imshow('im',im)
    if cv2.waitKey(10) & 0xFF==ord('q'):
        break

cam.release()
cv2.destroyAllWindows()

A: Open your trainer, change the recognizer.save to recognizer.write. Don't forget to run the trainer again. It works for me.

A: The issue is caused when loading the pre-trained .yml file. Even though you do not receive an error when loading the file, the recognizer does not properly register the the .yml file.
By changing how the training_data.yml file is generated is the key. In your training code change the
        recognizer.save() to recognizer.write().
I had this issue when trying to load the training data on my Raspberry Pi.
If any clarity is needed make sure to ask.
This method caused model.yml to be incorrectly loaded in my facialRecognition class
Ids , faces = getImageList(path)
recognizer.train(faces,np.array(Ids))
recognizer.save('model.yml')
Changing the following line solved the issue.
recognizer.write('model.yml')
Both methods generated the model.yml file as expected but
recognizer.read('model.yml')
only worked with write().

A: Welcome to Stack Overflow. The error you received is telling you that you need to call the train method in the parent class of LBPHFaceRecognizer before you ask it to do any recognition. Refer to the documentation here.

A: After all, if the error still there, try to manually specify the full path of recognizer.write().
Example:
recognizer.write('/home/pi/Desktop/.../trainer/trainer.yml')

This worked for me.


text:
Q: ASP.NET MVC : how to hold temporary data typed by user in create view of one controller while adding data in create view in other controller I have one model 1 with Name, Surname and IDAdress (this is foreign key to other model where I have Name of street, number...).
I create a controller and views (index, create, edit...) for for model 1 and model 2 (address). Then I go in create view for model 1 where user types Name, Surname and then it has link or button on create view for model 2.
My problem is when I type in data for Adresse and redirect after post in model 2 to view create of model 1 I lose Name and Surname that user already typed in.
I hope you understand what I want to ask. Do you have any idea how to solve this?
Maybe this picture can help
Maybe this will help to understand. As you see I am leaving Create View 1 temporary so I can add info about address and after create in view create 2 I am going back to create view number 1. But if user typed in Name and Surname before adding address it has to type in that info again because I don't know how to hold that data temporary while I am adding address in view number 2.
Is there maybe a way where Create view 2 opens over create view 1 so it does not even close or I need to store type in data in some new table in database and then call those info when I am returning to view number 1...

A: If I understood you right you can merge your models in one big view model. Also you need to add hidden inputs to view for fields you want to pass.


text:
Q: Full-Text keywords unicode I have a very large database with billions of words. I need to search inside these words, and the fastest way I know is using iFTS coming with SQL SERVER 2008.
The data is in Turkish. I mean the language of the data is Turkish. And SQL SERVER 2008 handles Full-Text searches with no problem, even in Turkish.
But the problem happens when I try to list the Full-Text words as described here: http://technet.microsoft.com/en-us/library/cc280900.aspx
The word columns returned from sys.dm_fts_index_keywords are keyword and display_term. But these columns are not in correct character set. For example there are both ı and i in Turkish charset. Similarly o and ö, g and ğ. But the words return are ascii encoded. Like kör is return as kor and için is returned as icin.
But when I do a CONTAINS search, SQL Server matches the search words correctly returns true results. I mean searches with kör and kor return different results, which is the true behavior.
So I need to get the words as they are stored in SQL, not their ascii representations.
I hope I could explain my problem.

A: It seems this has been fixed in SQL 2012... In SQL 2012 the columns, keyword and display term returned by query sys.dm_fts_index_keywords; are now returning correct Turkish words...


text:
Q: segmentation fault on malloc initializating 2d-array My program fails because of a segmentation fault. Using gdb i could see that the trouble was when i was initializing a 2d-array in my function.
My compiler flags were -Wall -Wpedantic -Wextra -Wconversion -std=gnu11
This is the function i'm using. The error raises on line 4. I don't understand why it breaks there, im fairly a beginner to C.
1 char ** get_categories_names(char * file_route, unsigned int maximum_categories) {
2     unsigned int category_counter = 0;
3
4     char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
5     char * category = "";
6     FILE * categories_config;
7     categories_config = fopen(file_route, "r");
8
9     if (categories_config == NULL)
10    {
11            perror("Error while opening the file.\n");
12            exit(EXIT_FAILURE);
13    }
14
15    while (fgets(category, 255, categories_config) && category_counter < maximum_categories) {
16            printf("%d", category_counter);
17            categories_list[category_counter] = malloc(100 * sizeof(char));
18            category[strcspn(category, "\n")] = 0;
19            categories_list[category_counter] = category;
20            category_counter++;
21    }
22    fclose(categories_config);
23    return categories_list;

This is the gdb result:
(gdb) step
11              char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) step
__GI___libc_malloc (bytes=40) at malloc.c:3028
3028    malloc.c: No existe el archivo o el directorio.

And this is the text file i was reading to:
horror
mystery
FPS
memes
comedy

A: There are a number of issues. I'll try to fix then in your code adding comments about the reasons. Please note that I didn't compile so there might be some typos
char ** get_categories_names(char * file_route, unsigned int maximum_categories) {
     unsigned int category_counter = 0;

     // don't cast the result of malloc
     char ** categories_list = malloc(maximum_categories * sizeof(char *));
     // declare category as array to provide memory for fgets()
     char category[255];
     FILE * categories_config;
     categories_config = fopen(file_route, "r");

     if (categories_config == NULL)
     {
           perror("Error while opening the file.\n");
           exit(EXIT_FAILURE);
     }

     // use sizeof array so you don't have to repeat array size
     while (fgets(category, sizeof category, categories_config) && category_counter < maximum_categories) {
              printf("%d", category_counter);

              category[strcspn(category, "\n")] = 0;
              // alloc the right size -- sizeof( char ) is always 1 and can be omitted
              categories_list[category_counter] = malloc(strlen(category)+1);
              // copy strings w/ strcpy()
              strcpy(categories_list[category_counter], category);
              // the two commands above could be replaced by
              //categories_list[category_counter] = strdup(category);
              category_counter++;
      }
      fclose(categories_config);
      return categories_list;

Besides, malloc() could return NULL. That should be checked too

A: regarding;
(gdb) step
11              char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) step
__GI___libc_malloc (bytes=40) at malloc.c:3028
3028    malloc.c: No existe el archivo o el directorio.

This is NOT saying that a seg fault event occurred.
Rather, it is saying that you do not have the source code for 'malloc.c' visible to gdb
To avoid this kind of problem, suggest:
(gdb) step
11              char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) next

which will exec the call to malloc(), but not stop until the next statement in your code


text:
Q: Spring MVC: how to require POST parameters in the request body and ignore query string parameters? I have a simple controller that provides an authentication web service.  It accepts username and password as POST parameters and returns a JSON result.  Because password is being submitted, I don't want to encourage anyone to submit it on the query string.  I want to enforce that it only be accepted in the request body.  This will ensure ssl encryption of the posted value.  How do I accomplish that in Sping MVC?
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<String> handleAuthenticateGet(
            @RequestParam(value = PRAConstants.USERNAME) String username,
            @RequestParam(value = PRAConstants.PASSWORD) String password)
    {
        boolean authSuccess = LDAPUtil.authenticateUser(username, password);
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<String>("{\"result\":" + authSuccess + "}", responseHeaders, HttpStatus.OK);
    }
}

A: Per Lee Meador, I've added this:
boolean authSuccess = false;
// if password is passed on the query string, then always return false. otherwise, go ahead and check with ldap
if ( !StringUtils.contains(request.getQueryString(), PRAConstants.PASSWORD) )
{
    authSuccess = LDAPUtil.authenticateUser(username, password);
}

that works for me...


text:
Q: Running a simple rack app with SSL on localhost? I have a simple rack app that is serving up a static file. I need to use SSL locally for development purposes. Any way to do with with rack?

A: I'd just grab the tunnels gem, then fire up an SSL proxy using that:
sudo tunnels 443 9292


text:
Q: Forcing a build when properties change in MSBuild I have set up my build so that I can pass in a number as a build property:
msbuild MyProject.sln /t:Build /p:Configuration="Debug" /p:SomeNumber="123"

The MSBuild project generates a file and adds it via:
<Compile Include="$(SomeFileContainingSomeNumber)" />

This file is only generated if SomeNumber is specified.
When I change or omit the number and build a second time, the MSBuild projects do not get rebuilt with the new value. I believe this is because none of the project files have changed.
How can I set up my project so that changing the SomeNumber property triggers a rebuild?

A: I'm using MSBuild 3.5. It seems that putting a Condition on a BeforeBuild Target interferes with its execution. When I moved the Condition from the Target to the individual actions within the target, I was able to get the desired behavior.
Using the following I was able to get MSBuild to compile properly every time, whether or not the SomeNumber property changed. The project may be rebuilding SomeFile.cs every time, whether or not its contents has changed, because its timestamp is changing.
<PropertyGroup>
    <SomeFile>SomeFile.cs</SomeFile>
</PropertyGroup>
<Target Name="BeforeClean">
    <Delete Files="$(SomeFile)" />
</Target>
<Target Name="BeforeBuild">
    <WriteLinesToFile Condition="'$(SomeNumber)' == ''" File="$(SomeFile)" Lines="//" Overwrite="true" />
    <WriteLinesToFile Condition="'$(SomeNumber)' != ''" File="$(SomeFile)" Lines="$(SomeNumber)" Overwrite="true" />
</Target>
<ItemGroup>
    <Compile Include="$(SomeFile)" />
</ItemGroup>

The Lines="//" is required because WriteLinesToFile will delete the file if you put nothing or whitespace there.


text:
Q: Spy on serial port communication I have the following setup. I have a hardware device connected to COM1 and COM2. In order to test it I have software simulators connected to COM1 and COM2 (RS-232 ports). These simulators receive and transmit data via my hardware device.
I need to calculate the throughput time of my hardware device. For example, if the simulator on COM1 sends a message at time A then I need to establish when it arrives at COM2, giving me Time B. The throughput is then simply B-A.
The problem I'm having is that I can't find a free serial port spy which works accurately enough for my circumstances. I've tried  Sysinternals' Portmon, but it is only accurate to a second and I need to know the answer to the nearest tenth of a second. I also tried Free Serial Port Monitor, but it has inaccurate timestamping.
Any suggestions on suitable software?

A: Use Portmon. Change the time format; it can show the time in milliseconds (click the timer button on the tool bar - or Ctrl + T or menu Options → Clock Time).
Or use Portmon with more data you can get accurately.


text:
Q: i cant get this AJAX jquery tutorial to work. wont load page  my pages wont load. can anyone suggest what is wrong? I tried changing the file path to the different files in case that was what was causing the problem. but still none of them are loading. what should happen is that when the user clicks the link, the page should be loaded inside the div.
<!doctype html>

<meta charset="utf-8">
<title> jquery example</title>

Home/
Portfolio/
Contact

Jquery
$(document).ready(function() {
    $('#content_area').load($('.menu_top:first').attr('href'));
});

$('.menu_top').click(function() {
    var href = $(this).attr('href');
    alert('clicked');
    $('#content_area').hide().load(href).fadeIn('normal');
    return false;
});

I am able to see the alert when i click on the .menu_top element. but it wont load it on the page. i tried renaming the files to .html and it still wont worl. i am running on a xammp local host, and that seems to work fine for everything else. i checked my console for errors and it doesnt return any errors.
i just finished some of the previous ajax tutorials and they loaded the data without any problems, so i ruled out that it was something concerning the local host.

A: Remove the Hash from your ID :)

to

A: I believe you're looking for $('.menu_top:first-child')


text:
Q: Generic async trait that returns the implemented Struct I'm getting blocked on what I think it's a simple problem. I'm still learning Rust, and I want to do the following:
I want to create an async trait (using async-trait) that will instantiate a DB connection instance and it will return the struct that is implementing that trait.
mongo.rs
#[async_trait]
pub trait DB {
    async fn init<T, E>() -> Result<T, E>;
}

Then: favorites.rs (See the implementation of the DB trait down below)
use async_trait::async_trait;
use mongodb::Collection;
use rocket::form::FromForm;
use rocket::serde::ser::StdError;
use serde::{Deserialize, Serialize};
use std::error::Error;
use uuid::Uuid;

pub struct FavoritesDB {
    collection: Collection<Favorite>,
}

#[derive(Debug)]
pub enum FavoritesError {
    UnknownError(Box<dyn Error>),
}

// Conflicts with the one down below
// impl From<Box<dyn Error>> for FavoritesError {
//     fn from(err: Box<dyn Error>) -> FavoritesError {
//         FavoritesError::UnknownError(err)
//     }
// }

impl From<Box<dyn StdError>> for FavoritesError {
    fn from(err: Box<dyn StdError>) -> FavoritesError {
        FavoritesError::UnknownError(err)
    }
}

#[async_trait]
impl mongo::DB for FavoritesDB {
    async fn init<FavoritesDB, FavoritesError>() -> Result<FavoritesDB, FavoritesError> {
        let main_db = mongo::init::<Favorite>("Favorites").await?;
        let db = FavoritesDB {
            collection: main_db.collection,
        };
        Ok(db)
    }
}

There are a list of problems with this:
1)
error[E0574]: expected struct, variant or union type, found type parameter `FavoritesDB`
  --> src\db\favorites.rs:41:18
   |
41 |         let db = FavoritesDB {
   |                  ^^^^^^^^^^^ not a struct, variant or union type
   |
help: consider importing this struct instead

*I've tried implementing From<Box<dyn tdError>> manually but it conflicts with what I have.

error[E0277]: `?` couldn't convert the error to `FavoritesError`
   --> src\db\favorites.rs:40:65
    |
40  |         let main_db = mongo::init::<Favorite>("Favorites").await?;
    |                                                                 ^ the trait `From<Box<dyn StdError>>` is not implemented for `FavoritesError`
    |
    = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
    = note: required because of the requirements on the impl of `FromResidual<Result<Infallible, Box<dyn StdError>>>` for `Result<FavoritesDB, FavoritesError>`
note: required by `from_residual`
   --> C:\Users\asili\.rustup\toolchains\nightly-2021-11-15-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\ops\try_trait.rs:339:5
    |
339 |     fn from_residual(residual: R) -> Self;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: consider further restricting this bound
    |
39  |     async fn init<FavoritesDB, FavoritesError + std::convert::From<std::boxed::Box<dyn std::error::Error>>>() -> Result<FavoritesDB, FavoritesError> {
    |                                               ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Some errors have detailed explanations: E0277, E0282, E0574.
For more information about an error, try `rustc --explain E0277`.

Just for more context, here's the DB struct and impl (Currently connecting to a local MongoDB) included in mongo.rs
pub struct Database<T> {
    client: mongodb::Database,
    pub collection: Collection<T>,
}

impl<T> Database<T> {
    pub async fn init() -> Result<mongodb::Database, Box<dyn Error>> {
        let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?;
        client_options.app_name = Some("My App".to_string());
        // Get a handle to the deployment.
        let client = Client::with_options(client_options)?;
        let db = client.database("rust-svelte");
        return Ok(db);
    }
}

pub async fn init<T>(collection: &str) -> Result<Database<T>, Box<dyn Error>> {
    let client = Database::<T>::init().await?;
    let collection = client.collection::<T>(collection);
    let db = Database { client, collection };
    Ok(db)
}

I've been searching for a few days over SO and the Rust community and my Google-Rust-Fu isn't good enough to spot what's the problem. Any ideas?

A: You've declared init to take 2 generic parameters: T and E.
This means that the code that calls init has to provide the concrete types to fill in those parameters. For example, if someone was using your library, it would be totally feasible for them to write init::<i64, ()>(), and your code should deal with that.
Because of that, when you define your impl DB for FavouritesDB, you write this:
async fn init<FavoritesDB, FavoritesError>() -> Result<FavoritesDB, FavoritesError>

This is no different to writing:
async fn init<T, E>() -> Result<T, E>

you've just given the type parameters different names that happen to match a struct that you're probably trying to use.
A better pattern might be an associated type. Instead of the caller deciding what the concrete types are (as is the case with generics), with associated types, the implementation of the trait on the type sets the type.
This is common with things like Iterator. Iterator has no generic parameters, but a single associated type Item. This is because it wouldn't make sense to be able to impl Iterator<String> for MyStruct and impl Iterator<i64> for MyStruct at the same time. Instead, we want to implement Iterator for a type once, and that implementation carries with it the definition of the types it expects.
So something like this (I've omitted the async-ness for brevity since it doesn't seem to be a factor here):
trait DB {
  type InitOk;
  type InitErr;

  fn init() -> Result<Self::InitOk, Self::InitErr>;
}

impl Db for FavouritesDB {
  type InitOk = FavouritesDB;
  type InitErr = FavouritesError;
  fn init() -> Result<Self::InitOk, Self::InitErr> {
    // now you can reference FavouritesDB the struct, rather than the generic parameter
  }
}

I'd also add you may want to not have the InitOk type, and just return Self, but that's up to you if you think you might want a struct to be able to create a different type.
For part 2, Rust assumes nothing (other than Sized) about generic parameters. If you want Rust to force a generic to have some property, you have to add a bound.
The compiler is telling you here that it can't use the ? operator to convert automatically, because it doesn't know that your error type has a From<Box<dyn Error>> implementation.
If you know that every error type is going to implement that, you can add it as a bound on the associated type, like this:
trait DB {
  type InitOk;
  type InitErr: From<Box<dyn Error>>;

  // ...
}


text:
Q: How to get the binding expression inside a BindingHandler in Knockout JS Lets say I have a bound span

And I have a custom binding
ko.bindingHandlers.MyBinding = {
   init: function (element, valueAccessor, allBindings, viewModel, context) {
        // I want to get the string "Name" here. NOT the value of Name.
   },
};

How do i get a string with the value of the binding expression inside the handler? ie how do i get "Name" not "Value of name".
I also need the expression so passing the string "Name" is not feasible.

A: You need to pass in Name as string and not as a reference:

ko.bindingHandlers.MyBinding = {
   init: function (element, valueAccessor, allBindings, viewModel, context) {
        var myBinding = valueAccessor(); // will contain 'Name';
        var valueOfmyBinding = viewModel[myBinding]; //value of the Name property
   },
};

You can still use your expression as a string because in Javascript you can eval altough eval() is a dangerous function: here is a sample JSFiddle.
Or if you only need to support simple property expression like Child.Name you can write your own parser where you split the string on the dots and foreach on the accessors.

A: Actually, Knockout does have a built-in way to do this. You do need to adapt your custom binding a little (namely, it becomes an object instead of a string value). Knockout allows you, along with the init and update properties, to specify a preprocess property. For example, suppose we have the following viewModel:
var app = { data: ko.observable('Hello World') };

And a simple binding that would convert the string passed to it fully to lowercase, and output both the binding's name and value (the property passed in the view obviously being data):
ko.bindingHandlers.lower = {
  update: function(elem, value) {
    var obj = ko.unwrap(value());
    elem.textContent = 'Name: ' + ko.unwrap(obj.name) +
      ' - Value: ' + ko.unwrap(obj.data).toLowerCase();
  },
  preprocess: function(value, bindingName) {
    return '{data:' + value + ', name:\'' + bindingName + '\'}';
  }
};

It's as simple as stringifying the value property passed to it & transforming the binding's value into an object with 2 keys (name & value here). Have a look. See Binding preprocessing for more info.

A: You could do the following, so you won't need the eval.

ko.bindingHandlers.MyBinding = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();

        var sp = value.split('.');
        var current = viewModel;
        for(var i=0;i<sp.length;i++) {
            var nNode = current[sp[i]];
            if ( nNode ) {
                current = nNode;
            }
        }
        $(element).html(current());
    }
};

As nemesv already explained, you need to give the Name as string value in your binding. After that you can use this to step through your viewmodel to retrieve the value. To display the value in the element I've added
    $(element).html(current());
Here the current() is at the deepest level in my viewmodel so it can be called and the return value can be used to update the html.

A: I propose to transfer the name of the property with use another binding.

ko.bindingHandlers.myBinding = {
    init: function(element, valueAccessor, allBindings, viewModel, context) {
      var nameOfProp = allBindings.get("nameOfProp");
    };
  }

JSFiddle

A: I like what pavel-chervov said above. In a similar vein if you don't mind using a bit of jQuery:

ko.bindingHandlers.MyBinding = {
    init: function (element, valueAccessor, allBindings, viewModel, context) {
        var nameOfProp = $(element).data('binding-name');
    },
};

A: I'm a bit late to the party on this, but here's what I did, and it works like a charm:
JS:
ko.bindingHandlers.myHandler = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var regex = /return ([^\s]+)\s*}/;

        //accessor will contain whatever expression was used in data-bind
        //so in this example it will be "myProp.childProp"
        var accessor = regex.exec(valueAccessor.toString())[1];

        //...
},
//...

HTML:

So the value of accessor (in case you missed the comment) will be "myProp.childProp"


text:
Q: When using vue-virtual-scroller where does content-tag and main-tag come from I am trying to understand the vue virtual scroller. I noticed in the demo there are a couple HTML attributes it uses...
<virtual-scroller v-if="scopedSlots" class="scroller" :item-height="itemHeight" :items="items" main-tag="section" content-tag="table" :buffer="buffer" :pool-size="poolSize">
link to the specific line on source code
Where does this ability come from and where is the documentation for it?

A: Breakdown:

*

*v-if - vue directive

*class - normal html attribute that you probably already know.

*item-height- computed Method.

*items - data object property.

*buffer - data object property

*pool-size - data object property
please notice that item-height for example is written as kebab-case on the html side, but should be written with camelCase on the javascript side. like so: itemHeight
about the content-tag, main-tag - worth a shot to ask the developer on github. those are not part of official vue api, nor part of html spec.

A: These are props declared in ../src/components/VirtualScroller.vue.
Both "content-tag" and "main-tag" are props of type String, meaning you can pass your choice of html elements. In your copied example, "section" and "table" is being passed to each prop, which is simply a string. If no value is passed, it would default to "div", which was set here: https://github.com/Akryum/vue-virtual-scroller/blob/master/src/components/VirtualScroller.vue
The string can also be passed dynamically, as they do for :item-height="itemHeight", where you would have :main-tag="mainTag" or :main-tag="anyCustomMainTag". This would allow you to set mainTag or anyCustomMainTag to your string value, which would also override the default div.


text:
Q: Package inputenc Error: Invalid UTF-8 byte sequence I'm writing a report with several imported code (I'm using listing package), and I come across the error in the title when the compiler started parsing one of the imported code text.
Looking at the log file I've found these lines:
The document does not appear to be in UTF-8 encoding.
Try adding \UseRawInputEncoding as the first line of the file
or specify an encoding such as \usepackage [latin1]{inputenc}
in the document preamble.
Alternatively, save the file in UTF-8 using your editor or another tool

Following these instructions I've added \UseRawInputEncoding at the beginning of my latex file. Then I've checked the encoding type of the file imported as the others is UTF-8 but nothing worked.
Any suggestion would be appreciated:)
My latex preamble:
\UseRawInputEncoding
%PREAMBOLO
\documentclass[a4paper,11pt]{report}

\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}

\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{textcomp}
\usepackage{enumerate}
\usepackage{xcolor}
\usepackage{listingsutf8}

\definecolor{codegreen}{RGB}{42, 184, 42}
\definecolor{codeblue}{RGB}{48, 48, 255}
\definecolor{codered}{RGB}{223, 15, 15}
\definecolor{codeyellownum}{RGB}{183, 183, 38}
\definecolor{codeyellowstring}{RGB}{251, 191, 71}
\definecolor{backcolour}{RGB}{236, 239, 244}

\lstdefinestyle{global}{
    language=Octave,
    inputencoding=utf8,
    extendedchars=true,
    backgroundcolor={\color{backcolour}},
    commentstyle={\color{codegreen}},
    keywordstyle={\color{codeblue}},
    keywordstyle=[2]{\color{codered}},
    otherkeywords={;,+,-,*,/,.,=,++,(,),[,],=+,=-},
    morekeywords=[2]{;,+,-,*,/,.,=,++,(,),[,],=+,=-},
    numberstyle=\tiny\color{black},
    stringstyle=\color{codeyellowstring},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2,
    literate={à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1,
}

\lstset{style=global}

\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{subfig}
\usepackage{float}
\usepackage{geometry}
\geometry{
a4paper,
left=25mm,
right=15mm,
top=25mm,
bottom=25mm
}

\usepackage{amssymb}
\usepackage{mathrsfs}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{mathtools}
\usepackage{xfrac}
\usepackage{stmaryrd}
\usepackage{enumitem}
\usepackage[all]{xy}

% Cambiare impostazioni di pagina
\setlength{\parindent}{0cm} % Lunghezza indentazione

% Dichiarazione nuovi comandi
\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\restr}[2]{\left.#1\right|_{#2}}
\newcommand{\ds}{\displaystyle}
% ALGEBRA
\newcommand{\acts}{\rotatebox[origin=c]{-170}{$\circlearrowright$}}
%
%

% Dichiarazioni nuovi ambienti
\newtheorem*{deff}{\normalfont\scshape Definizione}
\newtheorem*{thm}{\normalfont\scshape Teorema}
\newtheorem*{prop}{\normalfont\scshape Proposizione}
\newtheorem*{lemma}{\normalfont\scshape Lemma}
\newtheorem*{cor}{\normalfont\scshape Corollario}
\newtheorem*{oss}{\normalfont\scshape Osservazione}
\newtheorem*{example}{\normalfont\scshape Esempio}
\newtheorem*{exe}{\normalfont\scshape Esercizio}

A: I found that when I updated my OS to Monterey I had the same issue.  (I really updated my MacBook about 7 generations... which included the new OS)  I found that the issue was I had a number of '–' vs '-' in my files - and similar non standard characters.  (Long dash vs just a dash... I am moving a draft book from MS Word to LaTex. Word adds the long dashes automatically.)  When I eliminated them this solved the problem.


text:
Q: JRE system library not found exception in eclipse Dear All, I am eclipse3.1 IDE for java under fedora 8 environment. I installed fresh copy of eclipse and trying to run a program,it shows JRE system library not found exception popup. I added this library manually by BuildPath-----> Add external library but still i am getting that popup. How to solve this problem.

A: Go to Window - Preference - Java - Installed JREs page to specify the location of your jre or JDK.

A: Go to Project > Properties >Java Build Path > Libraries > Add Library > Next > Just Finish This is work for me

A: I'm no expert but maybe try checking in Java Build Path that your lib appears in the Libraries tab and that in "Order and Export" tab it is checked
otherwise have you tried refreshing cleaning and rebuilding?(sometimes eclipse is a bit slow in detecting changes
final check that the path of the library is the good one (it happened when I committed a project to the svn and used it on a different computer, everything was there but since the computers had different names (C:\jason... and C:\jasonlaptop...) it wasn't working.
let me know if it changed anything


text:
Q: Error message in graphics.py I'm a Highschool Student learning python and I'm a bit stuck on why I am getting an error message in this script. It is supposed to prompt the user for info on how old they are and then return the info in days, hours, and minutes. I'm using the Graphics.py module to accomplish this. The error I am getting is:
how old are you.py", line 17, in <module>
    years=entry1.getText()
AttributeError: 'NoneType' object has no attribute 'getText'

I know that the module is properly installed as the getText function works on another script. My code can be seen below. Thanks for any help!
from graphics import*

win=GraphWin('How Old Are You?',250,500)
win.setBackground ('Gray')

entry1= Entry(Point(125,100),10).draw(win)
entry2= Entry(Point(125,200),10).draw(win)
entry3= Entry(Point(125,300),10).draw(win)

Text(Point(125,50),'How many years old are you?').draw(win)
Text(Point(125,150),'What month in the year? (number)').draw(win)
Text(Point(125,250),'How many weeks into the month?').draw(win)
Text(Point(125,25),'When done click outside a box').draw(win)

win.getMouse()

years=entry1.getText()
months=entry2.getText()
days=entry3.getText()

totalDays=(years*365)+(months*30)+(days)
totalHours=((years*365)+(months*30)+(days))*24
totalMinutes=(((years*365)+(months*30)+(days))*24)*60

Text(Point(125,350),totalDays)
Text(Point(125,400),totalHours)
Text(Point(125,450),totalMinutes)

A: I don't know the graphics library you are using, but your error seems to be trying to accomplish too much at once.
You do:
entry1= Entry(Point(125,100),10).draw(win)
entry2= Entry(Point(125,200),10).draw(win)
entry3= Entry(Point(125,300),10).draw(win)

In each line here, you do create an object - by calling Entry(...), and call a method on that object. The return value of the draw method is what ends up stored in the variables.
Usually, in Python objects, methods won't return their object back. If the method does perform an action (like the name draw ) suggests, it will usually return None - and that is what is happening here, as we see in your error message.
So, all you have to do is to first create your entries, and after that call the draw method on them:
entry1= Entry(Point(125,100),10)
entry2= Entry(Point(125,200),10)
entry3= Entry(Point(125,300),10)
entry1.draw(win)
entry2.draw(win)
entry3.draw(win)

Aside from that, if you don't want your code to be so repetitive, you can create your
entries in a loop and store them in a Python list:
entries = []
for vpos in (100,200,300):
    entry = Entry(Point(125,vpos),10)
    entries.append(entry)
    entry.draw(win)

Text(Point(125,50),'How many years old are you?').draw(win)
Text(Point(125,150),'What month in the year? (number)').draw(win)
Text(Point(125,250),'How many weeks into the month?').draw(win)
Text(Point(125,25),'When done click outside a box').draw(win)

win.getMouse()

years, months, days = (entry.getText() for entry in entries)


text:
Q: Calculating the difference between durations with milliseconds in Ruby
TL;DR: I need to get the difference between HH:MM:SS.ms and HH:MM:SS.ms as HH:MM:SS:ms

What I need:
Here's a tricky one. I'm trying to calculate the difference between two timestamps such as the following:
In: 00:00:10.520
Out: 00:00:23.720

Should deliver:
Diff: 00:00:13.200

I thought I'd parse the times into actual Time objects and use the difference there. This works great in the previous case, and returns 00:0:13.200.
What doesn't work:
However, for some, this doesn't work right, as Ruby uses usec instead of msec:
In: 00:2:22.760
Out: 00:2:31.520
Diff: 00:0:8.999760

Obviously, the difference should be 00:00:8:760 and not 00:00:8.999760. I'm really tempted to just tdiff.usec.to_s.gsub('999','') ……

My code so far:
Here's my code so far (these are parsed from the input strings like "0:00:10:520").
tin_first, tin_second = ins.split(".")
tin_hours, tin_minutes, tin_seconds = tin_first.split(":")
tin_usec = tin_second * 1000
tin = Time.gm(0, 1, 1, tin_hours, tin_minutes, tin_seconds, tin_usec)

The same happens for tout. Then:
tdiff = Time.at(tout-tin)

For the output, I use:
"00:#{tdiff.min}:#{tdiff.sec}.#{tdiff.usec}"

Is there any faster way to do this? Remember, I just want to have the difference between two times. What am I missing?
I'm using Ruby 1.9.3p6 at the moment.

A: Using Time:
require 'time' # Needed for Time.parse

def time_diff(time1_str, time2_str)
  t = Time.at( Time.parse(time2_str) - Time.parse(time1_str) )
  (t - t.gmt_offset).strftime("%H:%M:%S.%L")
end

out_time = "00:00:24.240"
in_time  = "00:00:14.520"

p time_diff(in_time, out_time)
#=> "00:00:09.720"

Here's a solution that doesn't rely on Time:
def slhck_diff( t1, t2 )
  ms_to_time( time_as_ms(t2) - time_as_ms(t1) )
end

# Converts "00:2:22.760" to 142760
def time_as_ms( time_str )
  re = /(\d+):(\d+):(\d+)(?:\.(\d+))?/
  parts = time_str.match(re).to_a.map(&:to_i)
  parts[4]+(parts[3]+(parts[2]+parts[1]*60)*60)*1000
end

# Converts 142760 to "00:02:22.760"
def ms_to_time(ms)
  m = ms.floor / 60000
  "%02i:%02i:%06.3f" % [ m/60, m%60, ms/1000.0 % 60 ]
end

t1 = "00:00:10.520"
t2 = "01:00:23.720"
p slhck_diff(t1,t2)
#=> "01:00:13.200"

t1 = "00:2:22.760"
t2 = "00:2:31.520"
p slhck_diff(t1,t2)
#=> "00:00:08.760"

A: I figured the following could work:
out_time = "00:00:24.240"
in_time = "00:00:14.520"
diff = Time.parse(out_time) - Time.parse(in_time)
Time.at(diff).strftime("%H:%M:%S.%L")
# => "01:00:09.720"

It does print 01 for the hour, which I don't really understand.
In the meantime, I used:
Time.at(diff).strftime("00:%M:%S.%L")
# => "00:00:09.720"

Any answer that does this better will get an upvote or the accept, of course.

A: in_time = "00:02:22.760"
out_time = "00:02:31.520"
diff = (Time.parse(out_time) - Time.parse(in_time))*1000
puts diff

OUTPUT:
8760.0 millliseconds

Time.parse(out_time) - Time.parse(in_time) gives the result in seconds so multiplied by 1000 to convert into milliseconds.


text:
Q: GNOME shutdown dialog taking too much time to appear When I select the 'Power Off / Log Out' option from the top bar and then select the 'Power Off...' option, the shutdown dialog (the one that adds a gray overlay to desktop) is taking something like 5 to 30 seconds (randomly) to appear.
I have these GNOME Shell extensions active:

*

*Blyr

*Clipboard Indicator

*Impatience

*Keep awake!

*NetSpeed

*NoAnnoyance

The problem is present when all of them are disabled. The problem persists on both Xorg and Wayland.
What could be possibly the cause and how can I fix it?
Update: I get this error in journal when trying to shutdown:
Failed to load the backend: Failed to execute statement 'PRAGMA synchronous=OFF': file is not a database

and when the dialog appears:
Failed to get update info from PackageKit: Timeout was reached

A: Turns out there is a software named PackageKit, and the database of this software was corrupted, leading to this error. I fixed it using the commands from this question:
sudo apt-get remove --purge packagekit
sudo apt-get install ubuntu-software

(Other symptoms include getting this at the end of every single apt command: Error: timeout was reached)


text:
Q: Use Razor to render a multiple file Input I'm looking to render a multiple file input using the razor html keyword.
So far I have
 @Html.TextBox("file", "", new { type = "file" })

Which renders as
<input id="file" name="file" type="file" value>

I want to render it as
<input id="file" name="file" type="file" multiple>

I'm sure this is simple but after a fair amount of googling I haven't been able to find anything. Thank you for your time/help!

A: Use this
@Html.TextBox("file", "", new { type = "file", multiple = "multiple" })

Rendered HTML
<input id="file" multiple="multiple" name="file" type="file" value="">


text:
Q: Gambit Scheme FFI I am trying to use ffi to call opencv's cvReleaseCapture,
void cvReleaseCapture( CvCapture** capture );
http://www.ai.rug.nl/vakinformatie/pas/content/Highgui/opencvref_highgui.htm
I have tried,
(define release-capture (c-lambda ((pointer (pointer "CvCapture"))) void "cvReleaseCapture"))
didn't relly worked.

A: (c-define-type CvCapture (pointer (pointer (struct "CvCapture"))))
(define release-capture (c-lambda (CvCapture) void "cvReleaseCapture"))


text:
Q: What is an Arborescence (Graph Theory)? On Wikipedia, it states an arborescence is a digraph for which a vertex $u$ called the root and any other vertex $v$, there is exactly one directed path from $u$ to $v$.

In other words, does that mean an arborescence is a digraph whose underlying graph is a tree?

A: In fact, more is true. Given any tree, every edge can be given uniquely a direction that is towards the root of the tree. In other words, any tree can be uniquely converted into an arborescence. Conversely, any arborescence can be uniquely converted into a tree by changing each directed edge into an undirected edge.
EDIT: We always assume that there is given a root with the tree or arborescence.


text:
Q: Select count votes for each object and top voted objects I have two tables :
VOTE with fields pk:id, fk:uid, date and SUBMISSION with fields pk:id, ....
Tables have 1to1 relation on uid<-id fields. How I can now query for :

*

*list of objects together with their score

*list of 10 top rated objects ordered by score ?

A:     SELECT s.*,
           COUNT(*) AS cnt
      FROM SUBMISSION s
INNER JOIN VOTE v ON s.id = v.uid
  GROUP BY s.id
  ORDER BY cnt DESC
     LIMIT 10

Without ORDER BY and GROUP BY clauses you'll just retrieve all the submissions with votes count.
But I highly recommend you to create votes_count field in the SUBMISSION table and maintain it with trigger/code to store the precalculated count of votes there.


text:
Q: How to avoid Alarm manager overriding with same intervals of time with different message using dynamically? What happens if we select same intervals for two different message its not sending the respective manner,its taking the first message content and sending the second sms timing.
I want to send different sms with same intervals using dynamically.
MyAlaramactivity.java
else if (mytime.equals("Every 5 Minutes")) {
                        editor1.putString("p1",edittextSmsNumber.getText().toString());
                        editor1.putString("m1",edittextSmsText.getText().toString());
                        editor1.commit();
                        edittextSmsNumber.setText(" ");
                        edittextSmsText.setText(" ");

                        Calendar calendar = Calendar.getInstance();

                        calendar.set(datep.getYear(), datep.getMonth(),
                                datep.getDayOfMonth(),
                                timep.getCurrentHour(),
                                timep.getCurrentMinute(), 0);
                        Intent myIntent1 = new Intent(AndroidAlarmSMS.this,
                                MyAlarmService.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("service", 1);
                        myIntent1.putExtras(bundle);
                        //myIntent1.putExtra("service", "s1");
                        myIntent1.setData(Uri.parse("timer:myIntent1"));
                        pendingIntent1 = PendingIntent.getService(
                                AndroidAlarmSMS.this, 1, myIntent1, PendingIntent.FLAG_UPDATE_CURRENT);

                        AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
                        alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP,
                                calendar.getTimeInMillis(), 1000 * 60 * 2,
                                pendingIntent1);

                        // Millisec * Second *
                                                // Minute
                    } else if (mytime.equals("Every hour")) {
                        editor2.putString("p2",edittextSmsNumber.getText().toString());
                        editor2.putString("m2",edittextSmsText.getText().toString());
                        editor2.commit();
                        edittextSmsNumber.setText(" ");
                        edittextSmsText.setText(" ");
                        Calendar calendar = Calendar.getInstance();

                        calendar.set(datep.getYear(), datep.getMonth(),
                                datep.getDayOfMonth(),
                                timep.getCurrentHour(),
                                timep.getCurrentMinute(), 0);
                        Intent myIntent2 = new Intent(AndroidAlarmSMS.this,
                                MyAlarmService.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("service", 2);
                        myIntent2.putExtras(bundle);
                        myIntent2.setData(Uri.parse("timer:myIntent2"));
                        pendingIntent2 = PendingIntent.getService(
                                AndroidAlarmSMS.this, 2, myIntent2, PendingIntent.FLAG_UPDATE_CURRENT);

                        AlarmManager alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);

                        alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP,
                                calendar.getTimeInMillis(), 1000 * 60 * 3,
                                pendingIntent2);

This is my service class

public void onStart(Intent intent, int startId) {
  super.onStart(intent, startId);
  Bundle bundle = intent.getExtras();
  //String status= b.getString("service");
  status = bundle.getInt("service", 0);

  if(i==2)
   {
   i++;
   Toast.makeText(this, "Hiii", Toast.LENGTH_LONG).show();
   }
   else
   {
       String share_pref_file = "IMS";
          SharedPreferences prefs = getSharedPreferences(share_pref_file,
          Context.MODE_PRIVATE);
       if(status == 1)
       {
           String number = prefs.getString("p1", "");
           String message = prefs.getString("m1", "");
              //String message= prefs.getString("extraSmsText", "");

              Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
              Toast.makeText(this,
                     number,
                     Toast.LENGTH_LONG).show();

              SmsManager smsManager = SmsManager.getDefault();
              smsManager.sendTextMessage(number, null, message, null, null);
       }
       else if (status == 2)
       {
           String share_pref_file1 = "IMS2";
              SharedPreferences prefs2 = getSharedPreferences(share_pref_file1,
              Context.MODE_PRIVATE);
           String number = prefs2.getString("p2", "");
           String message = prefs2.getString("m2", "");
              //String message= prefs.getString("extraSmsText", "");

              Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
              Toast.makeText(this,
                     number,
                     Toast.LENGTH_LONG).show();
              try{
                  SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(number, null, message, null, null);
                      Toast.makeText(this, "Message sent successfully", Toast.LENGTH_LONG).show();
              }
              catch(Exception e)
              {
                  Toast.makeText(this,
                            "I will kill you enter correct number",
                             Toast.LENGTH_LONG).show();
              }

       }

Have to avoid alarammanager overriden for same intervals

A: Issue:
Pending intents are overriding.
Solution:
You just need to provide unique id to each pending intent
Example:
You have already provided 0 as id in
pendingIntent = PendingIntent.getService(
                                AndroidAlarmSMS.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

So don't provide 0 again in next pending intent, use 1 and 2 instead of 0 like mentioned below:
pendingIntent1 = PendingIntent.getService(
                                AndroidAlarmSMS.this, 1, myIntent1, PendingIntent.FLAG_UPDATE_CURRENT);

pendingIntent2 = PendingIntent.getService(
                                AndroidAlarmSMS.this, 2, myIntent2, PendingIntent.FLAG_UPDATE_CURRENT);

I hope it will be helpful !!

A: i reviewed your code, as you want to set  multiple alarams first you have to create alaram manager array and change your code to like this.. first you create one global integer variable with name fivemin
else if (mytime.equals("Every 5 Minutes")) {
fivemin=fivemin+1;

AlarmManager[] alarmManager=new AlarmManager[24];

ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();

Intent myIntent1 = new Intent(AndroidAlarmSMS.this,
                                    MyAlarmService.class);
                            Bundle bundle = new Bundle();
                    bundle.putInt("service", 1);
                    myIntent1.putExtras(bundle);

                            myIntent1.setData(Uri.parse("timer:myIntent1"));
                            pendingIntent = PendingIntent.getService(
                                    AndroidAlarmSMS.this, fivemin, myIntent1,0);

                            alarmManager[fivemin] =  (AlarmManager) getSystemService(ALARM_SERVICE);
                            alarmManager[fivemin].setRepeating(AlarmManager.RTC_WAKEUP,
                                    calendar.getTimeInMillis(), 1000 * 60 * 2,
                                    pendingIntent);

                            intentArray.add(pendingIntent);


text:
Q: Subscribe to DOM events within Ember app I've got a Ember CLI based blog. I currently resize all <img> inside posts upon clicking them using this function inside the application-controller.
I rely on on('init') and Ember.run.later and this feels just dirty.
How can I improve the subscription code below?
import Ember from 'ember';

export default Ember.ArrayController.extend({
  imageScaling: function() {
    Ember.run.later((function() {
      //Subscribe to the actual event
      Ember.$(".post-content img").on("click", function(){
        // RESIZE HERE
      })
    }), 3000)
  }.on('init')
});

A: If you're inserting all of your images inside Ember templates, you can always use the action helper:
<img {{action 'scaleImages' on='click'}} src='' />

I realize that's probably not the case though. The way I've dealt with DOM interactions in the past is to override the application view then set up and tear down my event handler there. You can also avoid the Ember.run.later call by modifying your jQuery event listener. Here's how I would do it:
// app/views/application.js
export default Ember.View.extend({
    setupImageScaling: function() {
        $('body').on('click.image-scaling', 'img', function() {
            // RESIZE HERE
        });
    }.on('didInsertElement'),

    teardownImageScaling: function() {
        $('body').off('click.image-sacling');
    }.on('willDestroyElement')
});

In my opinion, the above is the 'most Ember' way of handling this kind of situation.


text:
Q: PropertyGrid is not displayed properly with .NET 5 I have a winform project compiled to .NET 4.7.2.
It has a PropertyGrid element on the main form and it is displayed well.
After migrating to .NET 5, it does not look as expected:

Some text appears on top of the control and to view the value of any property - one has to click on it.

A: This is a (huge) regression with .NET 5.0.4. See here:
"The default value is not displayed in the correct position after setting SelectedObject property for PropertyGird control"
https://github.com/dotnet/winforms/issues/4593
It will be fixed in 5.0.5.


text:
Q: Minifying static files (js & css) using django-pipeline results in empty files I have gone through all of the related posts similar to the issue I have, but none of them seem to solve my problem therefore my question.
When I run python manage.py collectstatic django-pipeline generates minified css file which has no content. Can someone please advise how I can resolve this issue.
I don't see any errors in my terminal. Using django 1.5.
Here's my django-pipeline specific settings:
STATICFILES_STORAGE     = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_ENABLED        = True
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_JS_COMPRESSOR  = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_YUGLIFY_BINARY = '/usr/bin/env yuglify'

PIPELINE_CSS = {
    'page_style': {
        'source_filenames': (
          'css/header.css',
          'css/content.css',
          'jqm/grid.css'
        ),
        'output_filename': 'assets/compressed/page_style.min.css',
     }
}

A: Are you using Ubuntu and does typing node on the console return any output?
I just solved this (or a similar?) problem myself when I realized that I used apt-get to install Node(js) which turned out to install it as nodejs and not node (which is something else, according to Ubuntu).
If you which yuglify, you can find the path and edit the bang-line at the top to have to correct path to nodejs (it is currently #!/usr/bin/env node, for instance).
I changed mine to #!/usr/bin/env nodejs and it seemed to solve the problem.
YMMV.


text:
Q: ¿Como puedo acceder a una carpeta en la memoria interna en Android? No encuentro la forma para acceder a una carpeta en android. Tengo algunas imagenes que copie al crear mi aplicacion en una ruta de la memoria interna, quiero que al presionar un boton se abra esta carpeta, pero no se como hacerlo ni por donde empezar?

A: public void openFolder(){
   Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
   Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
       +  File.separator + "myFolder" + File.separator);
   intent.setDataAndType(uri, "text/csv");
   startActivity(Intent.createChooser(intent, "Open folder"));
}

Espero que esto te ayude a empezar


text:
Q: How to get access to TestContext::diagnostic when using the describe/it form of the native NodeJs Test Framework? I am using the native NodeJs Testing Framework (imported from node:test).
When using the test syntax, I have access to the TestContext as test(...) callback argument :
test('top level test', async (t) => {
  t.afterEach((t) => t.diagnostic(`finished running ${t.name}`));
  await t.test(
    'This is a subtest',
    (t) => {
      assert.ok('some relevant assertion here');
    }
  );
});

But how can I call diagnostic(...) when using the describe syntax ?
The example in the official documentation is not that helpful/incomplete (https://nodejs.org/api/test.html#beforeeach-fn-options) :
describe('tests', async () => {
  beforeEach(() => t.diagnostic('about to run a test'));
  it('is a subtest', () => {
    assert.ok('some relevant assertion here');
  });
});

since there is no TestContext argument given ...
Any help are appreciated :-)


text:
Q: Array.prototype.flat() creates an error when building Gatsby site When building, I get the following error:
WebpackError: TypeError: Object.entries(...).map(...).flat is not a function

I can gatsby deveop the app just fine, and all works as expected in the browser.
Any ideas on how to remedy this?

A: I'm not sure if this is ideal, but the only way I was able to fix this was by adding a polyfill and including it at the top of the offending file.
> yarn add array-flat-polyfill

// src/pages/page-with-error.js
import 'array-flat-polyfill';


text:
Q: thunderbird: different color for new email, when I am only a "cc" recipient, instead of regular "to" recipient Is there a way to use different color for new email in inbox, when I am only a "cc/bcc" recipient, instead of regular "to" recipient ?
I am alredy using custom color for new emails in inbox. This is what i have in my userChrome.css:
/* unread messages */
#threadTree treechildren::-moz-tree-cell-text(unread),
treechildren::-moz-tree-cell-text(hasUnreadMessages-true) {
    font-weight: bold !important;
    color: red !important;
}

How can I modify it, so that new emails are colored differently, depending wether I am in "to" or "cc/bcc" ?

A: While it seems they can't be set using CSS, colors can be set based on To, Cc, and Bcc state by setting up one or more message filters to tag the messages.
First, create a tag of the desired color, e.g. a tag named Cc/Bcc. Then, create a filter to tag messages at a particular email address received as either Cc or Bcc to Cc/Bcc, as shown below. Use your own email address, of course.
By default, there is no Bcc in the list of headers to match. A custom Bcc header entry needs to be added to the list of headers when setting up the rules. To do so:

*

*Select Customize... from the drop-down list for selecting the header to match,

*type Bcc in the "Customize Headers" dialog that appears,

*click Add,

*click OK.

One caveat: The functionality for removing a custom header seems not to work (at least in the 64-bit version of Thunderbird 68.8.0), so add carefully.


text:
Q: Extract all numbers in string to array I have a string like this
+3.15% price per day(+63.00% price at day 20)

and I want to be able to export it into an array so it becomes something like this
{3.15 , 63.00, 20}

Can someone help me with this? I'm really stuck at this right now, as I'm not 100% sure how to approach it :\ The reason why I want to do this is because I want to multiple the numbers inside that string by a number like 4, so the result will become
+12.60% price per day(+252.00% price at day 20)

Here are all the possible cases
-3.15% price per day(-63.00% price at day 20)

=>  -12.60% price per day(-252.00% price at day 20)

+0.76 price per day(+15.20 price at day 20)

=>  +3.04 price per day(+60.80 price at day 20)

A: // export numbers
string input = "+3% price per day(+60% price at day 20)";
int[] array = Regex.Matches(input, @"\d+").OfType<Match>().Select(e => int.Parse(e.Value)).ToArray();

// replace numbers
double k = 3;
string replaced = Regex.Replace(input, @"\d+", e => (int.Parse(e.Value) * k).ToString());

// replace only percents
k = 4;
string replacedPercents = Regex.Replace(input, @"(\d+)%", e => (int.Parse(e.Groups[1].Value) * k).ToString() + "%");

// floating conversion
input = "+0.87 price per day(+63.00 price at day 20)";
string replacedFloating = Regex.Replace(input, @"\+(\d+\.(\d+)|\d+)", e => "+" + (double.Parse(e.Groups[1].Value, CultureInfo.InvariantCulture) * k).ToString(e.Groups[2].Length == 0 ? "0" : "0." + new string('0', e.Groups[2].Length), CultureInfo.InvariantCulture));

// floating conversion with negatives
input = "-0.87 price per day(+63.00 price at day 20)";
string replacedFloatingNegative = Regex.Replace(input, @"([+-])(\d+\.(\d+)|\d+)", e => e.Groups[1].Value + (double.Parse(e.Groups[2].Value, CultureInfo.InvariantCulture) * k).ToString(e.Groups[3].Length == 0 ? "0" : "0." + new string('0', e.Groups[3].Length), CultureInfo.InvariantCulture));

replaced is
+9% price per day(+180% price at day 60)

replacedPercents is
+12% price per day(+240% price at day 20)

replacedFloating is
+12.60 price per day(+252.00 price at day 20)

replacedFloatingNegative is
-3.48 price per day(+252.00 price at day 20)


text:
Q: Old project now shows up blank (no more layers) I've been working on this project for months now. Today I opened it up and it was blank, no layers, no nothing. I'm using version 3.16 of QGIS
I've tried opening multiple other projects and they all show up blank.
Here's how it looks :


text:
Q: I can't get any data form my Google-Fit. I don't know how to build this query in c# I have Credentials and I was authorized. Then i want to get Data(for ex. weight or steps).
https://keestalkstech.com/2016/07/getting-your-weight-from-google-fit-with-c/
I tried this code, but initially had problems with time, then I had a nullable array, but in my account I have all information for a particular day(steps, updated weight). So then I tried to build request on developers.google.com but ERROR 400 (Bad Request):
#1
{
  "application": {
    "name": "MyCare"
  },
  "dataType": {
    "field": [
      {
        "format": "integerList",
        "name": "steps"
      }
    ],
    "name": "com.google.step_count.delta"
  },
  "device": {
    "manufacturer": "MyCare",
    "model": "xiaomi",
    "type": "phone",
    "uid": "",
    "version": "1.0"
  },
  "type": "derived"
}

#2
{
  "application": {
    "name": "MyCare"
  },
  "dataType": {
    "field": [
      {
        "format": "integerList",
        "name": "weight"
      }
    ],
    "name": "com.google.weight"
  },
  "device": {
    "manufacturer": "",
    "model": "",
    "type": "phone",
    "uid": "",
    "version": "1.0"
  },
  "type": "derived"
}

And i used userId "me". But when i tried to use clientId whith which one i was authorized i had an ERROR 403 "Unauthorized"....
How should I do this query or maybe there are some other variants to get data in c#. I use Google.Apis.Fitness.v1 and create a Fitness Service:
var service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName});
..}

I also found such way, but I have nullable array. I think this way is not correct, so help me to redo it:
var service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName});
            var dataSets = service.Users.Dataset.Aggregate(
    new AggregateRequest
    {
        AggregateBy = new[] {
        new AggregateBy {DataTypeName = "com.google.location.sample"}}
    }, "me")
    .ExecuteAsync();
            var result = dataSets.Result;
        }

Pls, help! I need to do it in 3 hours :(((
But a have this problem for 2 mounth.


text:
Q: Restrições banco PostgreSQL em aplicação comercial Quais as restrições em utilizar banco de dados PostgreSQL em minha aplicação comercial em C#?
Qual o limite de tamanho?
E de conexões simultâneas? Que problemas que posso vir a enfrentar, em questão de conexão em rede com outas máquinas?

A: Restrições de licenciamento:
Nenhuma, o código é aberto.
Tamanho máximo para um banco de dados:
ilimitado (existem bancos de dados de 32 TB)
Tamanho máximo para uma tabela:
32 TB
Tamanho máximo de uma linha:
1,6 TB
Tamanho máximo para um campo:
1 GB
Número máximo de linhas em uma tabela:
ilimitado
Número máximo de colunas em uma tabela:
250-1600, dependendo do tipos de coluna
Número máximo de índices em uma tabela:
ilimitado
Número máximo de conexões:
por padrão, 100 conexões simultâneas, mas pode ser configurado no postgresql.conf
Fonte: https://www.postgresql.org/message-id/42C3C382.5020108%40cineca.it

A: O licenciamento é tranquilo e pode fazer qualquer coisa.
Não há grandes restrições importantes, e pode rodar bem. Ou não. Porque geralmente o que mais faz diferença é a pessoa saber o que está fazendo, isso é muito mais difícil. Para a maioria das aplicações escolher alguma coisa que não seja o ideal é um problema menor. Até porque em geral a escolha errada é feita por desconhecimento geral e isso causará problema muito maior.
Estudar os fundamentos para conseguir avaliar todos os pontos é algo muito mais importe que saber algumas informações específicas. De que adianta saber quem descobriu o Brasil, se essa informação pode ser falsa, incompleta ou confusa, ou ainda ser irrelevante, ou não saber porque precisa saber disso?
Não há limitações de conexões no software a não ser por configuração. Claro que há um limite prático, mas depende de uma série de fatores. E isso não importa muito, porque em aplicações corporativas não chega nem perto e em aplicações web só chegará se foi tudo arquitetado errado.
O tamanho máximo de dados é teórico e não deve se preocupar, até porque se um fizer uma aplicação que precisa de tanto será um profissional que domina muito o assunto. Há limitações específicas que em quase tudo é teórico, novamente porque se ultrapassar está fazendo algo errado. Tudo tem solução. O mais importante limite é o número de colunas em uma tabela que é 250 em alguns casos, na prática o limite pode ser 1600 dependendo dos tipos usados, e se precisar mais que 250 tem grande chance de estar fazendo algo errado, e tem como contornar. Outro é o limite de 1GB por coluna, que é tranquilo pra quase tudo.
Tem uma resposta no SO que ainda mantém os limites descritos.
Não há limite de conexão de rede com outras máquinas, só bancos de dados não cliente-servidor é que possuem limitação nisso. Obviamente há um limite prático
A decisão de qual banco de dados usar e modelo adotado passa por outras coisas. Não é porque sabe disto que tomará a decisão certa de qual banco de dado usar.
Eu ia falar para sempre olhar na documentação para ver essas coisas, isso é o mais importante para saber o que fazer, mas neste caso específico tiraram, o que mostra que o produto começou ficar mais marketeiro e isso é um mal sinal, esse é um projeto que prezava muito pela engenharia.


text:
Q: Counting appropriate number of subarrays in an array excluding some specific pairs? Let's say, I have an array like this:
1 2 3 4 5

And given pair is (2,3), then number of possible subarrays that don't have (2,3) present in them will be,,
1. 1
2. 2
3. 3
4. 4
5. 5
6. 1 2
7. 3 4
8. 4 5
9. 3 4 5

So, the answer will be 9.
Obviously, there can be more of such pairs.
Now, one method that I thought of is of O(n^2) which involves finding all such elements of maximum length n. Can I do better? Thanks!

A: Let's see, this adhoc pseudocode should be O(n):
array = [1 2 3 4 5]
pair = [2 3]
length = array.length
n = 0
start = 0

while (start < length)
{
    # Find next pair

    pair_pos = start
    while (pair_pos < length) and (array[pair_pos,pair_pos+1] != pair)   # (**1)
    {
        pair_pos++
    }

    # Count subarrays

    n += calc_number_of_subarrays(pair_pos-start)  # (**2)

    # Continue after the pair

    start = pair_pos+2
}

print n

Note **1: This seems to involve a loop inside the outer loop. Since every element of the array is visited exactly once, both loops together are O(n). In fact, it is probably easy to refactor this to use only one while loop.
Note **2: Given an array of length l, there are l+(l-1)+(l-2)+...+1 subarrays (including the array itself). Which is easy to calculate in O(1), there is no loop involved. c/f Euler. :)

A: You don't need to find which subarrays are in an array to know how many of them there are. Finding where the pair is in the array is at most 2(n-1) array operations. Then you only need to do a simple calculation with the two lengths you extract from that. The amount of subarrays in an array of length 3 is, for example, 3 + 2 + 1 = 6 = (n(n+1))/2.
The solution uses that in a given array [a, ..., p1, p2, ..., b], the amount of subarrays without the pair is the amount of subarrays for [a, ..., p1] + the amount of subarrays for [p2, ..., b]. If multiple of such pairs exist, we repeat the same trick on [p2, ..., b] as if it was the whole array.
function amount_of_subarrays ::
  index := 1
  amount := 0
  lastmatch := 0

  while length( array ) > index do
    if array[index] == pair[1] then
      if array[index+1] == pair[2] then
        length2 := index - lastmatch
        amount := amount + ((length2 * (length2 + 1)) / 2)
        lastmatch := index
      fi
    fi
    index := index + 1
  od

  //index is now equal to the length
  length2 := index - lastmatch
  amount := amount + ((length2 * (length2 + 1)) / 2)

  return amount

For an array [1, 2, 3, 4, 5] with pair [2, 3], index will be 2 when the two if-statements are true. amount will be updated to 3 and lastmatch will be updated to 2. No more matches will be found, so lastmatch is 2 and index is 5. amount will be 3 + 6 = 9.


text:
Q: How to target an element using input type checkbox I have a dropdown type list that will get hidden after specific device width and by default, the dropdown box will be visible so the user is not able to collapse it.
The default state for input is also hidden.
Suppose the device width is 804px, and the dropdown gets hidden and input gets visible. By clicking the input the user can see the contents of the dropdown.
But for some reason, I'm unable to target the dropdown box using the input field.

input[type="checkbox"]:checked~.team-lists {
  display: flex;
  height: 430px;
}

Hire Developer Team

      <input type="checkbox" class="add-lists" id="team-lists" hidden>

    Android App Developers
    iOS App Developers
    Flutter App Developers

A: Your selector input[type="checkbox"]:checked~.team-lists targets any elements that have a CSS class of team-lists that are siblings (~) of an input with type checkbox which is in checked state. This does not match your HTML structure; for this to work both the checkbox and the target div would have to have the exact same parent element, with the div coming after the checkbox. Given your current approach, that would mean you'd have to put the div inside the label (which would be a very bad approach).
Up until recently, you can only select forward (subsequent siblings)/downward (descendants) in CSS, which means once your selector has reached your checkbox, there is no way to continue your selector so you can reach your div.team-lists.
To solve this age-old developer issue, CSS has introduced the very new :has() pseudo class, which so far is only supported in Safari, and in Chrome (starting from v 101) behind the experimental features flag.
Please note that for simplicity's sake I have removed your icon (which didn't work in your snippet either), and replaced it by the letters CB.

.hireDevs:has(input[type="checkbox"]:checked) .team-lists {
  display: flex;
  height: 430px;
}

Hire Developer Team

      <input type="checkbox" class="add-lists" id="team-lists" hidden>
      CB

    Android App Developers
    iOS App Developers
    Flutter App Developers

So for your specific use-case, if :has() is not yet an option, you'll have to resort to JavaScript:

document
  .getElementById('team-lists')
  .addEventListener('change', function(event) {
    document.querySelector('.team-lists').hidden = !this.checked;
  });
.team-lists:not([hidden]) {
  display: flex;
  height: 430px;
}

Hire Developer Team

      <input type="checkbox" class="add-lists" id="team-lists" hidden>
      CB

    Android App Developers
    iOS App Developers
    Flutter App Developers

A: You can target an input tag like this :
const input = document.querySelector("input[type=checkbox]");

const input = document.querySelector("input[type=checkbox]");
console.log(input);
input[type="checkbox"]:checked .team-lists {
  display: flex;
  height: 430px;
}

Hire Developer Team

      <input type="checkbox" class="add-lists" id="team-lists" hidden>

    Android App Developers
    iOS App Developers
    Flutter App Developers


text:
Q: How to log from Javascript Module in Firefox extension I'm modifying a Firefox extension that has been written by someone else, and I'm not very experienced with Javascript and Firefox, so my question is probably fairly simple.
I have a lot of code in a Javascript Module (.jsm file), and I want to produce some outputs form this module to help with debugging. I can't seem to use javascript alerts (alert("blah");) or log to the javascript console (console.log("blah");) as both of these give errors saying that console or alert cannot be found.
Is there any way to produce this sort of debugging output from code running in a Javascript Module? All I want is simple text output to help with my development/debugging process.

A: There are two common options:

*

*Use dump(), the output will be printed to OS console (on Windows you need to run Firefox with -console command line option to see it).

*Use Component.utils.reportError, the output will be printed to Error Console - use Ctrl-Shift-J to open it.


text:
Q: backbone method in java trees I'm trying to write a vine method/backbone method in java but it doesn't seem like I'm doing it correctly because I got a run time error.
Here is what I did so far:
public void vine() {
  class<T> p = new class<T>(), tmp, prev;
 tmp = root;
 while(tmp != null)
 {
  if( tmp.left != null )
   {
     prev = tmp.right;
    tmp.right = prev.left;
      prev.left = tmp;
   tmp = tmp;
  }
  else
  {
    tmp = tmp.right;
}

}
 }

the run time error seems to be at this line:   tmp.right = prev.left;
Can someone help?

A: Probably tmp.right is null at
prev = tmp.right;

Then you'll get a NPE on
tmp.right = prev.left;

Your code's missing what "root" actually is.


text:
Q: Why wicket maven archetype isn't web? I have a puzzle
I just figured out that when I was creating a maven project from wicket archetype the resulting project was not a web project. I tried everything I could: set the project to web module facet, add quicken nature. However the project didnt run on eclipse tomcat instance. I don't know what's happening cause a couple days before I was able to create wicket projects this way. I also tried removing ~/.m2 folder before creating maven project. After I removed it, projects where created with the web environment but when I clicked on run, it doesn't appear the run on server option. Just maven options : build, clean and so on.
I'm using:
Eclipse
Linux mint Lisa
Jdk1.7
Tomcat 7
M2eclipse
Quicken
Maven2
Any information you need just let me know.
Thanks.

A: Sorry for your lost time if you read my post. I'm so dumb that I should quit my career. I had installed jboss tools because I was about to use Hibernate for my project, then I changed to eclipselink jpa. So I decided to remove all jboss tools (This included, jboss maven wtp integration). Maven WTP integraiton is a drug that makes you happy. This, when creating an wicket project makes it runnable in tomcat.
Thus making it runnable to my eclipse tomcat instance. For future developers who want to setup an eclipse wicket project without knowing about maven commands (that's my case). Use this kit:

*

*Eclipse

*Tomcat

*Maven2

*M2e >> Eclipse maven integration

*Maven WTP integration.

Salvation steps: (WTP+MAVEN)

*

*Go to eclipse Options. Windows> PReference

*Open maven tree

*Select Discovery

*Click Open Catalog Button on right side panel.

*m2e wtp integration.

*Enjoy.


text:
Q: Fix CSV file with new lines I ran a query on a MS SQL database using SQL Server Management Studio, and some the fields contained new lines.  I selected to save the result as a csv, and apparently MS SQL isn't smart enough to give me a correctly formatted CSV file.
Some of these fields with new lines are wrapped in quotes, but some aren't, I'm not sure why (it seems to quote fields if they contain more than one new line, but not if they only contain one new line, thanks Microsoft, that's useful).
When I try to open this CSV in Excel, some of the rows are wrong because of the new lines, it thinks that one row is two rows.
How can I fix this?
I was thinking I could use a regex.  Maybe something like:
/,[^,]*\n[^,]*,/

Problem with this is it matches the last element of one line and the 1st of the next line.
Here is an example csv that demonstrates the issue:
field a,field b,field c,field d,field e
1,2,3,4,5
test,computer,I like
pie,4,8
123,456,"7

8

9",10,11
a,b,c,d,e

A: A simple regex replacement won't work, but here's a solution based on preg_replace_callback:
function add_quotes($matches) {
    return preg_replace('~(?<=^|,)(?>[^,"\r\n]+\r?\n[^,]*)(?=,|$)~',
                        '"$0"',
                        $matches[0]);
}

$row_regex = '~^(?:(?:(?:"[^"*]")+|[^,]*)(?:,|$)){5}$~m';

$result=preg_replace_callback($row_regex, 'add_quotes', $source);

The secret to $row_regex is knowing ahead of time how many columns there are.  It starts at the beginning of a line (^ in multiline mode) and consumes the next five things that look like fields.  It's not as efficient as I'd like, because it always overshoots on the last column, consuming the "real" line separator and the first field of the next row before backtracking to the end of the line.  If your documents are very large, that might be a problem.
If you don't know in advance how many columns there are, you can discover that by matching just the first row and counting the matches.  Of course, that assumes the row doesn't contain any of the funky fields that caused the problem.  If the first row contains column headers you shouldn't have to worry about that, or about legitimate quoted fields either.  Here's how I did it:
preg_match_all('~\G,?[^,\r\n]++~', $source, $cols);

$row_regex = '~^(?:(?:(?:"[^"*]")+|[^,]*)(?:,|$)){' . count($cols[0]) . '}$~m';

Your sample data contains only linefeeds (\n), but I've allowed for DOS-style \r\n as well.  (Since the file is generated by a Microsoft product, I won't worry about the older-Mac style CR-only separator.)
See an online demo

A: If you want a java programmatic solution, open the file using the OpenCSV library. If it is a manual operation, then open the file in a text editor such as Vim and run a replace command. If it is a batch operation, you can use a perl command to cleanup the CRLFs.


text:
Q: Which is the correct option: "a jungle covered in snow" or "a jungle covered with snow"?
Possible Duplicate:
"Covered with" vs "covered in" vs "covered by"

Which is the correct option: "a jungle covered in snow" or "a jungle covered with snow"? If both are possible what is the difference in meaning?

A: There's little difference in meaning, but each sees the scene from a slightly different aspect. Covered by snow emphasises the fact that it was snow that covered the jungle, while covered in snow describes the result of what the snow did.


text:
Q: SQL adding data into 1 row using while loop I need to get data into the same row in SQL, I am using a while loop. This might not be the right option. What I need to do is get all the data into one row. The code I have is adding a new row through each iteration. So first row must have data in column 1 through 5 not in a new row (see pic for how it is adding data now)
$length = count($row);
$i = 1
$j=1;
while ($i <= $length ){

$sql1="insert into Anser ([$i]) values ($j) ";
$stmt1 = sqlsrv_query($conn, $sql1);
if($stmt1 === false){
  die( print_r(sqlsrv_errors(), true));
}
  $i++;
  $j++;
}

A: This expression:
insert into Anser ([$i]) values ($j)

Inserts one row into the table, for each column.  That is why you are getting multiple rows.  What you want is to specify all columns at the same time:
insert into Answer([1], [2], [3], [4], [5])
     values (1, 2, 3, 4, 5);

Note that if when you construct the values clause, you should be using parameters rather than munging the query string with literal values.  This has multiple benefits:

*

*It protects against SQL injection attacks.

*It prevents syntax errors.

*It allows the query to be compiled only once, which can be a benefit if there are large numbers of inserts.


text:
Q: swift adding zoom to container view I have a page view controller embedded inside a container view in order to swipe between images. But now I am trying to add a touch that will make the image go full screen "lightbox" with zoom available and also swipe through the images while in full screen mode.
I can get it to work, and messing around with auto layout seems to be much work consider I have a lot of other stuff in that VC.
So does anyone know a good image slider from github written in swift? - without the need of cocopods.
thanks!

A: It's easy enough to write one yourself. In full-screen mode, use another UIPageViewController, because it already has the swipe left & right support built in.


text:
Q: Route name across api end points We have below two end points, having their respective Organization and Space
1) Dev environment:
a.b.c.org.cloud
2) Proof of Concept environment(POC): a.b.c.poc.io

There is an app(my-cool-app) with route name my-cool-app.a.b.c.poc.io running in POC environment.
Due to code smell issue in this app,  route name is decided by app source code(hard coded) but not through manifest.yml of cf push. This lead to same route name my-cool-app.a.b.c.poc.io for  my-cool-app in Dev environment.

1) Can app have same route name my-cool-app.a.b.c.poc.io  in dev environment(a.b.c.org.cloud)? Because we see this error org.cloudfoundry.client.v2.ClientV2Exception: CF-InvalidRelation(1002): The app cannot be mapped to this route because the route is not in this space. Apps must be mapped to routes in the same space. after cf push
2)
Does Dev and POC environment have same cloud controller database(CCDB)? Because CCDB maintains binding of app name with routename

A:
1) Can app have same route name my-cool-app.a.b.c.poc.io in dev environment(a.b.c.org.cloud)?

It depends on what you mean by "dev" and "poc" environments. If they are totally separate foundations, then yes. It should work. You just use DNS to control where actual traffic is routed.
If they are sharing the same cloud controller, like you have a "dev" and "poc" org, then it works but with restrictions. You can map the same route to two different apps, but they have to be in the same space. That's what this error is saying.

The app cannot be mapped to this route because the route is not in this space. Apps must be mapped to routes in the same space.

If you map the same route to two different apps, what you're effectively doing is splitting traffic across the two apps 50/50. If Cloud Controller were to allow this across orgs & spaces then you could have someone in a different org & space that is able to divert traffic from your app to another app, potentially malicious app, which would be a big security problem. Given this, Cloud Controller prevents that from being allowed.

2) Does Dev and POC environment have same cloud controller database(CCDB)? Because CCDB maintains binding of app name with routename

It sounds like your environments do, but that's not a strict requirement. You could have two totally separate foundations, one for Dev and one for POC, which do not share anything.


text:
Q: translate() takes exactly one argument (2 given) in python error import os
import re

def rename_files():
    # get the files from dir
    file_list=os.listdir(r"C:\OOP\prank")
    print(file_list)
    saved_path=os.getcwd()
    print("current working directory"+saved_path)
    os.chdir(r"C:\OOP\prank")
    #rename the files
    for file_name in file_list:
        print("old name-"+file_name)
        #print("new name-"+file_name.strip("0123456789"))
        os.rename(file_name,file_name.translate(None,"0123456789"))
        os.chdir(saved_path)

rename_files()

Here error is showing due to translate line ...help me what to do next ..I am using translate to remove the digit from filename.
Traceback (most recent call last):
    File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 17, in <module>
rename_files()
      File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 15, in rename_files
     os.rename(file_name,file_name.translate(None,"0123456789"))
     TypeError: translate() takes exactly one argument (2 given)

A: Higher versions in Python use this :
eg: oldname= "delhi123"
remove="1234567890"
table=str.maketrans("","",remove)
oldname.translate(table)

Overall solution for your query:
import os

def rename_file_names():
    file_list=os.listdir(r"C:\Users\welcome\Downloads\Compressed\prank")
    print (file_list)
    saved_path=os.getcwd()
    print("current working direcorty is"+saved_path)
    os.chdir(r"C:\Users\welcome\Downloads\Compressed\prank")
    remove="123456789"
    table=str.maketrans("","",remove)
    for file_name in file_list:
        os.rename(file_name,file_name.translate(table))

rename_file_names()

A: Change os.rename(file_name,file_name.translate(None,"0123456789"))
to     os.rename(file_name,file_name.translate(str.maketrans('','',"0123456789")))
and it will work.

A: str.translate requires a dict that maps unicode ordinals to other unicode oridinals (or None if you want to remove the character). You can create it like so:
old_string = "file52.txt"
to_remove = "0123456789"
table = {ord(char): None for char in to_remove}
new_string = old_string.translate(table)
assert new_string == "file.txt"

However, there is simpler way of making a table though, by using the str.maketrans function. It can take a variety of arguments, but you want the three arg form. We ignore the first two args as they are for mapping characters to other characters. The third arg is characters you wish to remove.
old_string = "file52.txt"
to_remove = "0123456789"
table = str.maketrans("", "", to_remove)
new_string = old_string.translate(table)
assert new_string == "file.txt"

A: If all you are looking to accomplish is to do the same thing you were doing in Python 2 in Python 3, here is what I was doing in Python 2.0 to throw away punctuation and numbers:
text = text.translate(None, string.punctuation)
text = text.translate(None, '1234567890')

Here is my Python 3.0 equivalent:
text = text.translate(str.maketrans('','',string.punctuation))
text = text.translate(str.maketrans('','','1234567890'))

Basically it says 'translate nothing to nothing' (first two parameters) and translate any punctuation or numbers to None (i.e. remove them).

A: import os

def rename_files():
    #1 get file names from folder
    list_files = os.listdir(r"C:\Personal\Python\prank")
    print(list_files)
    saved_path = os.getcwd()
    print(os.getcwd())
    os.chdir(r"C:\Personal\Python\prank\")

    #2 for each file, rename filename
    remove = "0123456789"
    table = str.maketrans("","",remove)
    for file_name in list_files:
        os.rename(file_name, file_name.translate(table))

    os.chdir(saved_path)

rename_files()

A: Instead of translate why not just do this:
os.rename(file_name,''.join([i for i in file_name if not i.isdigit()]))

A: if you use the python 3.X,try this:file_name.lstrip()
    os.rename(file_name,file_name.lstrip(None,"0123456789"))

A: This function
str.translate(table[, deletechars])

is only available upto python 2.7. If you are using higher version you can use following function which is quiet similar and available in higher version of python.
bytes.translate(table[, delete=b''])

It return a copy of the bytes object where all bytes occurring in the optional argument delete are removed
So In your code, change this line of code
os.rename(file_name,file_name.translate(None,"0123456789"))

with
file_name_bytes = str.encode(file_name)
os.rename(file_name, file_name_bytes.translate(None, b"0123456789")

A: Run the file with the command python secret_message.py . It works.
here is the entire code:
import os

def rename_files():
    #(1)get file names from a folder
    file_list = os.listdir(r"/Users/archananagaraja/Desktop/AN_Personal/Udacity_Python/prank")
    print(file_list)
    current_dir = os.getcwd()
    print("My current directory is: "+current_dir)
    os.chdir(r"/Users/archananagaraja/Desktop/AN_Personal/Udacity_Python/prank")
    #(2) for each file rename filename
    for file_name in file_list:
        os.rename(file_name, file_name.translate(None, "0123456789"))
rename_files()

A: instead of using function getcwd() it just works
import os

def rename_files():
    #(1) get file names from a folder

    file_list = os.listdir(r"D:\prank\prank")
    os.chdir(r"D:\prank\prank")
    #remove any numbers
    remove = "0123456789"
    chart = str.maketrans("","", remove)
    # files name renamed
    for file_name in file_list:
        os.rename(file_name, file_name.translate(chart))
        print(file_name)

A: Try this:
"".join(c for c in "123hello.jpg" if c not in "0123456789")

list comprehensions:
https://medium.com/swlh/list-comprehensions-in-python-3-for-beginners-8c2b18966d93


text:
Q: Unexpected action distribution for custom RL environment I am working on creating a custom environment and training a RL agent on it.
I am using stable-baselines because it seems to implement all the latest RL algorithms, and seems to be as close to "plug and play" as possible (I'd like to concentrate on creating the environment and reward function rather that the implementation details of the model itself)
My environment has an action space of size 127, and interprets it as a one-hot vector: Taking the index of the highest value in the vector as an input value.
For debugging, I create a bar chart, showing how many times each value has been "called"
Before training, I would expect the graph to show a roughly uniform distribution of "events":

but instead the "events" in the lower end of the action spec are massively more likely than the others:

I have created a colab to explain and reproduce the issue
I asked this question in a github issue, but they recommended I post the question here

A: The model.predict(obs) clips each action to the range [-1, 1] (because that is how you defined your action space).
Your array of action values thus looks something like
print(action)
# [-0.2476,  0.7068,  1.,          -1.,           1.,           1.,
#   0.1005,  -0.937,   -1. , ...]

That is, all actions that were larger than 1 are truncated / clipped to 1, and thus there are multiple maximum actions.
In your environment you compute the numpy argmax pitch = np.argmax(action), which returns the index of the first maximum value rather than a randomly chosen one (if there are multiple maxima).
You could choose a "random argmax" as follows.
max_indeces = np.where(action == action.max())[0]
any_argmax = np.random.choice(max_indeces)

I changed your env accordingly here.