2021-04-30

C++ CopyFile() copy from network drive to local drive in windows 10

I'm using Rad Studio for running C++ in window 10. I've been trying to copy a file from network drive to local drive. When I tried to copy a file from local to local, it worked! but when I tried to copy a file from server or mapped driver(Z:), there are no error, not copied. so it's hard to find the problem. I guess that most do need some sort of authentication. but I'm still stuck with it.

Here is my code.

String source = L"\\\\sever1\\Data\\program1.exe"; // Server to Local : result==> Not copied, no error.
// What I tried to test.
//   String source = L"E:\\file1\\083\\program1.exe";     //Local to Local : result==> It works!
//   String source = L"Z:\\program1.exe";         //mapped driver : result==> Not copied, no error.
String destination = L"C:\\Our Programs\\program1.exe";
result = CopyFile( source.w_str(), destination.w_str(), true);


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

How to use OpenCV to detect simple 2d character?

For my project, I need the program to find the location of a video game character on the screen (similar to one below):

character

Of course, there is no pre-built classifier for this in OpenCV. Would I have to train a NN classifier for this task, or is that over-engineering and there is a simpler solution?



from Recent Questions - Stack Overflow https://ift.tt/3gQrSpA
https://ift.tt/3xywCpF

Missing data points in line chart

Plotly has missing data points on the graph that are present in the x and y lists which are being used to draw the graph. I am not sure why.

x_axis_list = ['2019-00', '2019-01', '2019-02',.....'2019-54']
y_axis_list = [0,0,0,....1,2,0,0]

When I draw this out using Plotly:

my_fig = px.line(x=x_axis_list, y=y_axis_list,\
labels=dict(time_from_db="Time", \
num_of_accidents_from_db="Num of Accidents"), \
title="Number of Accidents Per Week")

dcc.Graph(id='my_fig', figure=my_fig)

I get weird line charts that looks something like the below figure. enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3u51Ty9
https://ift.tt/3t4ndCE

Hashmaps in javacc

I want to create a programming language that has multiple functions and a single main function. For the interpreter of the language I am using a hash map, but I do not know how to store intermediate values in the hash map. An example of a valid program includes:

DEF MAIN { ADDITION(x) } ;
DEF ADDITION { x+3 } ;

This is what I have so far:

HashMap<String, Function> Program() : {
    HashMap<String, Function> symbolTable = new HashTable<>();
}
{
    (FunctionDefinition(symbolTable))*
    <EOF>
    {return symbolTable;}
}

void FunctionDefinition(SymbolTable table)
{
    Function f;
    String name;
}
{
    <DEF> <SPACE>
    (
        (name = <MAIN>)
    |   (name = <FUNC> (<SPACE> <PARAM> ))
    <SPACE>
    f = FunctionBody()
    ";"
    {
        if (table.hashKey(name)) { System.out.println("do something");}
        else { table.add(name, f); }
    })
}

void FunctionBody() : {}
{
    <LEFT> <SPACE>
    Expression()
    <SPACE> <RIGHT>
}

void Expression() : {}
{
    AdditiveExpression()
}

void AdditiveExpression() : {
}
{
    MultiplicativeExpression() (<PLUS> MultiplicativeExpression()
    {
        try {
                int a = s.pop();
                int b = s.pop();
                stack.push(a+b);
        }
        catch (ClassCastException ex) {
            System.out.println("Only numbers can be used for arithmetic operations.");
            throw new ParseException();
        }
    })*
}

void MultiplicativeExpression() : {
}
{
    UnaryExpression() (<MUL> UnaryExpression()
    {
        try {
            int a = s.pop();
            int b = s.pop();
            stack.push(a*b);
        }
        catch (ClassCastException ex) {
            System.out.println("Only numbers can be used for arithmetic operations");
            throw new ParseException();
        }
    })*
}

void UnaryExpression() : {
    Token x;
}
{
    (x = <NUMBER> | x = <PARAM>)
    {s.push(x.image);}
}

Any help will be greatly appreciated.



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

In MIPS 32 Assembly, why is "la" used to print strings but "lw" used to print integers?

Just want to know the logic behind this. Why is la used for strings and lw used for integers? For example:

.data

age:   .word 30

.text
li $v0, 1
lw $a0, age
syscall

vs

.data

name:   .asciiz "Joe"

.text
li $v0, 4
la $a0, name
syscall


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

When I run my code setLayout is not working with JPanel

I keep getting the errors that:

The method setLayout(LayoutManager) in the type JFrame is not applicable for the arguments (GridLayout)
The constructor GridLayout(int, int) is undefined

When I look as to why it says that:

The method setLayout(LayoutManager) in the type Container is not applicable for the arguments (GridLayout)

and

Is anyone familiar with Swing?

Code:

public class YoutubeSwing extends MainSceneSwing{


    public static JFrame frameTwo = new JFrame();
    public static JPanel topPanel = new JPanel();
    public static JPanel secondPanel = new JPanel();
    public static String songTitle;
    public static String artistName;


    public static void main(String[] args) {
        runSimulation();
    }

    public static void runSimulation() {
        setUp();
    }

    public static void topPanel() {
        topPanel.setLayout(new FlowLayout());
        JLabel title = new JLabel("Not-ify", JLabel.CENTER);
        title.setForeground(Color.BLUE);
        title.setFont(Title);
        topPanel.add(title);
    }

    public static void secondPanel() {
        secondPanel.setLayout(new FlowLayout());
        JLabel subtitle = new JLabel("Youtube Music Player", JLabel.CENTER);
        subtitle.setFont(Text);
        secondPanel.add(subtitle);
        JLabel disclaimer = new JLabel("We may place adds before your music so that we can generate some revenue. Please note that we are starving students.", JLabel.CENTER);
        disclaimer.setFont(ButtonText);
        secondPanel.add(disclaimer);
    }

    
    public static void setUp() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(WIDTH, HEIGHT));
        frame.setTitle("Not-ify");
        frame.setLayout(new GridLayout(4,1));

        topPanel();
        secondPanel();

        JPanel thirdPanel = new JPanel();
        secondPanel.setLayout(new GridLayout(4, 1));
        thirdPanel.setLayout(new GridLayout(4,1));
        JTextArea artist = new JTextArea(
                "Please enter the artist of your choice: ");
        JTextArea artistAnswer = new JTextArea(
                "Drake");//**TODO Uncheck */
        JTextArea song = new JTextArea(
                "Please enter the song of your choice: ");
        JTextArea songAnswer = new JTextArea(
                "One Dance");//**TODO Uncheck */

        artist.setEditable(false);
        artistAnswer.setEditable(true);
        song.setEditable(false);
        songAnswer.setEditable(true);

        
        thirdPanel.add(artist);
        thirdPanel.add(artistAnswer);
        thirdPanel.add(song);
        thirdPanel.add(songAnswer);


        JButton start = new JButton("Start");
        ActionListener startListener = new YoutubePlayerButtonListener(start,artistAnswer,songAnswer);
        start.setForeground(Color.GREEN);
        start.setFont(Subtitle);
        start.addActionListener(startListener);

        frame.add(topPanel);
        frame.add(secondPanel);
        frame.add(thirdPanel);
        frame.add(start);

        frame.pack();
        frame.setVisible(true);
    }


    
    public static void start(String artistName, String song, String lyrics, String url, String youtubeLink) {
        // Set up screen
        frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameTwo.setSize(new Dimension(WIDTH, HEIGHT));
        frameTwo.setTitle("Not-ify");
        frameTwo.setLayout(new BorderLayout());

        JPanel leftPanel = new JPanel(); 
        leftPanel.setLayout(new GridLayout(2,1));

        JLabel nowPlaying = new JLabel("Currently Playing: " + song + " by " + artistName);
        nowPlaying.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        leftPanel.add(nowPlaying);
        
        JTextArea scrollLyrics = new JTextArea(lyrics);
        scrollLyrics.setAlignmentX(JTextArea.CENTER_ALIGNMENT);
        scrollLyrics.setEditable(false);
        JScrollPane scroll = new JScrollPane(scrollLyrics);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.getViewport().setView(scrollLyrics);
        leftPanel.add(scroll);


        JFXPanel youtubePlayer = new JFXPanel();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
        //Youtube panel
        WebEngine engine;

        WebView view = new WebView();
        engine = view.getEngine();

        engine.load(youtubeLink);
    
        youtubePlayer.setScene(new Scene(view));
        }});

        frameTwo.add(leftPanel, BorderLayout.CENTER);
        frameTwo.add(youtubePlayer, BorderLayout.SOUTH);
        frameTwo.pack();
        youtubePlayer.setVisible(false);
        frameTwo.setVisible(true);
    }
}

Thanks in advance for taking a look. It was working one second and then boom.



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

Adding a class const in php version 7.4 causes a required file to not be found

I'm getting the following exception error when I try to create a class level constant in my controller:

Expected to find class "App\common_code\site_constants" in file 
"/var/www/vhosts/symfony5/proj/src/common_code/site_constants.php"
while importing services from resource "../src/", but it was not
found! Check the namespace prefix used with the resource in
/var/www/vhosts/symfony5/proj/src/../config/services.yaml (which
is being imported from
"/var/www/vhosts/symfony5/proj/src/Kernel.php").

Here is my code:

<?php

// src/Controller/myController.php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class myController {

    // Class-Level local private constants.

    //
    // Adding this one constant causes an error about the
    // site_constants.php require file not being found.
    // Commenting this out and this error and no others happen.
    //

    private const PASSWORD_PROMPT = 'Enter a password.';

    /**
     * @Route("/BreakinOut/home")
     */
    public function home() : Response {

        //
        // Include the site_contants.php file that is
        // outside of the Controller directory, so the
        // file can contain just a
        // bunch of code.
        //

        require ( '../common_code/site_constants.php' );

        return new Response( 'Hi' );

    }
    // public home() : Response  function.

}

?>

The site_constants.php file only contains a few define statements, and none are for PASSWORD_PROMPT.

Why does adding the one constant cause this error?

Thanks.



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

My circular divs get stuck midway flipping when hovering and two of my divs can't get above the bottom div on hover

I am trying to make a responsive and functional diagram that when I hover it flips and shows information. So I made this Venn diagram with three circular divs on top of each other and when I hover my mouse over one of the divs it enlarges and flips showing information on the other side. What I get is a buggy transformation when hovering. I am not sure how to make the flipping smoother when hovering because right now I need to get my cursor on a specific area so the circle fully flips around and not get stuck. I tried using margin and padding for the ":hover" but that doesn't really work and it would also look too spaced out. Secondly is that when hovering on the top two circular divs they enlarge (like they are supposed to) and go above each other but never above the bottom circular div. I tried using z-index with a huge number but still doesn't make it go above the divs. Also, on javascript how would I make it so that when hovering the other circles have a blur?

It should look something like what I prototyped on figma. The venn diagram

And here is the HTML, CSS, and Javascript I used to make this version of the venn diagram.

<style>
#ven_diagram {
display: flex;
flex-direction: column;
width: 100%;
height: 355px;
margin-left: auto;
margin-right: auto;
}
#top {
width: 100%;
transform: translateX(0%) translateY(10%);
display: flex;
flex-direction: row;
justify-content: center;

}
#bottom {
width: 100%;    
display: flex;
flex-direction: column;
justify-items: center;
align-items: center;
position: relative;
bottom: 24%;
/*transform: translateX(0%) translateY(-40%);*/
}
.circle {
width: 220px;
height: 220px;  
cursor: pointer;
box-shadow: 3px 4px 4px rgba(0, 0, 0, 0.25);
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
}
.circleactive {
width: 260px;
height: 260px;
z-index: 900;
transition: 1s ease-in; 
}
.circletitle {
position: relative;
z-index: 999;
text-align: center;
font-family: Roboto;
font-style: normal;
font-weight: 900;
font-size: 24px;
line-height: 28px;
letter-spacing: 0.1em;
color: rgba(255, 255, 255, 1);
text-shadow: 5px 4px 4px rgba(0, 0, 0, 0.25), 0px 4px 4px rgba(0, 0, 0, 0.25);
}
#circle1 {
background: rgba(33, 218, 223, 1);
transform: translateX(25%) translateY(0%);
transform-style: preserve-3d;
transition: transform 1s ease-in;

}
#circle1:hover {
transform: rotateY(180deg);
}
.circle .side {
  backface-visibility: hidden;
  border-radius: 6px;
  height: 100%;
  position: absolute;
  overflow: hidden;
  width: 100%;  
}
.side .circle3p {

  transform: rotateY(180deg);
  display: flex;
  justify-content: space-around;    
}
#circle2 {
background: rgba(95,216, 21, .78);
transform: translateX(-25%) translateY(0%);
transform: translateX(25%) translateY(0%);
transform-style: preserve-3d;
transition: transform 1s ease-in;
}
#circle3 {
background: rgba(253,45, 45, .8);
transform: translateX(0%) translateY(-10%);
transform: translateX(25%) translateY(0%);
transform-style: preserve-3d;
transition: transform 1s ease-in;
}
#circle1 span {
margin-right: 50%;
font-weight: 500;
font-size: 24px;
letter-spacing: 0.1em;
color: #FFFFFF;
text-shadow: 2px 2px 4px rgba(184,184,184,0.70);
backdrop-filter: blur(4px);
}
#circle2 span {
margin-left: 50%;
font-weight: 500;
font-size: 24px;
letter-spacing: 0.1em;
color: #FFFFFF;
text-shadow: 2px 2px 4px rgba(184,184,184,0.70);
backdrop-filter: blur(4px);
}
#circle3 span {
font-weight: 500;
font-size: 24px;
letter-spacing: 0.1em;
color: #FFFFFF;
text-shadow: 2px 2px 4px rgba(184,184,184,0.70);
backdrop-filter: blur(4px); 
}
#circle1p{
display: none;  
}
#circle2p{
display: none;  
}
#circle3p{
display: none;      
}
#section1 {
height: 100vh;
}
#section1 h1{
color: black;
}
</style>

<section id="section1" class="section">
<div id="ven_diagram">
<div id="top" class="absol">
<div id="circle1" class="circle side" onmouseleave="removeActiveClasses();"><span>Mind</span><p class="side circle3p">has to do with how a person thinks, feels and acts as he or she copes with life. A person with good emotional health can feel, express and respond to a wide range of emotions in
healthy ways and form healthy relationships with others</p></div>
<div id="circle2" class="circle side" onmouseleave="removeActiveClasses();"><span>Social</span><p class="side circle3p">has to do with your relationships with others. People with good social health can connect
with and contribute to family, friends, and the wider community</p></div>
</div>
<div id="bottom" class="absol">
<span class="circletitle">Mental Health</span>
<div id="circle3" class="circle side" onmouseleave="removeActiveClasses();"><span>Spiritual</span><p class="side circle3p">has to do with how you find meaning and purpose in your life. People with good
spiritual health have a sense of something bigger than themselves and their own day-to-day lives</p></div>
</div>
<p>Mental wellness according to the World Health Organization, is defined as “a state of well-being in which the individual realizes his or her own abilities, can cope with the normal stresses of life, can work productively and fruitfully, and is able to make a contribution to his or her community.”</p>
</div>
</section>

<script>
// JavaScript Document
const circles = document.querySelectorAll('.circle');

circles.forEach((circle) => {
  circle.addEventListener('mouseover', () => {
    removeActiveClasses();
    circle.classList.add('circleactive');
  });
});

function removeActiveClasses() {
  circles.forEach((circle) => {
  circle.classList.remove('circleactive');  
  
  });
}
</script>


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

How can I solve syntaxerror:invalid or unexpected token in nestjs? [closed]

When I run the following command in command promt for new nestjs project 'npm run start:dev' I get this strange error:

  SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1072:16)
at Module._compile (internal/modules/cjs/loader.js:1122:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47

Does anyone know how to solve this?



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

ReactJs adding 'active' class to a button in a list of buttons

I have a list of buttons created dynamically with the .map function. I am trying to add an "active" class to the button onClick and get rid of the "active" class of the other buttons.

This is what I have so far. The issue is that it's adding the class but not getting rid of the class on the other buttons. Any help is appreciated! Thank you :)

const Buttons = (props) => {
  const [active, setActive] = useState(false);
  const handleClick = (event) => {
    event.preventDefault();
    setActive(true)
  }
    const buttons = props.buttons.map((btn,index) => {
        return(
        
      <button className={active === true ? 'active' : ''} id={btn.id} onClick={handleClick}>{btn.name}</button>
        )
    })
    return (
        <div>
         {buttons}
        </div>
    )
}
export default Buttons;


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

Python sqlite UPDATE Query

UPDATE T1
SET T1.size = (SELECT COUNT(DISTINCT T2.id) FROM T1 FULL OUTER JOIN T2 ON T1.address = T2.address)
WHERE ((SELECT strftime('%s','now')) - T1.Time) >86400
AND T1.status = 'Pending'

Could someone point out why this isn't working?

T1 schema: (id, address, time, size, status), T2 schema: (id, address, time)



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

Adding element class if background color is blue

I am pretty new to javascript and I am working on a page and trying to get a class added to an element based on the element's background color, if it is set to rgb(32, 44, 62) I want to add a class to the element. As it is coded now it adds it to all matching elements not just the ones with the background color. Below is my test of the code. Any insights would be extremely helpful.

https://codepen.io/tyearyean/pen/PoWvLwO

var basicBGColor = $('section.content_basic').css('background-color');

Javascript

    var basicBGColor = $('section.content_basic').css('background-color');

    $('section.content_basic').each(function() {
      if (basicBGColor == 'rgb(32, 44, 62)') {
        $(this).addClass('goldBorder');
      };
    });


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

using loop to calculate the interest with unknown time [closed]

I have to to write a program that could help me to calculate the interest rate with unknown time

the credit is about 10000 and the is 7% and to pay in instalments 1500 i want the redemption and the remain, when the program reach 0 remain should stop

double kredit = 10000;

const double ZinsenProzent = 0.07;

double Teilgung, Zinsen, Restschuld = 10000, Annuitaet = 1500;

do {
    Zinsen = Restschuld * ZinsenProzent;
    cout << "zinsen" << Zinsen << endl;

    Teilgung = Annuitaet - Zinsen;
    cout << "teilgung" << Teilgung << endl;

    Restschuld = Restschuld - Teilgung;
    cout << "rest ist" << Restschuld << endl;
} while (Restschuld > 0);


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

Control+J equivalent using Text to Columns functionality

I'm trying to split a cell with multiple rows of data into into individual cells. Using the Text to Columns functionality.

Text: https://www.howtoexcel.org/tips-and-tricks/how-to-separate-data-in-a-cell-based-on-line-breaks/

Video: https://trumpexcel.com/split-multiple-lines/

I found this video where he uses the Text to Columns functionality but in the video at the bottom of the page it shows him entering "control+j" for the other character. However, on macOS It doesn't work. What is the equivalent of this on the macOS?

thanks.



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

It is referenced and I still get undefined reference issue

class base_rec { 
    public: 
        base_rec():str(" "){}; 
        base_rec(string contentstr):str(contentstr){}; 
        void showme() const; 
    protected: 
        string str; 
    
};

class u_rec:public base_rec {
    public:
        u_rec():base_rec("undergraduate records"){};
        void showme() { cout << "showme() function of u_rec class\t"
            << str << endl;}
     
};
class g_rec:public base_rec {
    public:
        g_rec():base_rec("graduate records"){};
        void showme() { cout << "showme() function of g_rec class\t"
            << str << endl;}
};

int main() {
 base_rec *brp[2];
 brp[1] = new u_rec;
 brp[2] = new g_rec;
 for (int i=0; i<2; i++) {
 brp[i]->showme();
 }
}

Error Message:

main.cpp:(.text+0x58): undefined reference to `base_rec::showme() const' collect2: error: ld returned 1 exit status.

How can I fix it! the showme() is defined in base_rec



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

How to get the previous working day from Oracle?

We maintain a table listing actual holidays for years to come (Holidays, with two columns: M_DATE, and DESCR). I need to find the most recent day before the given one, that's neither listed in that table, nor is Saturday or Sunday.

Preferably -- without a loop :) How would I do that?



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

Django generic DeleteView authentication

I want to create a post that only the author and the authorized groups can delete.

class PostDeleteView(DeleteView):
   model = Posts
   template_name = 'deletepost.html'
   success_url = '/home'

Currently all users can delete posts.



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

Encrypting string in ADA

I have to do a task where I write 3 type of encrypting methods. I've done it but somewhy it only works for upper letters.

crypto.ads

package crypto is
   
 --private
   type keys_arr is array( Natural range <> ) of Natural;
   function Generate_key return Natural;
   function Generate_keys(len: Positive) return keys_arr;
   type keys(len:Positive) is record
      single_key : Natural :=Generate_key;
      multi_keys : keys_arr(1..len) := Generate_keys(len);
    end record;

   procedure print_key(k:keys);
   function shift_char(c: Character; n:Integer) return Character;
   function encrypt_caesar(x:String; k:keys ) return String;
   function encrypt_vigenere_with_numbers(x:String; k:keys ) return String;
   function encrypt_with_pos(x:String) return String;
   function decrypt_caesar(x:String; k:keys ) return String;
   function decrypt_vigenere_with_numbers(x:String; k:keys ) return String;



end crypto;

crypto.adb

with ada.numerics.discrete_random, Ada.Text_IO, Ada.Characters.Handling;
use Ada.Characters.Handling; --Ada.Characters;
package body crypto is


   subtype Lower is Character range 'a' .. 'z';
   subtype Upper is Character range 'A' .. 'Z';
  -- type R is range 1..26;
   -- upper letters from 65-90, lower letters from 97-122
   --source: https://www.adaic.org/resources/add_content/standards/05rm/html/RM-A-5-2.html
   function Generate_key return Natural is
      package Random_Key is new Ada.Numerics.Discrete_Random (Natural);
      use Random_Key;

      Generator : Random_Key.Generator;


   begin
      -- english alphabet consisting 26 letters;
      Random_key.Reset(Generator);
      return Random_key.Random(Generator) mod 26;
   end;

   function Generate_keys(len: Positive) return keys_arr is
      keys : keys_arr(1..len);
   begin

      for i in keys'range loop
          keys(i) := Generate_key;

      end loop;
      return keys;
   end;




   procedure print_key(k:keys) is
   begin
      Ada.Text_IO.Put_Line("generated single_key is :" & integer'image(k.single_key));
      Ada.Text_IO.Put_Line("generated multi_keys list is : ");
      for i in k.multi_keys'range loop
            Ada.Text_IO.Put(Integer'image(k.multi_keys(i)));
      end loop;
   end;


   --my math is not working here somewhy
   -- Its working for upper leters but not for lower letters
   function shift_char(c: Character; n:Integer) return Character is
      I : Integer;
   begin
      -- mod 26 to get the position of the letter in the range
      -- +n , than second mod 26 if the sum is more than 26
      --than add 97 or 65 because thats the beginning of the interval

      -- if Character'Pos(c)>96 AND Character'Pos(c)<123 then
        if Is_Lower(c) then
            I:= ((((Character'Pos(c) rem 26) + n) mod 26) + 97);
         -- elsif Character'Pos(c)<91 AND Character'Pos(c)>64 then
        elsif Is_Upper(c) then
            I:= ((((Character'Pos(c) rem 26) + n) mod 26) + 65);
        end if;

      return Character'val(I);
   end;



   function encrypt_caesar(x:String; k:keys ) return String is
   stringrange: string(x'first..x'last);
   begin
         for i in x'range loop

           if Is_Letter (x(i)) then
             stringrange(i):= shift_char(x(i),k.single_key);

           else
            stringrange(i):= x(i);
           end if;

         end loop;

      return stringrange;
   end;


   function encrypt_vigenere_with_numbers(x:String; k:keys ) return String is
      stringrange: string(x'first..x'last);

      ind : Natural := k.multi_keys'first;

   begin
      --ind:= k.multi_keys'first;
      for i in x'range loop

         if Is_Letter (x(i)) then
            stringrange(i):= shift_char(x(i), k.multi_keys(ind));

           -- if ind=k.multi_keys'last then
            --  ind:=k.multi_keys'first;
            --else ind := ind + 1;
           --end if;
            ind := (ind + 1) rem (k.multi_keys'length +1);
            if ind = 0 then ind := 1;
            end if;
         else
            stringrange(i):= x(i);
         end if;

      end loop;
      return stringrange;
   end;

   function encrypt_with_pos(x:String) return String is
      stringrange: string(x'first..x'last);
   begin
      --similar to shift char +encrypt caesar
         for i in x'range loop

           if Is_Letter(x(i)) then
            if Character'Pos(x(i))<123 AND Character'Pos(x(i))>96 then
                stringrange(i):= shift_char(x(i), Character'pos(x(i)) mod 97);
            elsif Character'Pos(x(i))<91 then
                stringrange(i):= shift_char (x(i), Character'pos(x(i)) mod 65);
            end if;

           else
            stringrange(i):=x(i);
           end if;

         end loop;

      return stringrange;
   end;

   -- opposite of encrypt caesar

   function decrypt_caesar(x:String; k:keys ) return String is
   stringrange: string(x'first..x'last);
   begin
      for i in x'range loop

           stringrange(i):= shift_char(x(i), -k.single_key);

      end loop;
      return stringrange;
   end;

   -- opposite of encrypt vigenere

   function decrypt_vigenere_with_numbers(x:String; k:keys ) return String is
      stringrange: string(x'first..x'last);

      ind : Natural:= k.multi_keys'first;
   begin
     -- ind:= k.multi_keys'first;
      for i in x'range loop

        if Is_Letter(x(i)) then
           stringrange(i):= shift_char(x(i), -k.multi_keys(ind));


         --if ind=k.multi_keys'last then
         --   ind:=k.multi_keys'first;
         --else ind := ind + 1;
         --end if;
          ind := (ind + 1) rem (k.multi_keys'length +1);
          if ind = 0 then ind:= 1; end if;
        else
          stringrange(i) := x(i);
        end if;
      end loop;
      return stringrange;
   end;

crypto demo:

with crypto, Ada.Text_IO, Ada.Integer_Text_IO;
use crypto,Ada.Text_IO, Ada.Integer_Text_IO;

procedure crypto_demo is
   k: Integer := 4;
   st : String := ("Ada Is Cool");
   st2 : String := ("Ada Is Cool");
   st3 : String := ("Ada Is Cool");
begin
   declare
        V: Keys(k);
   begin
      Print_key(V);
      new_Line(1);
      Put("before encryption with caesar: ");
      Put(st);
      new_Line(1);
      Put("encrypted:");
      st:=encrypt_caesar(st,V);
      Put(st);
      new_Line(1);

      Put("decrypted: ");
      st:=decrypt_caesar(st,V);
      Put(st);
      new_Line(1);

      Put("before encryption with vigenere: ");
      Put(st2);
      new_Line(1);

      Put("encrypted: ");
      st2:=encrypt_vigenere_with_numbers(st2,V);
      Put(st2);
      new_Line(1);

      Put("deecrypted: ");
      st2:=decrypt_vigenere_with_numbers(st2,V);
      Put(st2);
      new_Line(1);

      Put("before encryption with position: ");
      Put(st3);
      new_Line(1);

      Put("encrypted: ");
      st3:=encrypt_with_pos(st3);
      Put(st3);
      new_Line(1);
    end;
end crypto_demo;

So this is working for Upper letters but not for lower letters but im using the same method. The problem must be in my shift char function. Anyone have any idea?

Thank you PL



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

why dropdrow menu is not in the center

I need my dropdown menu under About menu and align in center of about menu. And when my site in moblie size dropdown are not in the center, They are on the right of site. I tried to coding dropdown link1hhh, link2, link3 to be the center but it's not align. What's wrong about html, css code so I want Dropdown be like this. enter image description here enter image description here Thanks

const body = document.querySelector("body");
const navbar = document.querySelector(".navbarr");
const menuBtn = document.querySelector(".menu-btn");
const cancelBtn = document.querySelector(".cancel-btn");
menuBtn.onclick = ()=>{
  navbar.classList.add("show");
  menuBtn.classList.add("hide");
  body.classList.add("disabled");
}
cancelBtn.onclick = ()=>{
  body.classList.remove("disabled");
  navbar.classList.remove("show");
  menuBtn.classList.remove("hide");
}
window.onscroll = ()=>{
  this.scrollY > 20 ? navbar.classList.add("sticky") : navbar.classList.remove("sticky");
}
.navbarr{
  padding-top: 85px;
  padding-bottom: 30px;
  background: #ffffff;
  position: sticky;
  top: 0;
  width: 100%;
  z-index: 2;
  transition: all 0.3s ease;
}
.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;

}
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;

}
.dropdown:hover .dropdown-content {
  display: block;
  }
.navbarr.sticky{
  background: #ffffff;
  padding: px 0;
  box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.1);
}
.navbarr .content{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.navbarr .logo a{
  color: #000000;
  font-size: 30px;
  text-decoration: none;
}
.navbarr .menu-list{
  display: inline-flex;
}
.menu-list li{
  list-style: none;
}
.menu-list li a{
  color: #000000;
  margin-left: 25px;
  text-decoration: none;
  font-weight: normal;
  transition: all 0.3s ease;
}

.icon{
  color: #000000;
  font-size: 25px;
  cursor: pointer;
  display: none;
}
.menu-list .cancel-btn{
  position: absolute;
  right: 80px;
  top: 110px;
}
@media (max-width: 1230px) {
  .content{
    padding: 0 60px;
  }
}
@media (max-width: 1100px) {
  .content{
    padding: 0 40px;
    margin-left: 5%;
    margin-right: 5%;
  }
}
@media (max-width: 900px) {
  .content{
    padding: 0 40px;
    margin-left: 0%;
    margin-right: 0%;
  }
  .menu-list .cancel-btn{
    position: absolute;
    right: 50px;
    top: 110px;
  }
}
@media (max-width: 1000px) {
  body.disabled{
    overflow: hidden;
  }
  .icon{
    display: block;
  }
  .icon.hide{
    display: none;
  }
  .navbarr .menu-list{
    position: fixed;
    height: 100vh;
    width: 100%;
    max-width: 100%;
    right: -100%;
    top: 0px;
    display: block;
    padding: 100px 0;
    text-align: center;
    background: rgb(255, 255, 255);
    transition: all 0.3s ease;
  }
  .navbarr.show .menu-list{
    right: 0%;
  }
  .navbarr .menu-list li{
    margin-top: 45px;
  }
  .navbarr .menu-list li a{
    font-size: px;
    margin-right: -100%;
  }
  .navbarr.show .menu-list li a{
    margin-right: 0px;
  }
}
<nav class="navbarr">
      <div class="content">
        <div class="logo">
          <a href="#"><img src="" width="80" height="80" alt="" /></a>
        </div>
        <ul class="menu-list">
          <div class="icon cancel-btn">
            <i class="fas fa-times"></i>
          </div>  
          <li><a href="menu.html">Menu</a></li>
          <li class="dropdown">
            <a href="javascript:void(0)" class="dropbtn">About</a>
            <div class="dropdown-content">
              <a href="#">Link 1hhh</a>
              <a href="#">Link 2</a>
              <a href="#">Link 3</a>
            </div>
          <li><a href="Contact.html">Contact</a></li>
        </ul>
        <div class="icon menu-btn">
          <i class="fas fa-bars"></i>
        </div>
      </div>
    </nav>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
          <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet">


from Recent Questions - Stack Overflow https://ift.tt/3xCLvHE
https://ift.tt/3nxhofQ

Problem with iteration over PolynomialFeatures

I am trying to code a for loop that iterates over the degrees of the polynomial and returns the r2 score. Below is my code:

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error

X_data=data[["Horsepower", "Peakrpm","Enginesize","Wheelbase","Compressionratio"]]
y_data = log_data

s = StandardScaler()

X_train, X_test, y_train, y_test = train_test_split(X_data, y_data,test_size=0.3,random_state=42)
X_train = s.fit_transform(X_train)
X_test = s.transform(X_test)

print(X_train.shape)
print(y_train.shape)
for i in range(3):
    poly = PolynomialFeatures(degree=i,include_bias=False, interaction_only=False)
     
    X_train=pd.DataFrame(poly.fit_transform(X_train),
    columns=poly.get_feature_names(input_features=data.columns))
    lr_poly=LinearRegression().fit(X_train,y_train)
    print(lr_poly.score(X_train,y_train))

and i am getting this error

could not broadcast input array from shape (143,5) into shape (143,0)

Should i do a reshape somewhere to X_train?

I understand that X_train gets different shape over the iterations because of the degree polynomial, but since it only gets more columns, why is this error keeps popping up?



from Recent Questions - Stack Overflow https://ift.tt/32ZTbFK
https://ift.tt/eA8V8J

Perl Regex Matching expressions without set of strings [closed]

I need a Perl Regex to match expressions that not have any string from a set of strings

As a example, suppose the set of strings {"red", "blue", "white"}

"A blue sky" Not matching the rule "A green house" Match the rule

The regex (red|blue|white) match the rule when a string is present, but I need the opposite



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

َIs it correct to speak of receiver operating curve (ROC) for k-nearest neighbor algorithm?

As far as I know, the ROC is plotted by changing the decision threshold, calculating FPR and TPR for each value of the decision threshold, and plotting the (FPR, TPR) points. I understand how that process is done in, for example, a Bayesian decision-making algorithm since it is clear that what is the "decision threshold" the Bayesian decision-making theory (the decision threshold locates on the point where the two discriminant functions are equal). Regarding that, I cannot understand what is the decision threshold in the KNN algorithm. without any decision threshold, how it is possible to draw a ROC? I will appreciate it if somebody could answer me.



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

How to run FreeRTOS on TM4C129EXL?

I am working on a C project for the university where a CoAP server is to be hosted on a TM4C129EXL. It is particularly important to choose a FreeRTOS operating system. Unfortunately, I had to learn that Texas Instruments has stopped supporting FreeRTOS. There are no options for me to switch to another operating system. It is for this reason that I turn to you.

I'm looking for a sample program in which Free RTOS is executed on a TM4C129EXL board. In the best case, I would be happy about a Code Composer Studio Project, as this is the IDE we work with from the university.

If you do not have any sample code available, I would be happy to receive any other information regarding FreeRTOS and CoAP of course with reference to the TM4C129EXL.



from Recent Questions - Stack Overflow https://ift.tt/32JLKCp
https://ift.tt/eA8V8J

2021-04-29

Using shinyjs delay to delay running a code by a calculate amount of milliseconds

I am trying the code below using delay from shinyjs package. What I am expecting is to show the modal AND play the audio after a predefined time from running the app (5 seconds in this example). I only can see the modal but audio is not playing. any guidance on what might be wrong?

thank you



library(shiny)
 
library(shinyjs)
 
ui <- fluidPage(
  useShinyjs(),
  h2(textOutput("currentTime")),
  br(),
  br(),
  h2(textOutput("target1")),
  h2(textOutput("till1")), 
  uiOutput('my_audio1')
 
)



server <- function(input, output, session) {
  
  
  
  output$currentTime <- renderText({
    invalidateLater(1000, session)
    paste("The current time is", format(Sys.time(), "%H:%M"))
  })
  
  t1 <- isolate({
    Sys.time() + 5
    
  })
 
  
  output$target1 <- renderText({
    
    paste("Target", t1)
  })
 
  
  output$till1 <- renderText({
    invalidateLater(1000, session)
    
    paste("Seconds till target:", round (t1-Sys.time()))
  })
 
  
  sys1 = isolate({
    Sys.time()
  })
  
  observe({
    print(sys1)
    print(t1)
    print(t1-sys1)
    print(as.numeric(t1-sys1, units = "secs")*1000)
  })
  
  
    
  observe ({
    delay (as.numeric(t1-sys1, units = "secs")*1000, 
           showModal(modalDialog(
             title = "",
             "Audio should play now"))  
    )
  })
  
 
  
  observe({
    delay (as.numeric(t1-sys1, units = "secs")*1000, 
  output$my_audio1 <-renderUI({
               tags$audio(src = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3", 
                          type = "audio/mp3", autoplay = NA, controls = NA, style="display:none;")
    })
  )
  })
  
  
 
}

# Create Shiny app ----
shinyApp(ui, server)




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

Auto update app desktop python with Pyqt5 and AWS RDS

I want to launch a desktop application to run customer records for my sister at work,

  • We are actually using local storage with sqlite3, but I will switch to AWS RDS sql

The application uses these packages:

from PyQt5 import uic,QtWidgets 

from reportlab.pdfgen import canvas

import sqlite3, csv

Our biggest problem is the update in the application that for each new functionality needs a new installation,

The packages I want to send in the update can contain .ui files,

I try unsuccessfully to use:

-Updater4pyi -PyUpdater -Esky

Esky seemingly out of phase and do not support some configurations and I believe that the tools doesn't work correctly freezing the app to .exe because de .ui files,

What is the possible solution to this issue?

Thank you in advance

Setup.py

import esky.bdist_esky
from esky.bdist_esky import Executable as Executable_Esky
from cx_Freeze import setup, Executable
include_files = ['consulta2.ui']
setup(
    name = 'cadastro',
    version = '1.0',
    options = {
        'build_exe': {
            'packages': ['sqlite3','csv'],
            'excludes': ['tkinter','tcl','ttk'],
            'include_files': include_files,
            'include_msvcr': True,
        },
        'bdist_esky': {
            'freezer_module': 'cx_freeze',
        }
    },
    data_files = include_files,
    scripts = [
        Executable_Esky(
            "controle.py",
            gui_only = False,
            #icon = XPTO #Coloque um icone aqui se quiser ,
            ),
    ],
    executables = [Executable('controle.py',base='Win32GUI')]
    )


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

Creating new user changes ansible tmp directory

I have a piece of ansible script which was running fine.

  user:
    name:     ""
    password: ""
    group:   ""
    groups:   ""
    uid:      ""
  with_items:
    - { name: perf, password: "", group: "perf",   groups: "perf", uid: 23564 }
    - { name: ora,   password: "",   group: "ora",     groups: "ora",          uid: 9965 }

The first user gets created as expected. The second user fails with the following error stating that tmp is not accessible.

"msg": "Failed to create temporary directory.In some cases, you may have been able to authenticate and did not have permissions on the target directory. 
Consider changing the remote tmp path in ansible.cfg to a path rooted in \"/tmp\", for more error information use -vvv. 
Failed command was: ( umask 77 && mkdir -p \"` echo /home/perf/.ansible/tmp `\"&& mkdir \"` echo /home/perf/.ansible/tmp/ansible-tmp-1619654689.74-17782-45103910875996 `\" 
&& echo ansible-tmp-1619654689.74-17782-45103910875996=\"` echo /home/perf/.ansible/tmp/ansible-tmp-1619654689.74-17782-45103910875996 `\" ), exited with result 1", "unreachable": true}], "warnings": ["The input password appears not to have been hashed. The 'password' argument must be encrypted for this module to work properly."]

Why is the ansible temp directory changed to /home/perf after a new user is created?



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

I am trying to format a user input first and last name as "Lastname, Firstname" Thank you in Advance

This is what I have so far. I have 90% of what I am trying to do just can't figure out how to properly format into "Lastname, Firstname" I am super new to assembly so I apologize if it is not perfect

global  _main
extern  _printf
extern  _scanf
extern  _fgets
extern  _TrimRight
extern  ___acrt_iob_func
extern  _ExitProcess@4

section .bss
Name: resw 1    ; Reserve space for your first name and last name values


section .data
prompt: db 'Enter Name: ',0
output: db 'Your Name is: .', 0ah,0
frmt:   db '%d',0   ; Define your format strings here

section .text
_main:

        push   prompt       ;  push the prompt string and call printf
        call   _printf
        add    esp, 4       ;  restore the stack pointer

        ; scanf("%d", Name);
        push   Name         ;  push the scanf parameters and call scanf
        push   frmt
        call   _scanf       
        add    esp, 8       ;  restore the stack pointer

        
       
BEGIN:    

        
        push  ecx
        push  dword [Name]
        push  dword [Name]
        
        push  output
        call  _printf
        add   esp, 8
        pop   ecx

        ; exit the program
        xor    ecx, ecx
        call    _ExitProcess@4


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

Google OAuth login in .NET Core / .NET 5 without using Identity

I'm having some trouble setting up Google as an external login provider in .NET 5 MVC app when not using Identity. External login using Facebook DOES work correctly, but external Google login DOES NOT. Twitter logins also do not work, but for the purposes of this question, lets focus on Google.

I have tested this on a small repro application that used Identity and both login providers worked correctly, so I'm assuming this is related to Identity not being used.

This is my current set up:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
            options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
            options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
        })
        .AddCookie(IdentityConstants.ApplicationScheme)
        .AddCookie(IdentityConstants.ExternalScheme)
        .AddFacebook(options =>
        {
            options.AppId = "{FacebookClientId}";
            options.AppSecret = "{FacebookClientSecret}";
        })
        .AddGoogle(options =>
        {
            options.ClientId = "{GoogleClientId}";
            options.ClientSecret = "{GoogleClientSecret}";
        });

    // ...
}

AccountController.cs

[HttpPost]
public ActionResult LoginExternal(string providerName, string returnUrl)
{
    var externalLoginCallbackUri = Url.Action("LoginExternalCallback", "Account", new { returnUrl });
    var properties = ConfigureExternalAuthenticationProperties(providerName, externalLoginCallbackUri);
    return Challenge(properties, providerName);
}

[HttpGet]
public async Task<ActionResult> LoginExternalCallback(string returnUrl)
{
    var loginInfo = await GetExternalLoginInfoAsync();
    if (loginInfo == null)
        return ExternalLoginFailed();

    // ...
    // gets no further
}

There are a couple of private methods in use above that are just copied from SignInManager:

private const string LoginProviderKey = "LoginProvider";
private const string XsrfKey = "XsrfId";

// SignInManager.GetExternalLoginInfoAsync()
private async Task<ExternalLoginInfo> GetExternalLoginInfoAsync(string expectedXsrf = null)
{
    var auth = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
    var items = auth?.Properties?.Items;
    if (auth?.Principal == null || items == null || !items.ContainsKey(LoginProviderKey))
    {
        return null;
    }

    if (expectedXsrf != null)
    {
        if (!items.ContainsKey(XsrfKey))
        {
            return null;
        }

        var userId = items[XsrfKey] as string;
        if (userId != expectedXsrf)
        {
            return null;
        }
    }

    var providerKey = auth.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
    var provider = items[LoginProviderKey] as string;
    if (providerKey == null || provider == null)
    {
        return null;
    }

    var schemes = (await _authenticationSchemeProvider.GetAllSchemesAsync())
        .Where(x => !string.IsNullOrEmpty(x.DisplayName));

    var providerDisplayName = schemes.FirstOrDefault(p => p.Name == provider)?.DisplayName
                              ?? provider;
    return new ExternalLoginInfo(auth.Principal, provider, providerKey, providerDisplayName)
    {
        AuthenticationTokens = auth.Properties.GetTokens(),
        AuthenticationProperties = auth.Properties
    };
}

// SignInManager.ConfigureExternalAuthenticationProperties()
private AuthenticationProperties ConfigureExternalAuthenticationProperties(string provider, string redirectUrl, string userId = null)
{
    var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
    properties.Items[LoginProviderKey] = provider;
    if (userId != null)
        properties.Items[XsrfKey] = userId;

    return properties;
}

When the user initiates a POST to /account/loginexternal?providerName=Google, they're shown the OAuth Google account selector, the user selects their account and a request is made to /account/loginexternalcallback.

At that point, when var auth = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme); is called the result indicates that the authentication was unsuccessful:

enter image description here

I'm a bit in the dark as to why this occurs. Is there a way to debug this process and determine why the authentication failed?

As far as I can tell, I've set up the credentials correctly in the Google Console (again, noting that this works when running using Identity):

enter image description here

Microsoft does have some docs on integrating social sign-in providers (Google specifically), but it doesn't delve in to the subject in enough detail to provide insight in to this problem. Other documentation relies on Identity, which I'm not using.

Am I doing something stupid here? The fact that Facebook login works is really throwing me off.



from Recent Questions - Stack Overflow https://ift.tt/3dYJ2PF
https://ift.tt/3e3efl4

Retrieving struct from array not working? [closed]

I am working on implementing an input manager on top of the Windows API. I have a struct name ButtonState that stores if a key is currently down and if it has changed within that frame. I have an array of these structs for all the supported buttons and I use the Windows defined VK_XXX codes to index that array. I update these structs properly, but when I try to access them through a function, it always returns false. I've run through it literally tens of times with the debugger trying to figure out what's happening but to no avail. Here is a photo of proof that I'm not crazy and that the values in the struct are in fact true but it returns false:

enter image description here

Here is the original method:

const bool Input::KeyDown(U32 keyCode)
{
    return buttonStates[keyCode].isDown;
}

Called using:

Input::KeyDown(VK_DOWN)


from Recent Questions - Stack Overflow https://ift.tt/3e1XtCU
https://ift.tt/3u1CZzr

how to create outputs for key points of bounding boxes on image in Neural network in Python

I've made a convolutional neural network which can classify one object on image (220, 220). The objects classes are only two - dogs and cats. I have 3385 '.jpg' pictures of dogs and cats on my PC. I have information about class of each object (1 or 0). Also I have information about two corners coordinates (from 0.0 to 1.0) of bounding boxes (0.0 is left/top corner of image and 1.0 is right/bottom corner of image) around of the objects. Convolutional net must have 5 outputs (1 output for classes and 4 outputs for two corners coordinates: x1,y1,x2,y2). I have 3047 train images 'x_train' shape (3047, 220, 220, 3) and labels information in 'y_train' shape (3047, 5). Also 338 test images in 'x_test' shape (338, 220, 220, 3) and test labels in 'y_test'. For example, y_train[0] has such elements array([1. , 0.555 , 0.18 , 0.70833333, 0.395 ]). But my neural network have such prediction results prediction[0] is array([1., 0., 0., 0., 0.], dtype=float32). And np.sum(prediction) is 338.0 which is number of test images. During the training parameters increased from 'loss: 4.8534 - accuracy: 0.5938' to 'loss: 533785.6875 - accuracy: 1.0000'. Could anyone help me with an advice what do I do wrong?

#Summary:
#Model: "sequential_1"
#conv2d_2 (Conv2D)            (None, 220, 220, 32)      896       
#max_pooling2d_2 (MaxPooling2 (None, 110, 110, 32)      0 
#conv2d_3 (Conv2D)            (None, 110, 110, 64)      18496     
#max_pooling2d_3 (MaxPooling2 (None, 55, 55, 64)        0         
#flatten_1 (Flatten)          (None, 193600)            0         
#dense_2 (Dense)              (None, 128)               24780928  
#dense_3 (Dense)              (None, 5)                 645 
#Total params: 24,800,965
#Trainable params: 24,800,965
#Non-trainable params: 0

import os
import cv2
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras.layers import Dense, Flatten, Dropout, Conv2D, MaxPooling2D
import time

model = keras.Sequential([
    Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=(220, 220, 3)),
    MaxPooling2D((2, 2), strides=2),
    Conv2D(64, (3, 3), padding='same', activation='relu'),
    MaxPooling2D((2, 2), strides=2),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(5, activation='softmax')
])

print(model.summary())
model.compile(optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy'])
his = model.fit(x_train, y_train, batch_size=32, epochs=2, validation_split=0.5)
model.evaluate(x_test, y_test)
prediction = model.predict(x_test)
print(np.sum(prediction))
# >>> 338.0


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

Switch Vue3 (PrimeVue) theme on load and click

Recommend way of including themes is by import in main.js file at root of the app:

import 'primevue/resources/themes/arya-orange/theme.css';

But I'm look for a way to switch CSS file based on user system theme and on user selection so i moved this in my main App.vue:

export default {
  name: "App",
  components: {
    HelloWorld,
    toDo,
  },
  mounted() {

    //window.matchMedia('(prefers-color-scheme: dark)').matches ? do dark : do light
  },
};

<style>
@media (prefers-color-scheme: dark) {
  @import url("assets/themes/arya-orange/theme.css");
}
@media (prefers-color-scheme: light) {
  @import url("assets/themes/arya-orange/theme.css");
}
</style>

I can not import anything inside mounted and in styles tag I can not import inside media also, both are not correct way of usage.

I can not find any other way online or guidance to solve this. All solutions are based on scoping components, using classes etc.

I could wrap all rules in one theme to

@media (prefers-color-scheme: dark) {

and another for light. But then again how could I switch on user selection?

Please advise.

EDIT:

I figured it out how can I do it on load:

(async () => {
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    await import('primevue/resources/themes/arya-orange/theme.css');
  }else {
    await import('primevue/resources/themes/saga-blue/theme.css');
  }
})();

If someone can advise how to do it on click.



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

Setting inset on NSTextView

I have a textview setup in a scrollview (using code not storyboard).

// 1. Text Storage
    let attrs = Style.body.attributes
    let attrString = NSAttributedString(string: text, attributes: attrs)
    textStorage = NSTextStorage(attributedString: attrString)
    
    // 2. Layout manager.
    layoutManager = LayoutManager()
    textStorage.addLayoutManager(layoutManager)
    layoutManager.delegate = self
    
    // 3. Layout Manager
    let containerSize = CGSize(width: self.bounds.width, height: .greatestFiniteMagnitude)
    let textContainer = NSTextContainer(size: containerSize)
    textContainer.widthTracksTextView = true
    layoutManager.addTextContainer(textContainer)
    
    // 4. TextView
    textView = NSTextView(frame: self.bounds, textContainer: textContainer)
    textView.delegate = self
    textView.typingAttributes = Style.body.attributes
    
    // 5. ScrollView
    scrollView = NSScrollView()
    scrollView.borderType = .noBorder
    scrollView.hasVerticalScroller = true
    scrollView.backgroundColor = .clear
    scrollView.drawsBackground = false
    scrollView.contentView.backgroundColor = .clear
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.borderType = .noBorder
    scrollView.hasVerticalScroller = true
    scrollView.documentView = textView
    
    // 6. Layout and sizing
    textView.minSize = NSSize(width: 0.0, height: scrollView.contentSize.height)
    textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
    textView.isVerticallyResizable   = true
    textView.isHorizontallyResizable = false
    textView.autoresizingMask = .width 
    

I want to add an inset around the textview so the scrollview bar doesn't cover my text. What is the best approach?



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

Using an input box and msg box to search for data in excel VBA

I'm working on a sub that requires me to make it so that a user can search for their ProductID with an input box and then let them know with a msgbox whether it was or was not found, but I can't get the code right. What am I doing wrong here? Totally lost (code below):

Sub test()

    Dim Worksheet As Range
    Dim ProductID As Variant

    ProductID = InputBox("Please enter the Product ID")

    With Worksheets(1).Range("A1:Z1000")
        Set ProductID = .Find("ProductID", LookIn:=xlWhole)

        If found Then
            MsgBox ProductID("was Found")
        Else
            MsgBox ProductID & (" was NOT Found")
        End If

    End With
End Sub


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

Discord.py Multi Ban

So I know that there are other solutions to solve this, but I want to incorporate the actual function into my on_message decorator. I can't get anything to work. I started with creating a parser to parse through the message so: my.ban @Tim @Tony @Trent --> ['tims_id',"tony's_id",'trents_id'] which worked.

Then I plugged it into a function I made which is supposed to return a list of member objects with those id's with client.get_user(user_id) which was buggy.

Finally the part that is causing the most trouble is actually running a ban command, not only is my command not working, but it's not taking the member object as a argument. Here is all of the code that pertains to these issues.

If someone could give me some pointers in the right direction or just offer a different approach in general, that would be greatly appreciated.

PARSER

def get_ids(message):
    message = message.replace("<","");message = message.replace(">","");message = message.replace("@","");message = message.replace("!","")
    message = message.split()
    for thing in message:
        if thing.isdigit():
            message[message.index(thing)] = message[message.index(thing)] + " "
            continue
        else:
            del message[message.index(thing)]
    message[0] = message[0] + " "
    message = "".join(message)
    message = message.split(" ")
    del message[-1];
    return message

PROPER COMMAND SYNTAX RECOGNITION

def is_calling_command(message_content,*command_names,current_channel=None,allowed_channel=None,prefix="my."):
    command_names = [x for x in command_names]
    for x in range(len(command_names)):
        command_names[x] = command_names[x].lower()
    message_content = message_content.lower()
    
    if current_channel is None and allowed_channel is None:
            for command_name in command_names:
                if not (prefix + command_name in message_content):
                    return False
            return True
    elif current_channel == allowed_channel:
        for command_name in command_names:
            if not (prefix + command_name in message_content):
                return False
        return True                 
    
    else:
        return False

ID TO OBJECT CONVERTER

def get_member_objects(message):
        objects = []
        ids = get_ids(message)
        for id in ids:
            objects.append(client.get_user(id))
        return objects

BAN COMMAND

@client.event
async def on_message(message):
if is_calling_command(message.content,"ban",current_channel=message.channel.id,allowed_channel=message.channel.id) and message.channel.permissions_for(message.author).administrator:
        connection = client.get_channel(message.channel.id)
        print(get_member_objects(message.content))
        for obj in get_member_objects(message.content):
            await client.ban(obj, reason="cause we said so")
            await connection.send("Banned!")

Here is the error message I'm getting [ERR_MSG][1] [1]: https://ift.tt/3gLPtrb



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

Xcode 12.5 - Packages cannot get information from info.plist

I recently updated my Xcode to version 12.5 and for some reason all of a sudden none of my packages were building correctly and producing errors. To fix this I removed the packages and added them back, which solved the build errors.

However now when I try to log into Facebook on my application using this package FacebookLogin I am presented with the error "App ID not found. Add a string value with your app ID for the key FacebookAppID to the Info.plist or call [FBSDKSettings setAppID:].'

I have tried to manually configure this but still run into issues with the URL Scheme.

Has anyone encountered any similar issues as me and knows a way to resolve this?

Thanks in advance.

EDIT: I downloaded Xcode 12.4 again and used a previous commit and was able to get my code working. It seems that are some errors on how Xcode 12.5 uses previous packages. For reference I am using Firebase (7.9.1) and Facebook (8.2.0)



from Recent Questions - Stack Overflow https://ift.tt/32XGTh0
https://ift.tt/eA8V8J

Is it possible to delete a foreign key using @DeleteMapping in java spring hibernate?

In other words change it to null on click. My reason for this is I have a main employees list and employees assigned to a project. I want to figure out a way to remove employees from the projects list without deleting them from the main total employees list as well.

For example this deletes an employee from the main list.

    @DeleteMapping("/jpa/users/{username}/employees/{employeeId}")
    public ResponseEntity<Void> deleteEmployee(
            @PathVariable String username, @PathVariable Long employeeId) {

        employeeJpaRepository.deleteById(employeeId);

        return ResponseEntity.noContent().build();
    }

But how do I delete the foreign key (projectId) of @DeleteMapping("/jpa/users/{username}/projects/{projectId}/employees/{employeeId}")?



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

Index mapping request in ElasticSearch using NEST in C#

I need to create an index with mapping using a json string provided from the input. I am trying to pass the json mapping string in a lowlevel client since my usecase has a long list of mappings which I can not do using a high-level client. However, it is creating a null mapping with the lowlevel client I am using. Below is a simple example of my mapping json string.

mappingString = {
"mappings" : {  
"exchangeid" : {
          "type" : "double"
        }
}

Below is the code snippet which I am using to create an index and then lowlevel request to create the mapping.

        CreateIndexResponse createIndexResponse = ElasticAccessor.Client.Indices.Create(IndexName, c => c
        .InitializeUsing(indexConfig));

        // Put mapping request
        StringResponse putMappingRequest = ElasticAccessor.Client.LowLevel.DoRequest<StringResponse>(HttpMethod.PUT, 
            "/" + IndexName + "/_mapping", 
            PostData.String(this.mappingString));

Any help or suggestion is greatly appreciated.



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

How to calculate sum of first cell [a1] in multiple excel files

I am trying to create a method that retrieves the first value of each csv file within a folder. Each csv file within the main directory contains a number in position a1 of the excel file. I want to get this number from each file in the directory, convert it to an int (as they are stored as a string in excel), calculate the sum of all numbers, and store it as an int variable.

I have this method here that gets all of the files, but I'm not sure how I implement a statement that reads the first value, converts it to int, then gets the sum.

public void LoadCashFlow()
{
    string path = @"C:\temp\CashFlow\";
    string[] fileEntries = Directory.GetFiles(path);
foreach (string fileName in fileEntries)
{
    //Get first value [a1]
    //Convert to int
    //Get sum of all values
    //Store as variable
}
}

How might I achieve this?

Edit: This is what I have tried:

public void LoadCashFlow()
{
    string path = @"C:\temp\CashFlow\";
    string[] fileEntries = Directory.GetFiles(path);

    foreach (string fileName in fileEntries)
    {
        // do something with fileName
        string[] lines = File.ReadAllLines(fileName);
        string[] data;


        for (int i = 0; i < lines.Length; i++)
        {
            data = lines[i].ToString().Split(',');

            string[] row = new string[data.Length];

            for (int j = 0; j < data.Length; j++)
            {
                row[j] = data[j].Trim();
            }
            int value = System.Convert.ToInt32(data.ToString());
            int sum = "Something here";
        }
    }
}


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

How do you tell the Apache Arrow Format Version for a given Library Version?

Apache Arrow in their documentation list that each release has two versions, a Library Version and a Format Version: https://arrow.apache.org/docs/format/Versioning.html

It appears that over the last year there have been 4 Library Versions, but it's hard to tell if the format version has changed in any of these Library Versions. Is there a way to tell what the Format Version is for a given Library Version?



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

What is the simplest way to create python flask swagger

I have written python program with some flask rest logic, and I want to know what is the easiest way to create flask swagger from it? I saw many tutorials with different packages but in my opinion they include too much manual work. Is there a package which does in 1 or 2 steps?



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

how fix error 500 with flask in apache windows 10

i'm trying to run a simple flask application on apache24 but in the end i get Internal server error, i'm going to attach my configuration files and code.

httpd.conf

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

at end file im add this:

AddHandler wsgi-script .wsgi
ScriptInterpreterSource Registry-Strict

LoadFile "c:/program files/python39/python39.dll"
LoadModule wsgi_module "c:/program files/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd"
WSGIPythonHome "c:/program files/python39"

httpd-vhost.conf:

<VirtualHost *>
    WSGIScriptAlias /SISPRAA "C:/Apache24/htdocs/SISPRAA/main.wsgi"
    <Directory "C:/Apache24/htdocs/SISPRAA">
        Require all granted
        Options Indexes FollowSymLinks Includes ExecCGI
    </Directory>
</VirtualHost>

this is my app.py

from flask import Flask, render_template
from flask_material import Material
from flask_fontawesome import FontAwesome
from pathlib import Path
from flask import send_file
import os
import re
import datetime
from lib.pyReportInfinited import init
from flask import jsonify 


app = Flask(__name__)
Material(app)
fa = FontAwesome(app)
downloads_path = str(Path.home() / "Downloads")

@app.route('/')
def index():
    return render_template('index.html')



@app.route('/makeReport', methods=["GET", "POST"])
def makeReport():

    #print ("init..")
    init()
    return jsonify(msg='end')


if __name__ == "__main__":
    app.run()

this is main.wsgi:

import sys
sys.path.insert(0, "C:/Apache24/htdocs/SISPRAA/")

from app import index as application

this result error 500 internal server :

enter image description here

if i commet last line error not found:

enter image description here

if i navigate to localhost only, its okay:

enter image description here

apache error.log

AH00558: httpd.exe: Could not reliably determine the server's fully qualified domain name, using fe80::d972:78ad:5f99:ed39. Set the 'ServerName' directive globally to suppress this message
[Wed Apr 28 19:11:52.022705 2021] [core:warn] [pid 8264:tid 680] AH00098: pid file C:/Apache24/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Wed Apr 28 19:11:52.022705 2021] [mpm_winnt:notice] [pid 8264:tid 680] AH00455: Apache/2.4.46 (Win64) mod_wsgi/4.7.1 Python/3.9 configured -- resuming normal operations
[Wed Apr 28 19:11:52.022705 2021] [mpm_winnt:notice] [pid 8264:tid 680] AH00456: Apache Lounge VS16 Server built: Mar 27 2021 11:42:37
[Wed Apr 28 19:11:52.022705 2021] [core:notice] [pid 8264:tid 680] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24'
[Wed Apr 28 19:11:52.022705 2021] [mpm_winnt:notice] [pid 8264:tid 680] AH00418: Parent: Created child process 15872
AH00558: httpd.exe: Could not reliably determine the server's fully qualified domain name, using fe80::d972:78ad:5f99:ed39. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd.exe: Could not reliably determine the server's fully qualified domain name, using fe80::d972:78ad:5f99:ed39. Set the 'ServerName' directive globally to suppress this message
[Wed Apr 28 19:11:52.428805 2021] [mpm_winnt:notice] [pid 15872:tid 784] AH00354: Child: Starting 64 worker threads.
[Wed Apr 28 19:11:57.598808 2021] [wsgi:error] [pid 15872:tid 1288] [client ::1:54512] mod_wsgi (pid=15872): Exception occurred processing WSGI script 'C:/Apache24/htdocs/SISPRAA/main.wsgi'.
[Wed Apr 28 19:11:57.598808 2021] [wsgi:error] [pid 15872:tid 1288] [client ::1:54512] TypeError: index() takes 0 positional arguments but 2 were given\r

can anybody help me ? pls



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

Converting 4 hex bytes to RGBA color

I have an 512x512 image file that uses every 4 bytes for a RGBA pixel. Here's an example:

1F 8B 08 00

The first (R), second (G), and third (B) bytes represent the RGB values, with each value ranging from 0 to 255. The last byte (A) represents the alpha channel, also ranging from 0 to 255. If I want a opaque pixel I must replace the last byte with FF (255 when converted to decimal). Once I converted the 4 bytes into RGBA I can use PIL to create the image, with the first 4 bytes being a pixel located in the upper left corner.

Now here is the 4 bytes, converted into a 1x1 RGBA pixel manually: image

And here's the pixel's RGBA values, based on the 4 bytes:

199(R) 239(G) 125(B) 213(A)

Basically, each byte should be converted into a number ranging from 0 to 255, with each 4 bytes being an RGBA value. I can put these values into a tuple, iterating every 4 values as an RGBA pixel, with the first pixel being on the upper left corner of the image.



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

Real time stdout redirect from a python function call to an async method

So I have a heavy time-consuming function call my_heavy_function and I need to redirect that output to a web interface that is calling it, I have a method to send messages to the web interface, let's called that method async push_message_to_user().

basically, it's something like

import time 

def my_heavy_function():
    time_on = 0 
    for i in range(20):
        time.sleep(1)
        print(f'time spend {time_on}')
        time_on = time_on+1

async def push_message_to_user(message:str):
    # some lib implementation 
    pass

if __name__ == "__main__":
    my_heavy_function() # how push prints to the UI ?
    

maybe there is a way giving my_heavy_function(stdout_obj) and use that "std_object"(StringIO) to do something like stdout_object.push(f'time spend {time_on}'). I can do that, but what I can't change the my_heavy_function() by an async version, to add push_message_to_user() directly instead of the print (it's used by other non-ascyn routines)

what I would want it's something like (pseudocode)

with contextlib.redirect_output(my_prints):
    my_heavy_function()
    while my_prints.readable():
        # realtime push
        await push_message_to_user(my_prints)

Thanks!



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

Hangfire Recurring Jobs Break

I've got a HangFire setup in a .NET Core app. I've got several recurring jobs that are set to run every 15 minutes. In the Set table, when the scheduling is working correctly, you can see the next run time in Epoch format:

enter image description here

However, seemingly at random, the scheduling seems to die, looking more like this instead:

enter image description here

As per @Satpal's suggestion, I connected the dashboard and that has shed some more light on the situation.

System.TypeLoadException
Could not load type 'X.API.Controllers.YController' from assembly 'X.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

System.TypeLoadException: Could not load type 'X.API.Controllers.YController' from assembly 'X.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
   at System.Reflection.RuntimeAssembly.GetType(QCallAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext)
   at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
   at Hangfire.Common.TypeHelper.TypeResolver(Assembly assembly, String typeName, Boolean ignoreCase)
   at System.TypeNameParser.ResolveType(Assembly assembly, String[] names, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)
   at System.TypeNameParser.ConstructType(Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)
   at System.TypeNameParser.GetType(String typeName, Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)
   at System.Type.GetType(String typeName, Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError)
   at Hangfire.Common.TypeHelper.DefaultTypeResolver(String typeName)
   at Hangfire.Storage.InvocationData.DeserializeJob()

I know that the method being called by the recurring job is available and working currently, as manually rescheduling one of the failed jobs has worked as expected. My suspicion is the methods are unavailable when deploying updates - the period in which the app service is restarting is maybe enough for the jobs to fail, and die. I believe this is supported by a section I found in Hangfire's documentation, where it notes that:

background processing will be stopped after 10 retry attempts with increasing delay modifier

Two questions that I have regarding this are:

  1. What is the best way to be notified of job failure? A quick google seems to suggest adding logging to Hangfire and using an error log event to trigger an email? Is there a better way?
  2. Is there a way to automatically retrigger recurring jobs that've been stopped due to job failure?

Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3t0fDsC
https://ift.tt/3e08NiI

SQL Query that calculates 'free' or 'reserved' items in a collection

We are creating a inventory system for items called readoutprobes and readoutprobekits. See the schema below.

enter image description here

A readoutprobekit, is a predefined collection of 1 or more readoutprobes, i.e. a kit. In a kit, a specific type of a readoutprobe, can only occur once.

The inventory for readoutprobes are tracked by a readoutprobe_containers table, monitoring a containers volume.

The inventory for readoutprobekits, are tracked by a readoutprobekit_containers table. However, a readoutprobekit do not track physical readoutprobe containers. Instead, its assumed that a physical readoutkit is properly 'assembled' using a set of physical readoutprobes.

Getting the count of physical readoutprobe containers, with a volume > 0, for a specific readoutprobe, is obtained from the readoutprobe_container table, and the same for the kits

However, we want to get a 'reserved count' number, (or 'free') for each readoutprobe, reflecting the kits that do exist, and do contain a specific readoutprobe.

For example, say we got a readoutprobe, named A, having a count of 42. Now, when creating a specific readoutprobe kit containing a readoutprobe named A, we want to have a count of 'reserved' being 1, for readoutprobe A (or free = 41).

If there is a way of adding to the query for readoutprobes and their stock, that would be preferable.

The 'master query' for readoutprobes looks like this:

SELECT readoutprobes.*,     
    v.total_volume,
    stock_containers.stock_count,
    aliquots.aliquots_count
FROM readoutprobes
LEFT JOIN (
    SELECT p.id, COUNT(*) stock_count, stock_containers.readoutprobe_id
    FROM  readoutprobes AS p, readoutprobe_containers AS stock_containers
    WHERE p.id = stock_containers.readoutprobe_id AND stock_containers.volume > 0 AND stock_containers.parent_container IS NULL 
    GROUP BY p.id
    ) AS stock_containers
    ON stock_containers.readoutprobe_id = readoutprobes.id        
LEFT JOIN (
    SELECT p.id, COUNT(*) aliquots_count, aliquot_containers.readoutprobe_id
    FROM  readoutprobes AS p, readoutprobe_containers AS aliquot_containers
    WHERE p.id = aliquot_containers.readoutprobe_id AND aliquot_containers.volume > 0 AND aliquot_containers.parent_container IS NOT NULL
    GROUP BY p.id
    ) AS aliquots    
    ON aliquots.readoutprobe_id = readoutprobes.id        
LEFT JOIN (
    SELECT readoutprobes.id, COALESCE(SUM(pt.volume),0) total_volume
    FROM readoutprobes, readoutprobe_containers AS pt
    WHERE readoutprobes.id = pt.readoutprobe_id
    GROUP BY readoutprobes.id
    ) AS v
    ON readoutprobes.id = v.id
GROUP BY readoutprobes.id    
ORDER BY readoutprobes.id;

Regarding the above query, its only aliquot containers that can be used in 'kits'.



from Recent Questions - Stack Overflow https://ift.tt/2Pv6fQ6
https://ift.tt/3aGkARf

Convert the indices to slices or integers :" TypeError: list indices must be integers or slices, not str"

I have created lists from my data frame (df1)and I am trying to subtract the values(high tide and low tide) and plot them but keep getting stuck with the maximums. Here is my code:

import pandas as pd
import numpy as np
df1 = pd.read_csv (r'C:\Intel\Solinst-cleaned up\yellow.csv', skiprows = 13, encoding= 'unicode_escape', parse_dates=[['Date', 'Time']])

# Normal condition (From Jan 20th to Feb 11th)
start = 50     # First row to consider
stop = 3200     # Last row to consider
interval = 75  # The desired chunk size
x=df1['Date_Time'][50:125]

y1=[]
for i in range(start, stop, interval):
    y1.append(df1["Mlevel"][i:(i + interval)])
    
#y1 = y1.reset_index(drop=True)

hightide=[]   
for i in range(start, stop, interval):
    hightide=max(y1[1].loc[y1['Mlevel'][i:(i + interval)]])

And I get :

File "C:/Users/mr179/Desktop/Research/PhD/codes/test.py", line 42, in hightide=max(y1[1].loc[y1['Mlevel'][i:(i + interval)]])

TypeError: list indices must be integers or slices, not str



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

2021-04-28

Express POST request body is undefined

I've been working on troubleshooting a very simple application and cannot assess why the request body of POST is undefined. I have used express.json() and body-parser and changed the Content-Type of the request to different formats and have gotten nothing back.

This is the backend code relevant to the issue

const morgan = require("morgan");
const { response } = require("express");
const { format } = require("morgan");
const express = require("express");
const app = express();
const cors = require("cors");

app.use(express.static("build"));
app.use(cors());
app.use(express.json());
app.use(morgan("combined"));

app.post("/api/phonebook/", (req, res) => {
  const body = req.body;
  console.log(req.body);
  console.log(body.content);
  if (!body.name) {
    return res.status(404).json({
      error: "no name",
    });
  }

  const personObj = {
    name: body.name,
    phone: body.phone,
    id: generateId(),
  };

  phonebook = phonebook.concat(personObj);
  response.json(personObj);
});

And this is an example POST

POST http://localhost:3000/api/phonebook/
Content-Type: application/json

{
    "name": "Bob",
    "phone": 123-456
}

The server is up and running and doing GET and DELETE requests both work.



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

paramiko.ssh_exception.BadAuthenticationType throwing Authentication error and SFTP pull is also failing

I am receiving the error- "ERROR_SFTP_PULL, AUTHENTICATION ERROR Server connection dropped": -Normal passwordless sftp (get) is working to the remote server from my local server, however SFTP PULL is failing through Python script. It was running normal 4 days ago. Surprisingly, file copied from remote server to local server with same size. However, because of error exception script is doing sys exit. Please guide to resolve the issue. Also it takes less than 1 sec to copy the file , however taking 15 minutes to copy and error out.

It looks bad at below code part:

1.  authReturnCode = "<class 'paramiko.ssh_exception.BadAuthenticationType'>", not sure please help
2.  errorKey = "INFO_SFTP_PULL, "+ eachFiles + " successfully copyied from SFX for " + custName

Failure log:
===========
2021-04-26 15:00:02,459 INFO::ipndProxyApp.py:787: Processing data for: eDCP
2021-04-26 15:00:02,851 INFO::transport.py:1746: Connected (version 2.0, client SSHD)
2021-04-26 15:00:03,860 INFO::transport.py:1746: Authentication (publickey) successful!
2021-04-26 15:00:03,922 INFO::sftp.py:158: [chan 0] Opened sftp connection (server version 3)
2021-04-26 15:15:15,376 INFO::sftp.py:158: [chan 0] sftp session closed.
2021-04-26 15:15:15,491 ERROR::ipndProxyApp.py:119: ERROR_SFTP_PULL, AUTHENTICATION ERROR Server connection dropped:

Normal log is:
=============
2021-04-22 15:00:02,138 INFO::ipndProxyApp.py:782: Processing data for: eDCP
2021-04-22 15:00:02,256 INFO::transport.py:1746: Connected (version 2.0, client SSHD)
2021-04-22 15:00:02,563 INFO::transport.py:1746: Authentication (publickey) successful!
2021-04-22 15:00:02,586 INFO::sftp.py:158: [chan 0] Opened sftp connection (server version 3)
2021-04-22 15:00:09,999 INFO::sftp.py:158: [chan 0] sftp session closed.
2021-04-22 15:00:10,003 INFO::ipndProxyApp.py:122: INFO_SFTP_PULL, FILE_2021-04-21-18-00-35.txt successfully copied from SFX for eDCP

Python Code:
===========


    import os, sys, logging, shutil
    import pysftp, mysql.connector
    import subprocess, csv, argparse
    from datetime import datetime, timedelta
    import time
    
    # Importing Configuration settings or other supporting scripts
    import settings
    import SQLqueries
    import fieldLengthVerification
    
    # Static Configuration settings, logging settings, global variables
    logging.basicConfig(filename='/var/log/ipnd.log', format='%(asctime)s %(levelname)s::%(filename)s:%(lineno)d: %(message)s', dateformat='%Y-%m-%d %I:%M:%S',level=logging.INFO)
    currentDateTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    currentDate = datetime.now().strftime("%Y-%m-%d")
    yesterdays_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
    twoDaysBack = (datetime.now() - timedelta(days=2)).strftime("%Y-%m-%d")
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None
    
    
    # Handling Authentication errors for the SFT authentications only
    def errorHandling(errorFromProgram):
        """
        Function to handle authentication error for sftp only, it accepts exception errors and return string keyword.
    
        Parameters:
        errorFromProgram (class) : Error class generated by Exceptions
    
        Returns:
        str: str(errorFromProgram) or "Authentication Success" or "AUTHENTICATION ERROR " + str(errorFromProgram)
        """
    
        # This function to perform error handling and return string against the provided input  
        
        authReturnCode = "<class 'paramiko.ssh_exception.BadAuthenticationType'>"
    
        # Handling RHEL version of sftp (<class 'paramiko.ssh_exception.AuthenticationException'>)
        if str(errorFromProgram) == "Authentication failed.":
            errorKeyWord = str(errorFromProgram)
            return errorKeyWord
    
        # Handling SUSE version of sftp (<class 'paramiko.ssh_exception.BadAuthenticationType'>)
        elif str(type(errorFromProgram)) == authReturnCode:
            errorExcetption,a = errorFromProgram
            errorKeyWord = errorExcetption
            return errorKeyWord
    
        # Handling other situation then provious two
        elif (str(errorFromProgram) != "Authentication failed.") or (str(type(errorFromProgram)) != authReturnCode):    
            errorKeyWord = "AUTHENTICATION ERROR " + str(errorFromProgram)  
            return errorKeyWord
    
        # Handling other conditions if not handled in provious if and elif
        else:
                    infoKeyWord = "Authentication Success"
            return infoKeyWord
    
    
    # Fetch eDCP Data files from SFX sftp server
    
    def fetchFilesFromSftpLocation(custName, fileSrcHost, remoteFileLocation, fileSrcUser, fileSrcPassPhrase, dateToProcessFiles):
        """
        Function to fetch files from remove servers and store in location directory, return nothing and accept following parameters
    
        Parameters:
        custName (str): Customer Name.
        fileSrcHost (str): Hostname (FQDN) or IP address of the source server from where files would be fetched.
        fileLocation (str): Remote file location.
        fileSrcUser (str): User to connect remote server to fetch files.
        fileSrcPassPhrase (str): Password to connect remote server to fetch files.
        dateToProcessFiles (str): Date to fetch the files for   
        """
    
        # try to connect SFX server over sftp
        try:
            sftp = pysftp.Connection(fileSrcHost, username = fileSrcUser)
    
            # change to remote directory
            sftp.chdir(remoteFileLocation)
            listOfFilesAtSFX = sftp.listdir()
    
            for eachFiles in listOfFilesAtSFX:
                
                if eachFiles.startswith("IPNDUP" + custName.upper() +"_" + dateToProcessFiles):
                    
                    # Fetch files from SFTP
                    try:    
                        sftp.get(eachFiles)
                                            
                        **errorKey = "INFO_SFTP_PULL, "+ eachFiles + " successfully copyied from SFX for " + custName**
    
                    except Exception as e:
                        errorKey = "ERROR_SFTP_PULL, "+ errorHandling(e)
                        #print(errorKey)
    
            sftp.close()
    
        # Capture Exception
        except Exception as e:
            errorKey = errorHandling(e)
            errorKey = "ERROR_SFTP_PULL, "+ errorKey
    
    
            # Checking conditions to generate ERROR or INFO
            if len(errorKey) > 0:
                    listOfErrorKeys = errorKey.split('_')
                    if "ERROR" in listOfErrorKeys:
                            logging.error("%s" % errorKey)
                            sys.exit(1)
                    else:
                            logging.info("%s" % errorKey)
    
            else:
                    logging.error("%s" % "No Error keywords found")


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

GPIO32 pin works in analog mode, always reads 0 in digital mode

I'm having some difficulty getting PCNT pulse counting working with a prototype ESP32 device board.

I have a water level sensor (model D2LS-A) that signals state by the frequency of a square wave signal it sends to GPIO32 (20Hz, 50Hz, 100Hz, 200Hz, 400Hz).

Sadly, the PCNT counter stays at 0.

To troubleshoot, I tried putting GPIO32 in ADC mode (attenuation 0, 10-bit mode) to read the raw signal (sampling it many times a second), and I'm getting values that I would expect (0-1023). But trying the same thing using digital GPIO mode, it always returns 0, never 1 in all the samples.

Since the PCNT ESP IDF component depends on reading the pin digitally, the counter never increments past 0.

So the real problem I'm having is: why aren't the ADC readings (between 0-1023) translating to digital readings of 0-1 as one would expect?



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

Using %T>% to complete a pipeline for an object

So far I have the result stored into the object result2.
The goal of the pipe is to take this filtered dataset,
THEN extract body_size and brain volume data,
THEN plot a scatterplot of body size and brain volume
THEN return a summary

I am trying to accomplish this by using the pipe operators to complete this pipeline, but I am doing something wrong.

result2<-fish %>%
  filter(body_size>0) %>%
  extract(body_size, brain_volume) %T>%
  plot() %>%
  summary()


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

Devide each value by its group's average

In pyspark how to create a second column where each value of first column is devided by its group's avg. That means that you do some grouping by another column and then devide each value by the avg per group.



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

Make group of flip boxes align on mobile

I don't really have any background of HTML or CSS. I've been figuring out how to change existing codes to help make sections of a website. The only issue is that I can't make it mobile-friendly. I made a code to create 8 flip boxes that work when you visit the website on a computer. However, they don't work so well on mobile. I don't really know what I'm doing, but is there anyway I can align the 8 boxes in one column for mobile use and use touch to make them flip? Thanks!

    <!DOCTYPE html>
<html>
<head>
<link href=https://fonts.googleapis.com/css?family=Montserrat:400,500,700,900|Ubuntu:400,500,700 rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  font-family: 'Montserrat', sans-serif;
  font-weight: 300; /* black */
}
.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  justify-items: center;
  align-items: center;
  grid-gap: 8px;
}

.flip-card {
  background-color: transparent;
  width: 275px;
  height: 250px;
  perspective: 1000px;
}

.flip-card-inner {
  border-style: hidden;
  position: relative;
  width: 100%;
  height: 100%;
  text-align: left;
  transition: transform 0.6s;
  transform-style: preserve-3d;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.flip-card-front {
  background-color: white;
  color: #152939;
  text-align: center;
}

.flip-card-back {
  background-color: white;
  color: black;
  transform: rotateY(180deg);
  line-height: 1.25;
}

li{
    margin: 10px 0;
}

.vertical-center {
  margin: 0;
  position: absolute;
  top: 45%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}
</style>
</head>
<body>
<section id="team">
  <div class="container">
    <div class="grid">
      <!-- #stakeholder benefits -->
      <!-- #regulatory agencies -->

      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Regulatory<br />Agencies</h2>
            <img src=https://i.ibb.co/t8ghC7J/Regulatory-Agencies.png alt="Regulatory-Agencies" width= "110">
          </div>
          <div class="flip-card-back">
               <div class="vertical-center">
            <ul>
            <br />
  <li style="font-size:15px;">Real-time monitoring & auditing</li>
  <li style="font-size:15px;">No need to go on-site to &ensp; review necessary paperwork</li>
  <li style="font-size:15px;">Access to digital database on contamination levels, origin and destination(s)</li>
</ul>
            </div>
          </div>
        </div>
      </div>

      <!-- #generators -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Generators<br /> &ensp; </h2>
            <img src=https://i.ibb.co/pj0M0cZ/Generator.png alt="Generator" width= "110">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
            <ul>
            <br />
  <li style="font-size:15px;">Access to real-time project updates</li>
  <li style="font-size:15px;">Limit exposure to regulatory penalties</li>
  <li style="font-size:15px;">Accurately forecast and &ensp; reduce costs with start-to-finish project insights</li>
  <li style="font-size:15px;">Cost-effective</li>
            </div>
          </div>
        </div>
      </div>

      <!-- #environmental consultants -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Environmental Consultants</h2>
            <img src=https://i.ibb.co/wQsdBgk/Environmental-Consultants.png alt="Environmental-Consultants" width="110">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
            <br />
           <ul>
   <li style="font-size:15px;">Easier vetting to review credentials of necessary companies</li>
  <li style="font-size:15px;">Single and centralized repository to access all &ensp; relevant documents</li>
</ul>
                                                </div>
          </div>
        </div>
      </div>

      <!-- #remediation consultants -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Certified Remediation Contractors</h2>
            <img src=https://i.ibb.co/tBczP7M/Certified-Remediation-Contractors.png alt="Certified-Remediation-Contractors" width= "100">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
           <ul>
            <br />
   <li style="font-size:15px;">Digital manifests save time, space, energy and money</li>
  <li style="font-size:15px;">Improve trucker &ensp; management</li>
  <li style="font-size:15px;">Easily post jobs in need of additional compliant &ensp; &ensp; truckers</li>
</ul>
            </div>
          </div>
        </div>
      </div>
      
      <!-- #remediation professionals -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Remediation Professionals<br />(i.e. LSRPs)</h2>
            <img src=https://i.ibb.co/rm6KSMZ/Remediation-Professionals.png alt="Remediation-Professionals" width="100">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
           <ul>
   <li style="font-size:15px;">Minimize paperwork by receiving necessary documents in the cloud</li>
  <li style="font-size:15px;">Streamlined updates to Regulatory Agencies</li>
</ul>
            </div>
          </div>
        </div>
      </div>

      <!-- #material truckers -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Material Truckers <br /> &ensp; </h2>
            <img src=https://i.ibb.co/xGdP24b/Truckers.png alt="Truckers" width= "120">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
            <br />
          <ul>
<li style="font-size:15px;">Easier hiring process with ability to upload credentials and list references for new &ensp; jobs</li>
  <li style="font-size:15px;">Eliminates need to call for or save paper manifest receipts</li>
  <li style="font-size:15px;">Faster pay through direct invoicing</li>
  <li style="font-size:15px;">Post available trucks for hire</li>
  </ul>
            </div>
          </div>
        </div>
      </div>

      <!-- #disposal facilities -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Disposal Facilities <br /> &ensp; </h2>
            <img src=https://i.ibb.co/4KCPWxB/Disposal-Facilities.png alt="Disposal-Facilities" width="110">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
            <br />
           <ul>
   <li style="font-size:15px;">Go green - no need to buy paper and printer cartridges &ensp; to print paper manifests</li>
  <li style="font-size:15px;">Easier manifest delivery - assign electronically to truckers ahead of time, no need to sign paper manifests at origin and destination</li>
</ul>
            </div>
          </div>
        </div>
      </div>
     
      <!-- #material testing labs -->
      <div class="flip-card">
        <div class="flip-card-inner">
          <div class="flip-card-front">
            <h2>Material Testing<br />Labs</h2>
            <img src=https://i.ibb.co/t8xWnfv/Material-Testing-Labs.png alt="Material-Testing-Labs" width="110">
          </div>
          <div class="flip-card-back">
            <div class="vertical-center">
           <ul>
            <br />
   <li style="font-size:15px;">Share results faster by integrating with TerraTrackr database</li>
   <li style="font-size:15px;">Upload testing lab results &ensp; and assign a unique project &ensp; ID for easy organization</li>
</ul>
            </div>
          </div>
        </div>
      </div>
</body>
</html>


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