Thursday, August 12, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Javascript - Chrome Extension -> How to Retrieve data from LocalStorage?

Posted: 12 Aug 2021 07:50 AM PDT

This is my Local Storage;

Image2

I get this data.

Image

How to Retrieve data from LocalStorage?
I want to get "product_img" data and other datas.
And I want to do if/else with them.

My Codes;

Background.js;

        case "selectWebsite":              chrome.tabs.query({active: true, currentWindow: true}, tabs => {                chrome.tabs.sendMessage(tabs[0].id, {choice: message.data, data:                 getStorageItem('productDetails')});              })    function getStorageItem(varName){    return JSON.parse(localStorage.getItem(varName));  }  

Content.js;

chrome.runtime.onMessage.addListener(function(msg, sender) {    if(msg.choice === "selectEbay") {      console.log(msg.choice);      console.log(msg.data);    }  });  

popupSelect.js;

    document.getElementById("selectBtn").onclick = function() {          let choice = document.querySelector("input[name=choice]:checked").value;          sendToBackground("selectWebsite", choice);          window.close();      }    function sendToBackground(eventName, eventData, callback) {      chrome.runtime.sendMessage({type: eventName, data: eventData},        function(response) {        })    }  

Anchor Tag for certain section: Working within the current screen but doesn't work as a link?

Posted: 12 Aug 2021 07:49 AM PDT

I currently have a file called Illustrations.js and exported it in a Storybook JS project as a story.

My page is supposed to be a documentation page and I want to have anchor tags so that when the user clicks on it, it jumps to that section and users can also copy and paste the link and it will automatically go to that section.

This is what my code looks like:

<div className="template-section-header" id="product_illustrations">    Product Illustrations            <a href="#product_illustrations" target="_self">      <img className="link-icon" src={iconsystemlink} />    </a>  </div>  

When I click on the link, it jumps to that section which is what I want. That part is working as intended.

Before clicking on the anchor tag

(the url is currently: http://localhost:9001/?path=/story/ccfk-%F0%9F%91%8B-%E2%A0%80templates--illustrations

After clicking on the anchor tag

(the url is still the same as above but clicks to that section

enter image description here

However thought when I crtl-click or copy and paste the link in a new tab. It only shows the top of the page.

When you copy and paste the link you get this. It just displays the top of the page

(the url of the actual link itself is (http://localhost:9001/iframe.html?id=ccfk-%F0%9F%91%8B-%E2%A0%80templates--illustrations&viewMode=story#product_illustrations)

enter image description here

I'm really confused on why this is so and any help or suggestions would be appreciated. Thank you

Dockerised PHP image deployment on Heroku returns 500

Posted: 12 Aug 2021 07:49 AM PDT

So I have a Php project that runs with docker compose-up command. It has everything that is usually needed, like composer.json and composer.lock. It successfully adds and deploys, but then returns 500 message without further explanation. Please help me deploy it or find an error.

here is docker-compose

version: '3.1'    services:    php:      build:        context: .        dockerfile: Dockerfile      ports:        - 80:80      volumes:        - ./src:/var/www/html      db:      image: mysql      command: --default-authentication-plugin=mysql_native_password      restart: always      environment:        MYSQL_ROOT_PASSWORD: example      adminer:      image: adminer      restart: always      ports:        - 8080:8080  

Dockerfile

FROM php:7.4-apache  RUN docker-php-ext-install mysqli  

Composer.lock

{      "_readme": [          "This file locks the dependencies of your project to a known state",          "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",          "This file is @generated automatically"      ],      "content-hash": "d751713988987e9331980363e24189ce",      "packages": [],      "packages-dev": [],      "aliases": [],      "minimum-stability": "stable",      "stability-flags": [],      "prefer-stable": false,      "prefer-lowest": false,      "platform": [],      "platform-dev": [],      "plugin-api-version": "2.1.0"  }  

Composer

{}  

Log from Heroku:

-----> Building on the Heroku-20 stack  -----> Using buildpack: heroku/php  -----> PHP app detected  -----> Bootstrapping...  -----> Installing platform packages...         NOTICE: No runtime required in composer.lock; using PHP ^7.3.0 | ^8.0.0         - php (8.0.9)         - composer (2.1.5)         - apache (2.4.48)         - nginx (1.20.1)  -----> Installing dependencies...         Composer version 2.1.5 2021-07-23 10:35:47  -----> Preparing runtime environment...         NOTICE: No Procfile, using 'web: heroku-php-apache2'.  -----> Checking for additional extensions to install...  -----> Discovering process types         Procfile declares types -> web  -----> Compressing...         Done: 22.4M  -----> Launching...         Released v18         https://rizor.herokuapp.com/ deployed to Heroku  

When working with the native mongoDB driver, Node.js and hyper terminal, I recieve an error saying "TypeError: Cannot read property 'n' of undefined"

Posted: 12 Aug 2021 07:49 AM PDT

Ok, I am using vs-code, hyper-terminal(git-bash), Javascript, Node.js, Express, MongoDB and it's native driver but while I finished up writing my code, I wrote node app.js(I am using app.js as my javascript file for this project) to see if my code works but it gave me an error saying TypeError: Cannot read property 'name' of undefined. And that 'n' was in line 46 which I basically went into and found assert.equal(3, result.result.n);. I don't see what's wrong with this and my full code is down below👇🏻

My app.js

const MongoClient = require('mongodb').MongoClient;  const assert = require('assert');    // Connection URL  const url = 'mongodb://localhost:27017';    // Database Name  const dbName = 'fruitsDB';    // Create a new MongoClient  const client = new MongoClient(url, { useNewUrlParser: true });    // Use connect method to connect to the server  client.connect(function(err) {      assert.equal(null, err);      console.log("Successfully Connected to the server");        const db = client.db(dbName);        insertDocuments(db, function() {          client.close();      });    });    const insertDocuments = function(db, callback) {      // Get the documents collection      const collection = db.collection('fruits');      // insert some documents        collection.insertMany([{              name: "Apple",              score: 8,              review: "Great fruit but I didn't really like the wax"          },          {              name: "Orange",              score: 6,              review: "Great for sour-candy-eaters like me!"          }, {              name: "Banana",              score: 10,              review: "Very nice! Gave me alot of energy!"          }      ], function(err, result) {          assert.equal(err, null);          assert.equal(3, result.result.n);          assert.equal(3, result.ops.length);          console.log("Inserted 3 documents into the collection");          callback(result);      });  }  

the error at hyper terminal

TypeError: Cannot read property 'name' of undefined      at C:\Users\*****\desktop\Projects\FruitsProject\app.js:46:39      at C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\utils.js:530:9      at C:\Users\Moham\*****\Projects\FruitsProject\node_modules\mongodb\lib\operations\execute_operation.js:49:55      at C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\utils.js:530:9      at completeEndSession (C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\sessions.js:147:17)      at C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\sessions.js:157:13      at Object.maybePromise (C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\utils.js:516:5)      at ClientSession.endSession (C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\sessions.js:133:  24)      at C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\operations\execute_operation.js:49:36      at C:\Users\*****\desktop\Projects\FruitsProject\node_modules\mongodb\lib\operations\insert.js:79:13  

PS: I am following a udemy full stack web development course and for my instructor, it worked right but for me, it just doesn't work. Please tell me if you spot any mistake.

Access Function Builder in Query builder return nothing

Posted: 12 Aug 2021 07:49 AM PDT

i am running a complex calculation through Update Query, i managed to get all other work done however am strugling to get this bit done. i use Function builder window to set the Update To field for the targeted field. My table is as following:

PHD_TAG Cal_Value Moisture CO2_EF CO2
ABC 100 0.5 0.45 *
FAC1 20
FAC2 7

My Function is to calculate and update the CO2 Field with a *

(1-((DLookup("Cal_Value", "TempTbl", "PHD_TAG = 'FAC1'"))+[Moisture])/100)*(DLookup("Cal_Value", "TempTbl", "PHD_TAG = 'FAC2'"))*[CO2_EF]/(22.4*44*24)  

the Query generated in Query builder "SQL Query" is as following:

UPDATE TempTbl SET TempTbl.CO2 = (1-((DLookUp("Cal_Value","TempTbl","PHD_TAG = 'FAC1'"))+[Moisture])/100)*(DLookUp("Cal_Value","TempTbl","PHD_TAG = 'FAC2'"))*[CO2_EF]/(22.4*44*24)  WHERE (((TempTbl.PHD_TAG)="ABC"));  

Appreciate Team Help

Why is my session storage variable 'header' Null

Posted: 12 Aug 2021 07:49 AM PDT

I am trying to create a pdf using react-pdf. In App.js I store my 'header' info in Session Storage. My current Invoice component:

import React from 'react';  import { Page, Document, Image, StyleSheet } from '@react-pdf/renderer';  import InvoiceTitle from './InvoiceTitle'  import BillTo from './BillTo'  import InvoiceNo from './InvoiceNo'  import InvoiceItemsTable from './InvoiceItemsTable'  import InvoiceThankYouMsg from './InvoiceThankYouMsg'    const styles = StyleSheet.create({      page: {          fontFamily: 'Helvetica',          fontSize: 11,          paddingTop: 30,          paddingLeft: 60,          paddingRight: 60,          lineHeight: 1.5,          flexDirection: 'column',      },      logo: {          width: 74,          height: 66,          marginLeft: 'auto',          marginRight: 'auto'      }  });    const headerString = sessionStorage.getItem("header");  const header = JSON.parse(headerString);    const Invoice = ({ invoice }) => (      <Document>          <Page size="A4" style={styles.page}>              <Image style={styles.logo} src={header.logoImage} />              <InvoiceTitle title='Invoice' />              <InvoiceNo invoice={invoice} />              <BillTo invoice={invoice} />              <InvoiceItemsTable invoice={invoice} />              <InvoiceThankYouMsg />          </Page>      </Document>  );    export default Invoice  

I am getting an error that header is null, even though I can see it in my Dev Tools under Session Storage. Why is header Null?

Problem with displaying the Facebook Feeds in the Flutter web application

Posted: 12 Aug 2021 07:48 AM PDT

I am trying to show the facebook page feeds in the flutter website, but facing some problems.

Got the iFrame html code from the facebook page plugin and placing it in the required place using the HTMLElementView widget. Facebook feeds are showing properly in the site, but facing below problem:

  1. Getting this console error, especially while scrolling the page :

Uncaught SyntaxError: Unexpected token ':' ky6FWSyPINF.js?_nc_x=Ij3Wp8lg5Kz:57 ErrorUtils caught an error: Cannot listen to an undefined element. [Caught in: Tried to listen to element of type click] Subsequent non-fatal errors won't be logged; see https://fburl.com/debugjs.

  1. Due to this error, the widget is reloaded every time in the UI and couple of https requests fired from the application which makes the site performance poor.

Here is the code:

class _SocialMediaSectionState extends State<SocialMediaSection> {      @override    void initState() {      ui.platformViewRegistry.registerViewFactory(          'facebook-feeds',              (int id) => html.IFrameElement()            ..width = "500"            ..height = "500"            ..src = 'https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2Fmuthurajamla%2F&tabs=timeline&width=340&height=500&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true&appId=582822522870331'            ..style.border = 'none');      super.initState();    }      @override    Widget build(BuildContext context) {          return Container(                          height: 500,                          width: 340,                          decoration: BoxDecoration(                              borderRadius: BorderRadius.all(Radius.circular(15)),                            color: Colors.white,                          ),                          child: HtmlElementView(                            viewType: 'facebook-feeds',                          ),                        )    }  }  

Regex: the last match before the first match of a specific token

Posted: 12 Aug 2021 07:49 AM PDT

I'm quite new to regex, there's my example:

<a href="https://www.wb1.com">Pie</a>  <a href="https://www.wb2.com">Banana</a>  <a href="https://www.wb3.com">Apple</a>  <a href="https://www.wb4.com">Source</a>  <a href="https://www.wb5.com">Source</a>  

I want to get the URL for the first occurrence of Source tohttps://www.wb4.com.

However, if I use <a href=(?s:.+?)Source<\/a> to find it, it gives me

<a href="https://www.wb1.com">Pie</a>  <a href="https://www.wb2.com">Banana</a>  <a href="https://www.wb3.com">Apple</a>  <a href="https://www.wb4.com">Source</a>  

, which starts from the first <a href= token, instead of the one nearest to the first occurrence of Source. I.e., I want to restrict <a href= to match the last one before the first occurrence of Source.

I'm using regex101 for my test.

Thanks in advance!

How to replace NAs from categorical data in R using mutation?

Posted: 12 Aug 2021 07:48 AM PDT

data goes like this:

survey <- data.frame("Death" = c(1, 1, 1, NA, 0,1,NA,0,1,0),                       "recover" = c(0, 0, 0, NA, 1,NA,0,1,0,NA))   

i have already tried the following piece of code, but it is not coming correctly.

my_imp = mice(survey ,m=5,method = c("","","","","","logreg","logreg"),maxit = 20)  

My desired output is to replace NAs with the same data from the same column. Please help me ,to solve this using mutation..

How do I round numbers in KDB?

Posted: 12 Aug 2021 07:49 AM PDT

It looks like I can hack floor and ceiling into a meta function for an arbitrary round, but is there a standard way to do:

round[3.1415;2] = 3.14  

from the core functions?

Delta tables in Databricks and into Power BI

Posted: 12 Aug 2021 07:49 AM PDT

I am connecting to a delta table in Azure gen 2 data lake by mounting in Databricks and creating a table ('using delta'). I am then connecting to this in Power BI using the Databricks connector.

Firstly, I am unclear as to the relationship between the data lake and the Spark table in Databricks. Is it correct that the Spark table retrieves the latest snapshot from the data lake (delta lake) every time it is itself queried? Is it also the case that it is not possible to effect changes in the data lake via operations on the Spark table?

Secondly, what is the best way to reduce the columns in the Spark table (ideally before it is read into Power BI)? I have tried creating the Spark table with specified subset of columns but get a cannot change schema error. Instead I can create another Spark table that selects from the first Spark table, but this seems pretty inefficient and (I think) will need to be recreated frequently in line with the refresh schedule of the Power BI report. I don't know if it's possible to have a Spark delta table that references another Spark Delta table so that the former is also always the latest snapshot when queried?

As you can tell, my understanding of this is limited (as is the documentation!) but any pointers very much appreciated.

Thanks in advance and for reading!

How to avoid VLA and malloc when using VULKAN VkEnum-foo-bar function in C language?

Posted: 12 Aug 2021 07:49 AM PDT

Vulkan programming in C language seems unavoidable to use either malloc or VLA, Look at the following example:

    uint32_t physicalDeviceNumber = 0;      vkEnumeratePhysicalDevices(*instance, &physicalDeviceNumber, NULL);        VkPhysicalDevice physicalDevice[physicalDeviceNumber];      vkEnumeratePhysicalDevices(*instance, &physicalDeviceNumber, physicalDevice);  

This code simply enumerate physical devices, since I don't know the exact number of GPUs, I call vkEnumeratePhysicalDevices to get the number. and then call it again to actually initialize them. On the second function call, the third argument, VkPhysicalDevice *pPhysicalDevices must be a defined array. Its length must equals to the number of GPUs, or the physical device initialization will be incomplete. See specification here.

Here comes the problem, the code above use a DANGEROUS feature in C language, called VLA, or "variable-length-array". This feature allows to create a memory chunk on stack with the size of runtime-generated number. They should definitely be avoided. This blog tells us why.

Another solution was to use malloc to solve this, I changed the code a bit:

    uint32_t physicalDeviceNumber = 0;      vkEnumeratePhysicalDevices(*instance, &physicalDeviceNumber, NULL);        VkPhysicalDevice *physicalDevice = (VkPhysicalDevice *)malloc(physicalDeviceNumber * sizeof(VkPhysicalDevice));      vkEnumeratePhysicalDevices(*instance, &physicalDeviceNumber, physicalDevice);  

And this one corrupt the program, of course. Type VkPhysicalDevice is actually a pointer, its real type is struct VkPhysicalDevice_T *, it points to a big chunk of memory which size is unknown. Also, using malloc is considered a BAD habit in vulkan programming. See discussion here.

So I was confused. This simple function cannot be safely used to initialize my GPU unless I know how much GPU my computer has. I'm not an expert in C, but I think there should be safer solution than those codes. If you know how, please provide plain C code and explain why.

ps: C++ code is NOT what I want, I know std::vector can solve this, but I'm not gonna use C++.

Stroustroup: free(): double free detected in tcache 2 when implementing vector::reserve()

Posted: 12 Aug 2021 07:49 AM PDT

The code given in Bjarne Stroustrup - Programming Chapter 19.5.6 "RAII for vector" doesn't work when calling push_back() then reserve(). Separately they work fine.

I get this error "free(): double free detected in tcache 2"
With debugging I see that after calling swap() inside reserve() the variable b.elem[0] has <error: Cannot access memory at address 0x55555556d>

The uninitialized_copy is written wrong in the book so maybe there's something else missing? Or am I doing something wrong?

#include <iostream>  #include <stdexcept>  #include <string>  #include <algorithm>    template <typename T>      class allocator      {      public:          // . . .          T *allocate(int n)  { return (T *)malloc(n * sizeof(T));} // allocate space for n objects of type T          void construct(T *p, const T &v) { new (p) T{v}; } // construct a T with the value v in p          void destroy(T *p)  { p->~T(); } // destroy the T in p          void deallocate(T *p, int n) { free(p); } // deallocate n objects of type T starting at p      };    template <typename T, typename A = allocator<T>  struct vector_base  {      A alloc;   // allocator,      T *elem;   // start of allocation      int sz;    // number of elements      int space; // amount of allocated space        vector_base()          : sz{0}, elem{nullptr}, space{0} {}      vector_base(const A &a, int n)          : alloc{a}, elem{alloc.allocate(n)}, sz{0}, space{n}      {      }      ~vector_base() { alloc.deallocate(elem, space); }        };  template <typename T, typename A = allocator<T>>  class vector : private vector_base<T, A> // me: make all members private by default  {                                        // read "for all types T" (just like in math)  public:      vector()          : vector_base<T, A>() {}        explicit vector(int s)          : vector_base<T, A>(this->alloc, s) // access vector_base's alloc through this->      {      }      //T &operator[](int n) { return this->elem[n]; }      const T &operator[](int n) const { return this->elem[n]; } // unchecked access      int size() const { return this->sz; }                      // the current size      int capacity() const { return this->space; }      void reserve(int newalloc);                 void push_back(const T &d);  };  template <typename T, typename A>  void print(const vector<T, A> &v, const std::string &s)  {      std::cout << '\n';      std::cout << s << ' ' << "size: " << v.size() << ' ' << "capacity: " << v.capacity() << ' ';      std::cout << "elements: ";      for (int i = 0; i < v.size(); ++i)          std::cout << v[i] << ' ';  }        template <typename T, typename A>  void vector<T, A>::reserve(int newalloc)  {      if (newalloc <= this->space)          return;                           // never decrease allocation      vector_base<T, A> b(this->alloc, newalloc); // allocate new space      uninitialized_copy(this->elem, this->elem + this->sz, b.elem);  // copy from caller of reserve() to b      for (int i = 0; i < this->sz; ++i)          this->alloc.destroy(&this->elem[i]); // destroy old      std::swap<vector_base<T, A>>(*this, b); // swap representations   } // at exit ~vector_base will deallocate    template <typename T, typename A> // 19.3.7  void vector<T, A>::push_back(const T &val)  {      if (this->space == 0)          reserve(8);       else if (this->sz == this->space)          reserve(2 * this->space);      this->alloc.construct(&this->elem[this->sz], val); // add val to position sz      ++this->sz;  }    int main()  try  {      vector<std::string> vs;      vs.push_back("test");      print(vs, "vs.push_back():");      vs.reserve(10);      print(vs, "vs.reserve(10):");    }  catch (std::exception &e)  {      std::cerr << "exception: " << e.what() << '\n';      return 1;  }  catch (...)  {      std::cerr << "exception\n";      return 2;  }  

Calculate maximum length of consecutive values in row over a set number

Posted: 12 Aug 2021 07:48 AM PDT

I have a random 10x10 DF (in reality its a few million rows):

df <- replicate(10, sample(0:5, 10, rep=T))

I need to calculate a column on at end of my df that is the a count of the maximum length of consecutive values equal or over a set number e.g. 3 or more.

Therefore, a single row that contained the values: 2,4,3,3,4,5,1,0,5,1 would return a value of 5, as the set of values 4,3,3,4,5 are all 3 or more and are consecutive.

while a 5 does occur again in the row which is above 3 its consecutive occurrence is less than 5 consecutives numbers over 3 earlier in the row.

Any help appreciated.

Player doesn't move and timer doesn't work

Posted: 12 Aug 2021 07:49 AM PDT

My player doesn't move and my timer doesn't count down like it should. I'll post my whole code, so you can recreate everything I have. The timer stuff is inside the main_loop_state_config right after the for loop.

import pygame, os  from pygame.locals import *  import random      ###############################################################  # Color-Codes  ###############################################################    ORANGE = (255, 140, 0)  RED = (255, 0, 0)  DARKBLUE = (0, 0, 139)  WHITE = (255, 255, 255)  BLACK = (0, 0, 0)  YELLOW = (255, 255, 0)  GREEN = (0, 255, 0)  DARKGREEN = (0, 98, 7)  LIMEGREEN = (50, 205, 50)  DARKGREY = (70, 70, 70)  BLUE = (0, 0, 255)  LIGHTBLUE = (173, 216, 230)  WOODY = (139,69,19)    LIST_OF_ALL_COLOR_NAMES = [ ORANGE, RED, DARKBLUE, WHITE, BLACK, YELLOW, GREEN, DARKGREEN, LIMEGREEN,                              DARKGREY, BLUE, LIGHTBLUE ]    ###############################################################  # Konstanten  ###############################################################    SCREEN_WIDTH = 1200  SCREEN_HEIGHT = 800  PANEL_SIZE = 160  SQUARE_SIZE = 80  #SIDEPANEL = pygame.Rect(pxl(13), pxl(0), pxl(2), pxl(10))  background = pygame.Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)    ###############################################################  # Measurement -> Maßeinheit und Bildschirmmaße  ###############################################################    def pxl (number_of_squares):      "number of squares -> number of pixels"      return SQUARE_SIZE * number_of_squares    ###############################################################  # Variablen  ###############################################################    level = 0  a = 1085  b = 80  gameDrawn = False  counter = 15  timerRect = pygame.Rect(pxl(13), pxl(0), pxl(1), pxl(1))  counterRect = pygame.Rect(pxl(14), pxl(0), pxl(3), pxl(1))      ###############################################################  # Classes -> Klassen  ###############################################################    class Wall(object):      def __init__(self, pos):          self.rect = pygame.Rect(pos[0], pos[1], pxl(1), pxl(1))    class End(object):      def __init__(self, pos):          self.rect = pygame.Rect(pos[0], pos[1], pxl(1), pxl(1))            class Player(object):      def __init__(self, pos):          self.rect = pygame.Rect(pos[0], pos[1], pxl(1), pxl(1))        #def move(dx, dy):          # Bewegung für x und y. Kollision wird überprüft          #if dx != 0:              #wallCollisionDetection((dx, 0))          #if dy != 0:              #wallCollisionDetection(0, dy)        def move(self, dx, dy):          walls = drawLevel(level)          # Den Spieler bewegen          self.rect.x += dx          self.rect.y += dy            for wall in walls:              if self.rect.colliderect(wall.rect):                  if dx > 0:                        self.rect.right = wall.rect.left                  if dx < 0:                      self.rect.left = wall.rect.right                  if dy > 0:                        self.rect.bottom = wall.rect.top                  if dy < 0:                      self.rect.top = wall.rect.bottom                          #def endCollisionDetection(self, dx, dy):    ###############################################################  # Listen  ###############################################################        move_list = []    max_move_list = [17]    levels =[[  "WWWWWWWWWWWWW",              "W          EW",              "W         WWW",              "W   WWWW    W",              "W   W       W",              "WWWWW  WWWW W",              "W   W     W W",              "W   W     W W",              "WP          W",              "WWWWWWWWWWWWW",          ]]    curr_moves = max_move_list[level]    ###############################################################  # Methoden  ###############################################################    def movePlayer(move_list):      for i in move_list:          if i == 1:              player.move(pxl(0), pxl(-1))          elif i == 2:              player.move(pxl(0), pxl(1))          elif i == 3:              player.move(pxl(1), pxl(0))          elif i == 4:              player.move(pxl(-1), pxl(0))    def drawGrid():      for x in range(0, SCREEN_WIDTH - PANEL_SIZE, SQUARE_SIZE):          for y in range(0, SCREEN_HEIGHT, SQUARE_SIZE):              rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)              pygame.draw.rect(screen, WHITE, rect, 1)    def drawRect():      pygame.draw.rect(screen, WHITE, (pygame.Rect(pxl(13), pxl(0), pxl(2), pxl(10))))    def drawStartMessage():        startText11 = "Das Spiel funktioniert so:"      startText22 = "Sobald es startet, haben sie 15 Sekunden Zeit um ihre Züge einzugeben."      startText33 = "Das Ziel ist es den Spieler (blaues Rechteck) ins Ziel (rotes Rechteck) zu bekommen."      startText44 = "Dazu haben sie neben den 15 Sekunden eine gewisse Anzahl an Zügen."      startText55 = "Drücken sie eine Taste zum Starten"      startText1 = font.render(startText11, True, BLACK)      startText2 = font.render(startText22, True, BLACK)      startText3 = font.render(startText33, True, BLACK)      startText4 = font.render(startText44, True, BLACK)      startText5 = font.render(startText55, True, BLACK)      startText1_rect = startText1.get_rect(center=(SCREEN_WIDTH/2, 160))      startText2_rect = startText2.get_rect(center=(SCREEN_WIDTH/2, 240))      startText3_rect = startText3.get_rect(center=(SCREEN_WIDTH/2, 320))      startText4_rect = startText4.get_rect(center=(SCREEN_WIDTH/2, 400))      startText5_rect = startText5.get_rect(center=(SCREEN_WIDTH/2, 640))        screen.blit(startText1, startText1_rect)      screen.blit(startText2, startText2_rect)      screen.blit(startText3, startText3_rect)      screen.blit(startText4, startText4_rect)      screen.blit(startText5, startText5_rect)    def drawLevel(level):      global gameDrawn      x = y = 0                walls = []        ends = []        players = []      if gameDrawn == False:          screen.fill(WOODY)          drawGrid()          drawRect()          for row in levels[level]:              for col in row:                  if col == "W":                      wall = Wall((x, y))                      walls.append(wall)                  if col == "E":                      end = End((x, y))                      ends.append(end)                  if col == "P":                      player = Player((x,y))                      players.append(player)                  x += 80              y += 80              x = 0          for wall in walls:              pygame.draw.rect(screen, BLACK, wall.rect)          for end in ends:              pygame.draw.rect(screen, RED, end.rect)          for player in players:              pygame.draw.rect(screen, BLUE, player.rect)      gameDrawn = True      #elif gameDrawn == True:          #for event in pygame.event.get():              #if event.type == pygame.USEREVENT:                   #drawTimer(counter)                  #counter -= 1        return players, walls, ends    #def drawPlayerPath():    #def getPlayerPath():  #    players, _, _ = drawLevel(level)  #    player_x, player_y = players[0]  #    for i in move_list:  #        if i == 1:  #            player_y += -1  #        elif i == 2:  #            player_y += 1  #        elif i == 3:  #            player_x += -1  #        elif i == 4:  #            player_x += -1  #        players.append((player_x, player_y))        def calcCounter():      global curr_moves      curr_moves += 1      return curr_moves    def drawCounter(curr_moves):      global screen      text_currMoves = font.render(str(curr_moves) + "/" + str(max_move_list[level]), True, BLACK)      pygame.draw.rect(screen, WHITE, counterRect)      screen.blit(text_currMoves, (1130,40))      if curr_moves == 0:          state = "running"          init_state = True    def writeMoves():      a = 1085      b = 80      for i in range(len(move_list)):          if move_list[i] == 1:              screen.blit(text_up, (a, b))          elif move_list[i] == 2:              screen.blit(text_down, (a, b))                      elif move_list[i] == 3:              screen.blit(text_right, (a, b))                      elif move_list[i] == 4:              screen.blit(text_left, (a, b))          b += 40                def wallCollisionDetection(player, wall, dx, dy):      walls = drawLevel(level)      players = drawLevel(level)      for wall in walls:          if player.rect.colliderect(wall.rect):              if dx > 0:                    player.rect.right = wall.rect.left              if dx < 0:                    player.rect.left = wall.rect.right              if dy > 0:                    player.rect.bottom = wall.rect.top              if dy < 0:                    player.rect.top = wall.rect.bottom            pygame.init()    clock = pygame.time.Clock()  pygame.time.set_timer(pygame.USEREVENT, 1000)  font = pygame.font.SysFont('Consolas', 30)      ###############################################################  # Game-States  ###############################################################    def init_state_start():      pass    def main_loop_state_start():      global state, init_state      for event in pygame.event.get():          if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:              running = False              pygame.quit()              print("Spiel wird beendet!")                            # User-Input wird erfasst            elif event.type == KEYDOWN:              state = "config"              init_state = True              # draw screen -> Startbildschirm wird "gemalt"      screen.fill(LIGHTBLUE)      drawStartMessage()    def init_state_config():      pass    def main_loop_state_config():      global level, end_rect, curr_moves, max_moves, i, j, counter      pygame.time.set_timer(pygame.USEREVENT, 1500)      drawLevel(level)      players, walls, ends = drawLevel(level)      for event in pygame.event.get():          if event.type == pygame.USEREVENT:              counter -= 1                counterT = font.render(str(counter), True, BLACK)              screen.blit(counterT, (1070, 40))                     if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:              running = False              pygame.quit()              print("Spiel wird beendet!")          elif event.type == KEYDOWN:              if event.key == K_UP:                                     move_list.append(1)                                          curr_moves -= 1              elif event.key == K_DOWN:                      move_list.append(2)                                         curr_moves -= 1              elif event.key == K_RIGHT:                      move_list.append(3)                                          curr_moves -= 1              elif event.key == K_LEFT:                      move_list.append(4)                      curr_moves -= 1              if counter == 0:                  state = "running"                  init_state = True           drawCounter(curr_moves)                          writeMoves()      pygame.display.flip()    def init_state_running():      pass    def main_loop_state_running():      global level      players, _, _ = drawLevel(level)        for event in pygame.event.get():          if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:              running = False              pygame.quit()              print("Spiel wird beendet!")          if event.type == KEYDOWN and event.key == K_SPACE:              print(move_list)          for player in players:              movePlayer(move_list)    ###############################################################  # Measurement -> Maßeinheit und Bildschirmmaße  ###############################################################    def pxl (number_of_squares):      "number of squares -> number of pixels"      return SQUARE_SIZE * number_of_squares    ###############################################################  # Font and Texts  ###############################################################      font = pygame.font.SysFont("Consolas", 20)  moveFont = pygame.font.SysFont(None, 30)  # Schrift für Züge  startFont = pygame.font.SysFont(None, 40)   # Schrift für den Startbildschirm  timerFont = pygame.font.SysFont(None, 30)   # Schrift für den Timer  text_up = font.render("OBEN", True, BLACK)  text_down = font.render("UNTEN", True, BLACK)  text_right = font.render("RECHTS", True, BLACK)  text_left = font.render("LINKS", True, BLACK)  screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))  # Fensterbreite und länge in pixeln, nur der Zeichenbereich      ###############################################################  # Generelles Setup  ###############################################################      # Schnelligkeit des Spiels festlegen, damit es überall gleich schnell läuft  state = "start"  init_state = True    ###############################################################  # Screen-Settings  ###############################################################      pygame.display.set_caption("Pygame")    ###############################################################  # Main-Game-Loop  ###############################################################        running = True  while running:      if state == "start":          if init_state:              init_state_start()              init_state = False          else:                  main_loop_state_start()      elif state == "config":          if init_state:              init_state_config()              init_state = False          else:                 main_loop_state_config()              if counter == 0:                  state = "running"                  init_state = True              if curr_moves == 0:                  state = "running"                  init_state = True      elif state == "running":          if init_state:              init_state_running()              init_state = False          else:              main_loop_state_running()                                           # update window      clock.tick(60)          # set refresh rate      pygame.display.flip()    ###############################################################  

It would be really amazing if you could help me and explain the error to me, since I have to do that stuff for university. Thank you really much :D

os.getenv does not work under vs code + jupyter

Posted: 12 Aug 2021 07:49 AM PDT

I can't get bellow simple 2 lines python code work uner my vscode with jupyter extension:

#%%  import os    print("key:" + str(os.getenv('TIINGO_KEY')))  

it out put: enter image description here

as I have added 'TIINGO_KEY' as enviroment variable under both of my fish and .bashrc

when I do it under my jupyter + Mac safari browser, or my fish terminal, the program out put exactly as expected like:

key:52c54923098  

---update

very strange, it turns out some kind of relation with bellow lines

import matplotlib.pyplot as plt  import pandas_datareader as pdr  

after I restart my vs code, actually it just works, but then I add above 2 lines, it goes to some crash when I run second time: enter image description here

TypeError: Cannot access member '_id' of undefined [closed]

Posted: 12 Aug 2021 07:48 AM PDT

Hello I am getting the following error for DB Trigger java script. It is MongoDB DB trigger - changeEvent function.The script will use changeEvent and insert a field if there is newly inserted record. Will you point out what I miss? Thank you in advance.

TypeError: Cannot access member '_id' of undefined

exports = function (changeEvent) {  const {documentKey,fullDocument} = changeEvent;  const docId = changeEvent.documentKey._id;  const collection = context.services.get("Cluster0").db("Driver").collection("Trip");  collection;  collection.updateOne({_id: docId },  {      "$set" :           {               "DocumentCreationDate" :{ "$toDate" : docId }          }  }  );  };  

Copy over data with concatenating few columns together

Posted: 12 Aug 2021 07:49 AM PDT

In my google sheets I have two sheets/tabs.

In Sheet 1 I have below columns

   |   A     |    B         |   C     |  D  -----------------------------------------------  1  | Phone#  |  St Address  |  City   | Buzzer#  -----------------------------------------------  2  | 123     |  Street 1    |Toronto  |  564  -----------------------------------------------  3  | 456     |  Street 2    |Cambridge|      -----------------------------------------------  4  | 523     |  Street 1    |Guelph   |    -----------------------------------------------  5  | 412     |  Street 1    |Barrie   |  985  

In my sheet 2 I want to copy all these data as below format. I am trying to copy over column A -> Phone# Column as is and concatenate column B | Column C | Column D columns together with ,. Where if There is Buzzer number I want to append word Buzzer end of the city name otherwise leave it blank.

   |   A     |  B  -----------------------------------------  1  | Phone#  |  Complete Address  -----------------------------------------  2  | 123     |  Street 1, Toronto, Buzzer 564  ------------------------------------------  3  | 456     |  Street 2, Cambridge  ------------------------------------------  4  | 523     |  Street 1, Guelph   ------------------------------------------  5  | 412     |  Street 1, Barrie, Buzzer 985  

And Here is How I have tried to copy over data from Sheet1 to sheet2 and concatenate columns B,C,D together

=Query('Sheet1'!A:D,"Select A and CONCATENATE((IF(D<>"",(CONCATENATE("Buzzer-"," ",D,", ")),"")),B,", ",C,", ",D) where A is not null",1)  

Obviously this didn't work. Any suggestions or Help please?

Postgres grouping by range

Posted: 12 Aug 2021 07:49 AM PDT

I have data looking like this enter image description here

What I am trying to achieve is data for historgram that would count values into specific ranges. For category A value range 1-100 and for category B value range 0-125 where value for category C = 5. The problem I have that is data in multiplerows and I need to filter first on C and then count values into ranges to display histogram. To get counts lets say per 10 seconds looking like this enter image description here

Code to generate data:

CREATE TEMP TABLE sample (       ts timestamp      ,category varchar(2)      , val int)        insert into sample values   (to_timestamp('01.01.2018 08:00:01', 'dd-mm-yyyy hh24:mi:ss'), 'A', 12)  (to_timestamp('01.01.2018 08:00:02', 'dd-mm-yyyy hh24:mi:ss'), 'A', 44),  (to_timestamp('01.01.2018 08:00:03', 'dd-mm-yyyy hh24:mi:ss'), 'C', 1),  (to_timestamp('01.01.2018 08:00:04', 'dd-mm-yyyy hh24:mi:ss'), 'B', 24),  (to_timestamp('01.01.2018 08:00:05', 'dd-mm-yyyy hh24:mi:ss'), 'B', 111),  (to_timestamp('01.01.2018 08:00:06', 'dd-mm-yyyy hh24:mi:ss'), 'C', 5),  (to_timestamp('01.01.2018 08:00:07', 'dd-mm-yyyy hh24:mi:ss'), 'A', 145)  

Azure app uploads from VSCode without linking static sources

Posted: 12 Aug 2021 07:48 AM PDT

I have an incredibly basic node.js server test app running on port 3000 in VSCode. The server appears to work via node on localhost or deployed to Azure, and hosts an index.html file. I have clients happy to talk to it.

    /* Server.js */            const express = require('express');      const app = express();      app.use(express.json());            app.get("/", function(request, response){          response.sendFile(__dirname + "/index.html");      });            app.post("/", function(request, result){          console.log(request.body["itema"] + " " + request.body["itemb"]);          result.send("Pong!!");      });            app.listen(3000, function(){          console.log("Server started on port 3000");      });  
    <!-- Index.html -->        <!DOCTYPE html>                <html>        <head>          <title>Simple App</title>          <link rel="stylesheet" href="style.css" type="text/css"/>        </head>        <body>          <h1>Test!</h1>        </body>      </html>  
    /*style.css*/        h1 {        color: tomato;      }  

Azure Configuration Settings


The index.html links to a css file which doesn't appear to be linked when deployed. I've tried deploying the app to azurewebsites.net through VSCode, however I'm seeing the same results. Only index.html is present in the sources view. I get an error claiming it can't render the source it didn't find.

"Refused to apply style from https://<appname>.azurewebsites.net/style.css because its MIME   type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is   enabled."  

If I view the advanced page (.scm.azurewebsites.net), again I can see only index.html.

Index only

But .scm.azurewebsites.net/wwwroot/ shows me the css file has been uploaded correctly.

Index and linked sources

I'm convinced it'll be a simple solution to someone and that the PATH variables will need to be set...somehow... but I've hit a brick wall and my Google-Fu has finally been exhausted.

Thanks!

How to pass variable inside JMESpath query?

Posted: 12 Aug 2021 07:49 AM PDT

I am trying to pass an environment variable inside a JMESpath query for an az cli command. Currently the problem is when I am passing the variable at standalone, I am able to get the result as expected but when I using the same command inside a while or for loop, the value is passing as null. Kindly help me on this and appreciate your effort. My script is as follows:

jq -c '.[]' 2data.json | while read i  do  echo "value of i is $i"  az postgres server firewall-rule show --ids $firewallName --query "[name == '$i'].{name:name}"  done  

Output:

value of i is "secondrule"  {    "name": null  }  value of i is "newRule"  {    "name": null  }  

2data.json file contains

[ "secondrule", "newRule" ]  

Manual execution of az command:

data="secondrule"  az postgres server firewall-rule show --ids $firewallName --query "[?name == '$data'].{name:name}"  

Output of manual execution: (expected)

[    {      "name": "secondrule"    }  ]  

How I can resolve this and pass the input as variable and get the desired output?

Trying to sort a column that got Multiple Strings (with some restrictions from my Employer)

Posted: 12 Aug 2021 07:49 AM PDT

I am having some Problems getting a table column sorted the way the employer wants me to. First i used If cases and "data-order" values to sort this column, but i was told i am not supposed to use hardcoded numbers because of possible "big number problems" or things like that. Now i am looking to get another solution but i seem to be stuck:

It's a table with 5 Columns, three of those columns got a pair of two Database Strings in them.

Columns are:

"Type" | "Worklist" | "Task Name/ Task Description" | "After Running hours/ Interval" | "Next due at date / in Running hours"

Now i am supposed to make the "After Running hours/ Interval" column sortable and the result should show first: every entry that actually got a "After Running hours" entry, ascending and the rest should be sorted by interval lenght (Intervals can be x day(s), x week(s), x month(s), x year(s) and both entrys (Interval and Running hours) might be empty and those cases should be at the bottom. Currently the code as shown below sorts After Running hours correctly but after that it goes 1 month(s) -> 1 week(s) -> 1 year(s) -> 2month(s) and so on. I was hoping anyone could give me a hint on how to fix that, maybe a hidden input with{{}} which would bring days/weeks/month/year into the right order.

            @if($task->worklistTask->running_hours)                  {{$task->worklistTask->running_hours . " h"}} <br>                  @if($task->worklistTask->interval && $task->worklistTask->intervalunit)                      {{ $task->worklistTask->interval }} {{ $task->worklistTask->intervalunit->name }}                      @else {{"-"}}              @endif              @elseif($task->worklistTask->interval && $task->worklistTask->intervalunit && ($task->worklistTask->intervalunit->name == 'day(s)'))                  {{"-"}} <br> {{ $task->worklistTask->interval }} {{ $task->worklistTask->intervalunit->name }}              @elseif($task->worklistTask->interval && $task->worklistTask->intervalunit && ($task->worklistTask->intervalunit->name == 'week(s)'))                  {{"-"}} <br> {{ $task->worklistTask->interval }} {{ $task->worklistTask->intervalunit->name }}              @elseif($task->worklistTask->interval && $task->worklistTask->intervalunit && ($task->worklistTask->intervalunit->name == 'month(s)'))                  {{"-"}} <br> {{ $task->worklistTask->interval }} {{ $task->worklistTask->intervalunit->name }}              @elseif($task->worklistTask->interval && $task->worklistTask->intervalunit && ($task->worklistTask->intervalunit->name == 'year(s)'))                  {{"-"}} <br> {{ $task->worklistTask->interval }} {{ $task->worklistTask->intervalunit->name }}                  @else {{"-"}} <br> {{"-"}}              @endif          </td>    Example Table  | Type    | Worklist | TaskN./ TaskDes.| ARH <br> Int.     | Nextdue/ iRHs|  |:------  |:--------:| :--------------:|:-----------------:|-------------:|  | Default | WLName1  | Task1/Taskstuff |100h <br> 1 year(s)|    -/-       |  | Default | WLName3  | Task4/Taskstuff |150h <br> -        |    -/-       |  | critical| WLName3  | Task5/Taskstuff |200h <br> 1 week(s)|    -/-       |  | Default | WLName1  | Task2/Taskstuff |- <br> 1 month(s)  |    -/-       |  | Solas   | WLName2  | Task3/Taskstuff |- <br> 1 week(s)   |    -/-       |  | Default | WLName4  | Task6/Taskstuff |- <br> 2 month(s)  |    -/-       |    We use the js-table plugin. Type and Worklist make no problems at all (Press the header and it gets sorted properly) "TaskN./TaskDes." only sorts the taskNames alphabetically but that seems to be no issue for the customer for now. Next due can't be sorted by "inRunningHours" but thats also not a problem for now.  Sorting the ARH/Int. ("After Running hours" / "Interval") Column at the moment sorts The Running hours, ascending, correctly. After that things get messed up. He still sorts the "rest of the string" alphabetically (everything without a running hours value will get a "-" but i would need them to be sorted after interval length.    The Previous version was unwanted and now i am looking for a new solution.  Previous solution:   ```<td data-order="@if($task->worklistTask->running_hours){{ $task->worklistTask->running_hours }}                          @elseif (!empty($task->worklistTask->interval) && $task->worklistTask->intervalunit->name == 'day(s)') {{50000 + $task->worklistTask->interval * 1}}                          @elseif (!empty($task->worklistTask->interval) && $task->worklistTask->intervalunit->name == 'week(s)') {{50000 + $task->worklistTask->interval * 7}}                          @elseif (!empty($task->worklistTask->interval) && $task->worklistTask->intervalunit->name == 'month(s)') {{50000 + $task->worklistTask->interval * 30}}                          @elseif (!empty($task->worklistTask->interval) && $task->worklistTask->intervalunit->name == 'year(s)') {{50000 + $task->worklistTask->interval * 365}}                          @else 999999 @endif">  

loop over aws provider to create ressources in every aws account

Posted: 12 Aug 2021 07:49 AM PDT

I have a list of objects in Terraform called users and the structure is the following:

variable "accounts" {    type = list(object({      id       = string #used in assume_role      email   = string      is_enabled = bool    }))  }  

What I am trying to achieve now is to create a simple S3 bucket in each of those AWS accounts (if the is_enabled is true). I was able to do it for a single account but I am not sure if there is a way to loop over a provider?

Code for a single account - main.tf

provider "aws" {    alias = "new_account"    region = "eu-west-3"      assume_role {      role_arn     = "arn:aws:iam::${aws_organizations_account.this.id}:role/OrganizationAccountAccessRole"      session_name = "new_account_creation"    }  }    resource "aws_s3_bucket" "bucket" {    provider = aws.new_account      bucket = "new-account-bucket-${aws_organizations_account.this.id}"    acl    = "private"  }    

Limiting containers to three fixed sizes

Posted: 12 Aug 2021 07:49 AM PDT

I'm looking at the react-grid-layout which is based on Material Design's 12 column grid. Is there a way to provide pre-defined sizes for containers to stick to the following 3 sizes: 1 full width (12 cols), half grid (6 cols) or 1/3 grid (4 cols)?

Sandbox

How to make mouse scroll work in AWS Workspace

Posted: 12 Aug 2021 07:49 AM PDT

I am using AWS Workspace with Linux for some work. And using Windows Client to connect to it.
Everything seems to be working fine except I cannot use mouse scroll in the workspace(not working in firefox/terminal/any-window). (scroll is working fine on the machine where the client is running)

Left-click and right-click both are working fine.

I tried to find it on AWS forums and SO too, but couldn't find anything related to this. If you try to search the same on Google, there is one similar thread - but it's related to mouse with some extra buttons.

Scrolling seems to be a basic functionality that should be provided. Any help would be appreciated. Thanks.

Is there a specific logical way to determine if there is an integer in a String?

Posted: 12 Aug 2021 07:49 AM PDT

I am wondering if using a for loop to determine if an integer is inside of a string, would be the best option. But I am not so sure.

How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext

Posted: 12 Aug 2021 07:48 AM PDT

How can I access current HttpContext to check for route and parameters inside AuthorizationHandlerContext of Custom Policy-Based Authorization inside ASP.NET Core 2?

Ref example: Custom Policy-Based Authorization

What does it mean for something to be thread safe in iOS?

Posted: 12 Aug 2021 07:49 AM PDT

I often come across the key terms "thread safe" and wonder what it means. For example, in Firebase or Realm, some objects are considered "Thread Safe". What exactly does it mean for something to be thread safe?

MAC OS X Xampp Access forbidden

Posted: 12 Aug 2021 07:48 AM PDT

I have installed the XAMPP in my MAC.

And i just tryed to open a folder and it's returned a error 403: Access forbidden!

I read on foruns that i need to change the httpd archive, but, after the changes, no change, the error Access forbidden! on my folder/sites continues.

The http.conf that i have changed are here: "Applications/XAMPP/xamppfiles/apache2/conf"

Alias /bitnami/ "/Applications/XAMPP/xamppfiles/apache2/htdocs/"  Alias /bitnami "/Applications/XAMPP/xamppfiles/apache2/htdocs"        <Directory />          Options All          AllowOverride All          Order deny,allow          Allow from all      </Directory>  

Thanks!

Reverse a string with php

Posted: 12 Aug 2021 07:49 AM PDT

I am trying to find a way to reverse a string, I've seen alternatives but i wanted to to it this way thinking outside the box and not using anyone else's code as an alternative, the code below reverses the string but I keep getting this error:

Notice: Undefined offset: 25 in C:\wamp\www\test\index.php on line 15

25 being the length of the string which is being deincremented.

//error_reporting(NULL);  $string = trim("This is a reversed string");    //find length of string including whitespace  $len =strlen($string);    //slipt sting into an array  $stringExp = str_split($string);    //deincriment string and echo out in reverse  for ($i = $len; $i >=0;$i--)  {  echo $stringExp[$i];  }  

thanks in advance

No comments:

Post a Comment