2021-09-30

Music Bot doesn't connect to Voice channel

Trying to make a simple music bot that only plays one link, but it doesn't connect to the voice channel, it doesn't give as a result any error so I can't do anything other than put all my code. Here is my Main.js

const {Intents} = require('discord.js');
const Discord = require('discord.js');
const botIntents = [ Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_MEMBERS];
const client = new Discord.Client({ intents: botIntents });
const prefix = '-';
const fs = require('fs');
const teo = "<@---------->";
const aime = "<@------------>";
const pagliac = "Di di no alla vita sociale! Ogni giorno migliaia di gamer perdono i propri amici per questa Vita sociale, Non si sa cosa sia pero se donate una piccola somma di: 4 reni, tua madre e forse anche tua sorella";

client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
    const command = require(`./commands/${file}`);

    client.commands.set(command.name, command);
}

client.once('ready', async () =>{
    console.log('Ready!');
    client.user.setActivity('Tua madre', { type: 'PLAYING' });
})

client.on ('message', message=>{
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'embed'){
        client.commands.get('embed').execute(message, args, Discord, client);
    } else if (command === 'pong'){
        message.channel.send('Aime e un pagliaccio, giochiamo a the forest');
    } else if (command === 'teo'){
        for (var i=0; i<5; i++){
            message.channel.send(teo);
        }
    } else if (command === 'aime'){
        for (let s=0; s<5; s++){
            message.channel.send(aime);
            message.channel.send(pagliac);
        }
    } else if (command === 'clear'){
        client.commands.get('clear').execute(message, args);
    } else if (command === 'ping'){
        message.channel.send(`Pingazzo pazzo di: ${Date.now() - message.createdTimestamp}ms. La latenza delle api ${Math.round(client.ws.ping)}ms`);
    } else if (command === 'acqua'){
        const siuum = new Discord.MessageEmbed()
        .setColor('#0011FF')
        .setTitle('Marmellata')
        .setDescription('marmellata')
        const sus = message.mentions.users.first();
        sus.send({embeds: [siuum]});
    } else if(command === 'bully'){
        client.commands.get('bully').execute(message)
    } else if(command === 'aimesus')
        client.commands.get('aimesus').execute(message)

});

Here is my music bot command, i think that it is correct because, i had already asked here, somebody for help.

const ytdl = require('ytdl-core');

module.exports ={
    name:'aimesus',
    description:'aaaaaaaaaaaam',
    execute(message, args){
        const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport, VoiceConnectionStatus } = require('@discordjs/voice');
        const url = 'https://www.youtube.com/watch?v=NevKVKbCNy4&ab_channel=NTDM'
        const stream = ytdl(url, {filter: 'audioonly'});
        const player = createAudioPlayer();
        const resource = createAudioResource(stream);
        const connection = joinVoiceChannel({
            channelId: message.channelid,
            guildId: message.guildid,
            adapterCreator: message.guild.voiceAdapterCreator
        })
        connection.subscribe(player);
        player.play(resource);
        
        console.log(generateDependencyReport());
        
    }
}


from Recent Questions - Stack Overflow https://ift.tt/3F0q1bb
https://ift.tt/eA8V8J

Trying to compare array but getting "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

Can someone help me understand and correct my short code for the error in the title?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 100)
a = 2

def f(x):
    if x<0.5:
        return a*x
    elif x>=0.5:
        return a*(1-x)

plt.plot(x, f(x))
plt.show()
      6 
      7 def f(x):
----> 8     if x<0.5:
      9         return a*x
     10     elif x>=0.5:


from Recent Questions - Stack Overflow https://ift.tt/3CUp9TC
https://ift.tt/eA8V8J

Requesting list of a users microhone and headset & phone devices

The audio, video conferencing devices, microhones headset and other devices which are used for microsoft team calls and conferences, where are thisdata is stored?

How can I request a list for this devices overall users or for a special user. Is an intune -license needed for that or are there other ways to request this information e.g. with a graph api call?



from Recent Questions - Stack Overflow https://ift.tt/39M0PXE
https://ift.tt/eA8V8J

Is cos(x) required to return identical values in different C++ implementations that use IEEE-754?

Is there any sort of guarantee - either in the C++ standard or in some other document - that C++ code computing cos(x) will produce identical values when compiled with g++, clang, MSVC, etc., assuming those implementations are using IEEE-754 64-bit doubles and the input value x is exactly equal? My assumption is "yes," but I'd like to confirm that before relying on this behavior.

Context: I'm teaching a course in which students may need to compute trigonometric functions of inputs. I can assure that those inputs are identical when fed into the functions. I'm aware that equality-testing doubles is not a good idea, but in this specific case I was wondering if it was safe to do so.



from Recent Questions - Stack Overflow https://ift.tt/39P9kkB
https://ift.tt/eA8V8J

New flutter rules caused this ERROR: The argument type 'String?' can't be assigned to the parameter type 'String'

I have a code like this:

  String? _token;
  DateTime? _expiryDate;
  String? _userId;
  Timer? _authTimer;

  Future<bool> tryAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey('userData')) {
      return false;
    }
    final extractedUserData =
        json.decode(prefs.getString('userData')) as Map<String, Object>;// FIRST ERROR
    final expiryDate = DateTime.parse(extractedUserData['expiryDate']);// SECOND ERROR

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token']; //THIRD ERROR
    _userId = extractedUserData['userId']; // THIRD ERROR
    _expiryDate = expiryDate;
    notifyListeners();
    _autoLogout();
    return true;
  }

But it gives me these errors:

The argument type 'String?' can't be assigned to the parameter type 'String'.

The argument type 'Object?' can't be assigned to the parameter type 'String'.

A value of type 'Object?' can't be assigned to a variable of type 'String?'. Try changing the type of the variable, or casting the right-hand type to 'String?'.

I found this code from a Flutter tutorial and tried to fix the errors by adding ? or ! marks after some variable types but it seems I couldn't do that well.

EDIT: By updating this line of the code

final extractedUserData = json.decode(prefs.getString('userData')) as Map<String, Object>;

to

final extractedUserData = json.decode(prefs.getString('userData')) as Map<String, dynamic>;

The first error still exists but the other errors gone. I also tried to update the line like

final extractedUserData = json.decode(prefs!.getString('userData')) as Map<String, dynamic>;

(changed prefs to prefs!) but couldn't help, and I don't know how to fix it?



from Recent Questions - Stack Overflow https://ift.tt/3umKv9j
https://ift.tt/eA8V8J

git use only from specific range of commit

I have a branch with several commits, example:

commit40
commit39
commit38
...
commit02
commit01

How could I make a new branch using the previous one with a range of commits? let's say since commit 38 to 40



from Recent Questions - Stack Overflow https://ift.tt/2Y3j74x
https://ift.tt/eA8V8J

Insert into table 10000 rows by 10000 in SQL Server

I am doing a query that retrieves 450 million rows, every time I run it I get an 'Active Transaction Full' error message.

I want to insert 10,000 rows by 10,000 rows on my table, instead of trying to insert all at once, is it possible please?

My query :

INSERT INTO ZED_COTIS.stockdenorm.[DossierRecouvrement_Ind]  
    SELECT DISTINCT 
        A.*   
    FROM 
        STOCK_Pleiade.stock.TDossierRecouvrement A      
    INNER JOIN 
        STOCK_Pleiade.stock.TClientIndividuel B ON A.RefUnClient = B.OID 


from Recent Questions - Stack Overflow https://ift.tt/3F2uMRs
https://ift.tt/eA8V8J

Try figuring out features which causes NaN loss

I'm trying to train the speech recognition model through our company's database. When I used Librispeech DB, there was no problem with model training. On the other hand, when using our company's DB, it causes NaN loss when training first epoch. As a result of searching, I found that certain wave files had problems like low quality, small volume, unmatched wave and text, and so on. Is there any way that I can check if wave file causes NaN loss when putting to model?



from Recent Questions - Stack Overflow https://ift.tt/2Y2D7Us
https://ift.tt/eA8V8J

Constant DB already define

I have several functions to get data from the database. And for that, I have a connection database. My several functions are located in one file function. And when I run the code I have a message notification like this. enter image description here

And this is for my function code

function getDataToko()
{
    $db = getDBConnection();

    $query = "SELECT * FROM master_toko WHERE status_ot='1' ORDER BY nama_ot DESC";
    $result = mysqli_query($db, $query);
    mysqli_close($db);
    return $result;
}

function getDataAkses()
{
    $db = getDBConnection();

    $query = "SELECT tk.nama_ot, ha. * FROM master_toko AS tk, master_hak_akses AS ha WHERE tk.id_ot = ha.id_ot AND ha.status_ha = '1'";
    $result = mysqli_query($db, $query);
    mysqli_close($db);
    return $result;
}

And this for the page html i called the function

<select class="form-control select2bs4" name="namaToko" required>
                            <option disabled="disabled" selected="selected">Pilih Toko</option>
                            <?php $toko = getDataToko();  ?>
                            <?php
                            while ($dataToko = mysqli_fetch_array($toko)) {
                            ?>
                              <option value="<?= $dataToko['id_ot'] ?>">
                                <?= $dataToko['nama_ot'] ?>
                              </option>
                            <?php
                            }
                            ?>
                          </select>
<tbody>
                    <?php
                    $n = 1;
                    $akses = getDataAkses();
                    while ($dataAkses = mysqli_fetch_array($akses)) {
                      if ($dataAkses['status_ha'] == 1) {
                        $status = "Aktif";
                        $idStatus = "1";
                      }
                      if ($dataAkses['status_ha'] == 2) {
                        $status = "Tidak Aktif";
                        $idStatus = "2";
                      }

                    ?>
                      <tr data-row-id="<?= $dataAkses['id_ha'] ?>">
                        <td>
                          <?php echo $n++; ?>
                        </td>
                        <td>
                          <?php echo $dataAkses['id_ha'] ?>
                        </td>
                        <td>
                          <?php echo $dataAkses['nama_ot'] ?>
                        </td>
                        <td>
                          <?php echo $dataAkses['nama_ha'] ?>
                        </td>
                        <td>
                          <?php echo $status ?>
                        </td>
                        <td>
                          <button type="button" class="view-detail btn btn-success" data-id="<?= $dataToko['id_ot'] ?>"> Edit </button>
                          <!-- <button onclick="document.getElementById('delete').style.display='block'" class="view-delete btn btn-danger">Delete</button> -->
                          <button type="button" class="view-delete btn btn-danger" data-id="<?= $dataToko['id_ot'] ?>" id="deleteButton"> Delete </button>
                          <?php
                          include 'hapus_toko.php';
                          ?>
                        </td>
                      </tr>
                    <?php
                      include 'edit_toko.php';
                    }
                    ?>

                  </tbody>

This my config.php

<?php
    function getDBConnection() {
    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'root');
    define('DB_PASSWORD', '');

    define('DB_DATABASE', 'dbcity');
    $db=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

    if(!$db) {
        die("<script>alert('Gagal tersambung dengan database.')</script>");
    }
    return $db;
}

?>


from Recent Questions - Stack Overflow https://ift.tt/3AQXL8o
https://ift.tt/3F1v5fn

How do I turn a PKDrawing into a String? [closed]

I want to allow people to write text using the Apple Pencil via PencilKit and then do character recognition on the resulting PKDrawing.

Apple's notepad app does this in iOS 14+ but there doesn't seem to be any API to do this on a PKDrawing?

Is there any way to do this other than do my own recognition using the individual strokes?

It looks like even in iOS 15, Apple is not exposing the internal API they are using. Or am I missing something?

Thanks in advance.



from Recent Questions - Stack Overflow https://ift.tt/2Y8Qv9K
https://ift.tt/eA8V8J

Why is there an error message even though the interaction is successful is working in discord.py?

I have created a !work command where the buttons help in navigating through pages. Each time a button is clicked, the embed is edited to the required page. I am getting an error message saying that the interaction failed even though the embed was edited properly. How do I fix this?

The code for editing the embed is here:

await interaction.message.edit(embed=new_embed)


from Recent Questions - Stack Overflow https://ift.tt/3kQCyWv
https://ift.tt/eA8V8J

check multiple files if they are empty in python

I have an n number of log files that a script regularly downloads and upload on slack for monitoring purposes. However with recent improvements in our postgresql database some of the log files are now empty (meaning no errors or long queues were recorded) this being said, I would need to segregate files that are empty vs not empty and if it's empty skip the file from being uploaded entirely and proceed with the ones that are not empty.

348 postgresql.log.2021-09-28-0000
679 postgresql.log.2021-09-28-0100
  0 postgresql.log.2021-09-28-0200
  0 postgresql.log.2021-09-28-0300
  0 postgresql.log.2021-09-28-0400
  0 postgresql.log.2021-09-28-0500
  0 postgresql.log.2021-09-28-0600
  0 postgresql.log.2021-09-28-0700
  0 postgresql.log.2021-09-28-0800
  0 postgresql.log.2021-09-28-0900
  0 postgresql.log.2021-09-28-1000
  0 postgresql.log.2021-09-28-1100
  0 postgresql.log.2021-09-28-1200
  0 postgresql.log.2021-09-28-1300
  0 postgresql.log.2021-09-28-1400
  0 postgresql.log.2021-09-28-1500
  0 postgresql.log.2021-09-28-1600
  0 postgresql.log.2021-09-28-1700
  0 postgresql.log.2021-09-28-1800
  0 postgresql.log.2021-09-28-1900
  0 postgresql.log.2021-09-28-2000
  0 postgresql.log.2021-09-28-2100
  0 postgresql.log.2021-09-28-2200
  0 postgresql.log.2021-09-28-2300

In this case we can see that only the files

348 postgresql.log.2021-09-28-0000
679 postgresql.log.2021-09-28-0100

contains 348 bytes and 679 bytes of data respectively.

How do I make it so that the python script that is being used right now would validate if the file is empty first before being uploaded?

The closest thing I have found right now is

import os
if os.stat("postgresql.log.2021-09-28-2300").st_size == 0: 
    print('empty')

but this only checks for one file at a time, and I would rather do it in the whole directory as the file names (Date in particular and time) would change.

I'm relatively new at this and this was just handed down to me at work and I'd appreciate guides on how to make it work thank you so much.



from Recent Questions - Stack Overflow https://ift.tt/2XYodhK
https://ift.tt/eA8V8J

Imagepicker 'XFile' is not a subtype of type 'File' in type cast and Firebase Storage image upload error

I am trying to select image from gallery with imagepicker and upload it to firebasestorage. When the application runs, it gives the error "Cannot open file, path = '' (OS Error: Bad address, errno = 14) and Unhandled Exception: type 'XFile' is not a subtype of type 'File' in type cast'.

GestureDetector(
                  onTap: () => pickPhotoFromGallery(),
                  child: CircleAvatar(
                    radius: 70,
                    // ignore: unnecessary_null_comparison
                    child: (_imageFile != null)
                        ? Image.file(_imageFile)
                        : Image.asset('assets/images/icon.png'),
                  ),
                ),

Future pickPhotoFromGallery() async {
    File imageFile =
        (await _imagePicker.pickImage(source: ImageSource.gallery)) as File;

    setState(() {
      _imageFile = imageFile;
    });
  }

When I click the save button, it says "Failed assertion: line 127 pos 12: 'file.absolute.existsSync()': is not true." I am encountering the error.

onPressed: uploading ? null : () => uploadImageAndSaveItemInfo(),
  uploadImageAndSaveItemInfo() async {
    setState(() {
      uploading = true;
    });

    String imageDownloadUrl = await uploadItemImage(_imageFile);

    saveItemInfo(imageDownloadUrl);
    saveItemInfoCategory(imageDownloadUrl);
  }


  Future<String> uploadItemImage(File mFileImage) async {
    final Reference storageReference =
        FirebaseStorage.instance.ref().child("thumbnail");

    UploadTask uploadTask = storageReference
        .child(_idController.text.trim() + ".jpg")
        .putFile(mFileImage);

    String downloadUrl = await uploadTask.snapshot.ref.getDownloadURL();
    return downloadUrl;
  }

Imagepicker was working in old versions, it gives an error in the latest version.



from Recent Questions - Stack Overflow https://ift.tt/3iifxKq
https://ift.tt/eA8V8J

Create docker service in manager node

Is there a way to force the creation of a docker service in a Docker Swarm in the manager node?

I can not use the --constraint node.hostname=... because I don't know the specific hostname for each stage where I deploy my application



from Recent Questions - Stack Overflow https://ift.tt/39Mcfuo
https://ift.tt/eA8V8J

issues while sending email with xampp on localhost

I am working on a project in which I need to send email. My send mail function is:

    ini_set('sendmail_path', "\"C:\xampp\sendmail\sendmail.exe\" -t");
    ini_set('smtp_server', 'smtp.gmail.com');
    ini_set('smtp_port', 25);
    ini_set('smtp_ssl', 'auto');
    ini_set('error_logfile', 'error.log');
    ini_set('auth_username', 'myemailAddreds@gmail.com');
    ini_set('auth_password', 'mygmail_password');

    //sendmail_from('myemailAddreds@gmail.com');

    $to = 'myemailAddreds@gmail.com';
    $subject = 'Hello from XAMPP!';
    $message = 'This is a test';
    $headers = "From: your@email-address.com\r\n";
    if (mail($to, $subject, $message, $headers)) {
       echo "SUCCESS";
    } else {
       echo "ERROR";
    }

But I am getting following error

Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\umtab\xampp\htdocs\umtab\email.php on line 23



from Recent Questions - Stack Overflow https://ift.tt/3F27Lye
https://ift.tt/eA8V8J

Postgres Explain - how to optimize

Performance is growing increasingly poor. Using explain, I see that there is a sequential scan in a nested loop - which is likely the performance issue. What I do not know is: how do I improve this?

Here is a link to the query and the explain output: https://explain.depesz.com/s/zmzp I'll include them here, too:

Query:

'''
SELECT
    "assets".*
FROM
    "assets"
    INNER JOIN "devices" ON "devices"."asset_id" = "assets"."id"
WHERE
    "assets"."archived_at" IS NULL
    AND "assets"."archive_number" IS NULL
    AND "assets"."assettype_id" = 3
    AND ((assets.lastseendate >= NOW() - INTERVAL '30 days')
        AND ((devices.stop_time IS NULL)
            OR (devices.stop_time >= NOW() - INTERVAL '30 days')
            OR (devices.launch_time IS NOT NULL
                AND devices.launch_time > devices.stop_time)))
'''

And here is the explain output:

Nested Loop  (cost=0.43..255815.01 rows=11889 width=218) (actual time=0.049..2187.719 rows=359445 loops=1)
  Buffers: shared hit=1499737 read=75
  I/O Timings: read=5.382
  ->  Seq Scan on assets  (cost=0.00..117666.24 rows=27484 width=218) (actual time=0.035..770.720 rows=359543 loops=1)
        Filter: ((archived_at IS NULL) AND (archive_number IS NULL) AND (assettype_id = 3) AND (lastseendate >= (now() - 'P30D'::interval)))
        Rows Removed by Filter: 2539219
        Buffers: shared hit=59691
  ->  Index Scan using devices_asset_id_ix on devices  (cost=0.43..5.02 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=359543)
        Index Cond: (asset_id = assets.id)
        Filter: ((stop_time IS NULL) OR (stop_time >= (now() - 'P30D'::interval)) OR ((launch_time IS NOT NULL) AND (launch_time > stop_time)))
        Rows Removed by Filter: 0
        Buffers: shared hit=1440046 read=75
        I/O Timings: read=5.382
Planning Time: 1.055 ms
Execution Time: 2264.396 ms

The only relevant index is this one:

devices_asset_id_ix

UPDATE: I've added several indexes as listed here:

add_index :devices, [:asset_id, :stop_time, :launch_time], name: "device_online_idx"
add_index :devices, [:asset_id, :stop_time]
add_index :devices, [:asset_id, :launch_time]
add_index :devices, :stop_time
add_index :devices, :launch_time

add_index :assets, [:assettype_id, :archived_at, :archive_number, :lastseendate], name: "asset_unexpired_idx"
add_index :assets, :assettype_id
add_index :assets, :archived_at
add_index :assets, :archive_number
add_index :assets, :lastseendate

This has changed the explain to look like this:

Nested Loop  (cost=0.99..179162.78 rows=11872 width=218) (actual time=0.050..1680.166 rows=359011 loops=1)
  Buffers: shared hit=1726893 read=33
  I/O Timings: read=0.226
  ->  Index Scan using asset_unexpired_idx on assets  (cost=0.56..41125.44 rows=27451 width=218) (actual time=0.037..315.869 rows=359110 loops=1)
        Index Cond: ((assettype_id = 3) AND (archived_at IS NULL) AND (archive_number IS NULL) AND (lastseendate >= (now() - 'P30D'::interval)))
        Buffers: shared hit=288537
  ->  Index Scan using devices_asset_id_ix on devices  (cost=0.43..5.02 rows=1 width=4) (actual time=0.002..0.003 rows=1 loops=359110)
        Index Cond: (asset_id = assets.id)
        Filter: ((stop_time IS NULL) OR (stop_time >= (now() - 'P30D'::interval)) OR ((launch_time IS NOT NULL) AND (launch_time > stop_time)))
        Rows Removed by Filter: 0
        Buffers: shared hit=1438356 read=33
        I/O Timings: read=0.226
Planning Time: 1.322 ms
Execution Time: 1757.047 ms

This got a 25% improvement. Is there any way to substantially improve this further?



from Recent Questions - Stack Overflow https://ift.tt/3zTUXGr
https://ift.tt/eA8V8J

Write a program that adds together all the integers from `1` to `250` (inclusive) and `puts`es the total

How would I do this using ruby and only using a while loop with if, elsif and else only?



from Recent Questions - Stack Overflow https://ift.tt/3B0IEcQ
https://ift.tt/eA8V8J

Firebase push notification not delivered if device is idle for few minutes and no charging state

Firebase push notification is working fine for all three states of app: foreground, background, killed.

But notification not delivered if device is idle for few minutes and no charging state. However on charging push notification is working no matter how long idle time is.

I have tried with:

  1. disabling 'Power saving mode'.

  2. disabling 'Adaptive power saving mode'.

  3. battery optimization for app.

  4. added in manifest

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
  5. removed [android:exported="false"] from

    <service
         android:name="firebase.MyFirebaseMessagingService" =>[android:exported="false"]>
         <intent-filter>
                 <action android:name="com.google.firebase.MESSAGING_EVENT" />
         </intent-filter>
     </service>
    
{
    "registration_ids": [
        "ei0....ySI"
    ],
    "data": {
       "priority" : "high",
        "title": "msg title",
        "body": "msg body"
    },
    "android": {
        "priority": "high"
    },
    "apns": {
        "headers": {
            "apns-priority": "10"
        }
    },
    "webpush": {
        "headers": {
            "Urgency": "high"
        }
    }
}


from Recent Questions - Stack Overflow https://ift.tt/3CRMrcM
https://ift.tt/eA8V8J

How to make this program run 4 times without ending

I just started "Introduction to C++" this semester, and I'm stuck on an exercise that involves taking data from a table and writing a program that will let you input and display each item (line by line) showing the Item, Cost, and calculated Total Cost.

The program I've written works perfectly for the first item, but I need it to repeat the same 3 questions (allowing user input of different items/costs/discounts each time it repeats the questions), while printing the calculated total after each question is answered. I'm assuming this will involve either a do-while loop or a for loop, but I can't figure out how to integrate what I've already written into a loop.

#include <iostream>
using namespace std;

int main()
{
    string Item;
    float Cost;
    float Discount;
    float TotalCost;

    cout << "What is the item? \n";
    cin >> Item;

    cout << "What is the cost? \n";
    cin >> Cost;

    cout << "What is the discount? \n";
    cin >> Discount;

    TotalCost = Cost - Discount;
    
    cout << Item << "'s Total Cost is " << TotalCost;
    
    return 0;
}

I've tried making a for loop (code I've tried below), but it doesn't work, and I haven't been able to find any loop examples in my book or online that involve accepting user input each time the process loops.

#include <iostream>
using namespace std;

int main()
{
    string Item;
    float Cost;
    float Discount;
    float TotalCost;

    for (int a = 0; a < 5; a++)
    {
        cout << "What is the item? \n";
        cin >> Item;

        cout << "What is the cost? \n";
        cin >> Cost;

        cout << "What is the discount? \n";
        cin >> Discount;

        TotalCost = Cost - Discount;

        cout << Item << "'s Total Cost is " << TotalCost;
    }

    return 0;
}


from Recent Questions - Stack Overflow https://ift.tt/3zWLtKm
https://ift.tt/eA8V8J

node js upload image and upload to ftp: works for one but not two images

var ftpClient = new ftp();
var form = new formidable.IncomingForm();
form.parse(request, function(err, fields, files) {
    if (files.shoplogo.name) {
        var dimensions = sizeOf(files.shoplogo.path);
        console.log(dimensions.width + " x " + dimensions.height);
        if (dimensions.width > 255 || dimensions.height > 255 || dimensions.width < 145 || dimensions.height < 145) {
            response.send('<script>alert("Das Bild darf nicht größer 250x250 oder kleiner als 150x150 sein."); history.back(); </script>');
            return;
        }
        if (files.shoplogo.size > 200000) {
            response.send('<script>alert("Das Bild darf nicht größer als 150 kb sein."); history.back(); </script>');
            return;
        } else {
            var oldpath = files.shoplogo.path;
            ftpClient.on('ready', function() {
                ftpClient.put(oldpath, '/web/shopContent/' + 'logo_' + fields.shopid + ".jpg", function(err, list) {
                    if (err) throw err;
                    ftpClient.end();
                });
            });
        }
    }
    if (files.shopcover.name) {
        var dimensions = sizeOf(files.shopcover.path);
        console.log(dimensions.width + " x " + dimensions.height);
        if (dimensions.width > 505 || dimensions.height > 505 || dimensions.width < 245 || dimensions.height < 245) {
            response.send('<script>alert("Das Bild darf nicht größer 500x500 oder kleiner als 250x250 sein."); history.back(); </script>');
            return;
        }
        if (files.shopcover.size > 200000) {
            response.send('<script>alert("Das Bild darf nicht größer als 150 kb sein."); history.back(); </script>');
            return;
        } else {
            var oldpath = files.shopcover.path;
            ftpClient.on('ready', function() {
                ftpClient.put(oldpath, '/web/shopContent/' + 'cover_' + fields.shopid + ".jpg", function(err, list) {
                    if (err) throw err;
                    ftpClient.end();
                });
            });
        }
    }
    ftpClient.connect({
        'host': 'host',
        'user': 'user',
        'password': 'pw'
    });
});

Working from scratch I managed to code a function that allows me to upload images to my server (from client) and then to upload it to FTP server. If the user selects one image a time everything works fine but uploading both images breaks.

I think the problem is how I handle the connection. How can I tweak the code?



from Recent Questions - Stack Overflow https://ift.tt/3ilgdPc
https://ift.tt/eA8V8J

2021-09-29

How can I get #text child node as element with beautifulSoup? - Python

I want to get every part of inner text of parsed <p> tag as soup-element with beautifulSoup in Python. Im currently migrating the parser from php to python. Here is some code on php and my tryings of recreating functional in Python beautifulSoup:

PHP (that working)

foreach($pTagNode->childNodes as $innerNode){
    if($innerNode->nodeName == "#text"){
        # Editing and parahrasing text part of <p> tag...
    }
    else if($innerNode->nodeName == "a"){
        # Do something with "a" tag, like removing blacklisted link or chaning text...
    }
}

PYTHON (that doesnt)

node = soup.select("p")[0]

# <a> tag
for pnode in node.select("a"):
    print("link found: " + pnode.string");
# <#text> tag
for pnode in node.select("#text"):
    print("text found: " + pnode.string) # This message doesnt shown :(

HTML structure I want to parse:

...
<body>
    <p>Some text 1 and this is <a href="">the link</p>
    <p>Some text 2 and this is <a href="">the another link</p>
    <p>Some text 3 and this is <a href="">the link 3</p>
</body>

I want to get from HTML: [Some text 1 and this is ][the link]

I am looking for a way how I can get #text as an element. For example, php has DomXPath that allows you to do this. Does anyone have any ideas? If something else is needed, I can supplement this question.



from Recent Questions - Stack Overflow https://ift.tt/39HZLEa
https://ift.tt/eA8V8J

Can anyone pls explain me in detail how this number got swaped step by step (comma operator) [closed]

#include<stdio.h>
int main(void)
{
int a=8,b=7,temp;
printf(“a=%d, b=%d\n”,a,b);
temp=a,a=b,b=temp;
printf(“a=%d, b=%d\n”,a,b);
return 0;
}

Can anyone pls explain me in detail how this number got swaped step by step (comma operator)



from Recent Questions - Stack Overflow https://ift.tt/3ukViAy
https://ift.tt/eA8V8J

SwiftUI - using ForEach with a Binding array that does not conform to identifiable / hashable

I have the a codable object as follows:

struct IncidentResponse: Codable {
    let incident: IncidentDetails?
}

struct IncidentDetails: Codable, Identifiable {
    let id: String?
    let reason: IncidentReasonResponse?
    let message: String?
    let startedAt: String?
    let endedAt: String?
}

struct IncidentReasonResponse: Codable, Identifiable {
    let id: String?
    let name: String?
    let code: String?
    let inOp: Bool?
}

Here is an example of an incident response when called from the API:

{
  "incident": {
    "id": "610aebad8c719475517e9736",
    "user": null,
    "reason": {
      "name": "No aircraft",
      "code": "no-aircraft",
      "inOp": true
    },
    "message": "test this",
    "startedAt": "2021-08-04T19:34:05+0000",
    "endedAt": null
  }
}

In SwiftUI, I am trying to display a list of these. So I have an array of these IncidentResponse objects named existingIncidents and then the following:

var body: some View {
    List {
        Section(header: Text("Existing incidents")) {
            if let existingIncidents = self.existingIncidents {
                ForEach(existingIncidents) { incident in
                    
                    VStack(alignment: .leading) {
                        HStack {
                            Image.General.incident
                                .foregroundColor(Constants.iconColor)
                            Text(incident.incident?.reason?.name ?? "")
                                .foregroundColor(Constants.textColor)
                                .bold()
                        }
                        Spacer()
                        HStack {
                            Image.General.clock
                                .foregroundColor(Constants.iconColor)
                            Text(incident.incident?.startedAt ?? "No date")
                                .foregroundColor(Constants.textColor)
                        }
                        Spacer()
                        HStack {
                            Image.General.message
                                .foregroundColor(Constants.iconColor)
                            Text(incident.incident?.message ?? "No message")
                                .foregroundColor(Constants.textColor)
                        }
                    }
                }
            }
        }
    }
    .listStyle(PlainListStyle())

However, I am unable to use existingIncidents as it is as it does not conform to Identifiable or Hashable (so I can't use the id: /.self workaround) ...

How can I get around this?

I tried to add a UUID into IncidentResponse like this:

struct IncidentResponse: Codable {
    let incident: IncidentDetails?
    var id = UUID().uuidString
}

However, this is then stopping the object from decoding properly from the API.



from Recent Questions - Stack Overflow https://ift.tt/39L7GQZ
https://ift.tt/eA8V8J

Error due to Maven, unable to build and install strongbox from code

I am looking to do some OSS work in order to get hands-on in Software Engineering. I want to contribute to the strongbox.

Problem faced:
I am not able to build strongbox with the build steps given here:

git clone https://github.com/strongbox/strongbox
cd strongbox
mvn clean install

Output:
After running the command mvn clean install the output that I receive is:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.inject.internal.cglib.core.$ReflectUtils$1 (file:/usr/share/maven/lib/guice.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of com.google.inject.internal.cglib.core.$ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO] 
[INFO] Strongbox: Resources [Common]                                      [jar]
[INFO] Strongbox: Resources [Storage API]                                 [jar]
[INFO] Strongbox: Resources                                               [pom]
[INFO] Strongbox: Commons                                                 [jar]
[INFO] Strongbox: Configuration                                           [jar]
[INFO] Strongbox: Data Service                                            [jar]
[INFO] Strongbox: Client                                                  [jar]
[INFO] Strongbox: Metadata [Maven API]                                    [jar]
[INFO] Strongbox: Testing [Core]                                          [jar]
[INFO] Strongbox: Security API                                            [jar]
[INFO] Strongbox: Storage [Core]                                          [jar]
[INFO] Strongbox: Event API                                               [jar]
[INFO] Strongbox: Authentication API                                      [jar]
[INFO] Strongbox: User Management                                         [jar]
[INFO] Strongbox: Authentication Provider [Default]                       [jar]
[INFO] Strongbox: Authentication Support                                  [jar]
[INFO] Strongbox: Authentication Provider [LDAP]                          [jar]
[INFO] Strongbox: Authentication Providers                                [pom]
[INFO] Strongbox: Authentication Registry                                 [jar]
[INFO] Strongbox: Security                                                [pom]
[INFO] Strongbox: Storage [API]                                           [jar]
[INFO] Strongbox: Cron [API]                                              [jar]
[INFO] Strongbox: Cron [Tasks]                                            [jar]
[INFO] Strongbox: Storage [Maven Layout Provider]                         [jar]
[INFO] Strongbox: Storage [Nuget Layout Provider]                         [jar]
[INFO] Strongbox: Storage [NPM Layout Provider]                           [jar]
[INFO] Strongbox: Storage [PyPi Layout Provider]                          [jar]
[INFO] Strongbox: Storage [Raw Layout Provider]                           [jar]
[INFO] Strongbox: Storage Layout Providers                                [pom]
[INFO] strongbox-storage-rpm-layout-provider                              [jar]
[INFO] Strongbox: Web Forms                                               [jar]
[INFO] Strongbox: REST Client                                             [jar]
[INFO] Strongbox: Testing [Web]                                           [jar]
[INFO] Strongbox: Testing                                                 [pom]
[INFO] Strongbox: Cron                                                    [pom]
[INFO] Strongbox: Storage [P2 Layout Provider]                            [jar]
[INFO] Strongbox: Storage Maven Layout                                    [pom]
[INFO] Strongbox: Storage                                                 [pom]
[INFO] Strongbox: AQL                                                     [jar]
[INFO] Strongbox: Web Core                                                [jar]
[INFO] Strongbox: Distribution                                            [pom]
[INFO] Strongbox: Masterbuild                                             [pom]
[INFO] 
[INFO] --------< org.carlspring.strongbox:strongbox-common-resources >---------
[INFO] Building Strongbox: Resources [Common] 1.0-SNAPSHOT               [1/42]
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ strongbox-common-resources ---
[INFO] 
[INFO] --- maven-enforcer-plugin:3.0.0-M3:enforce (enforce-jdk-and-maven-versions) @ strongbox-common-resources ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for Strongbox: Masterbuild 1.0-SNAPSHOT:
[INFO] 
[INFO] Strongbox: Resources [Common] ...................... FAILURE [  0.865 s]
[INFO] Strongbox: Resources [Storage API] ................. SKIPPED
[INFO] Strongbox: Resources ............................... SKIPPED
[INFO] Strongbox: Commons ................................. SKIPPED
[INFO] Strongbox: Configuration ........................... SKIPPED
[INFO] Strongbox: Data Service ............................ SKIPPED
[INFO] Strongbox: Client .................................. SKIPPED
[INFO] Strongbox: Metadata [Maven API] .................... SKIPPED
[INFO] Strongbox: Testing [Core] .......................... SKIPPED
[INFO] Strongbox: Security API ............................ SKIPPED
[INFO] Strongbox: Storage [Core] .......................... SKIPPED
[INFO] Strongbox: Event API ............................... SKIPPED
[INFO] Strongbox: Authentication API ...................... SKIPPED
[INFO] Strongbox: User Management ......................... SKIPPED
[INFO] Strongbox: Authentication Provider [Default] ....... SKIPPED
[INFO] Strongbox: Authentication Support .................. SKIPPED
[INFO] Strongbox: Authentication Provider [LDAP] .......... SKIPPED
[INFO] Strongbox: Authentication Providers ................ SKIPPED
[INFO] Strongbox: Authentication Registry ................. SKIPPED
[INFO] Strongbox: Security ................................ SKIPPED
[INFO] Strongbox: Storage [API] ........................... SKIPPED
[INFO] Strongbox: Cron [API] .............................. SKIPPED
[INFO] Strongbox: Cron [Tasks] ............................ SKIPPED
[INFO] Strongbox: Storage [Maven Layout Provider] ......... SKIPPED
[INFO] Strongbox: Storage [Nuget Layout Provider] ......... SKIPPED
[INFO] Strongbox: Storage [NPM Layout Provider] ........... SKIPPED
[INFO] Strongbox: Storage [PyPi Layout Provider] .......... SKIPPED
[INFO] Strongbox: Storage [Raw Layout Provider] ........... SKIPPED
[INFO] Strongbox: Storage Layout Providers ................ SKIPPED
[INFO] strongbox-storage-rpm-layout-provider .............. SKIPPED
[INFO] Strongbox: Web Forms ............................... SKIPPED
[INFO] Strongbox: REST Client ............................. SKIPPED
[INFO] Strongbox: Testing [Web] ........................... SKIPPED
[INFO] Strongbox: Testing ................................. SKIPPED
[INFO] Strongbox: Cron .................................... SKIPPED
[INFO] Strongbox: Storage [P2 Layout Provider] ............ SKIPPED
[INFO] Strongbox: Storage Maven Layout .................... SKIPPED
[INFO] Strongbox: Storage ................................. SKIPPED
[INFO] Strongbox: AQL ..................................... SKIPPED
[INFO] Strongbox: Web Core ................................ SKIPPED
[INFO] Strongbox: Distribution ............................ SKIPPED
[INFO] Strongbox: Masterbuild ............................. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.941 s
[INFO] Finished at: 2021-09-28T22:50:20+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:3.0.0-M3:enforce (enforce-jdk-and-maven-versions) on project strongbox-common-resources: org.apache.maven.plugins.enforcer.RequireJavaVersion failed with message:
[ERROR] 
[ERROR]  Ubuntu 11.0.11+9-Ubuntu-0ubuntu2.20.04 is not a supported JDK version! 
[ERROR]  See https://strongbox.github.io/developer-guide/getting-started.html 
[ERROR] 
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

From what I could deduce from the info in the Error message here, it is that there is an issue with the supported JDK version, as in the following line-

[ERROR] Ubuntu 11.0.11+9-Ubuntu-0ubuntu2.20.04 is not a supported JDK version!

Questions:

  1. What should I do to rectify this?
  2. Also, is this the best (time-efficient) way to build java software?
  3. And if I were to use IntelliJ IDEA, is it better to use it?
  4. The error message also suggests that the issue can be due to the maven plugin itself. Not sure though, I would appreciate it if someone points in the correct direction.

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:3.0.0-M3:enforce (enforce-jdk-and-maven-versions) on project strongbox-common-resources: org.apache.maven.plugins.enforcer.RequireJavaVersion failed with message:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

  1. Also, how to get rid of warnings at the starting of the output.

My system configs are:

  • OS: Ubuntu 20.04
  • Java version: 11.0.11 (installed from steps described here)
  • Maven version: 3.6.3 (installed from steps described here)

Other Info:

  1. I have settings.xml file in ~/.m2/

Thanks in advance



from Recent Questions - Stack Overflow https://ift.tt/3CVLjFa
https://ift.tt/eA8V8J

Can you run human pose estimation and object detection at same time in Detectron2

Is it possible to run human pose estimation and the object detection that identifies other objects such as cars, animals, etc?



from Recent Questions - Stack Overflow https://ift.tt/3EYhFAX
https://ift.tt/eA8V8J

Conditional Debit from Credits using SQL

I have one table cryptotransactionledger in below structure where transactions are stored. enter image description here

TRANSACTION_TYPEID is foreign_key from TRANSACTIONTYPE table (master table).

How can I write a query to implement below rules

  1. bitcoin-transferred should only be deducted from bitcoin-mined
  2. bitcoin-lost can be deducted from either bitcoin-received or bitcoin-mined in FIFO manner

Below is the expected result and DB fiddle to above table

transaction_name Remaining Amount
bitcoin-received 0
bitcoin-mined 10

Logic for remaining balance: bitcoin-received = transaction_typeid 101 - 104 (i.e. 5 - 10. Since bitcoin-received amount is just 5, only 5 coins out of 10 bitcoin-lost will be deduced from here. Remaining 5 will be deducted from bitcoin-mined in FIFO manner)

bitcoin-mined = transaction_typeid 102-103-104 (i.e. 20 - 5 - 5(balance after deduction from bitcoin-received (above line)))

http://sqlfiddle.com/#!4/0fd02/1

Thanks in advance



from Recent Questions - Stack Overflow https://ift.tt/2XW8u2O
https://ift.tt/3ieYKbp

How to set values in cell to write in Android Studio

I managed to set label for my Excel, but I want to set values to cells which is an array and I want to set values with For loop but with this code my for loop doesn't work and label 4 and 5 don't write in my Excel file. how can i set values to cells that those values change in every iteration?

String sdCard = getExternalFilesDir("/").getAbsolutePath();
File directory = new File(sdCard + "/MyFolder/");

//create directory if not exist
if(!directory.isDirectory()){
    directory.mkdirs();
    //Toast.makeText(getApplicationContext(),"dir",Toast.LENGTH_LONG).show();
}
//file path
File file = new File(directory, fileName);
WorkbookSettings wbSettings = new WorkbookSettings();
//wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook;
try {
    int a = 1;
    workbook = Workbook.createWorkbook(file, wbSettings);
    //Toast.makeText(getApplicationContext(),"done4",Toast.LENGTH_LONG).show();
    //Excel sheet name. 0 represents first sheet
    WritableSheet sheet = workbook.createSheet("Mydata1", 0);
    //Toast.makeText(getApplicationContext(),"done3",Toast.LENGTH_LONG).show();

    Label label0 = new Label(0,0,"Date");
    Label label1 = new Label(1,0,"time");
    Label label2 = new Label(2,0,"xCor");
    Label label3 = new Label(3,0,"score");
    Label label7 = new Label(2,1,xCor[2]);


    try {
        sheet.addCell(label0);
        sheet.addCell(label1);
        sheet.addCell(label2);
        sheet.addCell(label3);

        for(int i3 = 1; i3==j+1 ; i3++) {
            String text = xCor[i3];
            sheet.getWritableCell(text);
            Label label4 = new Label(2,i3,text);
            Label label5 = new Label(1,i3,text);
            sheet.addCell(label4);
            sheet.addCell(label5);
        }


        sheet.addCell(label7);
    } catch (RowsExceededException e) {
        e.printStackTrace();
    } catch (WriteException e) {
        e.printStackTrace();
    }
    workbook.write();
    try {
        workbook.close();
    } catch (WriteException e) {

        e.printStackTrace();
    }
} catch (IOException e) {
    e.printStackTrace();
}


from Recent Questions - Stack Overflow https://ift.tt/39NrYJz
https://ift.tt/eA8V8J

@EnableJpaRepositories annotation disables data.sql initialization script

My Spring Boot (v2.3.4) based application uses my custom library containing core entities and business logic. To use entities and repositories from this library I had to use @EnableJpaRepositories and @EntityScan annotations with proper packages provided.

I also wanted to initialize database with some required data (let's say the configuration) during application startup. I found that Spring Boot allows to use data.sql or data-${platform}.sql files to achieve that.

Long story short when using @EnableJpaRepositories annotation the data.sql script is not executed.

I did some digging in the code and found that when @EnableJpaRepositories annotation is not used then entityManagerFactory bean is of org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean type. This bean uses org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher bean post processor, which fires org.springframework.boot.autoconfigure.jdbc.DataSourceSchemaCreatedEvent event indicating the schema has been created. Class, which listens for this event is org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker. This listener invokes initSchema() method from org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer class. This method is responsible for whole initialization using data.sql script.

It looks like setting @EnableJpaRepositories annotation creates instance of different class for entityManagerFactory bean, which does not support this simple initialization.

My basic question is then how to make it all work with @EnableJpaRepositories annotation. I can always use Hibernate's import.sql file (which works fine) but I'm also trying to understand what exactly is going on under the hood I how can I control it.

UPDATE 1 28.09.2021

I did further investigation and @EnableJpaRepositories annotation does not change the instance type of entityManagerFactory but it causes silent exception (?) when creating org.springframework.scheduling.annotation.ProxyAsyncConfiguration bean (during creation of org.springframework.context.annotation.internalAsyncAnnotationProcessor bean). It looks like everything is related to @EnableAsync annotation, which I'm also using but didn't know it might be related. But it is - removing it makes the initialization work even with @EnableJpaRepositories.

UPDATE 2 28.09.2021

I've found full explanation for my issue. There are 4 conditions, which must be met to reproduce the issue:

  • @EnableJpaRepositories annotation in application configuration
  • @EnableAsync annotation in application configuration
  • Configuration implements AsyncConfigurer interface
  • Autowired any JpaRepository repository or any other bean which injects repository

Enabling asynchronous execution and implementing AsyncConfigurer makes the whole configuration to be instantiated before regular beans. Because Spring has to inject repository, it needs to instantiate entityManagerFactory bean too. Spring prints thenINFO level logs like below:

Bean 'entityManagerFactoryBuilder' of type [org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

One of not eligible BeanPostProcessors is DataSourceInitializedPublisher responsible for firing DataSourceSchemaCreatedEvent event. Without that event, data-${platform}.sql script won't be processed at all.

I'm not sure what is the role of @EnableJpaRepositories in that process but without it the problem does not occur.

Example

Minimal code to reproduce the issue (data.sql located in src/main/resources):

@Entity
public FileStore {
    ...
}

public interface FileStoreRepository extends extends JpaRepository<FileStore, Long> {
}

@Configuration
@EnableAsync
@EnableJpaRepositories
public class Configuration implements AsyncConfigurer {
    @Autowired
    private FileStoreRepository fileStoreRepository;

    ...
}

Solutions

There are two solutions I'm aware of:

  • Move AsyncConfigurer along with its overrided methods and @EnableAsync annotation to separate configuration class
  • Use @Lazy annotation on autowired bean like below:
@Lazy
@Autowired
private FileStoreRepository fileStoreRepository;

Similar problem was pointed by @Allen D. Ball and can be checked there.



from Recent Questions - Stack Overflow https://ift.tt/3AQZavO
https://ift.tt/eA8V8J

Why is meson interpreting my ccflags with the single quotes?

I'm editing a meson build file. a line that currently exists the the file is working perfectly.

if cc.has_argument('-Wno-format-truncation')                                                                                                                                                                                           
default_cflags += '-Wno-format-truncation'
endif

I've added a line because I want debug information:

default_cflags += '-ggdb -O0'

However, this is being interpreted with the single quotes, and breaking the make command.

-Wno-missing-field-initializers -D_GNU_SOURCE -march=native '-ggdb -O0' -DALLOW_EXPERIMENTAL_API -MD -MQ

Obviously, cc doesn't like this and is throwing an error. What is causing meson to interpret this output with the single quotes? I've tried double quotes and no quotes, but that throws other errors altogether.

Edit

This is a dpdk build file, so the compiler call is:

            executable('dpdk-' + name, sources,
                    include_directories: includes,
                    link_whole: link_whole_libs,
                    link_args: ldflags,
                    c_args: default_cflags,
                    dependencies: dep_objs)


from Recent Questions - Stack Overflow https://ift.tt/2XWGzQc
https://ift.tt/eA8V8J

How do I get ISO 3 Amount from given currency?

I am working with an API that expects currency to be multiplied by ISO 3 code.

Given I have a table that gives me the values for ISO 4217 as follows:-

CURRENCY, DECIMAL
JOD         3
AED         2
 and so on.

and for example: If the amount value was 500 AED; according to ISO code 3, you should multiply the value with 100 (2 decimal points); so it will become 50000. Another example: If the amount value was 100 JOD; according to ISO code 3, you should multiply the value with 1000 (3 decimal points); so it will become 100000.

Given I have the amount 500 and knowing the decimal for AED is 3 how do I get the 50000?

My approach is as follows but don't think its right.

decimal amount = 500m;
int decValue = 3;
var decimalAmount = (amount * decValue * 100); //50000


from Recent Questions - Stack Overflow https://ift.tt/3o7GzYV
https://ift.tt/eA8V8J

How to replace any character in any position according to the pattern

I have a problem like the below:

Given a string and a character and position need replace, for example as below:

Input: string: str = ABCDEFGH, prefix = "_" and position = 3, Output: result = AB_CDE_FGH

Input: string: str = 10000000, prefix = "_" and position = 3, Output: result = 10_000_000

Input: string: str = 10000000, prefix = "_" and position = 2, Output: result = 10_00_00_00

This is my code:

fun convertNumberByCharacter(pattern:String,position: Int,characters: String):String{
    val strBuilder = StringBuilder()
    val arr = pattern.toCharArray()
    return if (arr.size>position){
        for (i in 0..arr.size-1){
            if (i%position==0){
                strBuilder.append(characters)
            }
            strBuilder.append(arr[i])
        }
        strBuilder.toString()

    }else{
        pattern
    }
}

Note: DecimalFormat and NumberFormat cannot be used in this problem.

Please, Anyone could help me. Thank you.



from Recent Questions - Stack Overflow https://ift.tt/2Wk7uVM
https://ift.tt/eA8V8J

Add markers from json in php page with maps [duplicate]

I'm trying to plot markers in php page with Google Maps api controlled by radio buttons. All data markers are loading correctly (json) but the map does not render. Please see below the code that I'm trying to run. I rebuild all code, the service API returns [{"car":"16","bike":"20","skate":"63","lat":"19.79956153","lon":"42.51250001"},{"car":"23","bike":"21","skate":"65","lat":"19.79980055","lon":"42.51244114"},] Currently the error on console describes Uncaught ReferenceError: initialize is not defined at HTMLInputElement.onclick.

<html>
   <head>
      <title>Google Maps</title>
        <meta name="author" content=""/>
        <meta name="keywords" content="phone"/>
        <script src="https://maps.googleapis.com/maps/api/js?key=key"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>  
        <script>
            var latlng = { lat: 19.7, lng: 42.5 };
            var marker;
            var map;
            var markers=[];

            function addmarker(map, lat, lng, title ){
                marker = new google.maps.Marker({
                  position:{ lat:lat,lng:lng },
                  title:title,
                  draggable:true,
                  map:map
                });
                markers.push( marker );
            }
            function initialize() {
                var mapCanvas = document.getElementById('mapArea');
                var mapOptions = {
                  center: latlng,
                  zoom: 19,
                  mapTypeId: google.maps.MapTypeId.SATELLITE
                }
                function() {
                    var radio = "";
                    for (i = 0; i < document.getElementsByName('rd').length; i++) {
                        if (document.getElementsByName('rd')[i].checked) {
                            radio = document.getElementsByName('gender')[i].value;        
                        }        
                    }
                    $.ajax({
                      dataType: 'JSON',
                      url: 'http://webservice.net/data.php',
                      success: function(data) {                 
                          markers.forEach( function( e,i,a ){
                             e.setMap( null ); 
                          });

                          for( var o in data ){
                            var lat=Number(data[o].lat);
                            var lng=Number(data[o].lon);
                            var value=Number(data[o].radio);
                            
                            console.log( 'lat:%s, lng:%s',lat,lng );

                            addmarker.call( this, map, lat, lng, val );
                          }
                      },
                      error: function( err ){
                        console.log( err );  
                      }
                    })
                }
            }            
            google.maps.event.addDomListener(window, 'load', initialize());
        </script>    
    </head>
    <body>       
       <form action="" method="post">
            <input type="radio" value="car" name="rd"  />Car
            <input type="radio" value="clay" name="rd" />Bike
            <input type="radio" value="bike" name="rd" />Skate
            <input type="button" value="send"  onclick="initialize();"/>
       </form>  
       <div id="mapArea" style="width: 1000px; height: 600px;"> </div>
    </body>
</html>


from Recent Questions - Stack Overflow https://ift.tt/2Y1dGCM
https://ift.tt/eA8V8J

Using a new activity function creates -nan values in TensorFlow

I define a new activity function motivated by the reLU activation. However, it does not function correctly and I get -nan values after the first epoch.

import numpy as np
import tensorflow as tf
from tensorflow import keras 
from tensorflow.python.ops import math_ops

training_input=  np.random.random ([200,5]) * 200 #input data
training_input.astype(int)

training_output = np.random.random ([200,1]) # output data


def custom_act(alpha=0.0):  #new activity function      
    def new_act(x):
        neg = tf.cast(tf.math.greater_equal(0.0, x), dtype='float32')  # less than zero
        pos = tf.cast(tf.math.greater_equal(x, 0.0), dtype='float32') # greater than zero
        # if <0, then x. if>0, then scale it with alpha and exponential
        return  tf.cast( (neg*x) + (alpha*pos*(1-tf.math.exp(-x)) ) , tf.float32)
    return new_act  

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(5,)),
    tf.keras.layers.Dense(64, activation="relu"), 
    tf.keras.layers.Dense(32,activation=custom_act(alpha=0.1)),
    tf.keras.layers.Dense( 1) 
]) 

model.compile(loss="mse",optimizer =tf.keras.optimizers.Adam(learning_rate=0.1))

model.fit(training_input,training_output,epochs = 5,batch_size=20,verbose=1)

For instance, the first two columns in the first row are -16.0825386 43.0274544 and they turn into -16.0825386 0.1. After the first epoch, then I get all -nan. What might I be doing wrong?

[-nan -nan -nan ... -nan -nan -nan]
[-nan -nan -nan ... -nan -nan -nan]


from Recent Questions - Stack Overflow https://ift.tt/3iiaCtc
https://ift.tt/eA8V8J

STL generic algorithms - implicit conversion of the ranges element type to the predicates parameter type

Say I want to remove all punctuation characters within a std::string using the erase-remove idiom.

However, let str be of type std::string, this call won't compile

str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );

Now I guess, strictly speaking the std::ispunct callables parameter type is int and therefore doesn't match the ranges element type char. However, as a char is a numeric type it should be convertible to int. I'm working with Lippman's C++ Primer book which states

The algorithms that take predicates call the predicate on the elements in the input range. [...] it must be possible to convert the element type to the parameter type in the input range.

which imo is given in the above statement. Also std::ispunct returns an int, and thus should be usable as a condition.

So why does the compiler complain no matching function for call to 'remove_if'? (clang++ -std=c++11 -o main main.cc)

A fix would be to use a lambda

str.erase( std::remove_if(str.begin(), str.end(),
                          [] ( char ch ) { return std::ispunct(ch); }),
            str.end() );

still it suprised me that a lambda is necessary...

Thanks in advance!



from Recent Questions - Stack Overflow https://ift.tt/3ie8YZo
https://ift.tt/eA8V8J

Google Sheets query function needing to provide 0 value for no value found

The query function looks at a separate sheet with orders entered by a dealer. In some months the dealer may not have a order. The B:B column in current sheet is all the dealers in Ascending order. Then I have separate columns for by month view with 3 columns per month. Number of contracts, amount then average. My query calculates correctly, but if a dealer doesn't have a contract then it skips. So my list is out of order. I'm needing it to place a 0 if no value found. I have 2 versions of the query. J = amount, H = Dealer name, A = Date, the B = is the dealer list in current sheet. This query populates but out of order due to skipping NUll or NA. =QUERY('2021ContractsData'!A:V,"Select COUNT(J),SUM(J),AVG(J) WHERE MONTH(A)+1=1 Group By H LABEL COUNT(J) 'Contracts',SUM(J) 'Amount',AVG(J) 'Average'") This query populates nothing, it shows the Header names but no values in rows. =QUERY('2021ContractsData'!A:V,"Select COUNT(J),SUM(J),AVG(J) WHERE MONTH(A)+1=1 AND H='"&B2:B&"' Group By H LABEL COUNT(J) 'Contracts',SUM(J) 'Amount',AVG(J) 'Average'")

Thank you for taking the time to read and answer. Google Sheet View



from Recent Questions - Stack Overflow https://ift.tt/39RMBEp
https://ift.tt/eA8V8J

Is dotnet restore broken on macos?

This has recently just started happening.

dotnet --version
5.0.104

macOS Big Sur version 11.6

when I run

dotnet restore
  Determining projects to restore...
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.Cryptography.ProtectedData 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Windows.Extensions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.Principal.Windows 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.Permissions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Configuration.ConfigurationManager 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.Principal.Windows 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.Permissions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Windows.Extensions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.Principal.Windows 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.Cryptography.ProtectedData 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Configuration.ConfigurationManager 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.Permissions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.Principal.Windows 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.Cryptography.ProtectedData 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Configuration.ConfigurationManager 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.Permissions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Windows.Extensions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Configuration.ConfigurationManager 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Windows.Extensions 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.Cryptography.ProtectedData 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Drawing.Common 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Drawing.Common 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Drawing.Common 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Drawing.Common 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'Microsoft.Win32.SystemEvents 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'Microsoft.Win32.SystemEvents 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'Microsoft.Win32.SystemEvents 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'Microsoft.Win32.SystemEvents 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.AccessControl 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.AccessControl 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'System.Security.AccessControl 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'System.Security.AccessControl 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'Microsoft.NETCore.Platforms 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'Microsoft.NETCore.Platforms 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired.
/Users/xxx/Work/mvc/mvc.csproj : warning NU3028: Package 'Microsoft.NETCore.Platforms 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: ExplicitDistrust: The trust setting for this policy was set to Deny.
/Users/xxx/Work/mvc/mvc.csproj : error NU3037: Package 'Microsoft.NETCore.Platforms 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature validity period has expired.
  Failed to restore /Users/xxx/Work/mvc/mvc.csproj (in 753 ms).
  1 of 2 projects are up-to-date for restore.

Is this something broken in nuget?

How do I fix "The repository countersignature validity period has expired."?



from Recent Questions - Stack Overflow https://ift.tt/39Axnn8
https://ift.tt/eA8V8J

Hosting on netlify

My pg is running locally and with lsof -i :5432 my pg is running on my account just fine. But when I try to host on netlify I get

In Gemfile: pg Error during gem install

when trying to deploy the site full log below

I have also tried deploying to heroku as well but react routers for some reason is not working with it. It displays my homepage but my routes display nothing (works locally tho).

12:03:04 PM: Build ready to start
12:03:06 PM: build-image version: 081db65c3e4ce8423fedb40e7689a87de6f84667
12:03:06 PM: build-image tag: v4.3.1
12:03:06 PM: buildbot version: f650485c830eb31597911322420b99299a4303b8
12:03:06 PM: Building without cache
12:03:06 PM: Starting to prepare the repo for build
12:03:06 PM: No cached dependencies found. Cloning fresh repo
12:03:06 PM: git clone https://github.com/IvanWiesner/prison-joe-fixed
12:03:07 PM: Preparing Git Reference refs/heads/main
12:03:08 PM: Parsing package.json dependencies
12:03:08 PM: Different publish path detected, going to use the one specified in the Netlify configuration file: 'dist' versus 'dist/' in the Netlify UI
12:03:08 PM: Starting build script
12:03:08 PM: Installing dependencies
12:03:08 PM: Python version set to 2.7
12:03:09 PM: Downloading and installing node v16.10.0...
12:03:09 PM: Downloading https://nodejs.org/dist/v16.10.0/node-v16.10.0-linux-x64.tar.xz...
12:03:10 PM: Computing checksum with sha256sum
12:03:10 PM: Checksums matched!
12:03:13 PM: Now using node v16.10.0 (npm v7.24.0)
12:03:13 PM: Started restoring cached build plugins
12:03:13 PM: Finished restoring cached build plugins
12:03:13 PM: Required ruby-2.7.4 is not installed.
12:03:13 PM: To install do: 'rvm install "ruby-2.7.4"'
12:03:13 PM: Attempting ruby version ruby-2.7.4, read from .ruby-version file
12:03:14 PM: Required ruby-2.7.4 is not installed - installing.
12:03:14 PM: Searching for binary rubies, this might take some time.
12:03:16 PM: Found remote file https://rubies.travis-ci.org/ubuntu/20.04/x86_64/ruby-2.7.4.tar.bz2
12:03:16 PM: Checking requirements for ubuntu.
12:03:17 PM: Requirements installation successful.
12:03:17 PM: ruby-2.7.4 - #configure
12:03:17 PM: ruby-2.7.4 - #download
12:03:18 PM: No checksum for downloaded archive, recording checksum in user configuration.
12:03:18 PM: ruby-2.7.4 - #validate archive
12:03:21 PM: ruby-2.7.4 - #extract
12:03:23 PM: ruby-2.7.4 - #validate binary
12:03:23 PM: ruby-2.7.4 - #setup
12:03:24 PM: ruby-2.7.4 - #gemset created /opt/buildhome/.rvm/gems/ruby-2.7.4@global
12:03:24 PM: ruby-2.7.4 - #importing gemset /opt/buildhome/.rvm/gemsets/global.gems........................................
12:03:24 PM: ruby-2.7.4 - #generating global wrappers........
12:03:25 PM: ruby-2.7.4 - #gemset created /opt/buildhome/.rvm/gems/ruby-2.7.4
12:03:25 PM: ruby-2.7.4 - #importing gemsetfile /opt/buildhome/.rvm/gemsets/default.gems evaluated to empty gem list
12:03:25 PM: ruby-2.7.4 - #generating default wrappers........
12:03:25 PM: Using /opt/buildhome/.rvm/gems/ruby-2.7.4
12:03:26 PM: Using ruby version 2.7.4
12:03:26 PM: Using bundler version 2.2.26 from Gemfile.lock
12:03:27 PM: Successfully installed bundler-2.2.26
12:03:27 PM: 1 gem installed
12:03:27 PM: Using PHP version 8.0
12:03:27 PM: Started restoring cached ruby gems
12:03:27 PM: Finished restoring cached ruby gems
12:03:27 PM: Installing gem bundle
12:03:27 PM: [DEPRECATED] The `--path` flag is deprecated because it relies on being remembered across bundler invocations, which bundler will no longer do in future versions. Instead please use `bundle config set --local path '/opt/build/cache/bundle'`, and stop using this flag
12:03:27 PM: [DEPRECATED] The --binstubs option will be removed in favor of `bundle binstubs --all`
12:03:29 PM: Fetching gem metadata from https://rubygems.org/............
12:03:29 PM: Fetching rake 13.0.6
12:03:29 PM: Installing rake 13.0.6
12:03:29 PM: Fetching concurrent-ruby 1.1.9
12:03:29 PM: Fetching minitest 5.14.4
12:03:29 PM: Fetching builder 3.2.4
12:03:29 PM: Fetching zeitwerk 2.4.2
12:03:29 PM: Fetching racc 1.5.2
12:03:29 PM: Fetching rack 2.2.3
12:03:29 PM: Fetching crass 1.0.6
12:03:29 PM: Fetching erubi 1.10.0
12:03:30 PM: Installing builder 3.2.4
12:03:30 PM: Installing minitest 5.14.4
12:03:30 PM: Installing crass 1.0.6
12:03:30 PM: Installing rack 2.2.3
12:03:30 PM: Installing zeitwerk 2.4.2
12:03:30 PM: Fetching nio4r 2.5.8
12:03:30 PM: Installing racc 1.5.2 with native extensions
12:03:30 PM: Fetching websocket-extensions 0.1.5
12:03:30 PM: Installing erubi 1.10.0
12:03:30 PM: Fetching marcel 1.0.1
12:03:30 PM: Installing concurrent-ruby 1.1.9
12:03:30 PM: Installing websocket-extensions 0.1.5
12:03:30 PM: Installing marcel 1.0.1
12:03:30 PM: Fetching mini_mime 1.1.1
12:03:30 PM: Installing nio4r 2.5.8 with native extensions
12:03:30 PM: Fetching jsonapi-renderer 0.2.2
12:03:30 PM: Fetching bcrypt 3.1.16
12:03:30 PM: Installing mini_mime 1.1.1
12:03:30 PM: Installing jsonapi-renderer 0.2.2
12:03:30 PM: Fetching msgpack 1.4.2
12:03:30 PM: Installing bcrypt 3.1.16 with native extensions
12:03:30 PM: Using bundler 2.2.26
12:03:30 PM: Fetching byebug 11.1.3
12:03:30 PM: Installing msgpack 1.4.2 with native extensions
12:03:30 PM: Fetching ffi 1.15.4
12:03:30 PM: Installing byebug 11.1.3 with native extensions
12:03:30 PM: Installing ffi 1.15.4 with native extensions
12:03:48 PM: Fetching rb-fsevent 0.11.0
12:03:48 PM: Fetching method_source 1.0.0
12:03:48 PM: Fetching thor 1.1.0
12:03:48 PM: Fetching spring 2.1.1
12:03:48 PM: Fetching pg 1.2.3
12:03:48 PM: Fetching websocket-driver 0.7.5
12:03:48 PM: Fetching mail 2.7.1
12:03:48 PM: Fetching rack-test 1.1.0
12:03:48 PM: Installing method_source 1.0.0
12:03:48 PM: Installing spring 2.1.1
12:03:48 PM: Installing rack-test 1.1.0
12:03:48 PM: Installing thor 1.1.0
12:03:48 PM: Installing websocket-driver 0.7.5 with native extensions
12:03:48 PM: Installing rb-fsevent 0.11.0
12:03:48 PM: Installing pg 1.2.3 with native extensions
12:03:49 PM: Fetching rack-cors 1.1.1
12:03:49 PM: Fetching i18n 1.8.10
12:03:49 PM: Installing mail 2.7.1
12:03:49 PM: Installing i18n 1.8.10
12:03:49 PM: Installing rack-cors 1.1.1
12:03:49 PM: Fetching tzinfo 2.0.4
12:03:49 PM: Installing tzinfo 2.0.4
12:03:49 PM: Fetching puma 5.4.0
12:03:49 PM: Fetching bootsnap 1.8.1
12:03:49 PM: Fetching sprockets 4.0.2
12:03:49 PM: Fetching nokogiri 1.12.4 (x86_64-linux)
12:03:49 PM: Fetching rb-inotify 0.10.1
12:03:49 PM: Fetching faker 2.19.0
12:03:49 PM: Fetching activesupport 6.1.4.1
12:03:49 PM: Installing rb-inotify 0.10.1
12:03:49 PM: Installing bootsnap 1.8.1 with native extensions
12:03:49 PM: Installing sprockets 4.0.2
12:03:50 PM: Installing activesupport 6.1.4.1
12:03:50 PM: Installing puma 5.4.0 with native extensions
12:03:50 PM: Installing faker 2.19.0
12:03:50 PM: Installing nokogiri 1.12.4 (x86_64-linux)
12:03:53 PM: Fetching listen 3.7.0
12:03:53 PM: Fetching globalid 0.5.2
12:03:53 PM: Fetching case_transform 0.2
12:03:53 PM: Fetching activemodel 6.1.4.1
12:03:53 PM: Fetching rails-dom-testing 2.0.3
12:03:53 PM: Fetching loofah 2.12.0
12:03:53 PM: Installing case_transform 0.2
12:03:53 PM: Installing rails-dom-testing 2.0.3
12:03:53 PM: Installing globalid 0.5.2
12:03:53 PM: Installing listen 3.7.0
12:03:53 PM: Installing loofah 2.12.0
12:03:53 PM: Installing activemodel 6.1.4.1
12:03:53 PM: Fetching activejob 6.1.4.1
12:03:53 PM: Fetching rails-html-sanitizer 1.4.2
12:03:53 PM: Installing activejob 6.1.4.1
12:03:53 PM: Installing rails-html-sanitizer 1.4.2
12:03:54 PM: Fetching actionview 6.1.4.1
12:03:54 PM: Fetching activerecord 6.1.4.1
12:03:54 PM: Installing actionview 6.1.4.1
12:03:54 PM: Installing activerecord 6.1.4.1
12:03:54 PM: Fetching actionpack 6.1.4.1
12:03:54 PM: Installing actionpack 6.1.4.1
12:03:54 PM: Fetching activestorage 6.1.4.1
12:03:54 PM: Fetching actionmailer 6.1.4.1
12:03:54 PM: Fetching actioncable 6.1.4.1
12:03:54 PM: Fetching active_model_serializers 0.10.12
12:03:54 PM: Fetching railties 6.1.4.1
12:03:54 PM: Fetching sprockets-rails 3.2.2
12:03:54 PM: Installing actionmailer 6.1.4.1
12:03:54 PM: Installing actioncable 6.1.4.1
12:03:54 PM: Installing sprockets-rails 3.2.2
12:03:54 PM: Installing active_model_serializers 0.10.12
12:03:54 PM: Installing activestorage 6.1.4.1
12:03:54 PM: Installing railties 6.1.4.1
12:03:55 PM: Fetching actionmailbox 6.1.4.1
12:03:55 PM: Fetching actiontext 6.1.4.1
12:03:55 PM: Installing actionmailbox 6.1.4.1
12:03:55 PM: Installing actiontext 6.1.4.1
12:03:55 PM: Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
12:03:55 PM:     current directory: /opt/build/cache/bundle/ruby/2.7.0/gems/pg-1.2.3/ext
12:03:55 PM: /opt/buildhome/.rvm/rubies/ruby-2.7.4/bin/ruby -I
12:03:55 PM: /opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0 -r
12:03:55 PM: ./siteconf20210928-3304-6jjawu.rb extconf.rb
12:03:55 PM: checking for pg_config... no
12:03:55 PM: No pg_config... trying anyway. If building fails, please try again with
12:03:55 PM:  --with-pg-config=/path/to/pg_config
12:03:55 PM: checking for libpq-fe.h... no
12:03:55 PM: Can't find the 'libpq-fe.h header
12:03:55 PM: *** extconf.rb failed ***
12:03:55 PM: Could not create Makefile due to some reason, probably lack of necessary
12:03:55 PM: libraries and/or headers.  Check the mkmf.log file for more details.  You may
12:03:55 PM: need configuration options.
12:03:55 PM: Provided configuration options:
12:03:55 PM:    --with-opt-dir
12:03:55 PM:    --without-opt-dir
12:03:55 PM:    --with-opt-include
12:03:55 PM:    --without-opt-include=${opt-dir}/include
12:03:55 PM:    --with-opt-lib
12:03:55 PM:    --without-opt-lib=${opt-dir}/lib
12:03:55 PM:    --with-make-prog
12:03:55 PM:    --without-make-prog
12:03:55 PM:    --srcdir=.
12:03:55 PM: Creating deploy upload records
12:03:55 PM:    --curdir
12:03:55 PM:    --ruby=/opt/buildhome/.rvm/rubies/ruby-2.7.4/bin/$(RUBY_BASE_NAME)
12:03:55 PM:    --with-pg
12:03:55 PM:    --without-pg
12:03:55 PM:    --enable-windows-cross
12:03:55 PM:    --disable-windows-cross
12:03:55 PM:    --with-pg-config
12:03:55 PM:    --without-pg-config
12:03:55 PM: Failed during stage 'building site': Build script returned non-zero exit code: 1
12:03:55 PM:    --with-pg_config
12:03:55 PM:    --without-pg_config
12:03:55 PM:    --with-pg-dir
12:03:55 PM:    --without-pg-dir
12:03:55 PM:    --with-pg-include
12:03:55 PM:    --without-pg-include=${pg-dir}/include
12:03:55 PM:    --with-pg-lib
12:03:55 PM:    --without-pg-lib=${pg-dir}/lib
12:03:55 PM: To see why this extension failed to compile, please check the mkmf.log which can
12:03:55 PM: be found here:
12:03:55 PM: /opt/build/cache/bundle/ruby/2.7.0/extensions/x86_64-linux/2.7.0/pg-1.2.3/mkmf.log
12:03:55 PM: extconf failed, exit code 1
12:03:55 PM: Gem files will remain installed in
12:03:55 PM: /opt/build/cache/bundle/ruby/2.7.0/gems/pg-1.2.3 for inspection.
12:03:55 PM: Results logged to
12:03:55 PM: /opt/build/cache/bundle/ruby/2.7.0/extensions/x86_64-linux/2.7.0/pg-1.2.3/gem_make.out
12:03:55 PM: /opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:99:in
12:03:55 PM: `run'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/ext_conf_builder.rb:48:in
`block in build'
  /opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/tempfile.rb:291:in `open'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/ext_conf_builder.rb:30:in
`build'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:169:in
12:03:55 PM: `block in build_extension'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:165:in
`synchronize'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:165:in
12:03:55 PM: `build_extension'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:210:in
`block in build_extensions'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:207:in
12:03:55 PM: `each'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/ext/builder.rb:207:in
`build_extensions'
/opt/buildhome/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/rubygems/installer.rb:844:in
12:03:55 PM: `build_extensions'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/rubygems_gem_installer.rb:66:in
`build_extensions'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/rubygems_gem_installer.rb:26:in
12:03:55 PM: `install'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/source/rubygems.rb:192:in
`install'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/installer/gem_installer.rb:54:in
12:03:55 PM: `install'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/installer/gem_installer.rb:16:in
`install_from_spec'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/installer/parallel_installer.rb:186:in
12:03:55 PM: `do_install'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/installer/parallel_installer.rb:177:in
`block in worker_pool'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/worker.rb:62:in
12:03:55 PM: `apply_func'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/worker.rb:57:in
`block in process_queue'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/worker.rb:54:in
12:03:55 PM: `loop'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/worker.rb:54:in
`process_queue'
/opt/buildhome/.rvm/gems/ruby-2.7.4/gems/bundler-2.2.26/lib/bundler/worker.rb:91:in
12:03:55 PM: `block (2 levels) in create_threads'

An error occurred while installing pg (1.2.3), and Bundler cannot continue.

In Gemfile:
  pg
Error during gem install
12:03:55 PM: Build was terminated: Build script returned non-zero exit code: 1
12:03:55 PM: Failing build: Failed to build site
12:03:55 PM: Finished processing build request in 49.373621319s


from Recent Questions - Stack Overflow https://ift.tt/3F39naK
https://ift.tt/eA8V8J

C - Exposing 3rd party data structures in a library's public header file

I'm writing a library that wraps around a REST API and representing some of the data requires use of data structures like hash maps that are not available in the C standard library so internally I'm using 3rd party libraries for their implementations. Now I'd like to expose them in a response struct, I've come up with a couple of solutions:

  1. Just expose the type as it is and add a dependency on the 3rd party lib and make the user call the appropriate API functions (Eg hashmap_lib_get(users, "key") to get a value):
// header.h (Include guards excluded)
#include <hashmap_lib.h>

struct api_response {
    int field1;
    char *field2;
    HASHMAP_LIB_HM *users; // Map of users to their email. (example)
};

Issue: Requires extra user intervention, even more problematic in case the library is implemented using generic macros.

  1. Expose the type as a void pointer inside the struct and write duplicated wrappers for all appropriate functions:
// header.h
struct api_response {
    int field1;
    char *field2;
    void *users; // Don't touch
};

char *api_hashmap_get(void *hm, const char *key);

The internal implementation of api_hashmap_get would just be return hashmap_lib_get((HASHMAP_LIB_HM *) hm, key);

Issue: Requires duplication of various function definitions and requires the use of void pointers.

How is this problem usually solved in libraries ? The first solution would make sense if both the libraries were "related" with each other (Eg using an eventing system such as libevent to work with the user's application), but in this case it's just about general data structures so it doesn't make sense to me since the user would be using other libs for the same type of data structures aswell.



from Recent Questions - Stack Overflow https://ift.tt/3ouF1bJ
https://ift.tt/eA8V8J

In C#, what is wrong with my negative test of TryAsync?

I have the following method:

public TryAsync<bool> TryRelay(
    MontageUploadConfig montageData,
    File sourceFile,
    CancellationToken cancellationToken
) => new(async () =>
{
    byte[] fileContent = await _httpClient.GetByteArrayAsync(sourceFile.Url, cancellationToken);
    return await _attachmentController.TryUploadAttachment(montageData.EventId, fileContent, sourceFile.Name);
});

I created a couple tests to prove it works as expected. My test for a negative case is failing.

This is the test:

[Fact]
public static async Task TestRelayShouldCatchErrorsGettingFile()
{
    // Arrange
    Mock<IAttachmentControllerV6> mockAttachmentController = new();
    Mock<HttpMessageHandler> mockHttpMessageHandler = new();
    MontageUploadTaskProcessor mockProcessorUnderTest = CreateProcessor(mockAttachmentController, mockHttpMessageHandler);

    MontageUploadConfig montageData = new()
    {
        EventId = "Test001"
    };
    File sourceFile = new()
    {
        Name = "Test.pdf",
        Url = "https://www.example.com/test.pdf"
    };
    CancellationToken cancellationToken = default;

    const string message = "Expected Exception";
    mockHttpMessageHandler.SetupAnyRequest()
        .Throws(new SalesforceCacheException(message));

    // Act
    Result<bool> result = await mockProcessorUnderTest.TryRelay(montageData, sourceFile, cancellationToken)();

    // Assert
    Assert.True(result.IsFaulted);
    result.IfFail(exception =>
    {
        Assert.True(exception is Exception);
        Assert.Equal(message, exception.Message);
    });
}

This is the error:

WorkflowTests.TaskProcessor.OldOrg.MontageUploadTaskProcessorUnitTests.TestRelayShouldCatchErrorsGettingFile Source: MontageUploadTaskProcessorUnitTests.cs line 59 Duration: 144 ms

Message: SFCacheController.SalesforceCacheException : Expected Exception

Stack Trace: ThrowException.Execute(Invocation invocation) line 22 MethodCall.ExecuteCore(Invocation invocation) line 97 Setup.Execute(Invocation invocation) line 85 FindAndExecuteMatchingSetup.Handle(Invocation invocation, Mock mock) line 107 IInterceptor.Intercept(Invocation invocation) line 17 Interceptor.Intercept(IInvocation underlying) line 107 AbstractInvocation.Proceed() HttpMessageHandlerProxy.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken) HttpClient.GetByteArrayAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) <b__0>d.MoveNext() line 140 --- End of stack trace from previous location --- MontageUploadTaskProcessorUnitTests.TestRelayShouldCatchErrorsGettingFile() line 81 --- End of stack trace from previous location ---

The exception seems to be thrown after TryRelay() is invoked, but even before any assertions are attempted.

Am I wrong to expect TryAsync will catch and box the exception? Am I wrong to expect this to work in a test context? What do I need to do to make this test pass?



from Recent Questions - Stack Overflow https://ift.tt/3EVTlj3
https://ift.tt/eA8V8J

Usage of SIM card GlobalPlatform keys in field

Question 1. When a SIM manufacture personalizes a SIM card and then the mobile operator hand it over to an end user, are there any usage for GlobalPlatform (GP) keys (ENC,MAC,KEK,...)?

As long as I know the SIM file structure or its applets are accessible by (KID/KIC/KIK) over OTA RFM and RAM. So there is no need to have GP keys when SIM is in hands of customers.

Are there anywhere special (e.g. during OTA interactions that we require GP keys or not)? As I understood correctly, GP keys are usable when we physically can access a SIM card and we can directly send APDUs to the SIM. Am I right?

Question 2. Is it possible to access SIM/USIM file structure using global platform commands (e.g. is it possible to read record, read binary) using GP keys and access which ISD has? Typically file structure is accessible based on access conditions defined in 3GPP TS 51.011/ETSI TS 151 011 using PIN and ADM keys. But is it possible using GP keys and access which ISD has?



from Recent Questions - Stack Overflow https://ift.tt/2XYFh7h
https://ift.tt/eA8V8J

2021-09-28

How to use caret functions to achieve the same results as this for loop? Classification Random Forest caret

I want to run monte carlo cv 100 times on my data, my data is 2 class classification I want to use the caret package to achieve the same thing, mainly I'm confused about how to average the results of accuracy for example using caret?

# Initialize data for Binary classification
dataset$ID <- factor(dataset$ID)

# Initialize number of iterations
num_iter=100 

# Vectors to store results
acc_vec<-c()

# Function with for loop

    rf <- function(dataset)
    {
      for (i in 1:num_iter)
      {
        trainIndex <-createDataPartition(dataset$ID, p=0.8,list=FALSE)
        dataset_train <-dataset[trainIndex, ]
        dataset_test <-dataset[-trainIndex, ]
        rf <- randomForest(ID~., data=dataset_train, importance=TRUE) 
        x_test <- dataset_test[, -1]
        y_test <- dataset_test$ID

        predictions <- predict(rf, x_test)

        acc_vec <- append(acc_vec, accuracy(actual= y_test, predicted= predictions))

      }

      print(mean(acc_vec))
    }


from Recent Questions - Stack Overflow https://ift.tt/3i9fsIT
https://ift.tt/eA8V8J