Saturday, August 28, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Authorized Attribute always redirecting to '/Account/Login'

Posted: 28 Aug 2021 08:34 AM PDT

I have AuthController.cs and to routes:

auth/login - login page,
auth/register - register page.

Also I have another controller - ClientController.cs - which has [Authorized] attribute. When I trying to reach client's page, I automatically redirects to Account/Login but its not correct login path.

Question: how to change [Authorized] attribute redirect path?

How to use Shopify timber

Posted: 28 Aug 2021 08:34 AM PDT

I want to make cart drawer using timber in Shopify website can someone guide me to make cart drawer using timber in Shopify I have already downloaded timber file but don't know exactly which file to change

How to plot a function from two columns of my dataset in GraphPad?

Posted: 28 Aug 2021 08:33 AM PDT

I am having a little problem with GraphPad. I have to do a very fast graph using two variables, pressure and volume, and obtain a graph that looks like the following:

enter image description here

The data are in a dataset with two columns, one with the pressures and one with the volumes.

It looks like:

    Volume  Pressure  31,015996   16,092523  31,266866   22,051138  31,459981   27,791461  31,578972   53,271996  31,614586   58,451481  31,564627   43,292561  31,43287    67,763297  31,22724    51,872024  30,957583   85,671521  

I'm at a loss with how to proceed. I tried with:

Analyze --> Regression and Curves --> Plot a function but it does not seem to work.

I am sorry for the very basic question but I have never used GraphPad before.

Datapreprocessing TypeError: 'in <string>' requires string as left operand, not list

Posted: 28 Aug 2021 08:33 AM PDT

I'm writing a function for text preprocessing on a dataset:

def text_transform(text):      text = text.lower()      text = nltk.word_tokenize(text)            x = []      for i in text:          if i.isalnum():              x.append(x)                    text = x[:]       x.clear()             for j in text:          if j not in stopwords.words('english') and j not in string.punctuation:              x.append(j)      return x  

And I am getting the error on the stopwords part:

TypeError: 'in ' requires string as left operand, not list --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 text_transform('Hello How are you ?')

in text_transform(text) 12 13 for j in text: ---> 14 if j not in stop and j not in string.punctuation: 15 x.append(j) 16 return x

TypeError: 'in ' requires string as left operand, not list

Why x++ is not x+1 when logged on JS console? [duplicate]

Posted: 28 Aug 2021 08:33 AM PDT

I am extremely new to JS and wanted to try the following.

var dev=4;  console.log(dev++);  

I expected the output to be 5, but the output was 4. Can not understand the reason.

laravel using {{ $clinics->links }} pagination [closed]

Posted: 28 Aug 2021 08:33 AM PDT

<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-4 pb-2 mb-3 border-bottom">          <h1 class="h2">اضافة عيادة</h1>      </div>      @if(Session::has('message'))          <div class="alert alert-success" role="alert">{{Session::get('message')}}</div>      @endif                        <form class="form-horizontal" wire:submit.prevent="storeClinic">          <div class="form-group">              <label class="col-md-4 control-label">اسم العيادة</label>                  <div class="col-md-4">                      <input type="text" placeholder="اسم العيادة" id="name" name="name" class="form-control input-md" wire:model="name"/>                  </div>          </div>          <div class="form-group">              <label class="col-md-4 control-label"></label>              <div class="col-md-4">                  <button type="submit" class="btn btn-success">اضافة</button>              </div>          </div>      </form>    </main>  <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-4 pb-2 mb-3 border-bottom">          <h1 class="h2">العيادات</h1>      </div>      <table class="table table-striped">          <thead>              <th>كود العيادة</th>              <th>اسم العيادة</th>              <th colspan="2">تعديل/حذف</th>          </thead>          <tbody>              @foreach($clinics as $clinic)                  <tr>                      <td>{{$clinic->id}}</td>                      <td>{{$clinic->name}}</td>                      <td colspan="2">                          <a href="{{ route('admin.editclinic',['clinic_name'=>$clinic->name]) }}" type="button" class="btn btn-warning btn-sm">تعديل</a>                          <a type="button" wire:click.prevent="deleteClinic({{ $clinic->id }})" class="btn btn-danger btn-sm">حذف</a>                      </td>                  </tr>              @endforeach          </tbody>      </table>          {{$clinics->links()}}  </main>  

Is there a JavaScript method or a better solution to swap an array element and shift the rest of the elements?

Posted: 28 Aug 2021 08:34 AM PDT

var arr = ['100', 'A', 'B', 'C', 'D', 'E', 'F'];    var newIndex = 6;    // index where we want to swap the element  var oldIndex = 0;    // index from where we swapped the element  var replaceBy = arr[oldIndex];    if (newIndex < oldIndex) {      for (var i = newIndex; i <= oldIndex; i++) {          var saveCurrent = arr[i];          arr[i] = replaceBy;          replaceBy = saveCurrent;      }  } else if (newIndex > oldIndex) {      for (var i = newIndex; i >= oldIndex; i--) {          var saveCurrent = arr[i];          arr[i] = replaceBy;          replaceBy = saveCurrent;      }  }  console.log(arr); // logs out ["A", "B", "C", "D", "E", "F", "100"]   

I am looking for a better solution, possibly by just using 1 loop. So far I came up with the above solution. if and else if have same code except in the for block.

How to access variable from class in another file without executing function [duplicate]

Posted: 28 Aug 2021 08:34 AM PDT

I need to access a variable across different modules. This is an abstraction of a bigger code.
First, I execute the set.py from call.py. After set.py was executed I want to retrieve x in get.py - but, without executing set.py again! I only want the variable x. Is it possible?

constraints:

  1. It's no problem to have more functions in set.py

  2. x has to be declared in setvar()

  3. setvar() can only be executed once! (already done with call.py)

  4. class exe() is not really necessary, as long as set.py stays executable from another file

My example where get.py executes set.p again

call.py:

import set    call = set.exe().setvar()  

set.py:

class exe():        def setvar(self):            print('running....')                    self.x = 100    if __name__ == '__main__':      exe().setvar()  

get.py:

import set    y = set.exe()  y.setvar()     print(y.x)   

output:

running....  100  

desired output:

100  

Why do we need to add late modifier while declaring the variables?

Posted: 28 Aug 2021 08:34 AM PDT

Its a general question. Not coding related. Everywhere I follow flutter tutorials I see the simple variable declarations. But when I write the same code (I think because of updating) it requires to add late modifier. late modifier can be used while declaring a non-nullable variable that's initialized after its declaration. Declaration of variables that will be initialize later is done using late modifier. That's what I read on the google. Why it is necessary to declare non-nullable variables. Vscode always underlines the variable showing error. But ate modifier. What do we need to change when we change variables to late. Cause its making following tutorials very difficult. set state is not helping.

How can I make the text in a span tag slowly disappear and close its gap with CSS?

Posted: 28 Aug 2021 08:35 AM PDT

I created a code with the phrase I am super strong, I used animate from CSS to make the word super slowly fades away, the problem is that I am using position: absolute so the space gap left by the span closes and it does so instantly, while I wanted a effect that slowly closed the gap similar to how I made the span fade away with opacity. Here is a snippet of the code I made:

#title {    text-align: center;  }    #title > span {    animation-name: title;    animation-duration: 4s;    animation-iteration-count: infinite;  }    @keyframes title {    0%   {      opacity: 1;    }    50%  {      opacity: 0;      position: static;      }    100% {      opacity: 0;      position: absolute;    }  }
<h1 id="title">I am<span> super</span> strong</h1>

Extract the value of a variable from a text file

Posted: 28 Aug 2021 08:33 AM PDT

Following is the snippet of the text file (txt.toml):

value = 10.0  base = 14.0  outcome = 20.0  numbers = [12.0, 20.0]  input = false  Scheme = "default"  sigma = [1, 8, 11, 5]  

I want to access the value of the variable "base". I tried the following solution from here:

variable = {}  with open('txt.toml', 'r') as file:      for line in file:          name, value = line.replace(' ', '').strip('=')          variable[name] = value            print(variable['base'])  

Following error is thrown:

ValueError: too many values to unpack (expected 2)  

I am not able to fix this error. How can the value stored in the variable "base" be accessed?

Rows are not beeing added to table- javascript

Posted: 28 Aug 2021 08:33 AM PDT

I have here this code that gets me the latest pair from a smart contract:

document.getElementById("latestPairs").innerHTML = `<table class="table table-dark table-striped table-hover" id="latest"></table>`;  const table = document.getElementById("latest");       const rowHeader = `<thead>                              <tr>                              <th>Token0</th>                              <th>Token1</th>                              <th>Pair</th>                              </tr>                          </thead>`       table.innerHTML += rowHeader;      pcsfactoryC.events.PairCreated({fromBlock:'latest'})  .on('data', async function(event){           //console.log(event.returnValues);           // Do something here      let pairs =  event.returnValues          let token0 = event.returnValues['token0'];      let token1 = event.returnValues['token1'];      let getPair = event.returnValues['pair'];      console.log(token0 + " " + token1);      add_row("latest", [event.returnValues['token0'], event.returnValues['token1'], event.returnValues['pair']]);                    })       .on('error', console.error);  

It works in the console as expected however the rows arent beeing added to the table and i receive following error:

Uncaught (in promise) ReferenceError: add_row is not defined  

How can i fix this and make a dynamic table for my data?

Histogram - Going down a line when having 2+ letters of same word

Posted: 28 Aug 2021 08:33 AM PDT

I have a question saying this:


Write a function which receives a string ( containing only small letters and whitespaces ).

This function will print histogram for all letters with *, for example:

string - "aba ima", this will be printed:


abcdefghijklmnopqrstuvwxyz    **      *   *    *    *  

Now, I tried this code, although it is 80% done, the remaining 20% of the work I cant seem to get it...

My problem is how to print the other letters in the string.

For example, aba ima, it has three "a", I cant seem to get it to print 3 lines for it.

My code:

def histogram(string):      abc = "abcdefghijklmnopqrstuvwxyz"      print(abc)      for letter in abc:          if letter in string:              abc = abc.replace(letter, "*")          else:              abc = abc.replace(letter, "_")      return abc      print(histogram("aba ima"))  

my output:

abcdefghijklmnopqrstuvwxyz  **______*___*_____________  

can anyone help me? so I can do if it says: aba ima, so Ill have 3 lines of *?

I asked the same question in a forum in my country, no one could help me. Asked the same at reddit, same thing. I gave up on it almsot, then decided to ask here to see if any different... I was told in all scenarios that I have to use index and find, but I cant seem to understand how I need to use it with this function.. its really annoying, I am stuck on it for a week + and because of it I cant continue on to my next homework ( sorting and then recursions ). Please help on this if anyone can, thanks...

EDIT:

another try of my code, didnt upload but now I will:

def make_counters(alphabet):      counters = []      for i in range(0, len(alphabet)):          counters.append(0)  # must be a counter, so integer      return counters    abc = make_counters("abcdefghijklmnopqrstuvwxyz")    def histogram(string, alphabet):      print(alphabet)      counters = make_counters(alphabet)      for letter in alphabet:          if letter in alphabet:              alphabet.find(letter)          else:              pass        print(histogram("aba ima", abc))  

SECOND EDIT: like that?

def histogram(string):

  abc = "abcdefghijklmnopqrstuvwxyz"      print(abc)      for letter in abc:          if letter in string:              abc = abc.replace(letter, "*")              string = string.replace(letter, "*", 1)              print(abc)          else:              abc = abc.replace(letter, "_")      return abc  

the output is:

abcdefghijklmnopqrstuvwxyz  *bcdefghijklmnopqrstuvwxyz  **cdefghijklmnopqrstuvwxyz  **______*jklmnopqrstuvwxyz  **______*___*nopqrstuvwxyz  **______*___*_____________  

Process finished with exit code 0

How can I display the details from a parent object in a child input form with Angular Material?

Posted: 28 Aug 2021 08:33 AM PDT

I'm trying to display a object from a parent table in a child form input field with Angular Material. But it doesn't display the object values in the input fields. It only displays the <mat-label> that I have created. I have tried add placeholders with property binding but that result to a error.

this is my code: parent-template.html

<table class="mat-elevation-z8 table table-primary table-striped overview-no-margin">    <thead>    <tr>      <th scope="col">Product Tag</th>      <th scope="col">Product Status</th>    </tr>    </thead>    <tbody>    <tr (click)="onSelect(product)"        [class]="selectedProduct === product ? selectedProduct : null"        *ngFor="let product of products">      <td>{{product.tag}}</td>      <td>{{product.status}}</td>    </tr>    </tbody>  </table>    <button (click)="addRandomProduct()" class="addProduct btn-lg btn-primary">Add Product</button>  <app-product-detail [showProductDetail]="selectedProduct"></app-product-detail>  

parent-template.ts

export class ProductEditComponent implements OnInit {    public selectedProduct?: Product;    public products?: Product[];    // public  defaultRow?:number = 8;      constructor() { }      ngOnInit(): void {        this.products = [];      for (let i = 0; i < 8; i++){        this.addRandomProduct();        }    }      public onSelect(product: Product): void{      this.selectedProduct = product;      console.log(product)    }  }  

child-template.html

 <div *ngIf="showProductDetail" id="product-detail">        <form class="product-detail-panel mat-elevation-z8" >          <div id="detail-header">            <span><b>Update scooter </b></span><u>{{showProductDetail.tag}}</u><b> with scooter ID: </b> <u>{{showProductDetail.id}}</u>          </div>          <hr>          <mat-form-field class="product-tag" appearance="fill">            <mat-label>Tag:</mat-label>            <input matInput [(ngModel)]="showProductDetail.tag" >          </mat-form-field>          <mat-form-field class="product-status" appearance="fill">            <mat-label>Product Status:</mat-label>            <mat-select [(ngModel)]="showProductDetail.status" >              <mat-option value="STOCK">STOCK</mat-option>              <mat-option value="OUT OF STOCK">OUT OF STOCK</mat-option>              <mat-option value="COMING SOON">COMING SOON</mat-option>              <mat-option value="NOT DELIVRABLE">NOT DELIVRABLE</mat-option>              <mat-option value="ON SALE">ON SALE</mat-option>            </mat-select>          </mat-form-field>   </div>  

child-template.ts

export class ProductDetailComponent implements OnInit {    @Input() panelMessage = 'Select a product from the left panel:';    @Input() showProductDetail?: Product;      constructor() { }      ngOnInit(): void {    }    }  

Returning an object by value which should conceptually not be copied

Posted: 28 Aug 2021 08:35 AM PDT

I'd like to have an object whose constructor acts as a begin() and it's destructor acts as an end(), and provides functions that are only valid between these two calls as methods. However... I also want to use named constructors, and also have functions that act as factories for this object too.

// this is the object I'm returning by value  class DrawCommand {      DrawCommand(CanvasBuffer & guts, uint32 threadID); // private  public:      // begin(); starts  a draw command      static DrawCommand inMT(Canvas & canvas);     // for main thread      static DrawCommand inWK(const Job & jobRef);  // for worker threads        // end(); submits command to rendering thread      ~DrawCommand();         // returns false if draw can be ignored (doesn't need to be respected)      operator bool();        // commands which would break if used outside of begin() and end()      void doStuff();  };    // this class has a factory that returns by value  class Canvas{  public:      DrawCommand debugDrawCommandMT(){          DrawCommand cmd;          ...          return cmd;      }  };    // usage  {      DrawCommand cmd1 = DrawCommand::inMT(canvas);      cmd1.doStuff();  } // cmd1.~DrawCommand() upon exiting scope    if (DrawCommand cmd2 = canvas.debugDrawCommandMT()) {      cmd2.doStuff();  } // cmd2.~DrawCommand() upon exiting scope    

This means returning this object by value.

This is troublesome as RVO is an optional optimization with side effects. When omitted, this prompts calls to the constructor and destructor. These functions are expensive as they access resources guarded by mutex, so I need to avoid that behavior.

What is the easiest way to ensure this object behaves as if RVO is always taking place when returned?

To be specific, what I'm after is the behavior of RVO, I've been able to find information on what it is and how to hint it's usage to the compiler. But I want to get the side-effect of RVO in a reliable way. Conceptually, it should be as if the object returned isn't a copy, but the original, even if that's not reality.

pip: download only non installed dependencies

Posted: 28 Aug 2021 08:33 AM PDT

Is there is any way to not download the dependencies that are already installed?

I need to install the .whl files without having to download any extra files (missing dependencies ) during the installation, and also without unnecessarily having to download the whole bunch of dependencies during the download.

Using pip download <package-name> --no-deps does not download any dependencies at all.

Edit :
It seems that this problem only occurs when running from a kaggle notebook using !pip download

PHP. If Cookie exists do this - Else do that

Posted: 28 Aug 2021 08:33 AM PDT

I'm trying to create a little php function, which if a cookie exists, then use the css styles, else if it does not exist use these.

I'm using the code below, but it is using the if styles regardless if the cookie exists or not.

What am i doing wrong?

<?php if ( isset($_COOKIE['CookieLawInfoConsent']) ) : ?>  <style>      html.has-not-scrolled #desktop-header { top: 0px; }      #mobile-header { top: 0px; }      main {top: 0px;}  </style>  <?php else : ?>  <style>      @media all and (min-width: 1201px) and (max-width: 1235px) {         html.has-not-scrolled #desktop-header { top: 80px; }      #mobile-header { top: 80px; }      main {top: 80px;  }  </style>  <?php endif; ?>  

Flask, flask-jwt-extended - trying to custom handle Unauthorized error

Posted: 28 Aug 2021 08:35 AM PDT

I am building a flask webapp and I am trying to return custom error message in case of 401 error which is raised when auth header is missing. For Authentication I use Flask-Jwt-Extended. I want to overwrite expired_token_loader(callback) to return 401 error and then catch it using @app.errohandler(401) and redirect to login.
So far I have done this:

@jwt.unauthorized_loader  def unauthorized_callback(callback):      # Missing auth header      # abort(401)      return make_response("", 401)    @app.errorhandler(401)  def unauthorized(e):      return "Custom 401 Error", 401  

Found out in official Flask-JWT-Extended documentation that the function decorated with @jwt.unauthorized_loader must return a Flask Response.

So when I try to abort(401) as it is shown above and not return anything from unaturhorized_callback() it shows werkzeug.exceptions.Unauthorized: 401 Unauthorized: ...

And when I return make_response("", 401) it shows this, that means that the error handler did not handle the error:
enter image description here

Is there any way to throw the error through @jwt.unathorized_loader() and then handle it?
Thank you

Passport.js cookie not persist so login auth doesn't work even though session has the passport

Posted: 28 Aug 2021 08:33 AM PDT

I'm using the passport.js local strategy. I was testing it under proxy setting, localhost. Things worked fine until I prepare to deploy.

I changed the API address to include dotenv and set CORS settings on the server side.

CORS works fine, OPTIONS and the POST get 200 ok. cookie saved in client except I can't see the passport in the session console log on server. But still can see the passport in Mongo DB.

And also very weird thing for me is, I set a redirection after the login auth succeeded, but while it's failing the user stays in the login page still, and when re-attempt to log in, the cookie shows the passport object. But it doesn't persist.

client:

Axios.post(    `${process.env.REACT_APP_API_URI}/api/users/login`,      loginData,     { withCredentials: true, }  ).then((res) => res.data)  

server.js

app.use(helmet());  // app.use(express.static('public'));  app.use("/uploads", express.static("uploads"));    // Passport configuration.  require("./utils/passport");    // connect to mongoDB  mongoose    .connect(db.mongoURI, {      useNewUrlParser: true,      useUnifiedTopology: true,      useCreateIndex: true,      useFindAndModify: false,    })    .then(() => console.log("mongoDB is connected."))    .catch((err) => console.log(err));    // CORS Middleware   const corsOptions = {    origin: "http://localhost:8000",    optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204    credentials: true,    methods: ["POST", "GET", "DELETE", "PUT", "PATCH", "OPTIONS"],    allowedHeaders:      "Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept, x-access-token",  };    // app.use(cors(corsOptions));  app.options(/\.*/, cors(corsOptions), function (req, res) {    return res.sendStatus(200);  });    app.all("*", cors(corsOptions), function (req, res, next) {    next();  });    // to get json data  // support parsing of application/json type post data  app.use(express.json());    app.use((req, res, next) => {    req.requestTime = new Date().toISOString();    next();  });    //support parsing of application/x-www-form-urlencoded post data  app.use(express.urlencoded({ extended: true }));  app.use(cookieParser());    // db session store  const sessionStore = new MongoStore({    mongoUrl: db.mongoURI,    collection: "sessions",  });    // tell app to use cookie  app.use(    session({      secret: process.env.SESSION_SECRET_KEY,      resave: false,      saveUninitialized: false,      store: sessionStore,      cookie: {        httpOnly: true,        secure: false,        sameSite:"none",        maxAge: 24 * 60 * 60 * 1000, // 24 hours        //keys: [process.env.COOKIE_ENCRYPTION_KEY]      },      name: "pm-user",    })  );    // tell passport to make use of cookies to handle authentication  app.use(passport.initialize());  app.use(passport.session());    app.use(compression());    app.use(flash());    app.use((req, res, next) => {    console.log("req.session:", req.session);    // console.log('/////// req: ///////', req);    console.log("////// req.user: ", req.user, " //////");    next();  });    //---------------- END OF MIDDLEWARE ---------------------//  app.use("/api/users", require("./routes/users"));  app.use("/api/auth", require("./routes/passportAuth"));  app.use("/api/admin", require("./routes/admin"));  app.use("/api/search", require("./routes/search"));  app.use("/api/board", require("./routes/board"));  app.use("/api/article", require("./routes/article"));  app.use("/api/store", require("./routes/store"));  app.use("/api/program", require("./routes/program"));  app.use("/api/order", require("./routes/order"));    app.get("/", (req, res) => {    res.send("API Server is now working...");  });    //-------------------- END OF ROUTES ---------------------//  app.all("*", (req, res, next) => {    next(new AppError(`Can't find ${req.originalUrl} on this server.`, 404));  });    app.use(globalErrorHandler);    //----------------- END OF ERROR HANDLER ------------------//    // start server  const port = process.env.PORT || 8080;  const host = process.env.HOST;  const server = app.listen(port, host, () => {    console.log(`Server started: listening at http://${host}:${port}`);  });    

It would be a really big help if you can advise me where to look to fix it. I'm lost and in hurry... Thanks.

Difference between 'multi output' vs 'raw' in keras 'flow_from_dataframe'

Posted: 28 Aug 2021 08:34 AM PDT

I'm not sure about when to use raw vs multi output in the keras flow_from_dataframe class_mode parameter, as by the looks of it, they both provide a way to classifying data with multiple labels. Suppose say I have a dataframe with the image path as well as two columns/classes with labels for each given image, and I would like to create a model which classifies the images based on those classes, which class_mode would I use, and when would I use the other one?

Edit: attached an image of the dataframe I'm using

enter image description here

Action Required Google Play Policies. We have determined your app contains code to facilitate Disruptive Ads

Posted: 28 Aug 2021 08:34 AM PDT

I have one Web-view app in Google Play store. (only for Adroid) According to Google, they found that my app is not compliant with the Disruptive Ads policy. However, my App only has one interstitial ad by Google Admob...

Thus, Google Admob is making Disruptive Ads all the time? Or should I remove the interstitial ad?

Google Play vs Google Admob, nonsense...

How to print password protected PDF in android?

Posted: 28 Aug 2021 08:34 AM PDT

I am printing pdf using the below code which works fine for normal pdfs but crashes with password-protected pdf .is there any way by which we can print password-protected pdf or stop applications from crashing. application crashes even print() called inside a try-catch block.

Note: I am using com.github.barteksc:android-pdf-viewer for viewing protected pdfs

Exception :

java.lang.RuntimeException:     at android.print.PrintManager$PrintDocumentAdapterDelegate$MyHandler.handleMessage (PrintManager.java:1103)    at android.os.Handler.dispatchMessage (Handler.java:106)    at android.os.Looper.loop (Looper.java:246)    at android.app.ActivityThread.main (ActivityThread.java:8506)    at java.lang.reflect.Method.invoke (Native Method)    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:602)    at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1139)  

code that causing Exception:

val printManager = this.getSystemService(Context.PRINT_SERVICE) as PrintManager          val jobName = this.getString(R.string.app_name) + " Document"          try{              printManager.print(jobName, pda, null)          }          catch(ex:RuntimeException)          {              Toast.makeText(this,"Can't print pdf file",Toast.LENGTH_SHORT).show()          }  

PrintDocumentAdapter.kt

  var pda: PrintDocumentAdapter = object : PrintDocumentAdapter() {                    override fun onWrite(                      pages: Array<PageRange>,                      destination: ParcelFileDescriptor,                      cancellationSignal: CancellationSignal,                      callback: WriteResultCallback              ) {                  var input: InputStream? = null                  var output: OutputStream? = null                  try {                      input = uri?.let { contentResolver.openInputStream(it) }                            output = FileOutputStream(destination.fileDescriptor)                      val buf = ByteArray(1024)                      var bytesRead: Int                      if (input != null) {                          while (input.read(buf).also { bytesRead = it } > 0) {                              output.write(buf, 0, bytesRead)                          }                      }                      callback.onWriteFinished(arrayOf(PageRange.ALL_PAGES))                  } catch (ee: FileNotFoundException) {                      //Catch exception                  } catch (e: Exception) {                      //Catch exception                  } finally {                      try {                          input!!.close()                          output!!.close()                      } catch (e: IOException) {                          e.printStackTrace()                      }                  }              }                    override fun onLayout(                      oldAttributes: PrintAttributes,                      newAttributes: PrintAttributes,                      cancellationSignal: CancellationSignal,                      callback: LayoutResultCallback,                      extras: Bundle              ) {                  if (cancellationSignal.isCanceled) {                      callback.onLayoutCancelled()                      return                  }                  val pdi = PrintDocumentInfo.Builder("Name of file")                      .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build()                  callback.onLayoutFinished(pdi, true)              }          }  

How to convert unicode character to svg and then a favicon

Posted: 28 Aug 2021 08:35 AM PDT

I want to convert this unicode character 📘 into svg format. Because I want to use it as a favicon. How do I simply do this?

Why does Chrome request both .svg AND .ico favicons?

Posted: 28 Aug 2021 08:34 AM PDT

Most modern browsers support .svg favicons as of Sep 2020. See: https://caniuse.com/link-icon-svg

However, in order to support legacy browsers my site serves a .ico favicon in addition to a .svg favicon with the following html links in <head>:

<link rel="icon" type="image/x-icon" href="images/favicon.ico">  <link rel="icon" type="image/svg+xml" href="images/favicon.svg">  

This works as expected where browsers that support .svg favicons appropriately use the .svg favicon while browsers that do not use the .ico favicon. What I don't understand is why browsers that do support .svg favicons (like Chrome) also request the .ico favicon? See the Chrome waterfall below:

DevTools Network Tab

If Chrome has already successfully downloaded the .svg favicon why does it go on to request the .ico favicon as well? Shouldn't Chrome intelligently select only one favicon type to load without forcing the client to download unnecessary resources? Is there a way to instruct Chrome to only download the .svg favicon?

get id from url in react.js

Posted: 28 Aug 2021 08:33 AM PDT

i just want to make Ajax request to fetch data from API in REACT.JS, but every API need (id), i want to get that id from URL in browser, how can i do that? this is my code:

componentDidMount(){  fetch("http://localhost:8000/personal/1")  .then(res => res.json())  .then(json => {      this.setState({          isLoaded: true,          information: json,      })  })  

i make the API by Laravel, and every thing work good with this code above, but as i said, i want to get the id from url in browser not just write it as now, thank you :) }

How to make a grid container shrink to fit the content?

Posted: 28 Aug 2021 08:35 AM PDT

I'm trying to make a game with a grid. I have x divs with x divs inside them, to create the grid.

The problem is that I want the container div for all of this to only be as big as it needs to be (say, 5x5 squares at 25px each = 125px x 125px container div). The height is fine, but the width stretches to the end. Each box is to be 25px.

I've tried grid-template-rows: repeat(auto-fill, 25px) which doesn't seem to work. I can't set it to a specific width (125px) because the amount of squares is going to be dynamic (but always a square number).

* {    margin: 0px;    padding: 0px;    box-sizing: border-box;  }    #start {    position: relative;    width: auto;    margin: 50px auto;    display: grid;    grid-template-rows: repeat(auto-fill, 25px);  }    .row {    display: grid;    grid-template-columns: repeat(auto-fill, 25px);  }    .gameNode {    margin: 0px;    height: 25px;    width: 25px;  }    .even {    background-color: #666;  }    .odd {    background-color: #999;  }
<div id="start">    <div id="row_0" class="row">      <div class="gameNode odd" id="node_1"></div>      <div class="gameNode even" id="node_2"></div>      <div class="gameNode odd" id="node_3"></div>      <div class="gameNode even" id="node_4"></div>      <div class="gameNode odd" id="node_5"></div>    </div>    <div id="row_1" class="row">      <div class="gameNode even" id="node_6"></div>      <div class="gameNode odd" id="node_7"></div>      <div class="gameNode even" id="node_8"></div>      <div class="gameNode odd" id="node_9"></div>      <div class="gameNode even" id="node_10"></div>    </div>    <div id="row_2" class="row">      <div class="gameNode odd" id="node_11"></div>      <div class="gameNode even" id="node_12"></div>      <div class="gameNode odd" id="node_13"></div>      <div class="gameNode even" id="node_14"></div>      <div class="gameNode odd" id="node_15"></div>    </div>    <div id="row_3" class="row">      <div class="gameNode even" id="node_16"></div>      <div class="gameNode odd" id="node_17"></div>      <div class="gameNode even" id="node_18"></div>      <div class="gameNode odd" id="node_19"></div>      <div class="gameNode even" id="node_20"></div>    </div>    <div id="row_4" class="row">      <div class="gameNode odd" id="node_21"></div>      <div class="gameNode even" id="node_22"></div>      <div class="gameNode odd" id="node_23"></div>      <div class="gameNode even" id="node_24"></div>      <div class="gameNode odd" id="node_25"></div>    </div>  </div>

I expected the container div to take up only as much space as the squares, but it stretches across the entire page. The height seems fine.

Here is a screenshot of what it's doing:

enter image description here

It's creating a bunch of extra squares, filling the space rather than only filling the actual divs.

Am I handling this correctly, or should I be formatting my HTML differently to get the desired effect?

How do you initialize a global variable only when its not defined?

Posted: 28 Aug 2021 08:34 AM PDT

I have a global dictionary variable that will be used in a function that gets called multiple times. I don't have control of when the function is called, or a scope outside of the function I'm writing. I need to initialize the variable only if its not initialized. Once initialized, I will add values to it.

global dict  if dict is None:      dict = {}    dict[lldb.thread.GetThreadID()] = dict[lldb.thread.GetThreadID()] + 1  

Unfortunately, I get

NameError: global name 'dict' is not defined  

I understand that I should define the variable, but since this code is called multiple times, by just saying dict = {} I would be RE-defining the variable every time the code is called, unless I can somehow check if it's not defined, and only define it then.

Linux Git: Unable to access remote: error setting certificate verify locations

Posted: 28 Aug 2021 08:34 AM PDT

So I'm running OpenSUSE Leap 42.1, and Git 2.6.6. Up until today, I've had no problems pushing/pulling/fetching from a remote GitHub repo.

Now, today, I'm having this error message:

fatal: unable to access 'https://github.com/myName/myProject.git/': error setting certificate verify locations:    CAfile: /etc/ssl/certs/ca-certificates.crt    CApath: none  

Anytime I do a push/pull/fetch, I get this. My first thought was to check that filepath that's provided, and no file named ca-certificates.crt exists in /etc/ssl/certs.

So... I'm not entirely sure what to do. Not sure why this suddenly stopped working either, maybe an OS or git update broke it? Either way, looking to be pointed in the right direction.

Thanks.

Building a type description table for a struct at compile time

Posted: 28 Aug 2021 08:33 AM PDT

Have a library that accepts a struct defining the row format at compile time. Different users have different variations of the struct.

One example:

typedef struct { INT16U a, INT32S b } logrow_t;  

At run time I would like to iterate through this struct and print each element and its type.

The first solution that comes to mind is to build a table:

typedef struct { char var_name[16], char var_type[16], int bytelen } logrow_desc_t;    logrow_desc_t descriptions[] = { { "a", "INT16U", 2 }, { "b", "INT32S", 4 } };  

Is there a better solution that allows for any user of the library to specify a different row struct? Is there a way to leverage the preprocessor/compiler to build the descriptions table at compile time?

Create favicon from .svg in lumen

Posted: 28 Aug 2021 08:34 AM PDT

I'm starting to use lumen and I have to add a favicon but is .svg.

How do I create a favicon for all devices or sizes from a picture .svg?

No comments:

Post a Comment