text:
Q: OSX Server _www access to samba mounted directory I am having issues automatically mounting a smb share on our osx 10.6 server so that _www has the permissions to read the presented files.
If I mount using the graphical auto-mount utility supplied in osx, the operating system does not allow access to the files as _www
I have been able to get around this by issuing:
sudo -u _www mount_smbfs //sambauser:password@<ip addr>/ShareName /tmp/my_mnt
But this obveously requires a superuser password to be entered, I could easily do this on a Linux box in fstab by putting //host/share /path/to/mount/point smbfs username=remotename,password=remotepass,uid=_www 0 0 in fstab but seeing as osx has all-but done away with fstab I am unable to do so.
Is there something obveous I'm missing here?
Thanks
Stewart

A: This answer is stolen directly from http://hints.macworld.com/article.php?story=20100203124656707

*

*Add a new line to /etc/auto_master
 /-     auto_smb

*Put this in /etc/auto_smb
 /path/to/mountpoint -fstype=smbfs ://user:password@server/share

*Create the mountpoint
 mkdir /path/to/mountpoint
 chmod 755 /path/to/mountpoint

*Restart


text:
Q: Mirror iPad Pro screen to my Windows 10 PC via USB I need to mirror my iPad screen to my windows 10 computer without wifi (via USB). Is there a modern software solution that does not involve very low framerate or high latency ?

A: The good folks at Air Squirrels have the software that's the closest to your request. I have used them in the past, was delighted by the previous version of their Reflector app and it looks like they have a trial version so you can be sure of the value before buying it.

*

*https://www.airsquirrels.com/reflector/try
Since you require USB, be sure your non WiFi networking works before you invest if that's the key factor for you. Reverse tethering works for Macs out of the box so hopefully this is close enough for windows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extract exponents from a PDF (Python PDFminer)? I have mathematical exponents followed by words in a PDF (like footnotes, but they are before the word). I would like to extract them without having to use XML. So far I'm using PDFminer, which gives a good rendition of the text but the exponent is rendered as a normal number. It is essential to me to have that exponent, though.
The code I'm using is:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
import re

def convert_pdf_to_txt(path):

    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):

        interpreter.process_page(page)

    global text
    text = retstr.getvalue()
    #return text

    fp.close()
    device.close()
    retstr.close()
#print(convert_pdf_to_txt('fel_split.pdf'))

Either there is a method I don't know of to extract apices too, or I would have to transform them from the pdf to Python through the library into something else, not just a number. I don't know how to proceed.


text:
Q: Trying to send email using aws ses and attach zip file as attachment I am trying to use a zip file stored in aws s3 as an attachment in an email sent using aws ses.
The idea i have is GET the zipfile from s3 read it and pass to boto3 send_raw_email() api.
zip_response = s3_client.get_object(
    Bucket='bucket name',
    Key='access_key.zip'
    )
zip_streambody = zip_response['Body'].read()

#adding the attachment for send_raw_email() operation
'Define attachment and encode using mime app'
att = MIMEApplication(open(ATTACHMENT, 'rb').read())

'header to tell email client to treat it as attachment and give it a name'
att.add_header(
    'Content-Disposition',
    'attachment',
    filename=os.path.basename(ATTACHMENT)
)

When i do this i get a "ValueError: embedded null byte" in the MIMEApplication line. Why is this? How to fix it?
Any help is appreciated.

A: Solved using the procedure mentioned above. Code example:
#main module
zip_response = s3_client.get_object(
    Bucket='bucket name',
    Key='access_key.zip'
    )
zip_streambody = zip_response['Body'].read()
call_function_in_module2(zip_streambody)

#module 2

call_function_in_module2(x)
#write the streambody beginning with correct zip headers, save zip as follows,
#give path to lambda temp storage, /tmp/zip_name.zip. Save path to var, ATTACHMENT
with open('/tmp/my_key.zip', 'wb') as file:
        file.write(x)

#adding the attachment for send_raw_email() operation
'Define attachment and encode using mime app'
att = MIMEApplication(open(ATTACHMENT, 'rb').read())

'header to tell email client to treat it as attachment and give it a name'
att.add_header(
    'Content-Disposition',
    'attachment',
    filename=os.path.basename(ATTACHMENT)
)

send_raw_email()

doc for ses send_raw_email() code example:
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html#send-email-raw-headers


text:
Q: Why is this Xamarin.Forms autowire binding connecting my Command but not my Entry? I have this XAML
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
...
    x:Class="MyProj.LoginPageView"
    local:ViewModelLocator.AutoWireViewModel="True">
...cut for brevity...
        <Entry MinimumWidthRequest="60"  Grid.Row="0" Grid.Column="2"  VerticalOptions="Center" Text="{Binding Username, Mode=TwoWay}"/>
        <Entry Grid.Row="1" Grid.Column="2"  VerticalOptions="Center"  Text="{Binding Password, Mode=TwoWay}"/>
        <Button Text="Login" Command="{Binding LoginCommand}"/>
        <Button Text="Register" Command="{Binding RegisterCommand}"/>

Attached using autowiring to this viewmodel:
public class LoginPageViewModel: BindableObject
    {
        public ICommand LoginCommand { get; set; }
        public ICommand RegisterCommand { get; set; }

        private string username;
        private string password;

        public string Username { get { return username; } set { username = value; OnPropertyChanged("Username"); } }
        public string Password { get { return password; } set { password = value; OnPropertyChanged("Password"); } }

        public LoginPageViewModel()
        {
            LoginCommand = new Command(() =>
              Login());
            RegisterCommand = new Command(() =>
            Register());
        }

        private void Login()
        {

        }

        private void Register()
        {
            Console.WriteLine("sdfsd");
        }
    }

The command bindings are working fine and the Register and Login methods get called when I click the button. In the autowiring the binding context of the view is set to the viewmodel as follows:
        static ViewModelLocator()
        {

            _container = new TinyIoCContainer();

            //register viewmodels
            _container.Register<LoginPageViewModel>();
        }
        public static readonly BindableProperty AutoWireViewModelProperty =
    BindableProperty.CreateAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), default(bool), propertyChanged: OnAutoWireViewModelChanged);

        public static bool GetAutoWireViewModel(BindableObject bindable)
        {
            return (bool)bindable.GetValue(ViewModelLocator.AutoWireViewModelProperty);
        }

        public static void SetAutoWireViewModel(BindableObject bindable, bool value)
        {
            bindable.SetValue(ViewModelLocator.AutoWireViewModelProperty, value);
        }

        private static void OnAutoWireViewModelChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var view = bindable as Element;
            if (view == null)
            {
                return;
            }

            var viewType = view.GetType();
            var viewName = viewType.FullName.Replace(".Views.", ".ViewModels.");
            var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
            var viewModelName = string.Format(
                CultureInfo.InvariantCulture, "{0}Model, {1}", viewName, viewAssemblyName);

            var viewModelType = Type.GetType(viewModelName);
            if (viewModelType == null)
            {
                return;
            }
            var viewModel = _container.Resolve(viewModelType);
            view.BindingContext = viewModel;
        }

When I click register in debug mode the register method gets called which means the command binding has been connected but the value I put in the Entry fields for username and password aren't connected to the corresponding properties on the VM and the properties just have null values.


text:
Q: Calculating areas in continuous raster of flood map? I generated a flood hazard map (raster) of a certain area using ArcGIS 10.5 and classify the result into

*

*low    0.1 ÷ 0.5

*medium 0.5 ÷ 1.5

*high   > 1.5
After that, I overlay a Land Use map (polygon) in order to identify affected areas. Now, I want to count the area occupied by each class with respect to the land use map. Can anyone suggest methods for that?

A: You could convert your flood hazard raster to polygon using the "Raster to Polygon" tool. You can then interest this with the Land Use vector file and calculate the areas of each using the "Calculate Geometry" function in the attribute table.

A: What you need to use is Tabulate Area tool. In fact, this a direct application of Tabulate area tool, but it requires Spatial Analyst extension:

*

*in_zone_data: Use the land use as input zone feature,

*zone_field: choose the field that defines the land use

*in_class_data: use the flood reclass raster data that will have their area summarized within each land use zone.

*class_field: The field that holds the flood class values.

The output will be a table that gives the total area of each flood class within each land use zone in meter assuming your data are in UTM projection.


text:
Q: change header background based on average viewport color I'm looking for a way to change the background color, or/and opacity of a header element in a website based on the average color of the actual viewport. If the user is scrolling over a slider, or a colored fullwidth element, the header should be transparent or lighten up. If he's scrolling over a mostly white page with black text, the header background should darken.
I already saw, that there's a way to get the average color of a html5 canvas element, but that's not working with older browsers.
To simplify it: Would it also be possible to just recognize if the actual background-color behind the header is lighter or darker than a specified value and then lighten or darken the header background if necessary?


text:
Q: Data not loading in master textbox after Devexpress gridview events Hi i am new to devexpress gridview. i have a textbox(TotalDebit) outside grid and i have a devex gridview in which i am inserting,updating data. In my event handler when i insert new row in gridview i want to calculate the total debit and show in the master textbox outside gridview. i have calculated the total debit but the problem is it is not showing in the textbox outside gridview. Here is the code:
public void grvDetail_RowInserting(objectsender,DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
if (DetailTable.Rows.Count > 0)
           for (int i = 0; i < DetailTable.Rows.Count; i++)
           {

               if (DetailTable.Rows[i]["FlagDC"].ToString() == "D")
                   TotalDebit += Convert.ToDouble(DetailTable.Rows[i]["Amount"].ToString());
               else
                   TotalCredit += Convert.ToDouble(DetailTable.Rows[i]["Amount"].ToString());

           }

       txtDebit.Text = TotalDebit.ToString(); //textbox outside gridview
       txtCredit.Text = TotalCredit.ToString(); //textbox outside gridview

          }

A: See the Why is it impossible to update external control data during a callback to another control KB for explanation.


text:
Q: quarkus dev mode for CLI, how to restart app I just created a sample Quarkus CLI app. When I run it in dev mode, pressing [enter] does not restart the application.
Steps to reproduce:
I am using the quarkus CLI, on macOS Big Sur, default Terminal app. I generate a default cli app with the following command:
quarkus create cli --group-id=test --artifact-id=test --maven --java --code

Then, once I am inside the test folder, I run:
quarkus dev

The example code runs and dev mode stays waiting for changes, but if I update the sample code and press [enter] on the terminal as described in the quarkus guide for CLI apps, the app is not rerun.
I also tried maven directly as suggested on the guide:
mvn compile quarkus:dev

But the result is the same.
The example generated is very simple, and uses Quarkus 2.0.1 with the picocli extension. Works fine when compiled and run standalone.
Does anyone know what am I missing?
Thanks for any suggestions.

A: I think what you are seeing is a bug in 2.0 cli where create cli does not create a cli but just the standard app. Thus it won't reload until you hit localhost:8080.
it will be fixed in next version. sorry for inconvenience.
In the mean time you can use https://quarkus.io/guides/command-mode-reference which explains the minimal code and dependencies needed for a Quarkus cli.

A: Does your project have any tests? The picocli project created by the cli doesn't by default (yet?).
https://github.com/quarkusio/quarkus/pull/18700 should fix your issue (behavior of dev mode for projects without tests).


text:
Q: extra empty space/gap in webpage on large screen redulation in large display/screen there is gap on webpage at both sides.
how can I remove these extra empty space?
here's a screenshot. – https://snipboard.io/sTDY89.jpg
website url - https://mac.mbosuk.com


text:
Q: Kriging for unevenly spaced points using R? I started to read about Kriging and the implementation into R. In all the tutorials I found, a (regular) grid is used to do ordinary or universal kriging. My situation is as follows, I try to interpolate house prices, which of course do not lie on a regular grid. For all houses I have a set of covariates including features such as number of rooms and space. For a subset (approx. 20%), I have the corresponding house price. When doing Regression-kriging in estimating price ~ rooms + space, I cannot provide the data for the regular grid points.
Is there a way of using unevenly spaced prediction points or how is this best tackled?

A: Have you read the help for gstat::krige:
newdata: data frame or Spatial object with prediction/simulation
          locations; should contain attribute columns with the
          independent variables (if present) and (if locations is a
          formula) the coordinates with names as defined in 'locations'

You create a newdata data frame with the locations and attributes of your prediction locations and you get back predictions at those locations.


text:
Q: Crear OnItemClickListener dentro de un Listwiev personalizado con Json Necesito controlar la pulsación sobre el Listview personalizado para que realice una operación dependiendo el que se pulsa.
Os dejo el código de la pagina principal.
public class Mostrar_Productos extends Anadir_Productos_Principal {
    SmartImageView smartImageView;
    TextView txvnombre_listado;
    String nombrelistado;
    String imagenlistado;
    ArrayList<String> producto_array = new ArrayList<String>();
    ArrayList<String> pendiente_array = new ArrayList<String>();
    ListView list;
    ListadoProductosAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mostrar_productos);
        RecibirDatos();
        InsertarLogotipoyNombre();
        list = (ListView) findViewById(R.id.lv_productos);
        new TheTask().execute();
    }

    class TheTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            String str = null;

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://XXXXXXXXXX/XXXXX/XXXXXXXXXXXXX.php");
                //Configuramos los parametos que vaos a enviar con la peticion HTTP POST
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                pairs.add(new BasicNameValuePair("supermercado", nombrelistado));
                httppost.setEntity(new UrlEncodedFormEntity(pairs));
                HttpResponse response = httpclient.execute(httppost);
                str = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return str;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            String response = result.toString();
            try {
                JSONArray new_array = new JSONArray(response);

                for (int i = 0, count = new_array.length(); i < count; i++) {
                    try {
                        JSONObject jsonObject = new_array.getJSONObject(i);
                        producto_array.add(jsonObject.getString("nombre_producto").toString());
                        pendiente_array.add(jsonObject.getString("pendiente").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                adapter = new ListadoProductosAdapter(Mostrar_Productos.this, producto_array, pendiente_array);
                list.setAdapter(adapter);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                // tv.setText("error2");
            }
        }
    }

    private void InsertarLogotipoyNombre() {
        smartImageView =(SmartImageView)findViewById(R.id.imagenlogo_listado);
        txvnombre_listado = (TextView)findViewById(R.id.tv_Nombre_listado);
        String urlfinal = "http://XXXXXXXXXXXXX/"+imagenlistado;
        Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
        smartImageView.setImageUrl(urlfinal, rect);
        txvnombre_listado.setText(nombrelistado.toString());
    }

    private void RecibirDatos() {
        Bundle extras = getIntent().getExtras();
        String nombre = extras.getString("nombre");
        String imagen = extras.getString("imagen");
        imagenlistado = imagen;
        nombrelistado = nombre;
    }
}

y aquí os dejo el código del Adaptador.
public class ListadoProductosAdapter extends BaseAdapter {
    private Activity activity;
    private static ArrayList producto, pendiente;
    private static LayoutInflater inflater = null;

    public ListadoProductosAdapter(Activity a, ArrayList b, ArrayList bod) {
        activity = a;
        this.producto = b;
        this.pendiente = bod;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return producto.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.listado_productos, null);

        final CheckBox title2 =(CheckBox)vi.findViewById(R.id.ckb_apuntado);
        String product = producto.get(position).toString();
        String pendient = pendiente.get(position).toString();

        title2.setText(product);

        Boolean check = null;
        if (pendient.equals("SI")){
            check = true;
        } if (pendient.equals("NO")) {
            check = false;
        }

        title2.setChecked(check);
        return vi;
    }
}

Llevo ya varios días buscando una solución, pero solo encuentro si los datos se cargan através de un array creado manualmente y yo los datos los traigo de un servidor remoto.
Espero vuestra ayuda y si necesitáis alguna información mas decirlo. Gracias.

A: Esta sería una forma:
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mostrar_productos);
        RecibirDatos();
        InsertarLogotipoyNombre();

       list = (ListView) findViewById(R.id.lv_productos);

       //configura listener.
       list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          //Object listItem = list.getItemAtPosition(position);
        Toast.makeText(getAplicationContext, "Click en la posición "  + position, Toast.LENGTH_SHORT).show();
       }
     });

    new TheTask().execute();
  }

Regularmente se usa:

setOnItemClickListener Se usa cuando un das click a un elemento
  del adapter

pero también puedes hacer uso de :

OnItemLongClickListener Se usa cuando un das click a un elemento
  del adapter por un periodo prolongado.
setOnItemSelectedListener Se usa cuando un elemento del adapter
  es seleccionado.

A: Necesitas implementar en tu listView el método setOnItemClickListener(OnItemClickListener). Puedes hacer directamente:
listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
            String value = (String)adapter.getItemAtPosition(position);
            Toast.makeText(TuActivity.this, value, Toast.LENGTH_SHORT).show();
    }
});

Adicional a ello; tu código tiene detalles que sería bueno corregirlos.

*

*Los nombres de clases en Java se suelen escribir utilizando CamelCase, correcto AnadirProductosPrincipal incorrecto Anadir_Productos_Principal

*Los métodos y variables de forma similar, pero con la primera letra minúscula, ejemplo recibirDatos
De esa manera mantenemos la sintaxis mundial y nos comunicamos mejor.


text:
Q: How can I specify an interval number using regex? I have to check if a variable (php, preg_match) is from 1988 and 2011 using regex; I know how to do it with normal if/else, but I'd like to use regex for this!

A: Sometimes, regular expressions are not the only answer:
if (preg_match('/^\d{4}$/', $input) && $input >= 1988 && $input <= 2011) {
}

A: Wouldn't be that easy, as regex is meant to match character by character. You could use something like this (probably wouldn't be a good idea).
/(198[89]|199\d|200\d|201[01])/

A: Why do you want to do this using regex?
One solution could be something along the lines of (?:198[8-9]|199[0-9]|200[0-9]|201[0-1]).

A: Use preg_replace_callback :
<?php
preg_replace_callback('%([0-9]{4})%', function($match) {
    $number = $match[1];
    if($number < 1988 || $number > 2011) return; /* Discard the match */
    /* Return the replacement here */
}, $input);

This is in my opinion the most flexible solution.

A: Try this:
/^[12][90][8901][8901]\z/


text:
Q: Qt - reading from a text file I have a table view with three columns; I have just passed to write into text file using this code
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::WriteOnly)) {
    QMessageBox::information(0,"error",file.errorString());
}
QString dd;

for(int row=0; row < model->rowCount(); row++) {
     dd = model->item(row,0)->text() +  ","
                 + model->item(row,1)->text() +  ","
                 + model->item(row,2)->text();

     QTextStream out(&file);
     out << dd << endl;
 }

But I'm not succeed to read the same file again, I tried this code but I don't know where is the problem in it
QFile file("/home/hamad/lesson11.txt");
QTextStream in(&file);
QString line = in.readLine();
while(!in.atEnd()) {

    QStringList  fields = line.split(",");

    model->appendRow(fields);

}

Any help please ?

A: You have to replace string line
QString line = in.readLine();

into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();
    QStringList fields = line.split(",");
    model->appendRow(fields);
}

file.close();


text:
Q: How to authentication for ASP.NET Core Web API 6 by JWT token generated by Spring Security (Spring Boot 2.7.0)? I have file JwtTokenUtil.java
package com.example.multitenant.util;

import com.example.multitenant.constant.JWTConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.function.Function;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -2550185165626007488L;

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public String getAudienceFromToken(String token) {
        return getClaimFromToken(token, Claims::getAudience);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(JWTConstants.SIGNING_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public String generateToken(String userName, String tenantOrClientId) {
        return doGenerateToken(userName, tenantOrClientId);
    }

    private String doGenerateToken(String subject, String tenantOrClientId) {
        Claims claims = Jwts.claims().setSubject(subject).setAudience(tenantOrClientId);
        claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
        return Jwts.builder()
                .setClaims(claims)
                .setIssuer("system")
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWTConstants.ACCESS_TOKEN_VALIDITY_SECONDS * 1000))
                .signWith(SignatureAlgorithm.HS256, JWTConstants.SIGNING_KEY)
                .compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }

}

I have file
package com.example.multitenant.security;

import com.example.multitenant.constant.JWTConstants;
import com.example.multitenant.mastertenant.config.DBContextHolder;
import com.example.multitenant.mastertenant.entity.MasterTenant;
import com.example.multitenant.mastertenant.service.MasterTenantService;
import com.example.multitenant.util.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    MasterTenantService masterTenantService;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String header = httpServletRequest.getHeader(JWTConstants.HEADER_STRING);
        String username = null;
        String audience = null; //tenantOrClientId
        String authToken = null;
        if (header != null && header.startsWith(JWTConstants.TOKEN_PREFIX)) {
            authToken = header.replace(JWTConstants.TOKEN_PREFIX, "");
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
                audience = jwtTokenUtil.getAudienceFromToken(authToken);
                MasterTenant masterTenant = masterTenantService.findByClientId(Integer.valueOf(audience));
                if (null == masterTenant) {
                    logger.error("An error during getting tenant name");
                    throw new BadCredentialsException("Invalid tenant and user.");
                }
                DBContextHolder.setCurrentDb(masterTenant.getDbName());
            } catch (IllegalArgumentException ex) {
                logger.error("An error during getting username from token", ex);
            } catch (ExpiredJwtException ex) {
                logger.warn("The token is expired and not valid anymore", ex);
            } catch (SignatureException ex) {
                logger.error("Authentication Failed. Username or Password not valid.", ex);
            }
        } else {
            logger.warn("Couldn't find bearer string, will ignore the header");
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                logger.info("authenticated user " + username + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}

JWT token generate by Spring Security (for many RESTful end-points what written by Spring RESTful). Sample working token:
https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkb25odXZ5IiwiYXVkIjoiMSIsInNjb3BlcyI6W3siYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiaXNzIjoic3lzdGVtIiwiaWF0IjoxNjU1MzA0NDczLCJleHAiOjE2NTUzMjI0NzN9.9X3k1VJJOp937X6LJiWuizrZyBP8nROAYlcwiKriXEE
I need call web service to generate PDF invoice from ASP.NET Core Web API 6. Of course, I need validate perimssion/security by JWT token. How to authentication for ASP.NET Core Web API 6 by JWT token generated by Spring Security (Spring Boot 2.7.0)?
I want call ASP.NET Core Web API 6 APIs (with commercial .NET component back-end) directly without call via Spring web-service (with free and open source Java component back-end).
I think this is a tough problem when interface/integration between Java Spring Boot 2.7.0 and ASP.NET Web API 6 and hope you give me a working solution.
Some thing like this validate .Net JWT token to call Java APIs but in reverse direction.

A: For example I have a .net 6 api project, I installed Microsoft.AspNetCore.Authentication.JwtBearer package for JwtAuthentication.
In program.cs, I add the configuration like this, adding this configuration will make your api validate the token and check token if has correct issuer/autdience, if expired, more details can be seen in new TokenValidationParameters method:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = TokenHelper.Issuer,
                ValidAudience = TokenHelper.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(TokenHelper.Secret))
            };

        });
builder.Services.AddAuthorization();
...
...
...
app.UseAuthentication();
app.UseAuthorization();

And in my api controller, I added [Authorize] annotation so that if the input request doesn't contain request header like Authoration: Bearer xxxxxx, api will return 401 unauthorize:
[ApiController]
[Route("Hello")]
public class HelloController : ControllerBase
{
    [Authorize]
    [HttpGet]
    public async Task<string> GetAsync()
    {
        var accessToken = await TokenHelper.GenerateAccessToken("userOne");
        return accessToken;
    }
}

This is the code how I generate access token which is similar with yours by Java, follow this blog, token are the same, na matter generated by java or .net.
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace WebApiNet6
{
    public class TokenHelper
    {
        public const string Issuer = "http://mytest.com";
        public const string Audience = "http://mytest.com";
        public const string Secret = "p0GXO6VuVZLRPef0tyO9jCqK4uZufDa6LP4n8Gj+8hQPB30f94pFiECAnPeMi5N6VT3/uscoGH7+zJrv4AuuPg==";
        public static async Task<string> GenerateAccessToken(string userId)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Convert.FromBase64String(Secret);

            var claimsIdentity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.NameIdentifier, userId)
            });

            var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claimsIdentity,
                Issuer = Issuer,
                Audience = Audience,
                Expires = DateTime.Now.AddMinutes(15),
                SigningCredentials = signingCredentials,

            };
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);

            return await System.Threading.Tasks.Task.Run(() => tokenHandler.WriteToken(securityToken));
        }
    }
}

without token:


text:
Q: AVURLAsset duration of m3u8 video is 0 I'm trying to get duration of a remote video (streamed via http) in m3u8 format. For some videos with large local duration it is unable to get duration of an asset.
I'm currently using KVO to catch .Ready status of AVPlayerItem and then invoke delegate method.
let asset = AVURLAsset(URL: url)
let playerItem = AVPlayerItem(asset: asset!)
let player = AVPlayer(playerItem: playerItem!)

....

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if object as? AVPlayerItem == player?.currentItem {
        if keyPath == "status" {
            guard let status = player?.currentItem?.status
                else { return }

            delegate?.videoViewController(self, statusDidChange: status)
        }
    }
}

But I'm getting CMTime(value: 0, timescale: 0, flags: __C.CMTimeFlags(rawValue: 17), epoch: 0)
I also tried to get duration of the asset using loadValuesAsynchronouslyForKeys method, but this returns the same value.
When the delegate method is invoked the playerItem.asset.playable equals true, but all of following properties return 0:
print(asset?.duration)
print(playerItem?.duration)
print(playerItem?.asset.duration)
print(playerItem?.tracks[0].assetTrack.asset?.duration)


text:
Q: Change direction of a specific column header to RTL Telerik Report Table I have a problem with the direction of a specific column in Telerik Table Group.
With firebug I can find and change the direction of a table from LTR to RTL when I use two languages (Arabic/English).
BUt how can I change the direction of a specific column header and not the entire row or table in telerik Table Group?
Note : I use C# With Telerik Report R3 2017


text:
Q: What great writers have used coordinating conjunctions at the start of sentences? I had a discussion today with a friend over the validity of using (coordinating, correlative) conjunctions like but or and at the start of sentences.
His position was that it breaks a rule of grammar. However, I remembered a post on this site saying that conjunctions at the start of sentences is fine, and that lots of great writers have done that exact thing.
I mentioned this to him, and he challenged me to name an author who did this, and to provide him with examples of such. I found that to my shame I couldn't name even one.
So what famous authors actually have used conjunctions at the start of sentences, and how did they do it?

A: On a hunch I opened The Sound And The Fury by William Faulkner, once, at a random page and saw:

It was a while before the last stroke ceased vibrating. It stayed in the air, more felt than heard, for a long time. Like all the bells that ever rang still ringing in the long dying light-rays and Jesus and Saint Francis talking about his sister. Because if it were just to hell; if that were all of it. Finished. If things just finished themselves. Nobody else there but her and me. If we could just have done something so dreadful that they would have fled hell except us. I have committed incest I said Father it was I it was not Dalton Ames    And when he put Dalton Ames. Dalton Ames. Dalton Ames.

The choice of book wasn't random but I swear to you, I did not try multiple books or multiple pages. First time ;-)
Note that the initial "because" isn't always "grammatically incorrect", but in this case Faulkner uses it to introduce a dangling subordinate clause. There are some other sentence fragments with "if". There isn't actually a period in my edition before the "And", but to the extent that stream-of-consciousness writing can be said to have sentences at all, I think this starts one.
So I'm not sure that "great writers" are necessarily good authorities on style, since they fairly predictably break any "bureaucratic" rule you can think of for effect. In this case, the initial conjunctions are no barrier at all to clear communication (although perhaps the content itself is obscure). Even rules that you'd think are necessary for clear communication can go out of the window, though, to a particular end. The act of breaking a rule is in itself significant, and doesn't necessarily negate the rule's common applicability.
So, while the many examples given in other answers are excellent demonstrations that this particular "rule" is silly, beware arguing from the greatness of the author!

A: Mitch Albom, The Five People You Meet in Heaven, p. 11 paragraph 3:

But back at the Stardust Band Shell with Marguerite....

Mark Twain, The Adventures of Huckleberry Finn, last sentence of Chapter VI:

And how slow and still the time did drag along.

Henry Wadsworth Longfellow, The Song of Hiawatha, Introduction

"And the pleasant watercourses, you could trace them through the valley..."

Shakespeare, Hamlet, Prince of Denmark, Act 1, Scence 1, Horatious starts a speech:

And then it started like a guilty thing.

Also, Paul, in the letter to the Corinthians, on a number of occasions starts a sentence with "and" or "but".
[Yes, I know that the Twain citation is contained within dialog, and that the Longfellow citation is poetry, and the Shakespeare is from a play.]

A: The Oxford Dictionary of Quotations, third edition (1979), has a number of instances, as well.
Hans Christian Andersen, "The Emperor's New Clothes":

'But the Emperor has nothing on at all!' cried a little child.

Matthew Arnold, Culture and Anarchy (1869):

But that vast portion, lastly, of the working-class which, raw and half-developed, has long lain half-hidden amidst its poverty and squalor, and is now issuing from its hiding-place to assert an Englishman's heaven-born privilege of doing as he likes, and is beginning to perplex us by marching where it likes, meeting where it likes, bawling what it likes, breaking what it likes—to this vast residuum we may with great propriety give the name of Populace.

Jane Austen, Northanger Abbey:

'And what are you reading, Miss —?' 'Oh! it is only a novel!' replies the young lady: while she lays down her book with affected indifference or momentary shame.

Francis Bacon, "Of Death":

And therefore death is no such terrible enemy, when a man hath so many attendants about him that can win the combat of him.

Walter Bagehot, The English Constitution (1867):

But of all the nations in the world the English are perhaps the least a nation of pure philosophers.

Isaiah Berlin, Four Essays on on Liberty:

Injustice, poverty, slavery, ignorance—these may be cured by reform or revolution. But men do not live only by fighting evils.

The Bible (King James version):

But of the tree of the knowledge of good and evil, thou shalt not eat of it: for in the day that thou eatest thereof thou shalt surely die.

Thomas Browne, The Garden of Cyrus (1658):

But the quincunx of heaven runs low, and 'tis time to close the five ports of knowledge.

John Bunyan, The Pilgrim's Progress (1678):

Yet my great-grandfather was but a water-man, looking one way, and rowing another: and I got most of my estate by the same occupation.

Edmund Burke, Thoughts on the Present Discontents (1770):

I am not one of those who think that the people are never in the wrong. They have been so, frequently and outrageously, both in other countries and in this. But I do say, that in all disputes between them and their rulers, the presumption is at least upon a par in favour of the people.

Robert Burton, Anatomy of Melancholy:

Tobacco, divine, rare, superexcellent tobacco, which goes far beyond all their panaceas, potable gold, and philosopher's stones, a sovereign remedy to all diseases ... But, as it is commonly abused by most men, which take it as tinkers do ale, 'tis a plague, a mischief, a violent purger of goods, lands, health, hellish, devilish, and damned tobacco, the ruin and overthrow of body and soul.

Bishop Butler, The Analogy of Religion (1756):

But to us, probability is the very guide of life.

Samuel Butler, Note Books:

I believe that more unhappiness comes from this source than from any other—I mean from the attempt to prolong family connection unduly and to make people hang together artificially who would never naturally do so. The mischief among the lower classes is not so great, but among the middle and upper classes it is killing a large number daily. And the old people do not really like it much better than the young.

And that takes us through the letters A and B.

A: Examples from Tolkien's Legendarium
For my own demonstrative examples, I've chosen just one "great writer",  so that some measure of frequency of this phenomenon within a single writer's works can be taken.
Across The Silmarillion, The Hobbit, and The Lord of the Rings, J.R.R. Tolkien began sentences with these seven (potential) conjunctions the indicated number of times each, sorted in descending order of frequency:

Count
Word

2,871
But

1,972
And

731
For

358
So

273
Yet

78
Or

37
Nor

6,320
Total

False Positives
Because those just count sentence-starts, not running the text through a syntactic analyser to determine actual parts of speech, the numbers of at least some are inflated due to false positives.
Although but and so also have some false positives as well,
this is perhaps more true of for than of the others.  This is because for is much more often used as a preposition than as a conjunction. About conjunctive uses of for, the OED has this to say:

The use of for as a conj. has not been found earlier than the 12th c. The older lang. supplied the place of the conj. by locutions in which for prep. governed a neuter demonstrative pronoun followed by a relative particle: for ðon ðe, for ðý ðe, etc. (see for-thon, for-thy). The conjunctional use of for = for ðon ðe may be explained either as an extension of the functions of the prep. to govern a noun-sentence, or as an ellipsis.

In OE. for and fore seem to have been used indiscriminately as preps.; in ME. they were gradually differentiated.

B. conj.

*

*† 1. Introducing the cause of a fact, the statement of which precedes or follows: Because. Cf. A. 21 b. Obs. exc. arch.

*2 a. Introducing the ground or reason for something previously said: Seeing that, since. Cf. Gr. γάρ, L. nam or enim, Fr. car, Ger. denn.

*2 b. Introducing a detailed proof.

For while using for as a conjunction may sound literary or at times even archaic, it surely does occur in the register that Tolkien was writing in.

Corporal Citations
Below I provide three random samples from each set for each of the seven coordinating conjunctions which I tested for, generally one apiece from each of the three words named above:
But

*

*But above this gate, and behind it even to the mountains, he piled the thunderous towers of Thangorodrim, that were made of the ash and slag of his subterranean furnaces, and the vast refuse of his tunnellings.

*

*But after ages alone in the dark Gollum's heart was black, and treachery was in it.

*But against this Gandalf had spoken urgently, because of the evil that dwelt in the valley, where the minds of living men would turn to madness and horror, and because also of the news that Faramir had brought.

And

*

*And all the coasts and seaward regions of the western world suffered great change and ruin in that time; for the seas invaded the lands, and shores foundered, and ancient isles were drowned, and new isles were uplifted; and hills crumbled and rivers were turned into strange courses.

*

*And after all he never had any real hope in the affair from the beginning; but being a cheerful hobbit he had not needed hope, as long as despair could be postponed.

*And all those rings that he governed he perverted, the more easily since he had a part in their making, and they were accursed, and they betrayed in the end all those that used them.

For

*

*For as has been told and as is known to all, being written in lore and sung in many songs, Melkor slew the Trees of the Valar with the aid of Ungoliant, and escaped, and came back to Middle-earth.

*

*For he saw spiders swarming up all the neighboring trees, and crawling along the boughs above the heads of the dwarves.

*For there shall walk a power in the forests whose wrath they will arouse at their peril.

So

*

*So after a brief rest they set out again and were soon lost in a shadowy silent world, cut off from all view of the lands about, either the hills that they had left or the mountains that they sought.

*

*So following the hobbit, down into the lowest cellars they crept.

*So between them our enemies have contrived only to bring Merry and Pippin with marvellous speed, and in the nick of time, to Fangorn, where otherwise they would never have come at all!

Yet

*

*Yet after the fall of Sauron their power was ever at work, and where they abode there mirth also dwelt and all things were unstained by the griefs of time.

*

*Yet as Gimli after learned it was still two hours ere sunset of the day on which they had set out from Dunharrow; though for all that he could then tell it might have been twilight in some later year, or in some other world.

*Yet for a while I stand in the place of the Steward of Gondor, and it is mine to think first of its people.

Or

*

*Or because I do not go, and you desire still to be near me.

*

*Or why should I sit here in my tower and think, and watch, and wait, spending even my sons?

*Or would be, if Lugbúrz would let him alone.

Nor

*

*Nor could the stronghold of Morgoth be ever wholly encircled: for the Iron Mountains, from whose great curving wall the towers of Thangorodrim were thrust forward, defended it upon either side, and were impassable to the Noldor, because of their snow and ice.

*

*Nor did they hear or feel him trotting along well behind their torch-light as they led off their prisoners into the forest.

*Nor in all my realm shall it be openly spoken, while my power endures.

Special Effects
There is nothing especially unusual, let alone remarkable, about beginning a sentence with a coordinating conjunction.
At times, though, this is done for purposeful effect.  The most intense such effect in all of Tolkien's writings occurs in the following passage from the end of The Lord of the Rings when Faramir and Éowyn await news of the Captains of the West, who had gone off to the Black Gate while those two lay in the Houses of the Healing.
After the Ring is destroyed, a great eagle appears, truly a messenger of the "gods" (the Valar) sent to bring good tidings of great joy to a beleaguered people.  A new day is dawning in the city of the Tower of the Guard (Minas Tirith), for the eagle gives the city its old name back, the Tower of the Sun (Minas Anor).  The entire scene explodes with light.
Here the repetitive lines starting over and over again with either and or for are deliberately meant to evoke the Hebrew psalms as translated into the King James Version of the Bible.
To anyone familiar with the Psalms — as would all readers have been when Tolkien wrote it — the effect is a sublimely powerful one. The Sing and rejoice is clearly from the Psalms, as is the repetition of the conjunctions.  And lest there be any doubt remaining that this were done with full intent aforethought, he reverts to the Early Modern English of the KJV: note all the instances of ye and hath.
The following excerpt occurs in the chapter "The Stewart and the King" from Book VI of The Lord of the Rings by J.R.R. Tolkien (bold emphasis mine, to show the parts meant to evoke the Psalms):

      And so they stood on the walls of the City of Gondor, and a great wind rose and blew, and their hair, raven and golden, streamed out mingling in the air. And the Shadow departed, and the Sun was unveiled, and light leaped forth; and the waters of Anduin shone like silver, and in all the houses of the City men sang for the joy that welled up in their hearts from what source they could not tell.

      And before the Sun had fallen far from the noon out of the East there came a great Eagle flying, and he bore tidings beyond hope from the Lords of the West, crying:

          Sing now, ye people of the Tower of Anor,
          for the Realm of Sauron is ended for ever,
              and the Dark Tower is thrown down.

          Sing and rejoice, ye people of the Tower of Guard,
          for your watch hath not been in vain,
          and the Black Gate is broken,
          and your King hath passed through,
              and he is victorious.

          Sing and be glad, all ye children of the West,
          for your King shall come again,
          and he shall dwell among you
              all the days of your life.

          And the Tree that was withered shall be renewed,
          and he shall plant it in the high places,
              and the City shall be blessed.
              Sing all ye people!

   And the people sang in all the ways of the City.

Now go back and try rewriting that passage without any instances of and and for at the beginning of the sentences and independent clauses within.  It is an interesting experiment: you will see  this scintillating passage deflate like a beach ball all of whose air has escaped it.
We should all be grateful that Tolkien was a Professor of English, not someone cowed into insipid writing by obsequious obedience to fake "rules" which are themselves nothing but figments of prescriptivists' cruel unimaginations, for we should not otherwise have such stirring words of joy to inspire us.

A: I suppose I'm just piling on, since so many examples have already been provided. But when we are dispelling a persistent myth, there's no need to pull back any punches!
Here are 10 counterexamples breaking this so-called Tenth Commandment of Grammar; these authors would likely be considered "great writers" by most.

I. The Thirty Mile River was wide open. Its wild water defied the frost, and it was in the eddies only and in the quiet places that the ice held at all. Six days of exhausting toil were required to cover those thirty terrible miles. And terrible they were, for every foot of them was accomplished at the risk of life to dog and man. A dozen times, Perrault, nosing the way broke through the ice bridges, being saved by the long pole he carried, which he so held that it fell each time across the hole made by his body. But a cold snap was on, the thermometer registering fifty below zero, and each time he broke through he was compelled for very life to build a fire and dry his garments.
        (Jack London, The Call of the Wild)
II. At first Bartleby did an extraordinary quantity of writing.  As if long famishing for something to copy, he seemed to gorge himself on my documents.  There was no pause for digestion.  He ran a day and night line, copying by sun-light and by candle-light.  I should have been quite delighted with his application, had he been cheerfully industrious.  But he wrote on silently, palely, mechanically.
        (H. Melville, Bartleby the Scrivener)
III. There was a piece of ornamental water immediately below the parapet, on the other side, into which Mr. James Harthouse had a very strong inclination to pitch Mr. Thomas Gradgrind junior, as the injured men of Coketown threatened to pitch their property into the Atlantic. But he preserved his easy attitude; and nothing more solid went over the stone balustrades than the accumulated rosebuds now floating about, a little surface-island.
        (Dickens, Hard Times)
IV. Many days passed before we could speak to the Golden One again. But then came the day when the sky turned white, as if the sun had burst and spread its flame in the air, and the fields lay still without breath, and the dust of the road was white in the glow. So the women of the field were weary, and they tarried over their work, and they were far from the road when we came. But the Golden One stood alone at the hedge, waiting. We stopped and we saw that their eyes, so hard and scornful to the world, were looking at us as if they would obey any word we might speak.
        (A. Rand, Anthem)
V. At the next corner she got out, of course; and as she had no more money, she had to walk the rest of the way to the yards in the pouring rain. And so all day long she sat shivering, and came home at night with her teeth chattering and pains in her head and back.
        (Upton Sinclair, The Jungle)
VI. Men and women came to see her, met her down town, where she went to do her marketing, brought her home in their cars--and came in for a moment to talk and to rest, in the glamour that still played in her smile. But men who did not know her no longer followed her with admiring glances in the street; a diaphanous veil had come down over her beauty, destroying its vividness, yet bringing neither wrinkles nor fat.
        (Fitzgerald, The Lees Of Happiness)
VII. About midnight, while we still sat up, the storm came rattling over the Heights in full fury. There was a violent wind, as well as thunder, and either one or the other split a tree off at the corner of the building: a huge bough fell across the roof, and knocked down a portion of the east chimney-stack, sending a clatter of stones and soot into the kitchen-fire. We thought a bolt had fallen in the middle of us; and Joseph swung on to his knees, beseeching the Lord to remember the patriarchs Noah and Lot, and, as in former times, spare the righteous, though he smote the ungodly. I felt some sentiment that it must be a judgment on us also. The Jonah, in my mind, was Mr. Earnshaw; and I shook the handle of his den that I might ascertain if he were yet living. He replied audibly enough, in a fashion which made my companion vociferate, more clamorously than before, that a wide distinction might be drawn between saints like himself and sinners like his master. But the uproar passed away in twenty minutes, leaving us all unharmed; excepting Cathy, who got thoroughly drenched for her obstinacy in refusing to take shelter, and standing bonnetless and shawl-less to catch as much water as she could with her hair and clothes.
        (E. Bronte, Wuthering Heights)
VIII. It was nearly half-past twelve. He had just come back from church, hoarse and weary with preaching. He preached with fury, with passion, an iron man beating with a flail upon the souls of his congregation. But the souls of the faithful at Crome were made of india-rubber, solid rubber; the flail rebounded. They were used to Mr. Bodiham at Crome. The flail thumped on india-rubber, and as often as not the rubber slept.
        (A. Huxley, Chrome Yellow)
IX. I drew a great security in this particular from her mere smooth aspect. There was nothing in her fresh face to pass on to others my horrible confidences. She believed me, I was sure, absolutely: if she hadn't I don't know what would have become of me, for I couldn't have borne the business alone. But she was a magnificent monument to the blessing of a want of imagination, and if she could see in our little charges nothing but their beauty and amiability, their happiness and cleverness, she had no direct communication with the sources of my trouble.
        (Henry James, The Turn of the Screw)
X. "There's the scarlet thread of murder running through the colourless skein of life, and our duty is to unravel it, and isolate it, and expose every inch of it. And now for lunch, and then for Norman Neruda. Her attack and her bowing are splendid."
        (Doyle, A Study in Scarlet)

I suppose your friend could dispute that last one, because it's part of a fictional character's quotation, and therefore not bound to the rules of grammar. Still, I stand by the others I've excerpted. And besides, do you really want to argue with Sherlock Holmes?
By the way, a good way to find more is by searching for strings like . But or . And and making sure the "Match Case" option is set.

A: Perhaps he's heard of the King James Bible? It may be hard to read now but it's been called one of the greatest works of the English language. I recommend starting on the first page:

In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.


text:
Q: Logging every jsp:include I want to log every <jsp:include> tag.
Does the JavaServer Pages Standard Tag Library (JSTL) support logging and if so, how do I enable it?

A: You can implement a Filter and configure its mapping as following:
<filter>
    <filter-name>logging</filter-name>
    <filter-class>com.example.LoggingFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>logging</filter-name>
    <url-pattern>*.jsp</url-pattern>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>

This filter will intercept all RequestDispatcher.include() calls, including <jsp:include>. To get path to the included resource, use request.getAttribute("javax.servlet.include.servlet_path")

A: Not directly, but you could write your own tags. If you're sufficently crazy and industrious, you can write <thilo:include> tags that do <jsp:include> and call up a bit of Java code to do logging via log4j or such.

A: Find the actual Java code that implements this tag and check if there are any logging statements in it. If there are enable the class in your logging configuration. If there are no logging statements use AOP to define method interceptor which will log every invocation of Java implementation method. From a method interceptor you have access to invoked method arguments and if needed these can be logged as well.
Bear in mind that AOP may slow down the execution of your application. You may want to disable it in the production environment.

A: There is no simple way to achieve this. My solution was a small file pre.jsp which contains:
<%@page import="org.apache.log4j.Logger"%>
<%
    String __jspName = this.getClass().getSimpleName().replaceAll("_", ".");

    Logger log = Logger.getLogger(this.getClass().getName());
    log.info("BEGIN JSP "+__jspName);
%>
<!-- BEGIN <%=__jspName %> -->

In every file, I'd then add this line at the beginning:
<%@ include file="/pre.jsp" %>

and this one at the end:
<!-- END <%=__jspName %> --><% log.info("END JSP "+__jspName); %>


text:
Q: Two objects of the same class being equal using boolean equals() method Bit of a strange one,
I actually have managed to answer a question by looking at examples and messing with my code but I don't actually understand fully how it is working!
Any explanation would be great and much appreciated!
Code:
I have a class called Player and 3 objects being created in another class in the main method.
public boolean equals(Object obj) {

    if (this == obj) {
        return true;
    } else if (obj instanceof Player) {

        Player player = (Player) obj;

        if (player.getName().equals(this.getName())) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

A: Check the comments
public boolean equals(Object obj) {

    if (this == obj) { // if the references are the same, they must be equal
        return true;
    } else if (obj instanceof Player) {

        Player player = (Player) obj; // we cast the reference

        if (player.getName().equals(this.getName())) { // we compare the name
            return true; // they are equal if names are equal
        } else {
            return false; // otherwise, they aren't
        }
    } else {
        return false; // if the target object isn't of the type you want to compare, we choose to say it is not equal
    }
}


text:
Q: Create Queryable with correct ElementType from variable declared as the parent type of what the variable actually contains Question:
I have a question regarding type casting / generics -
Here's the signature of my method:
public bool FilterMyModel<T>(T model)

T is type Person, and model is an object that is actually of type ExtendedPerson, a child class of Person.
I need to create an IQueryable that has ElementType of ExtendedPerson and contains the object that's passed in the model parameter.**
What I've Tried:
I tried each of these 3 ways of constructing the queryable, but in all 3 cases, the resulting queryable's ElementType is Person (and if I feed that IQueryable into the filtering code it doesn't work).
var query = new[] { model }.AsQueryable();
var query2 = new[] { model }.AsQueryable<T>();
var query3 = ((IEnumerable<T>)new[] { model }).AsQueryable<T>();

I also tried casting the model to the ExtendedPerson type before declaring the IQueryable like this, but got error "{"The best overloaded method match for 'MyNamespace.CastHelper.CastValue(System.Linq.IQueryable)' has some invalid arguments"}" on the line var modelCast = castHelper.CastValue(model);
//// Cast model (to handle Extended data types, e.g. ExtendedPerson, passed to this method as bast type, e.g. Person)
Type castHelperGenericBase = typeof(CastHelper<,>);
Type[] castTypeArgs = { typeof(T), model.GetType() };
Type castHelperType = castHelperGenericBase.MakeGenericType(castTypeArgs);
dynamic castHelper = Activator.CreateInstance(castHelperType);
var modelCast = castHelper.CastValue(model);

Where this is the definition of CastHelper:
public class CastHelper<T,U> where U:T
{
    public IQueryable<U> CastValue(IQueryable<T> query)
    {
        return (IQueryable<U>)query;
    }
}

Is anyone able to assist me in figuring out how to create an IQueryable from model that will have ElementType of ExtendedPerson?
** Note:  I believe that having an IQueryable<> with ElementType=ExtendedPerson will make the filtering work - what I actually know for sure is that if I'm coming from the db instead of from a model object, and I query the ExtendedPersons table into an IQueryable, that IQueryable's ElementType is ExtendedPerson, and if I then cast that to IQueryable in a dynamic way, the filtering works
Note2: I know that many will question whether I SHOULD do such a thing - the reason why I want to is that we're allowing customers to add extensions to existing types in an existing app dynamically, and trying to keep the amount of code that has to be loaded to the appdomain dynamically at runtime to a minimum - so trying to make the part of the code that really needs to know the "true" type of the extended objects use reflection to do so, and everywhere else to pass them around as the parent type, and to dynamically load code only for the extension class definitions themselves if possible.
Many thanks for your assistance!!

A: The key to answering this question is knowing how to close a generic method. There are 2 options for where this can be done to fix the issue:
1) My original question asked how to directly cast the object inside of the method that received it as a parameter of the wrong type. That is answered here: stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
2) A second option is to call the method passing the parameter as an ExtendedPerson instead of as a Person - the below causes T to be read as the correct type:
var openGenericMethod = myFilteringClass.GetType().GetMethod("FilterMyModel");
MethodInfo closedGenericMethod = openGenericMethod.MakeGenericMethod(model.GetType());
closedGenericMethod.Invoke(viewFilter, new object[] { model });

Then, in FilterMyModel, I just have to define the queryable using a generic version of AsQueryable, not the non-generic version, as follows:
var query = new[] { model }.AsQueryable<T>();

Additional Notes:
- "myFilteringClass" is the class in which the "FilterMyModel" method shown above is defined.
- If it were not possible to change the value of T passed into the FilterMyModel method, I could just as easily have nested things a level deeper by defining an additional generic method in the same class, and calling it from FilterMyModel in this same way, having the same effect


text:
Q: Variable functions as a list but isn't technically a list? [Python] I'm pulling a list from a dictionary like so:
d={foo:[1,2,3]}
thelist=d[foo]

I'm able to get items from indexes of thelist but not like this:
for i in thelist:
    print thelist[i]

I get an error saying the "list index is out of range"
Additionally, when I run
thelist is list

it returns False
whats going on here

A: the list index out of range is because thelist[3] is not an allowed thing to call.
the for loop is trying to print thelist[i] for each i in thelist.  In this case thelist has 1, 2, and 3.  So it's trying to print thelist[1] (which is 2), thelist[2] (which is 3), and then thelist[3] which is undefined.
A bit more detail:
thelist = ['puppy', 1, 'dog']
for i in thelist:
    print i

gives

puppy
1
dog

as for thelist is list, instead try type(thelist).  The type of thelist is list.  So testing whether thelist is list (that is it is the class of things which we call list) rather than is a list (that is it is an example of the list class) will return False.

A: If you want to interate over a list using indices, than you should do as follows:
for i,v in enumerate(thelist):
    print(thelist[i])

Or alternatively:
for i in range(len(thelist)):
    print(thelist[i])

A: in python the default indexing strart from 0 and ends to its lenght-1
so thelist=d[foo] ie [1,2,3] will have index 0,1,2
for i in thelist:     # here i the element of list not index
    print thelist[i]

for i in range(len(thelist)):   # here i the index of list
    print thelist[i]

A: for l1 in thelist:
   print l1

you get:
1
2
3

in your code you're trying to access list using the list elements as index. Instead, to iterate over list' indexes, you should use range(len(theList))(from 0 to len(theList) -1) or reversed(range(len(theList)) (from len(theList) -1 to 0).
to check if a variable is a list use types
import types
x = [1,2,3]
if type(x) is types.ListType:
    print 'x is a list'

A: Each time you go through the for loop, i is set to one of the items in the list.
You'll also want to use the type() function to compare the types of thelist and a list (really []).
d={'foo':[1,2,3]}
thelist = d['foo']
for i in thelist:
    print i

print type(thelist)
print type(thelist) is type([])

returns
1
2
3
<type 'list'>
True


text:
Q: Are OpenGL functions actually context-specific? I know that I must pass glfwGetProcAddress function to gladLoadGLLoader function after context was initialized. GLFW documentation says that this function returns the address of the specified function for the CURRENT context. Based on this information, if I want to draw something on another context, I must type
glfwMakeContextCurrent(*window*)
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)

each time I want to change drawing context. However, it is enough to simply change the context with glfwMakeContextCurrent function. Documentation also remarks

The address of a given function is not guaranteed to be the same
between contexts.

But it seems like returned addresses are the actually same between contexts (In windows, at least). The question is, what is true way to do this, in order to achieve stable and portable behaviour?

A: Technically yes: function pointers retrieved from an OpenGL context are valid only for that specific context. However, for most practical purposes, you can ignore this. If two contexts can share objects, then they almost certainly share function pointers.
If you want to account for those cases where function pointers can't be shared across contexts, the best option is to write a loader specifically for dealing with that eventuality. You could for example modify GLAD to put OpenGL functions in a struct and then load the functions into different structs for different contexts.


text:
Q: Database trigger How to insert sum of values, from one table to another? I think best way is Triggers? Any idea?
I should insert sum of payment_amount seperately for each username from table Payments, to total_money table total_balance It should be inserted automaticly every time when new velues inserted to table Payments
For example: User "John" filled his account 2 time 100$ and 50$, Total in his account 150$
Example in tables:
Table: Payments
 ID      username     payment_amount    Status
+-------+-------------+-------------+-----------+
|   1   |  John       |     100     | Complete  |
+-------+-------------+-------------+-----------+
|   2   |  John       |     50      | Complete  |
+-------+-------------+-------------+-----------+
|   3   |  Alex       |     100     | Complete  |
+-------+-------------+-------------+-----------+

Table: total_balance
 ID      username      total_money
+-------+-------------+-------------+
|   1   |  John       |     150     |
+-------+-------------+-------------+
|   2   |  Alex       |     100     |
+-------+-------------+-------------+

A: I'd recommend not to keep redundant data. That is likely a recipe for desaster when inconsistencies occur. I suggest you use a view, that gives you the sums.
DROP TABLE total_balance;

CREATE VIEW total_balance
AS
SELECT p.username,
       sum(p.payment_amount) total_money
       FROM payments p
       GROUP BY p.username;

Or, if you only want to sum completed payments:
DROP TABLE total_balance;

CREATE VIEW total_balance
AS
SELECT p.username,
       sum(p.payment_amount) total_money
       FROM payments p
       WHERE p.status = 'Complete'
       GROUP BY p.username;

The figures in the view will always be accurate and reflect the current situation.


text:
Q: JSONField принимает любые значения от пользователя, что бы не ввёл - не только в формате json Необходимо получить от пользователя данные в jsonB, затем вывести их на экран в формате json. Использовал в модели JSONField, однако принимает любые значения от пользователя, что бы не ввёл
models.py
from django.contrib.postgres.fields import JSONField
from django.db import models

class UserForm(models.Model):
    name = models.CharField(max_length=200)
    data = JSONField()

    def __str__(self):
        return self.name

forms.py
from django import forms

class UserForm(forms.Form):
    name = forms.CharField(max_length=100)
    data = forms.CharField()

views.py
from django.shortcuts import render
from .forms import UserForm
from django.http import HttpResponse

def index(request):
    if request.method == "POST":
        name = request.POST.get("name")     # получение значения поля name
        data = request.POST.get("data")     # получение значения поля data
        return HttpResponse("
Name: {0}  JSON:{1}
".format(data, name))
    else:
        userform = UserForm()
        return render(request, "index.html", {"form": userform})

index.html

<meta charset="utf-8" />
<title>User Forms</title>

    <form method="POST">
        {% csrf_token %}

        {{ form }}

    <input type="submit" value="Submit" >
</form>

A: import json
from django.http import HttpResponse

def profile(request):
    data = {
        'name': 'Vitor',
        'location': 'Finland',
        'is_active': True,
        'count': 28
    }
    dump = json.dumps(data)
    return HttpResponse(dump, content_type='application/json')

Или так
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})


text:
Q: PHP Performance Load Comparing Two DateTime Objects I have an availability class which does many checks to see if a date is available, but one of these checks is to see whether the bookable product is within the booking window (i.e. in the future enough to meet the user criteria for same day bookings). The code is below -
private function set_within_booking_window(){
    $timezone = get_option('timezone_string');
    $starttime = cb_get_product_starttime($this->product_id, $this->date);
    $this->starttime = $starttime;
    //get booking window
    $window = new DateTime();
    $window->setTimezone(new DateTimeZone($timezone));
    $buffer = get_option("cb_same_day_buffer");
    $window->add(new DateInterval("PT".$buffer."H"));
    $this->window = $window;
    if($starttime < $window){
      $this->within_booking_window = false;
    } else {
      $this->within_booking_window = true;
    }
  }

Upon performance study, this entire operation is well-built and speedy EXCEPT the DateTime Comparison of if($starttime < $window) which basically KILLS the performance of this entire availability class. A pageload is less than 1 sec with that expression commented out and more than 26 seconds with it left in.
Everything I've read in the PHP documentation suggests that this is the best way to compare the two dateimes - but this just cannot be right...
Any feedback on performance when comparing two PHP DateTime Objects?


text:
Q: Exercise from Marcus on class groups I stumbled upon this:
Let $p$ be a prime of $K$ (a given number field) and let $m$ be the order of $[p]$ in $Cl(K)$. Suppose $\mathcal{P}|p$ is a prime of $L$ (here, $L/K$ is an extension of $K$). Show that $m/(m, f(\mathcal{P},p))$ divides the order of the class $[\mathcal{P}]$ in $Cl(L)$.
Any help is welcomed, thanks!

A: Here is an argument avoiding class field theory:
Let $a$ be the order of $\mathcal P$ in the class group of $L$. Then
$\mathcal P^a = (\alpha)$ for some integer $\alpha$ of $L$.  Taking norms
down to $K$, we find that
$p^{f(\mathcal P,p) a}$ is principal.  Thus $m$ divides $a f(\mathcal P,p)$,
and hence $m/(m,f(\mathcal P,p))$ divides $a$, as claimed.

A: This is closely related to the class-field-theoretic type argument I mentioned in the other answer.  Here's a fast solution (if possibly not the most elementary).
Note that by class field theory, specifically properties of the Artin symbol, the order $m$ of $[p]$ equals the relative inertia degree of $p$ in the Hilbert class field $K^{(1)}$ of $K$, and similarly for the order of $[\mathcal{P}]$ and the residue degree of $\mathcal{}P$ in $L^{(1)}/L$.  Now consider the following diagram:
$$
\newcommand{\ra}[1]{\!\!\!\!\!\!\!\!\!\!\!\!\xrightarrow{\quad#1\quad}\!\!\!\!\!\!\!\!}
\newcommand{\da}[1]{\left\downarrow{\scriptstyle#1}\vphantom{\displaystyle\int_0^1}\right.}
%
\begin{array}{llllllllllll}
L & \ra{m':=\text{ order of }\mathcal{P}} & L^{(1)} \\
\da{f:=f(\mathcal{P}/p)} & & \da{}\\
K & \ra{m :=\text{ order of }p} & \,K^{(1)} \\
\end{array}
$$
Here the labels on each arrow are the inertia degrees of a prime above $p$ in each extension.  Now by multiplicativity of inertia degrees in towers, we have $m\mid m'f$, so $\frac{m}{(m,f)}\mid m',$ as desired.

(Apologies for the sloppy diagram, I've never jury-rigged an xypic on MSE or MO before.  Can anyone make those arrows "headless"?  And/or move the$f(\mathcal{P}/p)$ to the left of the arrow?)

A: This is just a hint, that will hopefully help you realize where this $m/(m,f(\mathcal{P},p))$ comes from.
Let $m>1$ be a fixed integer and suppose that $a\in\mathbb{Z}$ is relatively prime to $m$. Then, for any $d\geq 1$, we have:
$$\operatorname{ord}(a^d) = \frac{\operatorname{ord}(a)}{\gcd(\operatorname{ord}(a),d)}.$$


text:
Q: Suggested document-oriented database (MongoDB) design I'm researching alternative database solutions for an existing e-commerce site, and thought I should give NoSQL a glance.
Our current design is a very traditional relational design. However, the site functionality and structure lends itself more to a CMS. The types of pages can be broken down as such:

*

*Category Listing (list products from a particular category or custom query)

*Home Page

*Sub-Category Home Page

*Custom content Page (press releases, promotional, etc...)

*Product

Each of these has many things in common, and could benefit from a document-oriented design.
ACID is not critical. Key transactional data (read: stock) is maintained elsewhere. Overselling is caught when orders are processed off-site. Stock is updated on the site from the off-site location at regular intervals.
Rough Collection Design:
{
  {
    "title":"Some page Title",
    "type":"Page",
    "key":"some-page-title",
    "body":"Lorem Impsum..."
  },
  {
    "title":"Some product",
    "type":"Product",
    "key":"widgets\/some-product",
    "data":{
      "stock":3,
      "price":25.13,
      "category":"Widgets",
      "images":["image1.jpg","image2.jpg"]
    }
  }
}

The other data (Customers, Orders, etc...) would be located in appropriately designed collections. The "Pages" are the most accessed items, and I would like to keep them centralized. Any thoughts or suggestions?


text:
Q: Show InfoWindow behind selected marker I'm attempting to show the InfoWindow behind the selected marker.
As so:

However i'm not having any luck.
I've tried setting the zValue on both the InfoWindow and the Marker.
Any thoughts?
Regards,
Scott.


text:
Q: Is there a way to incude style in a php session? I have a menu that scrolls down and will let you select what color you want for the background, but its only for one page, is there a way to include the style of the page near the beginning of the session so that it will go for all pages?

A: Are you using a PHP session at the moment?
The call to change the colour of the background should set a session variable.
Any pages being displayed should check the session to see if that variable is present.
Have a look at http://www.php.net/manual/en/session.examples.basic.php


text:
Q: Limiting distribution of a sequence of Poisson RVs Suppose that each random variable $B_i, i \in \mathbb{N}$ in an iid sequence of random variables $B_n$ has a Poisson($i$) distribution. How could I find the limiting distribution of $G_n = \sqrt{B_n}$?
My first idea was to see if $B_n$ converges in distribution to some limiting distribution $B$, and then use that fact to show that $G_n$ converges to some limiting distribution $G = \sqrt{B}$. However, $B_n$ does not converge to anything, so I can't use that line of reasoning.
How could I approach this problem?

A: $$
\frac{B_i - i}{\sqrt i} \overset{\mathcal L}\longrightarrow N(0,1) \text{ as } i\to\infty.
$$
$$
f(B_i) \approx f(i) + f'(i)(B_i-i)
$$
$$
\frac{f(B_i) - f(i)}{ f'(i) \sqrt i} \approx N(0,1)
$$
$$
f(x) = \sqrt x
$$
$$
f'(x) = \frac 1 {2\sqrt x}
$$
$$
f'(i)\sqrt i = \frac 1 2
$$
$$
2(\sqrt{B_i} - \sqrt i\,) \approx N(0,1)
$$
Notice that this implies there is no limiting distribution of $\sqrt{B_i}.$ There is, however, an "asymptotic distribution" of $\sqrt{B_i}.$ It is interesting that the variance of $\sqrt{B_i}$ remains bounded as $i$ grows.
The argument above is not fully rigorous; you need to cite the appropriate theorems. They can be found in Serfling's Limit Theorems of Mathematical Statistics.


text:
Q: Zabbix Pre-shared key encryption I'm trying to use psk encryption on agent with active checks on Windows 7, but wont work, don't know why.
Here's my agent conf :
TLSPSKFile=C:\zabbix\zabbix.txt
TLSPSKIdentity=psk001
TLSConnect=psk

When i remove psk option from config file works fine ...
Here is agent log:
4008:20160817:100235.765 using configuration file: C:\zabbix\zabbix_agentd.win.conf
4008:20160817:100235.766 agent #0 started [main process]
4820:20160817:100235.766 agent #1 started [collector]
5060:20160817:100235.766 agent #2 started [active checks #1]
5060:20160817:100235.769 no active checks on server [10.29.0.40:10051]: connection of type "unencrypted" is not allowed for host "IDX-INVENTORY"
4520:20160817:100251.897 Zabbix Agent stopped. Zabbix 3.0.0 (revision 58455).

PSK File :
852db2dca368484050c9b15810e3453f49cc8086b8dd2b04a1 1af4de3f74c42f

When try to start zabbix_agent service receive :

Where am I wrong ?

A: The default Zabbix Windows agent binaries are compiled without encryption support.
You can vote on a feature request to include encryption, and you can also find some builds with encryption attached to https://support.zabbix.com/browse/ZBXNEXT-3047 .


text:
Q: Drawing a rectangle on CGContext without using subclass of UIView How can I draw two different rectangles with black background without using subclass of UIView and using a CGContext?

A: Add whatever vanilla UIView objects you need in the appropriate positions, and set their background colours to whatever you like.
The drawing will be done in a CGContext, you just won't be able to control it.
Or, add a CALayer subclass of your own, set it to be the view's layer and draw your rectangles in there, in drawInContext:.
Or, set a different object as the delegate for the view's layer and draw it in the delegate method drawLayer:inContext:.


text:
Q: NoSuchElement exception using NextInt() using java Scanner Getting the following error, trying to use an outside method that I made to initialize a bunch of coordinate pairs I'm making for a battleship terminal reproduction. I have added hasNextInt() as a test before pulling the input in as someone mentioned in another thread: https://stackoverflow.com/questions/12832006/scanner-error-with-nextint
I'm getting an infinite loop when it goes into the second call of the method. though I don't have any issues if the second call to the method is commented out. My thought is its somehow taking the whitespace from the new line when I hit enter on the first coordinate pair, but I'm not sure how to clear that before it goes into the second method call so that I can actually enter values.
I initialize coordinates to 6 here to make sure that only valid coordinates are entered, which triggers the infinite loop. I also have initialized to 0, and thats when I get the exception here.
The Error:
Exception in thread "main" java.util.NoSuchElementException
        at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        at java.base/java.util.Scanner.next(Scanner.java:1594)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
        at Battleship.battleship.shipLocations(battleship.java:31)
        at Battleship.battleship.main(battleship.java:14)

    public static void main(String[] args){
        Scanner input = new Scanner(System.in); //read keyboard input
        //Begin the game
        System.out.println("Hello Mortals, Welcome to Battleship!");

        System.out.println("PLAYER 1, Enter your ships' coordinates.");
        //Take in player ones coordinates
        int[] coordinate1 = shipLocations(1);
//heres where the problem starts
        int[] coordinate2 = shipLocations(2);
        // int[] coordinate3 = shipLocations(3);
        // int[] coordinate4 = shipLocations(4);
        // int[] coordinate5 = shipLocations(5);

    input.close();
    }
    public static int[] shipLocations(int shipNumber){
        Scanner input = new Scanner(System.in);
        //I can either initialize over my input threshold check, to make sure only valid coordinates are available, or if I set to 0 it throws the exception error on the second method call.
        int coordinate1=6;
        int coordinate2=6;
        System.out.println("Enter Ship " + shipNumber + " location: ");

        if(input.hasNextInt()){
            coordinate1 =input.nextInt();
            coordinate2= input.nextInt();
        }
        int[] coordinates = new int[2];
        if(coordinate1 > 4 || coordinate2 > 4){
            Boolean invalidCoords = true;
            do{
                System.out.println("Invalid Coordinates. Choose different Coordinates.");
                System.out.println("Enter Ship " + shipNumber + " location: ");
                if(input.hasNextInt()){
                coordinate1 =input.nextInt();
                coordinate2 = input.nextInt();
                }
                if (coordinate1 < 5 && coordinate2 < 5){
                    invalidCoords=false;
                    coordinates[0]=coordinate1;
                    coordinates[1]=coordinate2;
                }
            }while(invalidCoords);
        }
        else{
            coordinates[0]=coordinate1;
            coordinates[1]=coordinate2;
        }
        input.close();
        return coordinates;
    }

A: Ah. For anyone wondering, it was the dang input.close(). I'm not entirely sure why you can't create a new scanner on each pass, but that was mentioned in other threads that you don't want to close it so I tried removing that from the method shipLocations.


text:
Q: How to remove item from sqlite database and recycle view on java android I have tried to initiate the function that removes one of my item from my sqlite database however nothing change. Supposedly there is a button on of the item in my recycle view that acts as a delete button to remove the object from the recycle view. But everytime i click it, nothing changed. Any tips on how to solve it?
this is my recycle view
package com.example.myapplication.recyclerview;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.DBhelper;
import com.example.myapplication.R;

import java.util.ArrayList;

public class bookingRecycleView extends RecyclerView.Adapter<bookingRecycleView.ViewHolder> {

    // variable for our array list and context
    private ArrayList<Booking> BookingArrayList;
    private Context context;
    DBhelper db;
    String name;
    // constructor
    public bookingRecycleView(ArrayList<Booking> BookingArrayList, Context context) {
        this.BookingArrayList = BookingArrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // on below line we are inflating our layout
        // file for our recycler view items.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rbooking_row, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // on below line we are setting data
        // to our views of recycler view item.
        Booking modal = BookingArrayList.get(position);
        holder.tv_name.setText(BookingArrayList.get(position).getName());
        holder.tv_bookingBategory.setText(BookingArrayList.get(position).getNotes());
        holder.tv_paymentStatus.setText(BookingArrayList.get(position).getBookingCheck());
        holder.button_delete_booking.setOnClickListener(view -> {

            Toast.makeText(view.getContext(),String.valueOf(BookingArrayList.get(position).getBookingid()),Toast.LENGTH_SHORT).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            // Set a title for alert dialog
            builder.setTitle("Are you sure you want to delete this ?");

            // Ask the final question
            builder.setMessage("Deleted data cannot be undone.");

            // Set the alert dialog yes button click listener
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override

                public void onClick(DialogInterface dialog, int which) {
                    db = new DBhelper(context);
                    db.deleteCourse(name);

                }

            });

            // Set the alert dialog no button click listener
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

            AlertDialog dialog = builder.create();
            // Display the alert dialog on interface
            dialog.show();

        });
    }

    @Override
    public int getItemCount() {
        // returning the size of our array list
        return BookingArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        // creating variables for our text views.
        public TextView tv_name,tv_bookingBategory,tv_paymentStatus;
        public Button button_delete_booking;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views
            tv_name = itemView.findViewById(R.id.tv_nameCrew);
            tv_bookingBategory = itemView.findViewById(R.id.tv_crewProgress);
            tv_paymentStatus = itemView.findViewById(R.id.tv_crewQuantity);
            button_delete_booking = itemView.findViewById(R.id.button_delete_booking);
        }
    }
}

dbhelper
package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.myapplication.recyclerview.Booking;

import java.util.ArrayList;

public class DBhelper extends SQLiteOpenHelper {
    public static final  String DBNAME="database.db";
    private static final String TABLE_NAME = "booking";

    public DBhelper(@Nullable Context context) {
        super((Context) context,"database.db", null, 1);
    }

    public DBhelper(DialogInterface.OnClickListener onClickListener) {
        super((Context) onClickListener,"database.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

         db.execSQL("create table users(username TEXT primary key, password TEXT )");
         db.execSQL("create table "+TABLE_NAME+"(serviceID INTEGER , name TEXT,notes TEXT,email TEXT,phone TEXT,bookingcheck INTEGER )");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("drop table if exists users");
        db.execSQL("drop table if exists " + TABLE_NAME);
        onCreate(db);
    }

    public Boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username",username);
        values.put("password", password);

        long result  = db.insert("users",null,values);
        if(result==-1)return false;
        else
            return true;

    }

    public void addNewBooking( int serviceID, String name,String notes, String phone, String email, int bookingcheck) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        // on below line we are passing all values
        // along with its key and value pair.

        values.put("serviceID", serviceID);
        values.put("name", name);
        values.put("notes", notes);
        values.put("phone", phone);
        values.put("email", email);
        values.put( "bookingcheck", bookingcheck);

        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values);

        // at last we are closing our
        // database after adding database.

    }

    public Boolean checkusername(String username){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username = ?", new String[] {username});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;

    }

    public Boolean checkuserpass(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username =? and password =?", new String[] {username,password});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;

    }

    public ArrayList<Booking> readCourses() {
        // on below line we are creating a
        // database for reading our database.
        SQLiteDatabase db = this.getReadableDatabase();

        // on below line we are creating a cursor with query to read data from database.
        Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

        // on below line we are creating a new array list.
        ArrayList<Booking> courseModalArrayList = new ArrayList<>();

        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModalArrayList.add(new Booking(cursorCourses.getInt(0),
                        cursorCourses.getString(1),
                        cursorCourses.getString(2),
                        cursorCourses.getString(3),
                        cursorCourses.getString(4),
                        cursorCourses.getInt(5)));
            } while (cursorCourses.moveToNext());
            // moving our cursor to next.
        }
        // at last closing our cursor
        // and returning our array list.
        cursorCourses.close();
        return courseModalArrayList;
    }

    public void deleteCourse(String name) {

        // on below line we are creating
        // a variable to write our database.
        SQLiteDatabase db = this.getWritableDatabase();

        // on below line we are calling a method to delete our
        // course and we are comparing it with our course name.
        db.delete(TABLE_NAME, "name=?", new String[]{name});
        db.close();
    }

}

this is my bookingactivity (where the recycleview is shown at)
package com.example.myapplication.booking;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.DBhelper;
import com.example.myapplication.R;
import com.example.myapplication.recyclerview.Booking;
import com.example.myapplication.recyclerview.bookingRecycleView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class BookingActivity extends AppCompatActivity {

    DBhelper db;

    LinearLayoutManager linearLayoutManager;

    public FloatingActionButton fbtn_createBooking;
    private bookingRecycleView BookingRecycleView;
    private ArrayList<Booking> BookingArrayList;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_booking);

        BookingArrayList = new ArrayList<>();
        db =new DBhelper(this);
        BookingArrayList = db.readCourses();

        BookingRecycleView = new bookingRecycleView(BookingArrayList, BookingActivity.this);
        recyclerView = findViewById(R.id. recycler_view);

        linearLayoutManager = new LinearLayoutManager(BookingActivity.this);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.setAdapter(BookingRecycleView);
        BookingRecycleView.notifyDataSetChanged();

        fbtn_createBooking =findViewById(R.id.fbtn_createBooking);

        fbtn_createBooking.setOnClickListener(new View.OnClickListener() {
            String name;
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(BookingActivity.this, AddBookingDetail.class);

                startActivity(intent);

            }
        });
    }

}

A: My guess is you are deleting the data from sqlite but not from BookingArrayList you have passed to the adapter. It would be clear if you show us your recycler activity, but i think what you did is fetch data from sqlite and add them to BookingArrayList. So when you delete the data you are doing it to the sql DB. you need to also remove it from the array and notify your adapter in order for it to have an effect on your view.