Sunday, May 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Display several tables in which a particular element

Posted: 23 May 2021 07:59 AM PDT

I am trying to display several tables in which a particular element should only be listed using a single database query only.

<table>      <tr>          <th colspan="4"><p>Plates</p></th>      </tr>      <?php      if(isset mysqli_query($query['category']) == ("Plates")){        while($row = mysqli_fetch_assoc($res)) {          ?>                    <tr>              <td></td>              <td><?php echo $row['name']; ?></td>              <td><?php echo $row['value']; ?></td>              <td></td>          </tr>          <?php      }  }      mysqli_free_result($res);      mysqli_close($conn);      ?>  </table>  

Making a simple Log class

Posted: 23 May 2021 07:59 AM PDT

I'm trying to make this simple Log class and getting linker issue when compiling, could anyone tell me what this mean?

Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Log C:\Users\Documents\Code Projects\Log\Log\MSVCRTD.lib(exe_main.obj)

Log.h

#pragma once  class Log {  public:      enum Level      {          LevelError, LevelWarning, LevelInfo      };        void SetLogLevel(Level level);      void Error(const char* message);      void Warn(const char* message);      void Info(const char* message);    private:      Level m_LogLevel = LevelInfo;  };  

Log.cpp

#include "Log.h"  #include <iostream>    void Log::SetLogLevel(Level level) {      m_LogLevel = level;  }    void Log::Error(const char* message) {      if (m_LogLevel >= LevelError)          std::cout << "[ERROR]: " << message << std::endl;  }    void Log::Warn(const char* message) {      if (m_LogLevel >= LevelWarning)          std::cout << "[WARNING]: " << message << std::endl;  }    void Log::Info(const char* message) {      if (m_LogLevel >= LevelInfo)          std::cout << "[INFO]: " << message << std::endl;  }  

I/Ads: Ad failed to load : 3 - Android

Posted: 23 May 2021 07:58 AM PDT

I have an app that is published on the play store and is enabled to show ads. I wanted to release an update since I've added some new features. However, the live ads are not loading, whilst the test ads are working fine. After I looked into this issue, I learned that the error code 3 represents no available ads at the moment. But what's strange is that the version of the app currently live on the play store shows real ads perfectly fine( the ads with the same pub ID). Also, I'd like to acknowledge that the AdMob account and the Ad units are a year old. But when I'm using the same ad units in the newer version( yet to be rolled out), I'm getting this error I/Ads: Ad failed to load : 3. It's been over 3-4 days since I'm getting this error and haven't fixed this until now. Other than feature addition, the following are the changes made to the app:

  1. version code
  2. version name
  3. Target SDK version
  4. Minimum SDK version
  5. Migrated to androidX ( due to some library incompatibility), live ads weren't showing before the migration also.
  6. Updated play-services-ads from 16.0.0 to 19.1.0

What do I do to fix this? Thanks in advance.

How can I access GlobalConfiguration.Configuration from a new ASP.NET Core WebApi project (.Net 5.0)?

Posted: 23 May 2021 07:58 AM PDT

The following statement now seems unsupported in WebApi:

var config = GlobalConfiguration.Configuration;  

Could anyone please point me in the right direction how I can obtain GlobalConfiguration.Configuration from a new ASP.NET Core WebApi project (.Net 5.0)?

GlobalConfiguration.Configuration seems unavailable in a new ASP.NET Core WebApi project (.Net 5.0) .

Steps to reproduce:

  1. Create a new "ASP.NET Core Web Api" project. (Target framework: .NET 5.0, Lang: C#)
  2. Install-Package Microsoft.AspNet.WebApi.WebHost -Version 5.2.7
  3. Make this change to Startup.cs:
public Startup(IConfiguration configuration)  {          var c = GlobalConfiguration.Configuration;    // this line was added          Configuration = configuration;  }  

Run the application, and you'll see:

System.TypeLoadException    HResult=0x80131522    Message=Could not load type 'System.Web.Routing.RouteTable'    from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.    Source=System.Web.Http.WebHost    StackTrace:     at System.Web.Http.GlobalConfiguration.<>c.<CreateConfiguration>b__11_0()     at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)     at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)     at System.Lazy`1.CreateValue()     at System.Lazy`1.get_Value()     at System.Web.Http.GlobalConfiguration.get_Configuration()     at AspNetCore5._0.Program.Main(String[] args) in C:\work\AspNetCore5.0\Program.cs:line 17  

Any help will be much appreciated. Thanks!

How to do case based search

Posted: 23 May 2021 07:59 AM PDT

We have a Donor table.

CREATE TABLE [dbo].[Donors](      [DonorId] [int] IDENTITY(1,1) NOT NULL,      [IdentificationNo] [nvarchar](250) NULL,      [IdentityTypeId] [int] NULL,      [Prefix] [nvarchar](50) NULL,      [DonorName] [nvarchar](500) NULL,      [EmailId] [nvarchar](250) NULL,      [ContactNo] [nvarchar](250) NULL,      [CreatedOn] [datetime] NOT NULL,      [ModifiedOn] [datetime] NULL  ) ON [PRIMARY]  GO    ALTER TABLE [dbo].[Donors] ADD  CONSTRAINT [DF_Donors_CreatedOn]  DEFAULT (getutcdate()) FOR [CreatedOn]  GO    INSERT INTO [dbo].[Donors]             ([IdentificationNo]             ,[IdentityTypeId]             ,[Prefix]             ,[DonorName]             ,[EmailId]             ,[ContactNo])       VALUES             (null, null, null, 'Anil', null, null),             (null, null, null, 'Indranil', null, null),             (null, null, null, 'Debarya', null, null),             (null, null, null, 'Dushyant', null, null),             (null, null, null, 'Rudranil', null, null)  GO  

We want to search either by DonorName or IdentificationNo or EmailId or ContactNo. For that written the following query

DECLARE @SearchTerm nvarchar(250) NULL  DECLARE @SearchBy [tinyint]  SET @SearchTerm = 'ANIL'  SET @SearchBy = 2  SELECT [DonorId], [IdentificationNo], [IdentityTypeId], [Prefix], [DonorName], [EmailId], [ContactNo]      FROM [dbo].[Donors]      WHERE 1 =               CASE                   WHEN @SearchBy = 1 AND [IdentificationNo] like '%' + @SearchTerm + '%' THEN 1                  WHEN @SearchBy = 2 AND [DonorName] like '%' + @SearchTerm + '%' THEN 1                  WHEN @SearchBy = 3 AND [EmailId] like '%' + @SearchTerm + '%' THEN 1                  WHEN @SearchBy = 4 AND [ContactNo] like '%' + @SearchTerm + '%' THEN 1                  ELSE 0              END  

But every time getting Msg 102, Level 15, State 1, Line 5 Incorrect syntax near 'NULL'.

What are we doing wrong?

Is there any better way to do this?

If you want to use fiddle, here is one ready link http://sqlfiddle.com/#!18/05ad44/1.

Express call a server function on client side and pass a variable to it

Posted: 23 May 2021 07:58 AM PDT

How can I call a function on an express server and pass a variable into it from a client script?

Arithmetic average in matrix

Posted: 23 May 2021 07:59 AM PDT

Hello i have a problem with code. I need to count 2 more options:

  • arithmetic average under the main diagonal
  • arithmetic average of the second diagonal I write this code below, but i dont know how i can count this 2 options. Any help will be nice to see. Thanks!

double arithmetic(int* arr, int n);

int main(){  int n, sum = 0, **A, *arr,l;  printf("Enter size of matrix: ");  scanf("%d", &n);  A = (int**)malloc(sizeof(int*) * n);  arr = (int*)malloc(sizeof(int*) * n);  if (!A)      printf("Error");            for (int i = 0; i < n; i++)  {      A[i] = (int*)malloc(sizeof(int) * n);      if (!A[i])          printf("Error");  }  printf("Give numbers by lines:\n");  for (int i = 0; i < n; i++)   {      for (int j = 0; j < n; j++)       {          scanf("%d", &A[i][j]);      }  }    printf("Give the line and column to count: ");  scanf("%d", &l);  for (int i = 0; i < n; i++)  {      arr[i] = A[l][i];  }  printf("Arithmetic average in line %d, is %.2f\n", l, arithmetic(arr, n));    for (int i = 0; i < n; i++)  {      arr[i] = A[i][l];  }  printf("Arithmetic average in column %d, is %.2f\n", l, arithmetic(arr, n));        for (int i = 0; i < n; i++)   {      arr[i] = A[i][i];  }  printf("Arithmetic average on main diagonal, is %.2f\n", arithmetic(arr, n));  

}

double arithmetic(int* arr, int n)   {      double sum = 0;      for (int i = 0; i < n; i++)       {          if (arr[i] > 0)              sum = sum + arr[i];                }      double result = sum/n;      return result;  }  

Do you want to make money easily with your mobile phone?

Posted: 23 May 2021 07:57 AM PDT

If you want to make money easily with your mobile phone, you have reached the right place, I am part of the @ advent.store.ro team and I want to make you a proposal: to be our partner 👏 it's simple, all you have to do is leave a message on the main page @ advent.store.ro on instagram and tell them that you are sent by me paul_andrei1712❤️ good luck !!

How to save the output of a command which was run in command prompt? [duplicate]

Posted: 23 May 2021 07:59 AM PDT

I have some text:

lbl = 'print("hhhh")\nprint("yes!")'  

Of which I'm running in a command prompt:

import os  os.system("python3 -c '%s'" % (lbl, ))  

It works, then displays the outcome on my cmd. I would like to save the output to a variable. I tried this:

ouput = os.system("python3 -c '%s'" % (lbl, ))  

I think there is a command in command prompt that needs to be written, I just don't know which one.

Issue with CORS on Node.js on HTTPS (Elastic Beanstalk)

Posted: 23 May 2021 07:57 AM PDT

I have a Node.js API that I've deployed with Elastic Beanstalk, and when I send an POST request to the API over HTTP, I have no problem getting a response. However, when I try to send a POST request to the HTTPS listener for the API from a site that's served over HTTPS, I am getting the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...

I see the failure is happening on the OPTIONS pre-flight request. I've seen many StackOverflow posts about this kind of error, but none of the suggestions I've tried have worked.

Here is how my Node.js file is handling the requests:

const express = require('express');  const bodyParser = require('body-parser');  const path = require("path");  const cors = require('cors');    const e = require('express');    const app = express();    app.use(cors());    app.use(bodyParser.json());  app.use(bodyParser.urlencoded({extended:false}));    app.use((req, res, next) => {      res.setHeader('Access-Control-Allow-Origin', '*');      res.setHeader('Access-Control-Allow-Headers', '*');      res.setHeader('Access-Control-Allow-Methods', 'GET, POST');        if('OPTIONS' === req.method) {          res.sendStatus(200);      } else {          next();      }  });      ...    

I would think the code would return 200 on the OPTIONS method based on the code above but it still gets denied.

Any suggestions on how I can resolve this CORS issue?

Assign unique ID based on match between two columns in PySpark Dataframe

Posted: 23 May 2021 07:57 AM PDT

I want to assign an auto incremental unique ID to a column in the dataframe.

If the column1 value is a match with column2 value flag will be enabled as true and for all those matches we need to assign a same ID. If there is no match of column1 value with column2 value flag will be False and we need to provide a unique ID for that column1 value.

Input df

ID Column1 Column2 flag
null 1 2 True
null 1 3 True
null 2 1 True
null 2 3 True
null 3 1 True
null 3 2 True
null 4 False
null 5 False
null 6 7 True
null 7 6 True

Output df

Here column1 value 1,2 and 3 form a match so we assign a single unique ID for all these 3 values(101), column1 value 4 is not a match so we assign next unique ID(102), column1 value 5 is also not a match so we assign next unique ID(103), column1 value 6 and 7 are matches so we assign same unique ID for 2 values(104)

ID Column1
101 1
101 2
101 3
102 4
103 5
104 6
104 7

How to access value inside this array

Posted: 23 May 2021 07:58 AM PDT

I have an array like this:

enter image description here

I need to access the value which is set to 876.

The code behind this array goes here:

       try {              $totalTck = $TransactionBuilder->triggerSmartContract(                  (array)$abi,                  $contractH,                  $function,                  $params,                  $feeLimit,                  $addressH,                  $callValue = 0,                  $bandwidthLimit = 0);                    dd($totalTck);          } catch (\IEXBase\TronAPI\Exception\TronException $e) {              die($e->getMessage());          }  

But I don't know how can I do that ?

Can you please help me on getting the value from this array...

Align types with ExceptT IO monad transformer

Posted: 23 May 2021 07:58 AM PDT

Trying to wrap my head around monad transformers, I could get some toy examples to work but here I'm struggling with a slightly more real-worldy use case. Building upon this previous question, with a more realistic example using ExceptT, where three helper functions are defined.

{-# LANGUAGE RecordWildCards #-}    -- imports so that the example is reproducible  import           Control.Monad.IO.Class     (MonadIO (liftIO))  import           Control.Monad.Trans.Except  import qualified Data.List                  as L  import           Data.Text                  (Text)  import qualified Data.Text                  as T  import           System.Random              (Random (randomRIO))    -- a few type declarations so the example is easier to follow  newtype Error = Error Text deriving Show  newtype SQLQuery = SQLQuery Text deriving Show  newtype Name = Name { unName :: Text } deriving Show  data WithVersion = WithVersion { vName :: Name, vVersion :: Int }    -- | for each name, retrieve the corresponding version from an external data store  retrieveVersions :: [Name] -> ExceptT Error IO [WithVersion]  retrieveVersions names = do      doError <- liftIO $ randomRIO (True, False) -- simulate an error      if doError          then throwE $ Error "could not retrieve versions"          else do              let fv = zipWith WithVersion names [1..] -- just a simulation              pure fv    -- | construct a SQL query based on the names/versions provided  -- (note that this example is a toy with a fake query)  mkQuery :: [WithVersion] -> SQLQuery  mkQuery withVersions =      SQLQuery $ mconcat $ L.intersperse "\n" $ (\WithVersion {..} ->          unName vName <> ":" <> T.pack (show vVersion)      ) <$> withVersion    -- | query an external SQL database and return result as Text  queryDB :: SQLQuery -> ExceptT Error IO Text  queryDB q = do      doError <- liftIO $ randomRIO (True, False) -- simulate an error      if doError          then throwE $ Error "SQL error"          else do              pure "This is the result of the (successful) query"  

The calls to randomRIO are there to simulate the possibility of an error. If doError is True, then the helper returns what would be the equivalent of Left $ Error "message" if using Either.

All the helpers above compile just fine, however the example wrapper function below doesn't compile:

-- | given a list of names, retrieve versions, build query and retrieve result  retrieveValues :: [Name] -> ExceptT Error IO Text  retrieveValues names = do      eitherResult <- runExceptT $ do          withVersions <- retrieveVersions names          let query = mkQuery withVersions          queryDB query      case eitherResult of          Left err     -> throwE err          Right result -> pure result  

The error given by GHC is as follows:

• Couldn't match type 'IO' with 'ExceptT Error IO'    Expected type: ExceptT Error IO (Either Error Text)      Actual type: IO (Either Error Text)  • In a stmt of a 'do' block:      eitherResult <- runExceptT                        $ do withVersions <- retrieveVersions names                             let query = mkQuery withVersions                             queryDB query  

I've tried using various functions in place of runExceptT, namely runExcept, withExcept, withExceptT but none of them worked. The closed I can get between Expected and Actual types is with runExceptT.

What should be changed in order for retrieveValues to compile and properly return "either" an Error or a result in the form of a Text?

I also think that using caseEitherResult of might be redundant here because all it does is essentially passing on either the result or the error, with no additional processing, so I attempted a more direct version, which also fails:

retrieveValues :: [Name] -> ExceptT Error IO Text  retrieveValues names = do      runExceptT $ do          withVersions <- retrieveVersions names          let query = mkQuery withVersions          queryDB query  

how would the bot display a different message depending on the person who typed the command

Posted: 23 May 2021 07:58 AM PDT

I am new to discord.js and want to know how I would make the bot say something different depending on the ${message.author}. For example:

Person 1: !hello

Bot: Nope, goodbye.

Person 2: !hello

Bot: Oh, hello!

my command handler has this sort of thing in the main/index.js:

    if(command === 'hello'){          client.commands.get('hello').execute(message, args);  

and in a js file called "hello", it has this:

module.exports = {      name: 'hello',      description: 'example message',      execute(message, args) {          message.channel.send(`example`);        }  }  

so if the bot could check who is typing in this sort of format, that would be really useful, thanks. Sorry for my lack of understanding.

I'm starting to learn c language. Kindly help me to solve this problem [closed]

Posted: 23 May 2021 07:58 AM PDT

Write a function that accept a character ch and a number n as arguments. The function that displays an n * n grid filled with ch. use the function in a program

A hack to write to 32-bit directories from 64-bit MSI package in WiX

Posted: 23 May 2021 07:59 AM PDT

Is there any solution to write files to 32-bit directories from 64-bit MSI package in WiX-toolset

How to convert polylines as arrays in kotlin?

Posted: 23 May 2021 07:57 AM PDT

I would like to convert my polylines to arrays, so that I could save them to firebase. How do I this 'polyline' to arrays. Can anyone help?

    private fun drawPolyline() {          val polyline = map.addPolyline(                  PolylineOptions().apply {                      width(10f)                      color(Color.BLUE)                      jointType(JointType.ROUND)                      startCap(ButtCap())                      endCap(ButtCap())                      addAll(locationList)                  }            )          polylineList.add(polyline)      }        private fun followPolyline() {          if (locationList.isNotEmpty()) {              map.animateCamera(                      (CameraUpdateFactory.newCameraPosition(                              setCameraPosition(                                      locationList.last()                              )                      )), 1000, null)          }        }  

I cannot create a linked list with cpp

Posted: 23 May 2021 07:59 AM PDT

Basically for my assignment I need to implement code to do Huffman coding. For that I need to take input as a string and then create a list of characters and their frequencies. I need to create a new node when there is a new character. I have tried doing it in C with no result. When I try to print my linked list I simply cannot get any output. I believe I have failed in creating the list from the start. My C code is below:

#include <stdio.h>  #include <stdlib.h>  #include <string.h>  #include <stdbool.h>    struct node {      char character;      int frequency;      struct node *next;  }head;    struct node *insert(int frequency, char character) {      struct node *newNode = malloc(sizeof(struct node));      newNode->character = frequency;      newNode->character = character;      return newNode;  }    void create_freq_list(struct node *initial, int str_size, char str[]) {      int i;      struct node *temp;      bool has_node;      for (i = 0; i < str_size; i++) {          temp = initial;          has_node = false;          while (temp->next != NULL) {              if (temp->character == str[i]) {                  has_node = true;                  temp->frequency++;              }              temp = temp->next;          }            if (has_node == false) {              while (temp->next != NULL) {                  temp = temp->next;                  if (temp->next == NULL) {                      temp->next = insert(0, str[i]);                  }              }          }      }  }    int main() {      struct node *temp;      char str[100];      gets_s(str, 100);      create_freq_list(&head, 100, str);        temp = &head;      while (temp->next != NULL) {          printf("'%c' : %d", temp->character, temp->frequency);          temp = temp->next;      }        getch();      exit(0);  }  

how to perform the same subsetting process on several dataframes *in-place* in R? [duplicate]

Posted: 23 May 2021 07:58 AM PDT

i'm looking for a way to quickly perform in-place subsetting of my dataframes in R.

say i have n dfs of varying lengths, all containing 3 columns: chr, start, end describing genomic regions altogether.

I created a vector of the legitimate 'chr' labels for that matter, let's say ["chr1", "chr2", ... , "chr12"].

some (or all) of my dfs has rows which contains invalid chromosomal names (e.g. "chr4_UG5432_random" or "chrX". the names doesn't really matter - just that they don't appear in my vector of "valid" labels), and I want to efficiently filter out rows with this invalid labels.

so the best solution I found so far is putting them all in a list, and using lapply on them with

subset(df,chr %in% c(paste0("chr",1:12)))

and I understand that afterwards I can use the functions list2env to retrieve the variables "holding" the modified dfs.

but i'm sure there is a much simpler way to perform this filtering in-place for each dataframe, without having to throw them in a list. any help is appreciated!

The method 'toDouble' was called on null when I call distance

Posted: 23 May 2021 07:58 AM PDT

I am getting my data from model class and when I switch from any other Tab screen to this screen it takes second or two to get away from this error:-

    The method 'toDouble' was called on null.      Receiver: null      Tried calling: toDouble().  

What is the reason for that and how can I get away from this? This is where I am displaying it and commented the line next to where link mentioned in console takes me to when clicked on error:-

           Padding(                      padding: const EdgeInsets.all(15.0),                      child: Card(                        color: themeProvider.isDarkMode? black :white,                        child: Padding(                          padding: const EdgeInsets.all(8.0),                          child: ListTile(                            title: Text(                              "Maximum distance",                              style: TextStyle(                                  fontSize: 18,                                  color: mRed,                                  fontWeight: FontWeight.w500),                            ),                            trailing: Text(                              "$distance Km.",                              style: TextStyle(fontSize: 16),                            ),                            subtitle: Slider(                                value: distance.toDouble(),/// Error takes me to this line.                                inactiveColor: Colors.blueGrey,                                min: 1.0,                                max: 500,                                activeColor: mRed,                                onChanged: (val) {                                  changeValues                                      .addAll({'maximum_distance': val.round()});                                  setState(() {                                    distance = val.round();                                  });                                }),                          ),                        ),                      ),                    ),  

This is another Error in same screen:-

     The getter 'start' was called on null.       Receiver: null       Tried calling: start           Padding(                      padding: const EdgeInsets.all(15.0),                      child: Card(                        color: themeProvider.isDarkMode? black :white,                        child: Padding(                          padding: const EdgeInsets.all(8.0),                          child: ListTile(                            title: Text(                              "Age range",                              style: TextStyle(                                  fontSize: 18,                                  color: mRed,                                  fontWeight: FontWeight.w500),                            ),                            trailing: Text(              "${ageRange.start.round()}- // Error take me here ${ageRange.end.round()}",                              style: TextStyle(fontSize: 16),                            ),                            subtitle: RangeSlider(                                inactiveColor: Colors.blueGrey,                                values: ageRange,                                min: 18.0,                                max: 100.0,                                divisions: 25,                                activeColor: mRed,                                labels: RangeLabels('${ageRange.start.round()}',                                    '${ageRange.end.round()}'),                                onChanged: (val) {                                  changeValues.addAll({                                    'age_range': {                                      'min': '${val.start.truncate()}',                                      'max': '${val.end.truncate()}'                                    }                                  });                                  setState(() {                                    ageRange = val;                                  });                                }),                          ),                        ),                      ),                    ),  

Disable button in UI based on input from module in Shiny app

Posted: 23 May 2021 07:57 AM PDT

In a Shiny app, I'm trying to disable an action button in the UI of the main app based on input from a module. Basically, I want the "Next Page" (submit) button to be disabled until the last item (item3) is completed. However, my app isn't updating the toggle state of the action button.

Here's a minimal reproducible example using a {Golem} structure:

app_ui.R:

library("shiny")  library("shinyjs")    app_ui <- function(request) {    tagList(      useShinyjs(),      fluidPage(        mod_mod1_ui("mod1_ui_1"),        actionButton(inputId = "submit",                     label = "Next Page")      )    )  }  

app_server.R:

library("shiny")  library("shinyjs")    app_server <- function( input, output, session ) {    state <- mod_mod1_server("mod1_ui_1")        # Don't show "Next Page" button until last item is completed    observe({      toggleState("submit", state == TRUE)      })    }  

mod_mod1.R:

library("shiny")  library("shinyjs")    mod_mod1_ui <- function(id){    ns <- NS(id)    tagList(      radioButtons(inputId = ns("item1"),                   label = "Item 1",                   choices = c(1, 2, 3, 4),                   selected = character(0)),            radioButtons(inputId = ns("item2"),                   label = "Item 2",                   choices = c(1, 2, 3, 4),                   selected = character(0)),            radioButtons(inputId = ns("item3"),                   label = "Item 3",                   choices = c(1, 2, 3, 4),                   selected = character(0))    )  }    mod_mod1_server <- function(id){    moduleServer( id, function(input, output, session){      ns <- session$ns            # When the last survey question is completed      completed <- logical(1)            observe({        lastQuestion <- input$item3        if(!is.null(lastQuestion)){          completed <- TRUE        } else {          completed <- FALSE        }        browser()      })            return(completed)       })  }  

Using browser() statements, it appears that the completed variable is correctly being updated in the module, but that the state variable isn't updating in the main app.

How to migrate Rstudio files and installed packages ( by version to a new computer )

Posted: 23 May 2021 07:58 AM PDT

Good afternoon !

I need to migrate a full installation of Rstudio to a new computer.

My old computer contains two versions of Rstudio.

I had tried the following code :

installed <- as.data.frame(installed.packages())    write.csv(installed, 'installed_previously.csv')    installedPreviously <- read.csv('installed_previously.csv')    baseR <- as.data.frame(installed.packages())    toInstall <- setdiff(installedPreviously, baseR)  

What I need to is to list the installed versions of Rstudio ( with their associated installed packages ). After that , I need to copy all R code files .

I'm searching a script that automate this migration.

Thank you for help !

Binary to Decimal Script in Python

Posted: 23 May 2021 07:58 AM PDT

I encountered an issue with my Python script that converts binary to decimals. The caveat with this script is that I can only use basic computational functions (+,-,*,/,**,%,//), if/else, and for/while loops.

Shown below is my script:

x = int(input("Enter your binary input: "))  z=0    while x != 0:        for y in range (0,20):                    if (x % 2 == 0):              z += 0*2**y              x = int(x/10)                                  elif (x % 2 != 0):              z += 1*2**y              x = int(x/10)    print(z)  

While my script works for binaries with short length (e.g., 1101 = 13), it does not work for long binaries (especially those that have a length of 20). For example, inputting a binary of "11111010010011000111", my script returns an output of "1025217" instead of "1025223".

Can anyone point me to my mistake?

Thank you in advance!

How do I randomize what a discord bot says?

Posted: 23 May 2021 07:58 AM PDT

This is my first time making a discord bot, here's my code, it seems to work, but it only randomizes it when I run it, then it repeats the same message, how would I make it choose a new quote each time?

import os  import discord  import random    client = discord.Client()    q_list = ('It came to me. My own. My love. My own. My precious', "Lost! Lost! My Precious is lost!!", "Bagginses? What is a Bagginses, precious?", "What has it got in its nasty little pocketses?", "Curse it and crush it! We hates it forever!")    random_q = random.choice(q_list)    @client.event  async def on_ready():      print('We have logged in as {0.user}'.format(client))    @client.event  async def on_message(message):      if message.author == client.user:          return        if message.content.startswith('smeagol'):          await message.channel.send(random_q)    bot_token = os.environ['bottoken']    client.run(bot_token)  

Saving polylines to firebase in Kotlin?

Posted: 23 May 2021 07:58 AM PDT

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {      super.onViewCreated(view, savedInstanceState)      val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?      mapFragment?.getMapAsync(this)  }    @SuppressLint("MissingPermission", "PotentialBehaviorOverride")  override fun onMapReady(googleMap: GoogleMap?) {      map = googleMap!!      map.isMyLocationEnabled = true      map.setOnMyLocationButtonClickListener(this)      map.setOnMarkerClickListener(this)      map.uiSettings.apply {          isZoomControlsEnabled = false          isZoomGesturesEnabled = false          isRotateGesturesEnabled = false          isTiltGesturesEnabled = false          isCompassEnabled = false          isScrollGesturesEnabled = false      }      observeTrackerService()  }    private fun observeTrackerService() {      TrackerService.locationList.observe(viewLifecycleOwner, {          if (it != null) {              locationList = it              if (locationList.size > 1) {                  binding.stopButton.enable()              }              drawPolyline()              followPolyline()          }      })      TrackerService.started.observe(viewLifecycleOwner, {          started.value = it      })      TrackerService.startTime.observe(viewLifecycleOwner, {          startTime = it      })      TrackerService.stopTime.observe(viewLifecycleOwner, {          stopTime = it          if (stopTime != 0L) {              showBiggerPicture()              displayResults()          }      })  }    private fun drawPolyline() {      val polyline = map.addPolyline(              PolylineOptions().apply {                  width(10f)                  color(Color.BLUE)                  jointType(JointType.ROUND)                  startCap(ButtCap())                  endCap(ButtCap())                  addAll(locationList)              }      )      polylineList.add(polyline)  }    private fun followPolyline() {      if (locationList.isNotEmpty()) {          map.animateCamera(                  (CameraUpdateFactory.newCameraPosition(                          setCameraPosition(                                  locationList.last()                          )                  )), 1000, null)      }  }    private fun onStartButtonClicked() {      if (hasBackgroundLocationPermission(requireContext())) {          startCountDown()          binding.startButton.disable()          binding.startButton.hide()          binding.stopButton.show()      } else {          requestBackgroundLocationPermission(this)      }  }                              }    private fun showBiggerPicture() {      val bounds = LatLngBounds.Builder()      for (location in locationList) {          bounds.include(location)      }      map.animateCamera(              CameraUpdateFactory.newLatLngBounds(                      bounds.build(), 100              ), 2000, null      )      addMarker(locationList.first())      addMarker(locationList.last())  }    private fun addMarker(position: LatLng){      val marker = map.addMarker(MarkerOptions().position(position))      markerList.add(marker)  }    private fun displayResults() {      val result = Result(              calculateTheDistance(locationList),              calculateElapsedTime(startTime, stopTime)      )            lifecycleScope.launch {          delay(2500)          val directions = MapsFragmentDirections.actionMapsFragmentToResultFragment(result)         findNavController().navigate(directions)          binding.startButton.apply {              hide()              enable()          }          binding.stopButton.hide()          binding.resetButton.show()      }  }    @SuppressLint("MissingPermission")  private fun mapReset() {      fusedLocationProviderClient.lastLocation.addOnCompleteListener {          val lastKnownLocation = LatLng(                  it.result.latitude,                  it.result.longitude          )          map.animateCamera(                  CameraUpdateFactory.newCameraPosition(                          setCameraPosition(lastKnownLocation)                  )          )          for (polyLine in polylineList) {              polyLine.remove()          }          for (marker in markerList){              marker.remove()          }          locationList.clear()          markerList.clear()          binding.resetButton.hide()          binding.startButton.show()      }  }        override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {      super.onRequestPermissionsResult(requestCode, permissions, grantResults)      EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)  }    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {      if (EasyPermissions.somePermissionPermanentlyDenied(this, perms[0])) {          SettingsDialog.Builder(requireActivity()).build().show()      } else {          requestBackgroundLocationPermission(this)      }  }    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {      onStartButtonClicked()  }    override fun onDestroyView() {      super.onDestroyView()      _binding = null  }    override fun onMarkerClick(p0: Marker?): Boolean {      return true  } `  

I would like to send the polylines to Firestore. How to send the polylines in code to Firestore? Can anyone help? My code has a map fragment with buttons. This is a distance tracking app. The app plots the distance using polylines. How to convert polylines to arrays. Here I am doing a location tracking app. I want to convert the polylines to arrays so that I could save it cloud.

SpringBoot 2.5.0 For Jackson Kotlin classes support please add "com.fasterxml.jackson.module: jackson-module-kotlin" to the classpath

Posted: 23 May 2021 07:57 AM PDT

Small question about a warning I am receiving please.

After the release of 2.5.0 of SpringBoot, I just did a version bump from 2.4.x to 2.5.0, without any code change.

Suddenly, on application start up, I am getting

kground-preinit] o.s.h.c.j.Jackson2ObjectMapperBuilder: For Jackson Kotlin classes support please add "com.fasterxml.jackson.module:jackson-module-kotlin" to the classpath

The thing is, my Springboot all is not a Kotlin app, it is a Java app.

It has nothing Kotlin.

Furthermore, I am not even doing any explicit JSON parsing.

May I ask how I can disable, resolve this warning please?

Do C++ ranges support projections in views?

Posted: 23 May 2021 07:58 AM PDT

I know algorithms (e.g. sort) in ranges support projection, but it seems to me that there is no way to get that functionality for views... Am I right?

As an example consider following working code:

#include <algorithm>  #include <ranges>  #include <vector>  #include <iostream>    enum Color {     Red,     Green,     Blue  };   struct Cat {     int age;     Color color;  };    int main() {      std::vector<Cat> cats{{.age = 10,.color=Color::Red}, {.age = 20,.color=Color::Blue}, {.age = 30,.color=Color::Green}};      auto is_red = [](const auto& cat) {return cat.color == Color::Red;};      for (const auto& cat: cats | std::views::filter(is_red)) {          std::cout << cat.age << std::endl;       }  }  

Is there a way to remove the lambda and do something like:

for (const auto& cat: cats | std::views::filter(&Cat::color, Color::Red) {  

note: my question is for member variable projection, but obviously in real code member function calls would be also needed.

Pascal's Triangle Scala: Compute elements of Pascal's triangle using tail recursive approach

Posted: 23 May 2021 07:58 AM PDT

In Pascal's Triangle the number at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. A sample Pascal's triangle would look like below.

    1     1 1    1 2 1   1 3 3 1  1 4 6 4 1  

I wrote a program that computes the elements of Pascal's triangle using below technique.

/**  * Can I make it tail recursive???  *  * @param c column  * @param r row  * @return   */  def pascalTriangle(c: Int, r: Int): Int = {    if (c == 0 || (c == r)) 1    else      pascalTriangle(c-1, r-1) + pascalTriangle(c, r - 1)  }  

So, for example if

i/p: pascalTriangle(0,2)    o/p: 1.    i/p: pascalTriangle(1,3)    o/p: 3.  

Above program is correct and giving the correct output as expected. My question is, is it possible to write tail recursive version of above algorithm? How?

Can't run classic ASP page on Windows 10 even after installing ASP support via "Turn Windows features on or off"

Posted: 23 May 2021 07:57 AM PDT

I get this error:

An error occurred on the server when processing the URL. Please contact the system administrator.

If you are the system administrator please click here to find out more about this error.

But I already installed classic ASP support on my IIS; why would I be getting this error? I tried restarting IIS and that didn't help; just in case the error message came from the application itself, I searched for it but didn't find it in the code anywhere.

Finding turning points of an Array in python

Posted: 23 May 2021 07:58 AM PDT

If I for example have an array:

A = (0,2,3,4,5,2,1,2,3,4,5,6,7,8,7,6,5,4,5,6)  

It can be seen that there are 4 turning points. (at A[4],A[6], A[13], A[17])

How can I use python to return the number of turning points?

import numpy as np  import scipy.integrate as SP  import math    def turningpoints(A):      print A      N = 0      delta = 0      delta_prev = 0      for i in range(1,19):          delta = A[i-1]-A[i]       #Change between elements          if delta < delta_prev:    #if change has gotten smaller              N = N+1               #number of turning points increases          delta_prev = delta        #set the change as the previous change      return N    if __name__ == "__main__":      A  = np.array([0,2,3,4,5,2,1,2,3,4,5,6,7,8,7,6,5,4,5,6])      print turningpoints(A)  

Currently, this system is flawed and certainly not very elegant. Any ideas?

No comments:

Post a Comment