Thursday, November 25, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Vuetify: Changing hexcode of a color

Posted: 25 Nov 2021 07:46 PM PST

Is it possible to change the hexcode for the colors outlined on this page for Vuetify?

Say I wanted to slightly alter the red color to something lighter. How could I do that?

Per the docs I have something like this but I want to change the color directly:

import Vue from 'vue';  import Vuetify from 'vuetify';    Vue.use(Vuetify);    export default new Vuetify({      theme: {          themes: {              light: {                  primary: '#123456'              }          }      }  });  

What is the proper way to escape quotes and slashes when running a Jest test with --collectCoverageFrom from Powershell via npm scripts?

Posted: 25 Nov 2021 07:45 PM PST

I am a React developer, and am used to running commands like the example below from Bash in Linux, but now I have to make it work in a Windows environment from Powershell:

npm test ExampleComponent --collectCoverageFrom='["**/ExampleComponent.tsx"]' --watch  

The npm test script just has "jest" in it, but I need to use it via the script so that I am using the version of jest in the project, not a global.

I use this when trying to fill-in gaps in code coverage in a specific file (ExampleComponent.tsx), so I want Jest to reassess the coverage for just that one file when I save changes to the test file (ExampleComponent.test.tsx in this case).

This is what I ran in Powershell (Added the quotes in "--" because Powershell doesn't treat -- as bash does, and switched from forward slash to backslash for Windows):

npm test "--" ExampleComponent --collectCoverageFrom='["**\ExampleComponent.tsx"]' --watch  

This is how jest gets called as per the output from npm:

jest "ExampleComponent" "--collectCoverageFrom=[**\ExampleComponent.tsx]" "--watch"  

In Powershell (version 7.2, if that matters), the command above doesn't restrict the coverage check to the specified file. It does only test the specified file, but the collectCoverageFrom option is ignored presumably because the pattern jest receives is mangled by Powershell.

How can I escape the quotes and slashes from a Powershell commandline to replicate the bash invocation at the top? Based on answers regarding escaping in Powershell, I've tried combinations of multiple backslashes and multiple quotes in a myriad of permutations, but none of them have worked so far.

How do I modify my code to add another submenu level to my CSS only, dropdown menu

Posted: 25 Nov 2021 07:45 PM PST

Hi and thanks in advance,

I have some CSS that displays 3 levels of dropdown but I need it to work for the 4th level also. I tried copying the 3rd level code and just adding an extra li or ul but it does not work. It needs to be just CSS with no jquery code. The last tier does not align to the left of the parent tier but rather, appears inline with the parent incorrectly.

`    <!DOCTYPE html   <head>  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">    <style type="text/css">     /* Menu General Styles */  .menuBackground {                  background-color: #164149; /* Dark Green */                  color: White;                  float: left:         /* The float property specifies how an element should float, left, right, none, inherit (from parent)*/                  text-align: left;    /* To align text left*/                  white-space: nowrap; /* Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line. The text continues on the same line until a <br> tag is encountered */                  margin-left: 1px;    /* This moves the menu bar to left align with the banner because of the Context Editor container misaligning it */                  margin-top: 12px;    /* This moves the menu bar up or down from the banner */  }    /* Adjust the text position in the drop-down menus to vertically align text with their icons */  .nav-text {                  display: inline-block;                  vertical-align: -2px;  }    /* Create a right facing black arrow for the year ranges in the files menu */  .arrow {                  width: 0;                   height: 0;                   border-left: 4px solid transparent;                  border-right: 4px solid transparent;                  border-bottom: 4px solid black;                  display: inline-block;                  padding-bottom: 5px; /* align and centre the arrow with the text */  }    /* Transform the arrow to the right orientation */  .right {    transform: rotate(90deg);    -webkit-transform: rotate(90deg);  }    .dropDownMenu,  .dropDownMenu ul {                  list-style: none;    /* Lists have default markers/bullets. To remove these, add list-style: none; to <ul> or <ol>: */                  margin: 0px;            /* Lists have a default margin. To remove this, add margin: 0; to <ul> or <ol>: */                  padding: 0px;        /* Lists have a default padding. To remove this, add padding: 0; to <ul> or <ol>: */                  font-weight: Normal;                  font-family: Calibri;                  font-size: 14px;  }      /* This is the menu list at the top level */  .dropDownMenu li {                  background-color: #164149; /* Dark Green */                  color: White;                                      position: relative; /*HTML elements are positioned static by default. Static positioned elements are not affected                                      by the top, bottom, left, and right properties. An element with position: relative; is positioned relative to its normal position.                                                       Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be                                                       adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.*/  }    .dropDownMenu a {                  padding: 12px 20px;                  display: block;                  text-decoration: none;                  background-color: #164149; /* Dark Green */                  color: White;                  font-family: Calibri;                  font-weight: Normal;                  font-size: 14px;  }    .dropDownMenu a:hover {                  background-color: white; /* White with black font  - when top menu hovered over */                  color: black;  }      /* Level 1 Drop Down Menu */  .dropDownMenu > li {                  display: inline-block;                  vertical-align: top;                  margin-left: -4px; /* solve the 4 pixels spacing between list-items */                  background-color: #164149; /* Dark Green */                  color: White;  }    .dropDownMenu > li:first-child {                  margin-left: 0;  }    .dropDownMenu > li > a {                  background-color: #164149; /* Dark Green */                  color: White;  }  .dropDownMenu > li > a:hover {                  /*background-color: #164149;  Dark Green */                  /* color: White; */  }        /* Level 2 */  .dropDownMenu > li > ul {                  text-align: left;                  width: auto; /* change auto value with 200px if you want a bigger menu */                  display: none;                  position: absolute;                  top: 100%;                  left: 0;                  z-index: 9999999; /* if you have YouTube iframes, is good to have a bigger z-index so the video can appear above the video */                  font-weight: normal;                   font-family: Calibri;                  font-size: 14px;  }    .dropDownMenu > li:hover > ul {                  display: block;                  background-color: #bddbdb;  /* Light Blue - when menu droped down */                  color: Black;  }      .dropDownMenu ul li a {                  background-color: #bddbdb; /*Light Blue - when menu droped down */                  color: Black;                  padding: 10px 20px;                  font-weight: normal;                   font-family: Calibri;                  font-size: 14px;  }    .dropDownMenu ul li a:hover {                  background-color: #164149; /* Dark Green */                  color: White;  }    /* Make arrow white when this 2nd level menu is hovered */  .dropDownMenu ul li a:hover .arrow{                  border-bottom: 4px solid white;  }    .dropDownMenu > li:hover > a {      background-color: white;  /* White with black font for top menu button - when child menus hovered over */      color: Black;  }      /* Level 3 */  .dropDownMenu > li > ul > li > ul {                  text-align: left;                  display: none;                  background-color: #bddbdb; /* Light Blue - when menu droped down */                  color: Black;                  position: absolute;                  left: 100%;                  top: 0;                  z-index: 9999999;                  font-weight: normal;                   font-family: Calibri;                  font-size: 14px;  }    .dropDownMenu > li > ul > li a {                  padding: 10px 20px;  }    .dropDownMenu > li > ul > li:hover > ul {                  display: block;                  background-color: #164149; /* Dark Green */                  color: White;  }    .dropDownMenu > li > ul > li:hover > a {      background-color: #164149;  /* Sustain dark green with white font for the second level menu selected - when child menus hovered over */      color: White;  }    /* Sustain WHITE arrow on 2nd level menu when 3nd level menu is hovered */  .dropDownMenu > li > ul > li:hover > a .arrow{                  border-bottom: 4px solid white;  }      /* Level 4 */  .dropDownMenu  > li > ul > li > ul > li > ul{                  text-align: left;                  display: none;                  background-color: #bddbdb; /* Light Blue - when menu droped down */                  color: Black;                  position: absolute;                  left: 100%;                  top: 0;                  z-index: 9999999;                  font-weight: normal;                   font-family: Calibri;                  font-size: 14px;  }    .dropDownMenu  >li > ul > li > ul > li a {                  padding: 10px 20px;  }    .dropDownMenu > li > ul > li > ul > li:hover > ul{                  display: block;                  background-color: #164149; /* Dark Green */                  color: White;  }    .dropDownMenu  > li > ul > li > ul > li:hover > a {      background-color: #164149;  /* Sustain dark green with white font for the second level menu selected - when child menus hovered over */      color: White;  }    /* Sustain WHITE arrow on 2nd level menu when 4th level menu is hovered */  .dropDownMenu  > li > ul > li > ul > li:hover > a .arrow{                  border-bottom: 4px solid white;  }  </Style>  </head>    <body>    <div class="menuBackground">      <ul class="dropDownMenu">          <li><a>Home</a>              <ul>                  <li><a href="">Home Page 1</a></li>                  <li><a href="">Home Page 2</a></li>              </ul>          </li>          <li><a>Files</a>              <ul>                  <li><a href="#"><span class="nav-text">&nbsp;&nbsp;2021&nbsp;&nbsp;&nbsp;<i class="arrow right"></i>&nbsp;2023</span></a>                      <ul>                          <li><a href="">2021</a></li>                              <ul>                                  <li><a href="">2021 Part A</a></li>                                  <li><a href="">2021 Part B</a></li>                              </ul>                          <li><a href="">2022</a></li>                          <li><a href="">2023</a></li>                      </ul>                  </li>                  <li><a href="#">&nbsp;&nbsp;2018&nbsp;&nbsp;&nbsp;<i class="arrow right"></i>&nbsp;2020</span></a>                      <ul>                          <li><a href="">2018</a></li>                          <li><a href="">2019</a></li>                          <li><a href="">2020</a></li>                      </ul>                  </li>                  <li><a href="#">&nbsp;&nbsp;2015&nbsp;&nbsp;&nbsp;<i class="arrow right"></i>&nbsp;2017</span></a>                      <ul>                          <li><a href="">2015</a></li>                              <ul>                                  <li><a href="">2015 Part A</a></li>                                  <li><a href="">2015 Part B</a></li>                                  <li><a href="">2015 Part C</a></li>                              </ul>                          <li><a href="">2016</a></li>                          <li><a href="">2017</a></li>                      </ul>                  </li>              </ul>          </li>                                              </ul>  </div>    </body>    </html>  

`

Mediawiki redirect from old URL path to new

Posted: 25 Nov 2021 07:45 PM PST

I have old URL path for all pages

example.com/w/Page_title  

Now I changed it to

example.com/Page_title  

using Short URL manual for Apache

And the question is: How to make 301 redirects from old path for users that coming back using bookmarks?

my LocalSettings.php

$wgForceHTTPS = true;    $wgScriptPath = "/wiki";  $wgArticlePath = "/$1";  

and mod_rewrite:

RewriteEngine On  # Short URL for wiki pages  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d  RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/index.php [L]  # Redirect Main Page to /  RewriteRule ^/*$ /index.php?title=Main_Page [L,QSA]  RewriteRule .*\.ico$ - [L]  

Charts.js Position outside labels at the start of the segment

Posted: 25 Nov 2021 07:43 PM PST

I'm trying to make a pie chart of outside datalabels position from center to at the start point of the segment. I moved outside datalabels at the center. It's still problem how to move at the starting point of the segment. I am using chartjs-datalabels-plugin.


This my code right now:

<script>      var ctx = document.getElementById("myChart").getContext('2d');      var data = {          labels: ["wake up","","","","have breakfast", "bursh teeth", "take a shower", "take a bath", "get dressed", "go to school", "study English"],              datasets: [                  {                      backgroundColor: ["#FA8072","#FFFF66","#FFC0CB","#a4dded","#3498db","#F0E68C","#3498db","#a4dded","#F0E68C","#FFC0CB","#90EE90"],                        data:[80, 15, 13, 12,40, 12, 50, 20, 30, 20, 12],                      //labels: ["0:00", "23:00", "22:00", "20:00 ", "19:00 ", "14:00", "13:00", "10:00","9:00","8:00",""],                      labels: ["0:00","8:00","","9:00","10:00","13:00","14:00","19:00","20:00","22:00","23:00"],                      borderWidth: 1,                                        }              ]          };                  let numSectors = 11;          let sectorDegree = 360 / numSectors;          let width = (ctx.canvas.width - parseInt(4 * 2));          let fontSize = 16;          let b = (width / 2) - 3;          let c = b - (fontSize * 1.8);          let a = Math.sqrt((Math.pow(b, 2) + Math.pow(c, 2)) - (2 * b * c * Math.cos((sectorDegree / 2) * Math.PI / 180)));          let offset = a - (fontSize * 1.2);          let alignAngle = (Math.asin(Math.sin((sectorDegree / 2) * Math.PI / 180) * c / a) * 180 / Math.PI) - (sectorDegree / 2);          console.log(sectorDegree);      myChart = new Chart(ctx, {                  type: 'pie',                  plugins: [ChartDataLabels],                  data: data,                  options: {                      layout: {                          padding: {                              left: 200,                              right: 200,                                                      },                      },                                            plugins: {                          legend: {                              display: false                          },                          title: {                              display: true,                              text: ''                          },                          tooltip: {                              callbacks: {                                  label: function(a) {                                      return a.label;                                  }                              }                          },                          datalabels: {                                                            labels: {                                  title: {                                                                            anchor: 'end',                                      align: function(context) {                                          return (sectorDegree * context.dataIndex) - alignAngle;                                      },                                      offset: function(context){                                          return ;                                      },                                                                       clamp: true,                                                                                                        formatter: function(value, ctx) {                                          return ctx.dataset.labels[ctx.dataIndex];                                      }                                  },                                  value: {                                      align: 'end',                                      formatter: (value, ctx) => {                                          return ctx.chart.data.labels[ctx.dataIndex];                                      },                                      font: {                                          weight: 'bold',                                          size: 14,                                          color: '#333'                                      },                                      rotation: [-90, -76, -40 , -20, -90, -90, 0, 0, 0 , -90, 90, -350,20, 30, 45 , 54.9, 58, 68,70 ],                                                                  }                              }                          }                      }                  }              });  </script>  

Pie chart with outer datalabels start from center

LINQ queries always sort by primary key value even when orderby clause explicitly calls to sort with a different value

Posted: 25 Nov 2021 07:43 PM PST

I am working on my first personal C# project and am incorporating LINQ to make queries against a SQL Server database. I am experiencing an issue with LINQ where queries always sort the records returned from the table according to their primary key value even though orderby clauses exist in the query.

My objective is to query a table that includes columns for first name and last name (both of type varchar); sort by first name; then sort by last name. The problem code consists of two sections. The first is the original query:

var dayShiftCrew =              from information in context.EmployeeInformations              where information.EmployeeShiftType.Shift == "Day" && information.EmployeePositionType.Position == "Crew"              orderby information.EmployeeNamesAndNumber.FirstName, information.EmployeeNamesAndNumber.LastName              select information.EmployeeNamesAndNumber;  

The second part is a foreach statement that populates another table with the query results:

foreach (var employee in dayShiftCrew)              {                  var position =                      from selection in context.EmployeeInformations                      where selection.EmployeeID == employee.EmployeeID                      select selection.Position;                    string query2 = $@"USE Employees; INSERT INTO WeeklySchedule_{month}_{day}_{year} " +                      @"(EmployeeID, Name, Position) VALUES " +                      $@"({employee.EmployeeID}, '{employee.FirstName + (" ") + employee.LastName}', '{position.First()}');";                    SqlCommand command2 = new SqlCommand(query2, connection);                  command2.ExecuteNonQuery();              }  

When I view the destination table after it is populated, the records are not arranged according to the query's orderby clause. I have executed variations of this code multiple times, and each time the records appear in the same sequence. The sequence in the destination table matches the sequence in the original table, which leads me to think that either the query is sorting by the records' primary key value or is not sorting at all and simply returning the records in their original sequence.

I'm sure that there is something that I'm overlooking, but I have been experimenting for a while with this code and cannot find a solution to sort correctly. I have tried both kinds of syntax for LINQ queries; tried using one orderby rule instead of two; and rewrote lines for immediate instead of deferred execution.

Other specific details: The from clause refers to a table with a composite primary key that includes four foreign-key relationships. The query returns an IQueryable that contains the desired records, albeit in the wrong order. No exceptions are thrown at compile or runtime, and no other unexpected behavior is occurring apart from this.

Is this Bubble Sort or Quick Sort?

Posted: 25 Nov 2021 07:43 PM PST

#include <stdio.h>  #include <conio.h>  #include <time.h>  #include <stdlib.h>  #define MAX 10    int main() {    int data[10], no, i, j, n, c;      printf("\n Enter no of elements :");    scanf("%d", &no);    printf("\nEnter the data");    for (i = 0; i < no; i++) {      scanf("%d", &data[i]);    }    n = MAX;    do {      for (i = 0; i < n - 1; i++) {        if (data[i] > data[i + 1]) {          data[i] = data[i] + data[i + 1];          data[i + 1] = data[i] - data[i + 1];          data[i] = data[i] - data[i + 1];        }      }      n = n - 1;      for (i = MAX - 1, c = 0; i >= c; i--) {        if (data[i] < data[i - 1]) {          data[i] = data[i] + data[i - 1];          data[i - 1] = data[i] - data[i - 1];          data[i] = data[i] - data[i - 1];        }      }      c = c + 1;    } while (n != 0 && c != 0);    printf("The sorted array is:");    for (i = 0; i < no; i++) {      printf("%d\t", data[i]);    }  }  

I was confident it was bubble sort at first glance until I saw the second looping which make me confused why would it sorting from behind as well. Could anyone tell me if it's Bubble Sort or another sorting? Thank you in advance!

Infinty loop in constuctor - Creating the same istances of related objects

Posted: 25 Nov 2021 07:46 PM PST

I got stuck in an endless loop creating the same objects over and over in the models.

But from the beginning:

I have two related models, lets call A and B

A could has many B and B belongs to one A.

And since model B refers to the fields of A, I added it as protected property to avoid creating new object when calling B method related with A fields.

The constuctor of B looks like:

public function __construct(int $id = null)  {      parent::__construct($id);        $a = $this->get('a_id');       if ($a) {          $this->a = new A($a);      }  }  

and A:

public function __construct(int $id = null)  {      parent::__construct($id);        $this->date = new CarbonPL($this->get('date'));      $this->initB();  }  

But then I realized that calling initB() creates again the same instance o B with creating the same A and so on forever

private function initB()  {      if (!$this->isReferenced()) { // Checks wheter is instance exists in DB          return;      }      $query = B::getIDQuery();      $query .= ' WHERE is_del IS FALSE';      $query .= ' AND a_id = ' . $this->id;        $ids = Helper::queryIds($query);        foreach ($ids as $id) {          $this->B[] = new B($id);      }  }  

I need that object of A contains loaded of B and vice verse, because a lot of B refer to A field and vice versa, but how to prevent yourself from such an endless loop.

I quickly got the idea of an extra parameter in B which would be A, and if it were, I wouldn't have to reuse the constuctor. But I don't really like this solution because of the second parameter and I was wondering how to solve it in a different (better) way, preferably so that you can still only enter the identifier.

B conctructor after that fix:

public function __construct(int $id = null, A $a = null)  {      parent::__construct($id);        if ($a) {          $this->a = $a;      } else {          $a = $this->geti('a_id');          if ($a) {              $this->a = new A($a);          }      }  }  

creating dynamic routes using nodejs

Posted: 25 Nov 2021 07:43 PM PST

app.js

  // Calling Routes    require("./routes")(app);  

router folder index.js

module.exports = function (app) {    app.use("/", require("./all_routes"));  }  

all_routes.js

var express = require("express");  var router = express.Router();    router.get("/", function (req, res, next) {   res.render("home/index.html");  });    //About Page  router.get("/about", function (req, res, next) {   res.render("about/index.html");  });    //Contact   router.get("/contact", function (req, res, next) {   res.render("contact/index.html");  });    //product  router.get("/product", function (req, res, next) {   res.render("product/index.html");  });    //product list  router.get("/product/demo-product", function (req, res, next) {   res.render("demo-product/index.html");  });    router.get("/product/request-product", function (req, res, next) {   res.render("request-product/index.html");  });    //service  router.get("/service", function (req, res, next) {   res.render("product/index.html");  });    //service list  router.get("/service/what-we-do", function (req, res, next) {   res.render("what-we-do/index.html");  });    router.get("/service/how-we-do", function (req, res, next) {   res.render("how-we-do/index.html");  });    

I am trying to reduce the code in all_routes.js file has same code is repeating again and again

I searched online and trying to create it dynamically but getting no success is there any way I can reduce the line of code as I have given the follow of my code above

if statement, going back and forth

Posted: 25 Nov 2021 07:44 PM PST

i am new to python, but have programmed some structured text, and a tiny bit c++ now i am working on a problem using if statements and it doesnt seem to work the way i am used to

example code:

more_guests = 0  loop = bool; loop = False  ferdig = int; ferdig = 1  while loop == False:      guests = []      more_guests = 0      if int(ferdig) == 1:          guest = input("type in guest ")          more_guests = int(input("done? 1 for yes 2 for no "))          if int(more_guests) == 1:            guests.append(guest)            ferdig == 3          elif int(more_guests) == 2:              guests.append(guest)              ferdig == 2          else:              print("unvalid answer, please use 1 or 2")              ferdig == 1      elif int(ferdig) == 2:          ferdig = 1      elif int(ferdig) == 3:          print(guests)      else:          loop = True  

ive tried making sure its an integer and so on, just keep getting stuck on done? 1 for yes 2 for no, it always loop me back to type in guest

while using structured text i often used this way of going back and forth, but i cant seem to understand it in python, maybe i should rather use case/switch? anyways if anyone could help me understand if you can use the IF statement this way in python is highly appreciated

Chain functions with callbacks TypeScript

Posted: 25 Nov 2021 07:44 PM PST

After reading an article about Handling Failure by Vladimir Khorikov, I try to implement it using TypeScript.

The example code was written in C#, which I can understand only the idea, not the code.

Here is my implementation so far.

export class Result<T> {    success: boolean;    private error: string | null;    private _value: T;      get value(): T {      if (!this.success) {        throw new Error('Cannot get value of an error result.');      }        return this._value;    }      get errorMessage(): string {      if (this.success || this.error === null) {        throw new Error('Cannot get error message of a success result.');      }        return this.error;    }      get failure(): boolean {      return !this.success;    }      private constructor(success: boolean, error: string | null, value?: T) {      if (success && error != null) {        throw new Error('Success result cannot have error message');      }        if (!success && (error === null || error.length === 0)) {        throw new Error('Failed result must have error message');      }        this.success = success;      this.error = error;      this._value = value as T;    }      /**     * Create failure result     * @param errorMessage error message     * @returns failureResult     */    static fail<T>(errorMessage: string): Result<T> {      return new Result(false, errorMessage);    }      /**     * Create success result     * @param value     * @returns successResult     */    static ok<T>(value?: T): Result<T> {      return new Result(true, null, value);    }      /**     * Combine multiple results into one result     * @param results     * @returns result     */    static combine(...results: Result<any>[]): Result<any> {      for (let result of results) {        if (result.failure) {          return result;        }      }        return Result.ok();    }      /**     * Do things on success result     * @param func     * @returns result     */    onSuccess(func: Function): Result<T> {      if (this.success) {        func();      }        return this;    }      /**     * Do things on failure result     * @param func     * @returns result     */    onFailure(func: Function): Result<T> {      if (this.failure) {        func();      }        return this;    }      /**     * Do things on both success and failure result     * @param func     * @returns result     */    onBoth(func: Function): Result<T> {      func();        return this;    }  }  

I am struggling to implement the chain functions.

In the example code, the onSuccess, onFailure, and onBoth functions are chained beautifully.

return Result.Combine(billingInfoResult, customerNameResult)          .OnSuccess(() => _paymentGateway.ChargeCommission(billingInfoResult.Value))          .OnSuccess(() => new Customer(customerNameResult.Value))          .OnSuccess(              customer => _repository.Save(customer)                  .OnFailure(() => _paymentGateway.RollbackLastTransaction())          )          .OnSuccess(() => _emailSender.SendGreetings(customerNameResult.Value))          .OnBoth(result => Log(result))          .OnBoth(result => CreateResponseMessage(result));  

But in my code, it can only trigger void function. The function can't pass its result to the next function.

Could you show me how to implement this? Any suggestions would be appreciated.

Missing Bootstrap pagination page numbers in Laravel 8

Posted: 25 Nov 2021 07:44 PM PST

I copied the table from blade file B which pagination is working fine to blade file A. But the pagination is not working on Blade file A. It does have 10 results shown, but the page number navigation is missing.

Here's a screenshot for reference: Missing page numbers

Here is my code:

Blade file A

<div class="row">      <div class="col-xs-12 col-sm-12 col-md-12">          <table class="table table-bordered">              <tr>                  <th></th>                  <th>No</th>                  <th>Zone</th>                  <th>Code</th>                  <th>Description</th>              </tr>              @foreach ($items as $key => $item)              <tr>                  <td>{{ Form::checkbox('item[]', $item->id, false, array('class' => 'name')) }}</td>                  <td>{{ $loop->index+1 }}</td>                  <td>{{ $item->zone }}</td>                  <td>{{ $item->code }}</td>                  <td>{{ $item->description }}</td>              </tr>              @endforeach          </table>      </div>  </div>  

Blade file B:

<table class="table table-bordered">    <tr>       <th>No</th>       <th>Zone</th>       <th>Code</th>       <th>Description</th>       <th width="280px">Action</th>    </tr>      @foreach ($items as $key => $item)      <tr>          <td>{{ ++$i }}</td>          <td>{{ $item->zone }}</td>          <td>{{ $item->code }}</td>          <td>{{ $item->description }}</td>          <td>              {{-- <a class="btn btn-info" href="{{ route('items.show',$item->id) }}">Show</a> --}}              @can('item-edit')                  <a class="btn btn-primary" href="{{ route('items.edit',$item->id) }}">Edit</a>              @endcan              @can('item-delete')                  {!! Form::open(['method' => 'DELETE','route' => ['items.destroy', $item->id],'style'=>'display:inline']) !!}                      {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}                  {!! Form::close() !!}              @endcan          </td>      </tr>      @endforeach  </table>  

Controller A:

public function create(Request $request)  {      $items = Item::paginate(10);      $sites = Site::get(["name", "id"])->all();      // $states = State::all();      // $cities = City::where("state_id",14)->get(["name", "id"]);      return view('services.create', compact('sites', 'items'))          ->with('i', ($request->input('page', 1) - 1) * 5);  }  

Controller B:

public function index(Request $request)  {      $items = Item::orderBy('id', 'DESC')->paginate(10);      return view('items.index', compact('items'))          ->with('i', ($request->input('page', 1) - 1) * 5);  }  

Why can compactMap not remove nil values from an array of optional Any?

Posted: 25 Nov 2021 07:45 PM PST

I have this simple code, what I am trying to do is removing nil values from [Any?] and make an [Any]. But compactMap does not work!

let optionalString: String? = nil  let optionalInt: Int? = nil    let customTuple = (optionalString, "a", "b", "c", optionalInt)    let arrayOfChildren: [Mirror.Child] = Array(Mirror(reflecting: customTuple).children)    let arrayOfChildrenValues: Array<Any?> = arrayOfChildren.map({ element in element.value })    let compactArrayOfChildrenValues: Array<Any> = arrayOfChildrenValues.compactMap({ element in element })    print(compactArrayOfChildrenValues)  

The printed result:

[nil, "a", "b", "c", nil]

For example, the following simple test would work! But my code in top does not! What I am missing here?

let optionalString: String? = nil  let optionalInt: Int? = nil  let array: [Any?] = [optionalString, "Hello, world!", optionalInt, 1000]  print(array.compactMap({ element in element }))  

result:

["Hello, world!", 1000]

Error saying constructor does not use parameters in an inherited class in Java

Posted: 25 Nov 2021 07:45 PM PST

I'm trying to write a subclass for a hash table that implements a Symbol Table. It's meant to have the exact same functionality as the superclass except for the hash method, so everything else is exactly the same. I'm using

public class QuadProbingHT<Key, Value> extends LinearProbingHT<Key, Value> implements SymbolTable<Key, Value> {        public QuadProbingHT() {          super();      }  

for a class signature/constructor. The superclass constructor takes no parameters. Here is its signature/constructor:

public class LinearProbingHT<Key, Value> implements SymbolTable<Key, Value> {    protected int M;  private int N;  protected Entry[] keys;    public LinearProbingHT() {      M = 997;      N = 0;      keys = new Entry[M];      for (int i = 0; i < M; i++) {          keys[i] = null;      }  }    public int hash(Key k) {      int retval = k.hashCode() & 0x7fffffff % M;      return retval;  }  

Here's how I'm testing in Main:

import java.util.Arrays;import java.util.HashSet;import java.util.Set;    public class Main {  public static void main(String[] args) {    testIntegers(new QuadProbingHT<Integer, Integer>());}    public static void testIntegers(SymbolTable<Integer, Integer> st) {}}  

which gives me an error:

Main.QuadProbingHT does not take parameters

It seems like this constructor is not supposed to take parameters. Generics and for the most part inheritance are new to me, but I've tried playing around with the < > symbols in the signature, in the super, and nothing seems to be working. Is there a reason why it seems to be expecting parameters when the superclass constructor takes no parameters?

Here's the entire QuadProbingHT class:

public class QuadProbingHT<Key, Value> extends LinearProbingHT<Key, Value> implements SymbolTable<Key, Value> {    public QuadProbingHT() {      super();  }    @Override  public int hash(Key k) {      int retval = k.hashCode() & 0x7fffffff % M;      if (keys[retval] != null) { //collision alert          int i = 1;          while (keys[k.hashCode() & 0x7fffffff % M + i * i] != null) {//collision alert              i++;          }      }      return retval;  }  

}

Symbol table interface:

public interface SymbolTable<Key, Value> {    // put key-value pair into the table  void put(Key key, Value val);    //get value paired with key  Value get(Key key);    //remove key (and its value) from table  void delete(Key key);    //is there a value paired with key?  boolean contains(Key key);    //is the table empty?  boolean isEmpty();    //number of key-value pairs  int size();    //all keys in the table  Iterable<Key> keys();  

}

How'd i loop through every string.gmatch in a string then replacing the matches with a bytecoded version of that?

Posted: 25 Nov 2021 07:47 PM PST

How'd I change everything that it matches in the string without changing the non matches?

local a = "\" Hello World! I want to replace this with a bytecoded version of this!\" but not this!"    for i in string.gmatch(a, "\".*\"") do      print(i)  end  

For example I want "\"Hello World!\" Don't Replace this!" to "\"\72\101\108\108\111\32\87\111\114\108\100\33\" Don't Replace this!"

express.js app knex.js async connection with aws secrets manager call is firing out of order

Posted: 25 Nov 2021 07:44 PM PST

I've been stuck on this for days, it feels like no matter how I structure it, the aws secret manager call ALWAYS returns after the app gets initialized. npm run start fires app.js file, this triggers knex and everything runs in order but the secrets response with the username/password seems to come back after everything's already initialized.

knex.js:

console.log("knex.js")  const environment = process.env.APP_ENV || 'development'  const config = require('../knexfile.js')[environment];  const knex = require('knex')(config);    module.exports = knex  

knexfile.js:

require('dotenv').config();  const path = require('path')  const pathToCert = path.resolve(__dirname, 'root.cert'); // where to save a file    console.log("knexfile.js")    var AWS = require('aws-sdk');  region = 'us-east-2'  secretName = 'blah'  var client = new AWS.SecretsManager({    region: region  });  async function getConfig() {    console.log("in get config")    return await new Promise((resolve, reject) => {      client.getSecretValue({ SecretId: secretName }, function (        err,        data      ) {        let secret = JSON.parse(data.SecretString);        console.log("returning it***************" + secret.password + " " + secret.username + " " + pathToCert)        let connectionString = `postgresql://${secret.username}:${secret.password}@some-host:1234/defaultdb?sslmode=verify-full&sslrootcert=${pathToCert}&options=--cluster`        resolve(connectionString)        return        })    })  }  const config = {    development: {      client: 'pg',      version: 7.2,      connection: getConfig(),      migrations: {        directory: './knex/migrations',      },      seeds: {        directory: './knex/seeds'      }    }    }  console.log("exporting module")  module.exports = config  

The console returns:

knex.js  knexfile.js  in get config  exporting module  Listening on: 3000  returning it***************pass username C:\project-webservice\root.cert  

Does anyone see what I'm doing wrong?

How to find a word after a specific word?

Posted: 25 Nov 2021 07:46 PM PST

I need to find the one word after the specific word If you guys have any idea in the Formula.

Eg: I have in column D2

P/N:101174 JOYSTICK, 2 AXIS, DEUTSCH

So the word after P/N: is 101174

I am using the formula :

=TRIM(LEFT(SUBSTITUTE(TRIM(MID($D2,SEARCH("P/N",D2)+LEN("P/N")+1,LEN(D2)))," ",REPT(" ",100)),COLUMN(D:D)*100))  

the outcome will be :

101174 JOYSTICK, 2 AXIS,  

And what the formula means? because i also google it. Especially the 100 at the last sentence is what for ?

CSS Position Relative to background-img for inner div

Posted: 25 Nov 2021 07:43 PM PST

I have the following HTML for the outer div to centre and contain the back ground image. This works fine. I want to create a inner div relative to the image size to place the div in a black square in the image. the image size is 1783x1481 and the corners for the inner div should be TopLeft: 397,318 TopRight: 1140,318 BottomLeft: 397,903 BottomRight: 1140,903

I'm not sure how to approach this, do I use percentages? do I use view-height scaling?

<style>  .outer {  position: relative;   background-image: url(terminal.png);   background-repeat: no-repeat;   background-position: center;   background-size: contain;   height: 100vh;   margin-left: auto;   margin-right: auto;   display: block;  }  </style>  <div id="outer"><div id="inner">Example Text here</div><div>  

Accessing a service IP of a service inside a consul service mesh

Posted: 25 Nov 2021 07:43 PM PST

Cansomeone help with Consul Service Mesh help me understanding this query please mentioned here

https://discuss.hashicorp.com/t/getting-empty-reply-when-accessing-a-pod-ip-which-has-consul-sidecar-containers/32389/2

k get pod -o wide -n consul-k8s  

counting-d9d58c4cb-fr5cr 2/2 Running 0 33h 10.288.0.157

Now if do curl as below with Pod IP

k exec network-toolspod-f64c586f4-7nzrd --curl 10.288.0.157:9001/counting  

% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 curl: (52) Empty reply from server command terminated with exit code 52

The same curl command works as expected giving response if there are no consul sidecar containers present along with the deployment by using annotation 'consul.hashicorp.com/connect-inject': 'true' . Can someone throw some light on this and help me understand this please

Oracle sys user as sysdba connection is failing with ORA-01017: invalid username/password; logon denied

Posted: 25 Nov 2021 07:44 PM PST

Oracle sys user database connection with ORACLE_SID is not working. dev is my ORACLE_SID .

 sqlplus sys/manager@dev  as sysdba    SQL*Plus: Release 12.1.0.2.0 Production on Thu Nov 25 01:25:33 2021    Copyright (c) 1982, 2014, Oracle.  All rights reserved.    ERROR:  ORA-01017: invalid username/password; logon denied  

But without ORACLE_SID connection is working

sqlplus sys/manager  as sysdba    SQL*Plus: Release 12.1.0.2.0 Production on Thu Nov 25 01:34:05 2021    Copyright (c) 1982, 2014, Oracle.  All rights reserved.      Connected to:  Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production  With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options    SQL>  

Looks like this connection is using OS authentication. Because if I provide wrong password for sys user still connection works.

Any help why with ORACLE_SID sys user connection is not working?

In my database sec_case_sensitive_logon parameter is set to false.

SQL> show parameter sec_case_sensitive_logon    NAME                                 TYPE        VALUE  ------------------------------------ ----------- ------------------------------  sec_case_sensitive_logon             boolean     FALSE  

Groupby year-month and find top K columns with target having smallest absolute values in the last day of each month using Python

Posted: 25 Nov 2021 07:47 PM PST

With sample data and code below, I'm trying to groupby year-month and find top K columns having smallest absolute values with target columns in the end of each month:

import pandas as pd  import numpy as np  from statistics import stdev    np.random.seed(2021)  dates = pd.date_range('20130226', periods=90)  df = pd.DataFrame(np.random.uniform(0, 10, size=(90, 6)), index=dates, columns=['A_values', 'B_values', 'C_values', 'D_values', 'E_values', 'target'])    k = 3    # set k as 3    value_cols = df.columns[df.columns.str.endswith('_values')]  

For example, if we set k=3, then for February 2013, we find A_values, B_values and E_values having smallest abs values with target, then using them as abs_1, abs_2 and abs_3 for this month. Same logic for other year-month. For rows which have on data for last day of month, then results for that month will be NaNs since we only take last day's data to calculate abs() values.

My trial code, but it does not calculate the abs values of last day of each month. Also it raises an error: TypeError: nsmallest() missing 1 required positional argument: 'columns'.

def calculate_abs(x1, x2):      x2 = np.array(x2)      res = np.mean(np.abs(x1 - x2), axis=0) # Here I use mean for each month, but I only need to take last day      # print(res)      return res    def find_topK_smallest_abs(group):      abss = calculate_abs(group[value_cols], group[['target']])      print(abss)      cols = abss.nsmallest(k).index      out_cols = [f'abs_{i+1}' for i in range(k)]      rv = group.loc[:, cols]      rv.columns = out_cols      return rv    df.groupby(pd.Grouper(freq='M')).apply(find_topK_smallest_abs)  

How could I achieve that correctly? Should I use resample('M')? Sincere thanks at advance.

EDIT: to filter last day of each month:

df.loc[df.groupby(df.index.to_period('M')).apply(lambda x: x.index.max())]  

Out:

            A_values  B_values  C_values  D_values  E_values    target  2013-02-28  9.623960  6.165574  0.866300  5.612724  6.165247  9.638430  2013-03-31  2.717608  6.296843  0.087207  1.681396  4.635223  9.347712  2013-04-30  1.849324  2.510323  4.442528  1.106902  2.794064  5.927628  2013-05-26  4.930571  2.338785  9.823048  6.893207  6.312104  5.273122  

Reference link:

Groupby year-month and drop columns with all NaNs in Python

Globle module without import not working nestjs

Posted: 25 Nov 2021 07:45 PM PST

I am trying to implement a global module in nest.js

I have created service like below

export interface ConfigData {      DB_NAME:        string;  }    @Injectable()  export class ConfigManager {      private static _instance?: ConfigManager;      public static configData:ConfigData | null;      private constructor() {          console.log(ConfigManager)          if (ConfigManager._instance)              ConfigManager._instance = this;          else{              ConfigManager._instance = new ConfigManager()              ConfigManager.configData = <ConfigData|null><unknown>ConfigManager.fetchSecretData()          }      }      private static async fetchSecretData():Promise<ConfigData|null>{          // some data from db      }      // static get instance() {      //     return ConfigManager._instance ?? (ConfigManager._instance = new ConfigManager());      //     //return ConfigManager._instance ?? (ConfigManager._instance = ConfigManager.fetchSecretData()) //new ConfigManager());      // }        }  

configuration.module.ts

@Global()  @Module({      providers: [ConfigManager],      exports: [ConfigManager],  })  export class ConfigurationModule {}  

and in app.module.ts added ConfigurationModule in imports

also adding private constructor on service unable it to add in module.ts file

I am expecting that I should be able to configData anywhere without importing the ConfigManager. but its not working...

ConfigManager is not available without import.

Any help highly appreciated.

Thanks

ModuleConcatenation bailout: Cannot concat with ./node_modules/@angular/animations/fesm2015/animations.js

Posted: 25 Nov 2021 07:46 PM PST

I am trying to run my angular app on docker and once I do docker run, I am getting this error at the end of ng build --aot --configuration production --build-optimizer

I am not getting this error when I run the same ng build command in local , Build is completed successfully.

I checked the versions of angular app pacakages with ng --versionVersion command when I run docker build and it is same as local environment.

Error at the end of docker run

my package.json

{    "name": "sample",    "version": "0.0.0",    "license": "MIT",    "scripts": {      "ng": "ng",      "start": "ng serve",      "build": "ng build --prod",      "test": "ng test",      "lint": "ng lint",      "e2e": "ng e2e"    },    "private": true,    "dependencies": {      "@angular-devkit/build-optimizer": "0.3.2",      "@angular/animations": "^5.1.3",      "@angular/cdk": "^5.0.3",      "@angular/common": "^5.0.0",      "@angular/core": "^5.1.3",      "@angular/forms": "^5.0.0",      "@angular/http": "^5.0.0",      "@angular/material": "^5.0.3",      "@angular/material-moment-adapter": "^8.0.0",      "@angular/platform-browser": "^5.0.0",      "@angular/platform-browser-dynamic": "^5.0.0",      "@angular/router": "^5.0.0",      "@molteni/export-csv": "0.0.2",      "@swimlane/ngx-datatable": "11.3.0",      "angular-froala-wysiwyg": "^2.9.1",      "angular2-multiselect-dropdown": "^2.9.0",      "bootstrap": "^3.3.7",      "core-js": "2.6.12",      "exceljs": "^2.0.1",      "file-saver": "^1.3.2",      "hammerjs": "^2.0.8",      "intl": "^1.2.5",      "jquery": "^3.2.1",      "lodash": "4.17.20",      "moment": "2.29.1",      "ng2-dnd": "^5.0.2",      "ng2-dragula": "^1.5.0",      "ng2-pdf-viewer": "^4.1.1",      "ng2-toastr": "^4.1.2",      "ng2-tree": "^2.0.0-rc.6",      "ngx-bootstrap": "^2.0.3",      "ngx-cookie-service": "^1.0.10",      "ngx-device-detector": "1.3.9",      "papaparse": "^4.3.7",      "ramda": "^0.25.0",      "rxjs": "^5.5.2",      "web-animations-js": "^2.3.1",      "xlsx": "^0.12.3",      "zone.js": "^0.8.14"    },    "devDependencies": {      "@angular-devkit/core": "0.0.29",      "@angular/cli": "^1.6.1",      "@angular/compiler": "^5.2.1",      "@angular/compiler-cli": "^5.0.0",      "@angular/language-service": "^5.0.0",      "@types/highcharts": "^5.0.44",      "@types/jasmine": "~2.5.53",      "@types/jasminewd2": "~2.0.2",      "@types/node": "~6.0.60",      "codelyzer": "^4.0.1",      "handlebars": "4.7.6",      "html-webpack-plugin": "^2.30.1",      "jasmine-core": "~2.6.2",      "jasmine-spec-reporter": "~4.1.0",      "karma": "~1.7.0",      "karma-chrome-launcher": "~2.1.1",      "karma-cli": "~1.0.1",      "karma-coverage-istanbul-reporter": "^1.2.1",      "karma-jasmine": "~1.1.0",      "karma-jasmine-html-reporter": "^0.2.2",      "karma-junit-reporter": "^2.0.1",      "karma-phantomjs-launcher": "^1.0.4",      "karma-sonarqube-unit-reporter": "0.0.21",      "phantomjs": "~2.1.0",      "phantomjs-prebuilt": "^2.1.7",      "protractor": "~5.1.2",      "ts-node": "~3.2.0",      "tslint": "~5.7.0",      "typescript": "~2.4.2",      "webpack-dev-server": "^2.11.0"    }  }    

Unable to send Ripple (Cryptocurrency Coin - XRP) to Wallet

Posted: 25 Nov 2021 07:43 PM PST

I am trying to use the below code to send ripple (Cryptocurrency Coin)- XRP to another address, but i am getting the below error :

"Uncaught (in promise) Error: Faucet URL is not defined or inferrable."

Included the below JS reference in HTML file,

script src="https://unpkg.com/xrpl@2.0.0/build/xrpl-latest-min.js" script type="application/javascript" src="send-xrp.js"

What am i missing???

send-xrp.js ===========

    // Dependencies for Node.js.      // In browsers, use a <script> tag instead.      if (typeof module !== "undefined") {        // Use var here because const/let are block-scoped to the if statement.        var xrpl = require('xrpl')      }            // Example credentials      const wallet = xrpl.Wallet.fromSeed("I ENTERED MY SECRET KEY HERE")      console.log(wallet.address)             // Connect -------------------------------------------------------------------      async function main() {        console.log("Connecting to Testnet... I CHANGED BELOW TO PRODUCTION NETWORK")        const client = new xrpl.Client('wss://xrplcluster.com')        await client.connect()              // Get credentials from the Testnet Faucet -----------------------------------        console.log("Getting a wallet from the Testnet faucet...")        const {wallet, balance} = await client.fundWallet()              // Prepare transaction -------------------------------------------------------        const prepared = await client.autofill({          "TransactionType": "Payment",          "Account": wallet.address,          "Amount": xrpl.xrpToDrops("35"),          "Destination": "ENTERED MY DESTINATION KEY HERE"        })        const max_ledger = prepared.LastLedgerSequence        console.log("Prepared transaction instructions:", prepared)        console.log("Transaction cost:", xrpl.dropsToXrp(prepared.Fee), "XRP")        console.log("Transaction expires after ledger:", max_ledger)              // Sign prepared instructions ------------------------------------------------        const signed = wallet.sign(prepared)        console.log("Identifying hash:", signed.hash)        console.log("Signed blob:", signed.tx_blob)              // Submit signed blob --------------------------------------------------------        const tx = await client.submitAndWait(signed.tx_blob)              // Wait for validation -------------------------------------------------------        // submitAndWait() handles this automatically, but it can take 4-7s.              // Check transaction results -------------------------------------------------        console.log("Transaction result:", tx.result.meta.TransactionResult)        console.log("Balance changes:", JSON.stringify(xrpl.getBalanceChanges(tx.result.meta), null, 2))              // End of main()        client.disconnect()      }            main()  

Get value from nested arrays of objects

Posted: 25 Nov 2021 07:45 PM PST

I have data that is structured like the following:

const arr = [{      id: 0,      name: 'Biomes',      icon: 'mdi-image-filter-hdr',      isParent: true,      children: [{          id: 1,          name: 'Redwood forest',          icon: 'mdi-image-filter-hdr'      }]  },{      id: 2,      name: 'Trees',      icon: 'mdi-pine-tree',      children: [{          id: 8,          name: 'Redwood',          icon: 'mdi-pine-tree'      }]  }];    

The top level is an array of objects, and each object can have a child field children which itself can be an array of objects. If I know the value of id, how can I find the object (or more importantly the object name), based on that id value?

How to clone a javascript ES6 class instance

Posted: 25 Nov 2021 07:44 PM PST

How do I clone a Javascript class instance using ES6.

I'm not interested in solutions based on jquery or $extend.

I've seen quite old discussions of object cloning that suggest that the problem is quite complicated, but with ES6 a very simple solution presents itself - I will put it below and see if people think it is satisfactory.

edit: it is being suggested that my question is a duplicate; I saw that answer but it is 7 years old and involves very complicated answers using pre-ES6 js. I'm suggesting that my question, which allows for ES6, has a dramatically simpler solution.

Status bar is back (visible) when controls of videoplayer in fullscreen are shown (visible)

Posted: 25 Nov 2021 07:47 PM PST

I use WebView for loading a video. I overrided onShowCustomView (to go to fullscreen) and onHideCustomView (to get out of fullscreen) methods. When I go to fullscreen mode a variable fullscreen is set to true and OnSystemUiVisibilityChangeListener calls GoFullscreen() function that sets SYSTEM_UI_FLAG_FULLSCREEN flag and also hides Action Bar:

decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); getSupportActionBar().hide();

But when I go to fullscreen mode status bar is visible if video controls are visible. So status bar hides only if video controls are gone (not visible).

Screenshots to see a problem with controls of video and statusbar:

------------normal (ok)

normal mode

-----fullscreen with video controls (not ok) -------- fullscreen without video controls (ok) enter image description here enter image description here

Code:

public class TestActivity extends AppCompatActivity {  private MyWebChromeClient mWebChromeClient = null;  private View mCustomView;  private LinearLayout mContentView;  private FrameLayout mCustomViewContainer;  private WebChromeClient.CustomViewCallback mCustomViewCallback;  private Bundle webViewBundle;  private WebView mWebView;  private int viewWidth;  private int viewHeight;  private LinearLayout.LayoutParams layoutParams;  private View decorView;  private Boolean Fullscreen = false;    private void GoFullscreen() {      decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);      getSupportActionBar().hide();  }    @Override  protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_main);        decorView = getWindow().getDecorView();      decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {          @Override          public void onSystemUiVisibilityChange(int visibility) {              if (Fullscreen) {                  GoFullscreen();              } else {                  decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);                  getSupportActionBar().show();              }          }      });        mWebView = (WebView) findViewById(R.id.webView);      mWebView.setBackgroundColor(Color.BLACK);      mWebChromeClient = new MyWebChromeClient();      mWebView.setWebChromeClient(mWebChromeClient);      mWebView.setWebViewClient(new WebViewClient(){          @Override          public boolean shouldOverrideUrlLoading(WebView view, String url) {              return false;          }      });      WebSettings webSettings = mWebView.getSettings();      webSettings.setJavaScriptEnabled(true);        viewWidth = 480;      viewHeight = (int) (((double) viewWidth) * 0.5625); // video aspect 16:9      layoutParams = new LinearLayout.LayoutParams(viewWidth, viewHeight);      mWebView.setLayoutParams(layoutParams);        if (webViewBundle != null) {          mWebView.restoreState(webViewBundle);      } else {          mWebView.loadUrl("http://vk.com/video_ext.php?oid=-89326201&id=171643607&hash=2b18b090e13222dc&hd=1");      }  }    @Override  public void onPause() {      super.onPause();      webViewBundle = new Bundle();      mWebView.saveState(webViewBundle);      mWebView.onPause();  }    @Override  public void onResume() {      super.onResume();      mWebView.onResume();  }    @Override  public void onDestroy() {      super.onDestroy();      mWebView.destroy();  }    public class MyWebChromeClient extends WebChromeClient {      @Override      public void onShowCustomView(View view, CustomViewCallback callback) {          // if a view already exists then immediately terminate the new one          if (mCustomView != null) {              callback.onCustomViewHidden();              return;          }          Fullscreen = true;          FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);          mContentView = (LinearLayout) findViewById(R.id.activity_main);          mCustomViewContainer = new FrameLayout(TestActivity.this);          mCustomViewContainer.setLayoutParams(LayoutParameters);          mCustomViewContainer.setBackgroundResource(android.R.color.black);          view.setLayoutParams(LayoutParameters);          mCustomViewContainer.addView(view);          mCustomView = view;          mCustomViewCallback = callback;          mContentView.setVisibility(View.GONE);          GoFullscreen();          mCustomViewContainer.setVisibility(View.VISIBLE);          setContentView(mCustomViewContainer);      }        @Override      public void onHideCustomView() {          if (mCustomView != null) {              // Hide the custom view.              mCustomView.setVisibility(View.GONE);              // Remove the custom view from its container.              mCustomViewContainer.removeView(mCustomView);              mCustomView = null;              mCustomViewContainer.setVisibility(View.GONE);              mCustomViewContainer = null;              mCustomViewCallback.onCustomViewHidden();              // Show the content view.              Fullscreen = false;              mContentView.setVisibility(View.VISIBLE);              setContentView(mContentView);          }      }  }    @Override  public void onBackPressed() {      if (mCustomViewContainer != null)          mWebChromeClient.onHideCustomView();      else if (mWebView.canGoBack())          mWebView.goBack();      else          super.onBackPressed();  }  

}

How to solve it?

p.s. build.gradle API: compileSdkVersion 23 / buildToolsVersion "23.0.1" / minSdkVersion 19 / targetSdkVersion 23

UPDATE: seems to be problem only on KitKat. I've tested on API 23 smartphone and it doesn't have this problem. Still need to fix it for KitKat devices

How to give relational condition in pg_select function

Posted: 25 Nov 2021 07:44 PM PST

In pg_select function the third argument is a array used to specify the column name and its value.

It works like an and condition if we give more than one key => value. I have id column in my table I want to fetch the rows which has id value more than 1000.

How to give value in associative array in pg_select function for the above requirement.

I need answer without using pg_query function.

Export DataGrid to PDF using c#

Posted: 25 Nov 2021 07:44 PM PST

I'm new to c#. Can you suggest a useful link to convert datagrid to PDF.

How can I echo a newline in a batch file?

Posted: 25 Nov 2021 07:44 PM PST

How can you you insert a newline from your batch file output?

I want to do something like:

echo hello\nworld  

Which would output:

hello  world  

No comments:

Post a Comment