text:
Q: How to implement a type-level max function over a union of literals, in TypeScript? Given a union of number literals, e.g.:
type Values = 1 | 2 | 5

Is it possible to create a generic type-level function that extracts the maximum, i.e.:
type Max<T> = ???

type V = Max<Values>
//   V = 5

A: The tersest illegal (see microsoft/TypeScript#26980) version of Max I can come up with (that uses variadic tuples slated to come out in TS4.0) is this:
type MaxIllegal<N extends number, T extends any[] = []> = {
    b: T['length'], r: MaxIllegal<N, [0, ...T]>
}[[N] extends [Partial<T>['length']] ? "b" : "r"];

type MaxValuesIllegal = MaxIllegal<Values>; // 5

That sort of illegal circularity works until it doesn't, which is one reason it's not supported.  If you put in a value other than a non-negative integer, it recurses until there's a compiler error:
type OopsNegative = MaxIllegal<-1 | 3>; // error! Type instantiation is excessively deep and possibly infinite.

This can probably be worked around, but it gets worse: the recursion here bottoms out after only a few dozen levels, so you can't even use a number like 55 without getting an error:
type OopsTooBig = MaxIllegal<3 | 55 | 9>; // error! Type instantiation is excessively deep and possibly infinite.

One alternative is to programmatically generate a helper type like LEQ consisting of all the non-negative integers less than or equal to a given key, up to some max value you can choose... here I'm doing 100 or 99 or something:
// console.log("type LEQ={"+Array.from({length:100},(_,i)=>i+":"+Array.from({length: i+1},(_,j)=>j).join("|")).join(", ")+"}")
type LEQ = { 0: 0, 1: 0 | 1, 2: 0 | 1 | 2, 3: 0 | 1 | 2 | 3, 4: 0 | 1 | 2 | 3 | 4, 5: 0 | 1 | 2 | 3 | 4 | 5, 6: 0 | 1 | 2 | 3 | 4 | 5 | 6, 7: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7, 8: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8, 9: 0 | 1 | 2 | 3 | 4 | 5 ... SNIP!

Then you can write some code to pluck out the right values without using illegal circularity:
type Same<T, U, Y = T, N = never> = [T] extends [U] ? [U] extends [T] ? Y : N : N;
type ToLEQ<N extends number> = { [K in keyof LEQ]: [N] extends [Exclude<LEQ[K], K>] ? never : K }[keyof LEQ]
type Max<N extends number, U extends number = ToLEQ<N>> = { [K in keyof LEQ]: Same<U, LEQ[K], K> }[keyof LEQ]

It works for your example:
type MaxValues = Max<Values>; // 5

This works for 55 now because we're not overloading the stack:
type NotTooBigAnymore = Max<3 | 55 | 9> // 55

It still doesn't work when you give it an unexpected value like -1, but here it at least just gives you the max value it has instead of going completely off the deep end:
type OopsNegativeOkayIGuess = Max<-1 | 3> // 99

and as I said you can probably work around it by filtering the passed-in value before running Max on it.  After all we have a big LEQ type sitting around:
type Max<N extends number, U extends number = ToLEQ<Extract<N, keyof LEQ>>> = { [K in keyof LEQ]: Same<U, LEQ[K], K> }[keyof LEQ]

And that gives you
type OopsNegativeOkayIGuess = Max<-1 | 3> // 3

which happens to be true (although Max<1 | 2.5> will be 1 which is false).

In any case, this is really pushing the compiler past anything I'd be comfortable recommending for a production code base.  Really we should be pushing for microsoft/TypeScript#26382 to be implemented so that the compiler can just do math at the type level.  So you might want to go there and give it a  and possibly describe your (hopefully compelling) use case.

Okay, hope that helps; good luck!
Playground link to code

A: Oh boy. I created a monster that seems to work, but because of the limitations of circular types, it cannot be done as a single step.
type DropFirst<T extends TupleLike> = T extends readonly [any, ...infer U] ? U : [...T];

type Longer<T, U extends TupleLike> = U extends [] ? T : T extends [any, ...U] ? T : U;

type TupleLike<T = unknown> = readonly T[] | readonly [T];

type Head<T> = T extends [infer U, ...any[]] ? U : never;

type TupleOf<T, Length extends number, Queue extends any[] = []> = {
  done: Queue,
  next: TupleOf<T, Length, Prepend<T, Queue>>;
}[Yield<Queue, Length>]

type Yield<Queue extends any[], Length extends number> =
  Queue['length'] extends Length
    ? "done"
    : "next"

type Prepend<T, U extends any[]> =
  ((head: T, ...tail: U) => void) extends ((...all: infer V) => void)
    ? V
    : []

type FindLongestTuple<T extends readonly number[][], Accumulator extends number[] = []> = {
  done: Accumulator;
  next: FindLongestTuple<DropFirst<T>, Longer<Head<T>, Accumulator>>;
}[T extends [] ? 'done' : 'next'];

type GenerateTuples<T extends readonly number[]> = {
  [K in keyof T]: TupleOf<1, T[K] & number>
}

/**
 * Usage:
 */
type Input = [4, 5, 6, 1, 2];

type Step1 = GenerateTuples<Input>;
type Step2 = FindLongestTuple<Step1>
type Result = Step2['length']; // 6

Playground
I bet there is a simpler way to do that. ;-)


text:
Q: MYSQL php database insert including image upload Im trying insert user input into my databases. I want to add title and description into the advert table and an image to to the pictures table.
this is what i have come up with so far but it doesnt work at all. this is a posthandler.php page which will be called when the user presses submit. Variable at the top are assigned input names from the html page.  I have both path name and blob in my pictures database at the moment to see which option will work best.
please help
<?php

session_start();
echo "You are signed in as ". $_SESSION['username'];

 include 'mysql.php';

 $title='title';
 $des='des';
 $image='image';

if(isset($_POST['submit'])) {
   $error = "";
     if (!empty($_POST['title'])) {
             $title= $_POST['title'];
        } else {
             $error = "Please enter a title for your Ad.
";
        }
        if (!empty($_POST['des'])) {
             $des = $_POST['des'];
        } else {
             $error = "Please describe your item
";
        }
        if (!empty($_POST['image'])) {

           $image=addslashes($_FILES['image']['tmp_name']);
           $name=addslashes($_FILES['image']['name']);
           $image=file_get_contents($image);
           $image=base64_encode($image);
           $filepath = "images/".$filename;
           move_uploaded_file($filetmp,$filepath);
           $image = $_POST['image'];

        } else {

        }

        if (empty($error)) {

        $conn= mysql_connect("localhost","km","data");
        if (!$conn){
            die ("Failed to connect to MySQL: " . mysql_error());

        mysql_select_db("mdb_km283",$conn);

        $sql = "INSERT INTO Advert (title, description) VALUES ('$_POST[title]','$_POST[des]')";
        $sql2 = "INSERT INTO Pictures(image, Path) VALUES ('$_POST[image]' $filepath)";

        mysql_query( $sql,$sql2, $conn );
        //mysql_query( $sql2,$conn );
        mysql_close($conn);

            echo 'Upload successfull';
        }

        }
}

  ?>

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<link rel="stylesheet" type=text/css" href="stylesheet.css">
Logout

ERROR - Please go back and fix the below:

<?php
    if (!empty($error)) {
        echo'
Upload failed. Please go back and fix the below
 The following error(s) returned:
' . $error . '
';
    } else {

    echo '<meta http-equiv="refresh" content="0; URL=user.php">';

    }

?>

A: $filename = $_FILES['image']['name'];
$filepath = 'image/' . $filename;
$filetmp = $_FILES['image']['temp_name'];
$result = move_uploaded_file($filetmp,$filepath);
if(!$result)
         echo "Photo field was blank";
else
         echo "uploaded";

then write ur mysql code here ....

redpajama_set_name: RedPajamaStackExchange


text:
Q: CollectionView lag while scrolling Sir, I am a beginner. I am unable to understand this. I am facing the lag while scrolling the collectionView. i remove the Cell-shadow then lagging is gone. but i want to add shadow. my cellforItem code is:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        NSString *cellIdentifier = @"cellCollection";
        [self.MainCollectionView registerClass:[CVC_ImageWithLabel class] forCellWithReuseIdentifier:cellIdentifier];
        CVC_ImageWithLabel *customCell = (CVC_ImageWithLabel *)[self.MainCollectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

        //cell text
        customCell.NameLabel.text = [data_Array objectAtIndex:indexPath.row];
        //cell image
        customCell.CellImage.image=[UIImage imageNamed:[image_Array objectAtIndex:indexPath.row]];
        customCell.CellImage.contentMode = UIViewContentModeScaleAspectFit;

        return customCell;
    }

Can you help me sir?
i have tried to add below code but failed to do so.
customCell.layer.shouldRasterize = YES;
customCell.layer.rasterizationScale = [UIScreen mainScreen].scale;

A: You should setup one more property of layer - shadowPath:
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
self.layer.shadowOffset = CGSizeMake(0, 1);
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect: self.bounds cornerRadius: self.layer.shadowRadius].CGPath;

This path defines the outline used to construct the layer's shadow instead of using the layer's composited alpha channel. Specifying the path explicitly using this property will usually improve rendering performance

A: Add shadows as images, it's way better for performance. You can use image slicing to help with scaling of images.


text:
Q: How to reset Cascading DropDownList for Ajax Control Toolkit to its default prompt text (server side)? How to reset Cascading DropDownList for Ajax Control Toolkit to its default prompt text (server side)?

A: You can reset dropdownlist to its default prompt text using PromptValue property.
ddl.SelectedValue = ddl.PromptValue;


text:
Q: How do I call an API in an ELM app, my code won't handle the response data? New to Elm can anyone help me understand why this code returns my error "could not load the page"? I am pretty sure it has something to do with the data being returned being JSON and I have not yet figured out how to manage that.
Basically i am new to Elm and want to take it a little further by working with more JSON data from free APIs can anyone lend a hand?

import Browser
import Html exposing (Html, text, pre)
import Http

-- MAIN

main =
    Browser.element
     { init = init
     , update = update
     , subscriptions = subscriptions
     , view = view
     }

--  MODEL

type Model
    = Failure
    | Loading
    | Success String

init : () -> (Model, Cmd Msg)
init _ =
    ( Loading
    , Http.get
        { url = "http://api.openweathermap.org/data/2.5/weather?q=naples&APPID=mykey"
        , expect = Http.expectString GotText
        }
    )

-- UPDATE

type Msg
  = GotText (Result Http.Error String)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    GotText result ->
      case result of
        Ok fullText ->
          (Success fullText, Cmd.none)

        Err _ ->
          (Failure, Cmd.none)

-- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none

-- VIEW

view : Model -> Html Msg
view model =
  case model of
    Failure ->
      text "I was unable to load your book."

    Loading ->
      text "Loading..."

    Success fullText ->
      pre [] [ text fullText ]

UPDATE -

This works in Ellie but not locally compiling using Elm 19

Something is off with the body of the `init` definition:

39|>  ( Loading
40|>  , Http.get
41|>      { url = "http://127.0.0.1:8080/test"
42|>      , expect = Http.expectString GotText
43|>      }
44|>  )

The body is a tuple of type:

    ( Model, Json.Decode.Decoder a -> Http.Request a )

But the type annotation on `init` says it should be:

    ( Model, Cmd Msg )

-- TYPE MISMATCH ---------------------------------------------- src/Fizzbuzz.elm

The 1st argument to `get` is not what I expect:

40|   , Http.get
41|>      { url = "http://127.0.0.1:8080/test"
42|>      , expect = Http.expectString GotText
43|>      }

This argument is a record of type:

    { expect : b, url : String }

But `get` needs the 1st argument to be:

    String

-- TOO MANY ARGS ---------------------------------------------- src/Fizzbuzz.elm

The `expectString` value is not a function, but it was given 1 argument.

42|       , expect = Http.expectString GotText
                     ^^^^^^^^^^^^^^^^^
Are there any missing commas? Or missing parentheses?

UPDATED - I made a change to try sending any JSON to Elm from my Go webserver to confirm some things leaned by your answers thanks.

A: You are trying to make a cross-domain request. The mechanism for doing this is called CORS (Cross-Origin Resource Sharing). To enable CORS requests, the server must explicitly allow requests from your domain using the access-control-allow-origin response header. The open weather API does not have this header, so when the browser tries to request the data it is blocked by browser security restrictions.
You'll need to do one of the following:

*

*ask openweather to whitelist your domain for CORS response headers (unlikely to be possible)

*proxy the openweather request from your own domain's servers

The latter is more likely to be possible, but it also means you'll be able to keep your API key a secret. If you are making weather requests from the client then anyone that loads your web page will be able to see the API key on the requests their browser makes as well as in the source code of your webpage.
The working example given by @5ndG uses an API that has an access-control-allow-origin response header that explicitly whitelists Ellie, which is why it works there. You can look at the requests and responses using your browser's dev tools to see that this is the case.
good luck!

A: Your code should manage fine with a JSON response. It will just give you a JSON string. (Though probably you will want to decode your JSON so you can use it.)
I tried your code with a testing API I found on Google that returns some JSON: https://jsonplaceholder.typicode.com/todos/1
It works fine, displaying the JSON string as expected, so perhaps your url has something wrong with it?
See this Ellie for the working example.
It might also be a good idea to not throw away the Http error in your update function; it provides useful information when debugging.


text:
Q: Error: Could not find or load main class? I have a class called TestInventory.java, with other classes in the default package, all in the src folder. However, when I run it, I get:
Error: Could not find or load main class
Here is my code
 import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.Scanner;
    //@ author Jane Choe
    public class TestInventory {

        public void main(String[] args) throws FileNotFoundException {
            Inventory inv = new Inventory();

            // TODO:  Read in the input file and populate the movieList. Manage exceptions.
            // On a failed movie load print the message
            // "Exception " + e.getMessage() + " for film " + title. No loading."
            FileReader file = new FileReader("movies_db.txt");
            Scanner sc = new Scanner (file);

            while (sc.hasNextLine()){
                String line = sc.nextLine();
                String [] splitline = line.split("-");
                //if (splitline[6]== null){// has as many parameters as an action movie
                    //try {// try adding to action
                System.out.println("p");
                        inv.add(new Action(splitline[0], Integer.parseInt(splitline[1]), Integer.parseInt(splitline[2]),
                                Integer.parseInt(splitline[3]), Integer.parseInt(splitline[5])));

                    //}
                    //catch{
                    //  System.out.println("Exception + e.getMessage() + " for film " + title. No loading.");
                    //}
                //} // if loop
            }/*
            else{
                try {// try adding to RomCom
                    inv.add(RomCom((splitline[0], Integer.parseInt(splitline[1]), Integer.parseInt(splitline[2]),
                            Integer.parseInt(splitline[3]), (splitline[4]),
                            Integer.parseInt(splitline[5]), Integer.parseInt(splitline[6]));
                }
                catch{
                    System.out.println("Exception + e.getMessage() + " for film " + title. No loading.");
                }
            }
        }
        */

        //DO NOT CHANGE
        System.out.println("Inventory should now contain file contents.");
                            System.out.println(inv.toString());

                            Movie starWars = new Action("Star Wars - A New Hope", 1977, 121, 3.8, 89);
                            inv.add(starWars);

                            Movie numberFour = new Action("I Am Number Four", 2011, 101, 3.2, 11);
                            inv.add(numberFour);

                            Movie someoneLikeYou = new RomCom("Someone Like You", 2011, 101, 3.2, 2, 5);
                            inv.add(someoneLikeYou);

                            Movie crazyStupidLove = new RomCom("Crazy, Stupid, Love 2", 2013, 113, 3.9, 1, 3);
                            inv.add(crazyStupidLove);

                            System.out.println("Inventory should now contain 13 movies. " + (inv.size() == 13));
    /* add this in later
                            if(inv.remove(crazyStupidLove.getTitle(), crazyStupidLove.getYear())) {
                                System.out.println("Successfully removed 'Crazy, Stupid, Love'");
                                if(!inv.remove(crazyStupidLove.getTitle(), crazyStupidLove.getYear())) {
                                    System.out.println("Successfully ignored second remove attempt for 'Crazy, Stupid, Love'");
                                }
                            }
    */
                            try {
                                inv.add(new RomCom("27 Dresses", 2008, 103, 4.4, 1, 1));
                            } catch (IllegalArgumentException e) {
                                System.out.println("Successfully threw exception on invalid parameter.");
                            }

                            try {
                                inv.add(someoneLikeYou);
                            } catch (MovieInventoryException e) {
                                System.out.println("Successfully threw exception on duplicate add attempt.");
                            }

                            System.out.println("Inventory should now contain 12 movies. " + (inv.size() == 12));

                            System.out.println("Inventory should not contain 'The Matrix'? " + !inv.contains("The Matrix", 1999));
                            System.out.println("Inventory should not contain 'Something Borrowed'? " + !inv.contains("Something Borrowed", 2009));
                            System.out.println("Inventory should not contain '27 Dressed'? " + !inv.contains("27 Dressed", 2008));

                            System.out.println("\n" + inv.toString());
    }

    }

I also have a red exclamation point next to my project.
Any help would be greatly appreciated.

A: You are forgetting the "static" in your main method.
public static void main(String[] args) {
  //do something
}


text:
Q: (VHDL) Issue with outputs in vhdl entity I have problems with the output of the vhdl entity that always sends out U.
I looked at various forums but I could not find a solution.
The project is a 5-story lift that has to wait 5 seconds to close the door and 10 seconds to get to the next plane up to the target.
Use Logisim (v 2.13.22) and ghdl (v 0.29.1).
Does anyone have any idea what the problem might be? Thanks in advance

Here the vhdl code i made.
    library ieee;
       use ieee.std_logic_1164.all;
       use ieee.numeric_std.all;

    entity Elevator is
        Port (
            clk : in std_logic;

            rst : in std_logic;
            rstPorta : in std_logic;
            rstMotore : in std_logic;

            zero : in std_logic;
            one : in std_logic;
            two : in std_logic;
            three : in std_logic;
            four : in std_logic;

            upEngine : out std_logic;
            downEngine : out std_logic;

            ledReady: out std_logic;
            ledUp: out std_logic;
            ledDown: out std_logic;
            ledDoorOpen: out std_logic;
            ledDoorClosed: out std_logic;

            ledBusy: out std_logic;
            ledUsable: out std_logic;

            doorOpenEngine : out std_logic;
            doorCloseEngine : out std_logic;

            cntPiano : out std_logic_vector(4 downto 0)
        );
    end Elevator;

    architecture Ascensore of Elevator is
        type state_type is (s0,s1,s2,s3,s4);
        signal current_s,next_s: state_type;
        signal cf, df: std_logic_vector(3 downto 0);    -- vettore a 4 bit
        signal countPorta: std_logic_vector(2 downto 0);    -- vettore a 3 bit
        signal countMotore: std_logic_vector(3 downto 0);   -- vettore a 4 bit

        begin

        -- Questo processo modifica il segnale countPorta in modo tale da segnalare il tempo rimanente prima della chiusura della porta
        process (clk,rstPorta)
            begin
            if (rstPorta='1') then countPorta <= "000"; -- Condizione di bypass della porta, apre la porta senza tempi d'attesa, per casi di emergenza
                elsif (clk'event and clk='1') then
                    if (countPorta = "100") then countPorta <= "011";
                        elsif (countPorta = "011") then countPorta <= "010";
                        elsif (countPorta = "010") then countPorta <= "001";
                        else countPorta <= "000";
                    end if;
            end if;
        end process;

        -- Questo processo modifica il segnale countMotore in modo tale da segnalare il tempo necessario all'arrivo al piano successivo
        process (clk,rstMotore)
            begin
            if (rstMotore='1') then countMotore <= "0000";  -- Condizione di bypass del motore, ferma lo spostamento in casi di emergenza
                elsif (clk'event and clk='1') then
                    if (countMotore = "1001") then countMotore <= "1000";
                        elsif (countMotore = "1000") then countMotore <= "0111";
                        elsif (countMotore = "0111") then countMotore <= "0110";
                        elsif (countMotore = "0110") then countMotore <= "0101";
                        elsif (countMotore = "0101") then countMotore <= "0100";
                        elsif (countMotore = "0100") then countMotore <= "0011";
                        elsif (countMotore = "0011") then countMotore <= "0010";
                        elsif (countMotore = "0010") then countMotore <= "0001";
                        else countMotore <= "0000";
                    end if;
            end if;
        end process;

        -- Questo processo serve a controllare le chiamate dell ascensore nei vari piani
        process (clk,rst)
            begin
            -- si inizializza ascensore considerando che esso parta dal piano 0 in una condizione priva di richieste esterne (stato 3)
            if (rst='1') then
                df <= "0000";
                cf <= "0000";

                upEngine <= '1';
                downEngine <= '1';

                ledReady <= '1';
                ledUp <= '1';
                ledDown <= '1';
                ledDoorOpen <= '1';
                ledDoorClosed <= '1';

                ledBusy <= '1';
                ledUsable <= '1';

                doorOpenEngine <= '1';
                doorCloseEngine <= '1';

                current_s <= s3;
            end if;

            -- verifica se vi sono state richieste nei vari piani ad ogni ciclo di clock assegnando a df (desired floor) il piano della richiesta
            if (clk'event and clk='1') then
                if (zero = '1') then df <= "0000";
                    elsif (one = '1') then df <= "0001";
                    elsif (two = '1') then df <= "0010";
                    elsif (three = '1') then df <= "0011";
                    elsif (four = '1') then df <= "0100";
                end if;

                -- lo stato corrente corrisponde allo stato successivo
                current_s <= next_s;
            end if;

        end process;

        -- Processo Ascensore
        process (current_s, cf, df, clk)
            begin
            if (clk'event and clk='1') then
                case current_s is
                    -- STATO 0: fase di salita ascensore fino a che il piano desiderato non e' uguale al piano corrente
                    when s0 =>
                        if(cf < df) then

                            upEngine <= '1';

                            -- se il motore non e' ancora arrivato al piano resta nello Stato 0
                            if((countMotore= "1001") or (countMotore= "1000") or (countMotore= "0111") or (countMotore= "0110") or (countMotore= "0101") or (countMotore= "0100") or (countMotore = "0011") or (countMotore = "0010") or (countMotore = "0001"))
                                then then next_s <= s0;
                            end if;

                            -- se sono passati 10 sec, siamo arrivati al piano. cf verra' aumentato
                            if(countMotore = "0000") then
                                if (cf = "0000") then cf <= "0001";
                                    elsif (cf = "0001") then cf <= "0010";
                                    elsif (cf = "0010") then cf <= "0011";
                                    elsif (cf = "0011") then cf <= "0100";
                                end if;
                            end if;

                            -- se il piano desiderato e' > del corrente fai un altro ciclo dello Stato 0
                            if(cf < df) then
                                next_s <= s0;
                            end if;

                            -- se il piano desiderato e' = al corrente vai nello Stato 2
                            if(cf = df) then
                                ledUp <= '0';
                                upEngine <= '0';
                                next_s <= s2;
                                countPorta <= "100";
                            end if;

                        end if;

                    -- STATO 1: fase di discesa ascensore fino a che il piano desiderato non e' uguale al piano corrente
                    when s1 =>
                        if(cf > df) then

                            downEngine <= '1';

                            -- se il motore non e' ancora arrivato al piano resta nello Stato 1
                            if((countMotore= "1001") or (countMotore= "1000") or (countMotore= "0111") or (countMotore= "0110") or (countMotore= "0101") or (countMotore= "0100") or (countMotore = "0011") or (countMotore = "0010") or (countMotore = "0001")) then
                                elsif(countMotore = "0000") then next_s <= s1;
                            end if;

                            -- se sono passati 10 sec, siamo arrivati al piano. cf verra' diminuito
                            if(countMotore = "0000") then
                                if (cf = "0100") then cf <= "0011";
                                    elsif (cf = "0011") then cf <= "0010";
                                    elsif (cf = "0010") then cf <= "0001";
                                    elsif (cf = "0001") then cf <= "0000";
                                    else cf <= cf;
                                end if;
                            end if;

                            -- se il piano desiderato e' < del corrente fai un altro ciclo dello Stato 1
                            if (cf > df) then
                                next_s <= s1;
                            end if;

                            -- se il piano desiderato e' = al corrente vai nello Stato 2
                            if(cf = df) then
                                ledDown <= '0';
                                downEngine <= '0';
                                next_s <= s2;
                                countPorta <= "100";
                            end if;
                        end if;

                    -- STATO 2: fase di apertura della porta nel piano desiderato
                    when s2 =>
                        if(countPorta = "000") then next_s <= s3;
                        else next_s <= s2;
                        end if;

                    -- STATO 3: ascensore in attesa di richieste con porta aperta
                    when s3 =>
                        doorOpenEngine <= '1';
                        doorCloseEngine <= '0';
                        ledDoorOpen <= '1';
                        ledDoorClosed <= '0';
                        ledReady <= '1';
                        ledUp <= '0';
                        ledDown <= '0';
                        ledBusy <= '0';
                        ledUsable <= '1';
                        if(cf = df) then
                            next_s <= s3;
                        end if;
                        if ((cf<df) or (cf>df)) then
                            countPorta <= "100";
                            next_s <= s4;
                        end if;

                    -- STATO 4: fase di chiusura della porta e selezione dello stato successivo per la salita (Stato 0) o discesa (Stato 1) dell'ascensore
                    when s4 =>
                        if((countPorta = "100") or (countPorta = "011") or (countPorta = "010") or (countPorta = "001")) then
                            next_s <= s4;

                            elsif((countPorta = "000") and (cf<df)) then
                                doorOpenEngine <= '0';
                                doorCloseEngine <= '1';
                                ledDoorOpen <= '0';
                                ledDoorClosed <= '1';
                                ledReady <= '0';
                                ledUp <= '1';
                                ledDown <= '0';
                                ledBusy <= '1';
                                ledUsable <= '0';
                                countMotore <= "1001";
                                next_s <= s0;
                            elsif((countPorta = "000") and (cf>df)) then
                                doorOpenEngine <= '0';
                                doorCloseEngine <= '1';
                                ledDoorOpen <= '0';
                                ledDoorClosed <= '1';
                                ledReady <= '0';
                                ledUp <= '0';
                                ledDown <= '1';
                                ledBusy <= '1';
                                ledUsable <= '0';
                                countMotore <= "1001";
                                next_s <= s1;
                        end if;
                end case;
            end if;
        end process;

    end Ascensore;

A: Most of the times, errors like this occur because of erroneous connection of ports in testbench, for to be sure about this, you can check the connection, but if you can't find any mistake, you can test your module without testbench and use force value and force clock But if it is still unknown, your mistake is in wave selection to view.
good luck

A: I am not sure where you are at with this design but I am hoping you made some progress on your own since posting.
Now, to the heart of your problem. The signals upEngine, downEngine, ... , doorCloseEngine and current_s are not assigned in a single process. They are driven in both the third and fourth process  statements which therefore constitutes a case of multiply driven nets.
In your simulator, look for a command that will report the drivers for any given signal. Here is what I see in Vivado for the upEngine signal (your line numbers might not match exactly -- I was tweaking the code):
 report_drivers {/Elevator/upEngine}
 Drivers for /Elevator/upEngine
   U : Net /Elevator/upEngine
     U : Driver /Elevator/line__125 at C:/temp/new1.vhd:125
     1 : Driver /Elevator/line__82 at C:/temp/new1.vhd:82

This is somewhat subtle. VHDL employs a resolution function to decide what to do when there are multiple drivers. In this case, since the signals are std_logic type, the std_logic_1164 library specifies the resolution function and it says that 'U' always wins in a contest between two values. So, no matter what is driven in the third process, the uninitialized signals in the 4th process will contribute 'U' and determine the signal state. (At least until the state machine gets to a state that actually drives a known value onto upEngine).
You might have noticed in your simulation that signals ledUp and ledDown were 'X' after the first rising clock edge. That is because they are both multiply driven as well -- however one driver contributes '1' and the other '0'. The resolution function says in that case that the result is unknown -- 'X'.
Check the log output of your synthesis tool as it should report these multiply driven nets as errors or possibly just warnings. (There is a time and place for multiply driven nets in designs that use tri-state signal assignments or ones that employ wired-and/or logic.)
Happily, the solution is simply to merge everything into a single process and try again. I suspect you will have additional work to do as the logical function of your design is not apparent to me in my cursory examination of it. (As a useful exercise, change all std_logic types to bit and re-analyze. The multiply driven nets stand out like a sore thumb.)
Here are some tips concerning the coding style you have employed:

*

*Use the rising_edge() function rather than clk'event and clk='1'. While unusual, the later approach can lead to subtle simulation errors if the clk transitions to '1' from say 'X' or 'U' which might lead you to believe the circuit is working only to discover that the hardware behaves differently.

*You want your state machine to be reset. So the Processo Ascensore should have either a synchronous or asynchronous reset signal clearing the state register.

*You have several if statements that appear to be decrementing various signals. The if-elsif-elsif compound statement synthesizes to a priority encoder which will result in longer combinatorial paths and possibly slower timing. Always look for an opportunity to use a case statement to implement parallel logic.

*With that said, what your VHDL really needs is to use unsigned type signals to implement the decrement arithmetic necessary for the various counters in your design. For example, the countPorta signal should be declared as unsigned(2 downto 0) and the clocked process that operates on it should simply specify countPorta <= countPorta - "001"; -- same for the other decrementing counters.

*The third process incorrectly (but not illegally) specifies two distinct if clauses where only one is necessary. In fact, the second if clause always 'wins' as it comes later when evaluating the assignment to signal df.
Since you have not supplied a testbench after your original post, as requested by @user1155120, I can go no further. Good luck.


text:
Q: Stop iframe youtube video I would like to stop playing a youtube video when I click on a div. I don't know how to do this and I do not get it to work when using information online.
This is what I have done!
I have linked the youtube iframe API:
<script src="https://www.youtube.com/iframe_api"></script>

Then I have an iframe in my html file:
<iframe id="vid" src="https://www.youtube.com/embed/P2lm356ycwY?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

Then in my script I have this code:
$("#popupvid").click(function(){
    $("#popupvid").css("display","none");
    $("#vid").css("display","none");

    //Code to make the youtube video stop here:

});

What do I need to write so that the video stops here!
Thanks in advance!

A: Please try this jquery.
<script>
$(document).ready(function () {
$(function(){
    $('#popupvid').click(function(){
        $('iframe').attr('src', $('iframe').attr('src'));
    });
});
});
</script>

A: $(document).ready(function () {
    $("iframe").mouseover(function() {
        $("iframe").each(function () {
            $(this)[0].contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
        });
    });
});

this will stop all videos, change mouse over event to click and the first iframe to the id of your div


text:
Q: How to filter out errors in Ubunty system log files? How to find errors in Ubunty system log files, in particular, errors that can cause various problems and proving that system is damaged, not small arbitrary errors. I mean search for lines with error, corrupted, failed, crash messages in log files. Which log files is most important? I installed Glogg log explorer utility. Is there method to scan multiple log files and filter out important error messsages to separate file for analysis?

A: The simplest way to do this is by using grep in a terminal window.  The log file you should check first, is syslog.  So, typing:
grep -i -e fail -e error -e corrupt /var/log/syslog
would give you all the lines that contain the key words you type after each -e switch.  The -i switch tells grep to ignore case.

A: Nowadays on an Ubuntu system with journald, you can actually filter all logs by priority based on metadata, rather than by looking for text strings that might (or might not) imply the priority.
Use journalctl to display logs.  It has many filtering options, but the one to find errors is this:
-p, --priority=
           Filter output by message priorities or priority ranges. Takes either a single numeric or textual log level (i.e. between
           0/"emerg" and 7/"debug"), or a range of numeric/text log levels in the form FROM..TO. The log levels are the usual syslog
           log levels as documented in syslog(3), i.e.  "emerg" (0), "alert" (1), "crit" (2), "err" (3), "warning" (4), "notice" (5),
           "info" (6), "debug" (7). If a single log level is specified, all messages with this log level or a lower (hence more
           important) log level are shown. If a range is specified, all messages within the range are shown, including both the start
           and the end value of the range. This will add "PRIORITY=" matches for the specified priorities.

So if you want to search all logs for anything classified as Emergency, Alert, Critical, or Error (these are the 4 most severe levels), then use:
journalctl -p 0..3

A: The simplest way to do this is by using grep in a terminal window. The log file you should check first is Syslog. So, typing:
grep -i -e fail -e error -e corrupt /var/log/syslog


text:
Q: Submit downloads cgi instead of redirecting to web page I have a web page for login. When I press the Submit button it is supposed to check user name and password and then if successful it should redirect me to a new web page or even if unsuccessful it should redirect me to another web page. I am using POST in my form and using a .c file to check the user name and password which will printf the new web pages for both successful login and unsuccessful login. The problem I am having is that when I press Submit it tries to download my .cgi file and asks permission to save it instead of redirecting to my new web pages. Is anything wrong with my HTML file or is there something wrong with my .c file. What might be the problem and what can I do to fix it? I am attaching my part of the c file thats supposed to print the new web page.
  printf("Content-type: text/html;charset=utf-8\n\n");
  int c;
  FILE *file;
  file = fopen("Success.txt", "r");
  if (file) {
  while ((c = getc(file)) != EOF)
            putchar(c);
            fclose(file);
            }

//Here I open a txt file that contains all my info(tags) for the html page that needs to be printed and then I use putchar to print everything.


text:
Q: Learning Javascript (puppeteer) Im trying to learn to do some requests at the web, with javascript using puppeteer.
So i finally got from a random website, the value of tag a after some div.
But i dont know how to put this code in a "for" to get 10 values (10 tags a sequential).
This is how i got the value (Its working):
const resultado0 = await page.evaluate(() => {
        return document.querySelectorAll('.ui.divided.list > a')[0].textContent;
      });
      console.log(`O valor é ${resultado0}`);

How i tryied to do with for (Not working "ReferenceError: i is not defined"):
for (var i = 0; i < 9; i++) {
    const resultado = await page.evaluate(() => {
      return document.querySelectorAll('.ui.divided.list > a')[i].textContent;
    });
    console.log(`O valor é ${resultado}`);
  }

So i dont want to repeat the same code and put ([1],[2],[3],...), how can i do it?
Thanks
EDIT: FORGOT TO TELL THAT I CANT PRINT THE RESULT WITH querySelectorAll ITS RETURN UNDEFINED.
EX:
const resultado = await page.evaluate(() => {
      return document.querySelectorAll('.ui.divided.list > a').textContent;
    });
    console.log(`O valor é ${resultado[0]}`);

A: You need to loop within page.evaluate (different contexts), and even so, you'll get by easier with Array::map:
const resultado0 = await page.evaluate(() => {
  // Get the elements as a DOM node list
  const elements = document.querySelectorAll(".ui.divided.list > a");
  // Convert to an array we can map over, then map over to get the text content.
  return Array.from(elements).map((el) => el.textContent);
});
console.log(`O valor é ${resultado0}`);

A: I see the problem you have
you are using a await request without async function
see further details in this documentation :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
In the case where you console log the variable "resultado", the await is not yet resolved
const resultado = await page.evaluate(() => {
      return document.querySelectorAll('.ui.divided.list > a')[i].textContent;
    });
    console.log(`O valor é ${resultado}`);

Implement an async function that does that call may resolve your problem


text:
Q: How to recreate a vmx file? As the title says does anyone know how to create a lost vmx file?
The files in which we still have are the associated VMDKs and the log file

A: The vmx file simply holds the virtual machine configuration. Simply create a new VM using the vSphere Client and associate your current vmdk files with it.


text:
Q: Azure Active Directory Login: Web App Permissions, User Consent not triggered I have currently set up a AAD instance and I am authenticating my users against it via my web app, and it's working great.
When I added and configured the application on AAD, I added the required Application and Delegated Permissions to access the Office365 Calendar API. However, the only thing that is missing is that during the login flow users aren't being prompted to grant consent for the permissions, as it should happen from what I've read in your docs: https://msdn.microsoft.com/en-us/library/azure/dn132599.aspx#BKMK_Consent
I'm not sure what I'm missing. Apparently, from the docs,

After the user has signed in, Azure AD will determine if the user
  needs to be shown a consent page. This determination is based on
  whether the user (or their organization's administrator) has already
  granted the application consent. If consent has not already been
  granted, Azure AD will prompt the user for consent and will display
  the required permissions it needs to function. The set of permissions
  that is displayed in the consent dialog are the same as what was
  selected in the Permissions to other applications control in the Azure
  Management Portal.

So maybe somehow I have already probably implicitly granted admin consent for those permissions, but I don't know how that happened.
I've attached the permissions I configured on the AAD App.

Any help would be appreciated.

A: If an admin creates an application in their tenant using the AUX portal (manage.windowsazure.com), and requests permissions to other applications, then users in that same tenant are pre-consented for that application. Note this behavior is NOT true for our other App Registration Portals (portal.azure.com or identity.microsoft.com)
I believe this is why you are not seeing the consent dialogue when user's in your tenant are signing into your application. If you would like to push the consent dialogue experience, there are a few different things you can do:

*

*You can use query strings to prompt "consent" or "admin_consent" during login. Check here: https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx

*You can delete the service principal for your application from your tenant using AAD PowerShell. You can learn how to do that here: https://msdn.microsoft.com/en-us/library/azure/dn194113.aspx

*You can have a user from another tenant try to login to your multi-tenant application.

*You can create your application under a non-admin account.

I hope this helps!
Shawn Tabrizi

A: Try this:
What is the Resource parameter in Windows Azure AD tenant application oAuth 2.0 specification
Changing the resource parameter to https://graph.windows.net did the trick for me.
Furthermore, Microsoft support suggests disabling all permissions except "Enable sign-on and read users' profiles", apparently to avoid permission related problems. I understand that this is not a solution in your case, but at least it gives you a test case.


text:
Q: Angular http.get + WebApi = Cors failure on server side I have a C# web api including a controller attributed like this on class level:

[EnableCors(origins: "http://localhost:51664,http://localhost,...", headers: "*", methods: "*")]

I can make ajax calls, e.g. form localhost just fine.
Now I am starting with AngularJS and the http.get-method fails with the following message:
XMLHttpRequest cannot load http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my AngularJS code:

    <script>
        var myApp = angular.module('myApp', []);

        myApp.controller("myController", function($scope, $http) {

            var onSuccess = function(data, status, headers, config) {
                $scope.data = data;
            };

            var onError = function(data, status, headers, config) {
                $scope.error = status;
            }

            var promise = $http.get("http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40");

            promise.success(onSuccess);
            promise.error(onError);
        });
</script>

In Fiddler, I can see, that the header of the AngularJS-HTTP-Get request has an "Origin: null" entry, which seems to be related to the problem. I think, if instead "null" the value would be "http://localhost", it should work.
Can anyone help me out?
Thank you!

A: Could it be because in your [EnableCors] attribute, you need to change headers: "", methods: "" to headers: "*", methods: "*"?
Also, you should not include a forward slash at the end of the origins url (if you did).

A: We had the same issue in our project and we tried so many options as per the suggestions from various web sites. But the thing that worked/working in our case is writing custom CORS provider as mentioned here.

A: Upppps!
When running in the fresh air today I suddenly was aware why Origin was null. It was, because I was not calling the web site in IIS, but instead I opened the file directly in the file system. For sure, there was no valid URL when doing so, and the Origin was null for the web server.


text:
Q: Calculate average timespan I am to calculate average of a set of time spans, where each time span is a subtraction between two dates.
DateTime a = GetStartDateTime();
DateTime b = GetEndDateTime();

var delta = b.Subtract(a).TotalDays;

Date format is like 22.08.2016 21:00:00
Is there any way to do this more rationally?
Also, I am curious why my delta is always like 0.26914351851851853, in other words why it is not integer?
UPDATE:
Here is example time spans:
23.08.2016 10:31:38 - 22.08.2016 21:00:00
24.08.2016 14:32:26 - 24.08.2016 21:00:00
17.08.2016 8:36:51 - 01.01.2016 21:00:00
17.08.2016 8:34:27 - 15.03.2016 21:00:00

A: Perform a simple mean calculation across the Ticks value of all your TimeSpans and create a new TimeSpan from the result. That will represent the average or mean TimeSpan. e.g.
        var timeSpanList = new List<TimeSpan>();
        var provider = CultureInfo.InvariantCulture;
        timeSpanList.Add(
            new TimeSpan(
                DateTime.ParseExact("23.08.2016 10:31:38", "dd.MM.yyyy H:mm:ss", provider).Ticks -
                DateTime.ParseExact("22.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
        timeSpanList.Add(
            new TimeSpan(
                DateTime.ParseExact("24.08.2016 14:32:26", "dd.MM.yyyy H:mm:ss", provider).Ticks -
                DateTime.ParseExact("24.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
        timeSpanList.Add(
            new TimeSpan(
                DateTime.ParseExact("17.08.2016 8:36:51", "dd.MM.yyyy H:mm:ss", provider).Ticks -
                DateTime.ParseExact("01.01.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
        timeSpanList.Add(
            new TimeSpan(
                DateTime.ParseExact("17.08.2016 8:34:27", "dd.MM.yyyy H:mm:ss", provider).Ticks -
                DateTime.ParseExact("15.03.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
        var totalTicks = 0L;
        foreach(var ts in timeSpanList)
        {
            totalTicks += ts.Ticks;
        }
        var avgTicks = totalTicks / timeSpanList.Count;
        var avgTimeSpan = new TimeSpan(avgTicks);


text:
Q: How to make AutoHotkey script for selecting a pen in OneNote(UWP)? To give you an intro, I am not a programmer but a biologist who is learning a bit of programming.
Now I use OneNote a lot and continuously switch between typing and touch-based inking.
Now OneNote UWP does not have a shortcut for selecting a pen.
But I found out that by pressing Alt+d and then down and then continuously pressing right six times and then pressing enter, one can switch to pen via keyboard.
Now I want to automate the above process and link it to Numpad 1.
So I tried AutoHotkey and tried to learn making a script of the above command but still no success.
This is what I tried (3-4 different ways):
Numpad1::
!d
Down
Right
Right
Right
Right
Right
Right
Right
Enter

I know this script is wrong but I can't find the correct way to do it.

A: You're off to a good start! In order to send the keystrokes, you'll need to use one of the variations of the Send command. In addition, we can also make it so that it only work when OneNote is the active window using the #If directive. (It makes hotkeys context-sensitive.)
I don't have OneNote on my machine, but please verify that the title contains "OneNote" for the following script to work.
SetTitleMatchMode , 2
#If WinActive("OneNote")
Numpad1::Send , !d{down}{right 6}{enter}
#If

Edit: I installed OneNote to try it out. It appears to run too quickly. I added a key delay of 75ms and changed Send to SendEvent, which obeys the key delay. This worked fine for me:

SetTitleMatchMode , 2
SetKeyDelay , 75
#If WinActive("OneNote")
Numpad1::SendEvent , !d{down}{right 6}{enter}
#If


text:
Q: s3distcp not working for me on CDH4.5 I'm running CDH4.5.  I was trying to use distcp to s3n but am getting issues since I upgraded to 4.5.
I'm trying to get s3distcp up and running, but am getting issues.  I downloaded it, and am running this command:
hadoop jar /usr/lib/hadoop/lib/s3distcp.jar  --src hdfs://NN:8020/path/to/destination/folder --dest s3n://acceseKeyId:secretaccesskey@mybucket/destination/

but I'm getting error of:
INFO mapred.JobClient:  map 100% reduce 0%
INFO mapred.JobClient: Task Id : attempt_201312042223_10889_r_000001_0, Status : FAILED
Error: java.lang.ClassNotFoundException: com.amazonaws.services.s3.AmazonS3
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at com.amazon.external.elasticmapreduce.s3distcp.CopyFilesReducer.executeDownloads(CopyFilesReducer.java:209)
    at com.amazon.external.elasticmapreduce.s3distcp.CopyFilesReducer.reduce(CopyFilesReducer.java:196)
    at com.amazon.external.elasticmapreduce.s3distcp.CopyFilesReducer.reduce(CopyFilesReducer.java:30)
    at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:506)
    at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:447)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:268)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax

INFO mapred.JobClient: Job Failed: NA
13/12/12 13:55:25 INFO s3distcp.S3DistCp: Try to recursively delete hdfs:/tmp/985ffdb0-1bc8-4d00-aba6-fd9b18e905f1/tempspace
Exception in thread "main" java.lang.RuntimeException: Error running job
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:586)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:216)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at com.amazon.external.elasticmapreduce.s3distcp.Main.main(Main.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:208)
Caused by: java.io.IOException: Job failed!
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1388)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:568)

I then put access key and id into my core-site.xml on all the data and name node:
<property>
    <name>fs.s3.awsSecretAccessKey</name>
    <value>bippitybopityboo</value>
  </property>
  <property>
    <name>fs.s3.awsAccessKeyId</name>
    <value>supercalifragilisticexpialadoscious</value>
  </property>
  <property>
    <name>fs.s3n.awsSecretAccessKey</name>
    <value>bippitybopityboo</value>
  </property>
  <property>
    <name>fs.s3n.awsAccessKeyId</name>
    <value>supercalifragilisticexpialadoscious</value>
  </property>

and still was getting same error when i tried this:
hadoop jar /usr/lib/hadoop/lib/s3distcp.jar  --src hdfs://NN:8020/path/to/destination/folder --dest s3n://mybucket/destination/

Is there some configuration I'm supposed to do, or am I missing some jar files or executing it incorrectly?
Thanks for any help

A: Had the same issue.  The fix was to change from s3n to s3a.
# change from this
--dest s3n://acceseKeyId:secretaccesskey@mybucket/destination/
# to this
--dest s3a://acceseKeyId:secretaccesskey@mybucket/destination/

See also here: S3 Support in Apache Hadoop
s3 is deprecated s3n is not maintained so use s3a going forward.
S3A is the recommended S3 Client for Hadoop 2.7 and later

A successor to the S3 Native, s3n:// filesystem, the S3a: system uses
  Amazon's libraries to interact with S3. This allows S3a to support
  larger files (no more 5GB limit), higher performance operations and
  more. The filesystem is intended to be a replacement for/successor to
  S3 Native: all objects accessible from s3n:// URLs should also be
  accessible from s3a simply by replacing the URL schema.
Unmainteained: S3N FileSystem (URI scheme: s3n://)
S3N is the S3 Client for Hadoop 2.6 and earlier. From Hadoop 2.7+,
  switch to s3a
A native filesystem for reading and writing regular files on S3.With
  this filesystem is that you can access files on S3 that were written
  with other tools. Conversely, other tools can access files written
  using Hadoop. The S3N code is stable and widely used, but is not
  adding any new features (which is why it remains stable).
S3N requires a compatible version of the jets3t JAR on the classpath.
Since Hadoop 2.6, all work on S3 integration has been with S3A. S3N is
  not maintained except for security risks —this helps guarantee
  security. Most bug reports against S3N will be closed as WONTFIX and
  the text "use S3A". Please switch to S3A if you can -and do try it
  before filing bug reports against S3N.
(Deprecated) S3 Block FileSystem (URI scheme: s3://)

A: You need the AWS SDK for Java. Grab it from http://aws.amazon.com/de/sdkforjava/ and either put the jar into /usr/lib/hadoop/lib or pass it with the -libjars option. Assuming version 1.7.1 of the AWS SDK the command would then look like:
hadoop jar /usr/lib/hadoop/lib/s3distcp.jar \
    -libjars aws-java-sdk-1.7.1/lib/aws-java-sdk-1.7.1.jar \
    --src hdfs://NN:8020/path/to/destination/folder \
    --dest s3n://acceseKeyId:secretaccesskey@mybucket/destination/

References:

*

*AWS SDK for Java: http://aws.amazon.com/de/sdkforjava/

*libjars option: http://grepalex.com/2013/02/25/hadoop-libjars/


text:
Q: Site got SQLi injected while using bind_param Today I discovered my site got hacked through SQLi injection. Even though I am using bind_param I thought this was impossible.
if($_GET['api'] == 'info')
  {
  $status = 'Test';
  $stmt = $mysqli->prepare("INSERT INTO information(one, two, status) VALUES (?,?,?)");
  $stmt->bind_param('sss', $_GET['1'], $_POST['2'], $status);
  $stmt->execute();
  $stmt->close();
  }

What am I doing wrong?

A: Well your statements are mutually exclusive. Either you know for sure that it was SQL injection - and in this case you know which it was; or you have no evidence that it was SQL injection and not something else.
Speaking of the given code snippet - no, it's impossible to inject through this code.
So, either it was SQL injection, in some place where you weren't using bind_param, or it was some other kind of attack.


text:
Q: check inner join table existance my tbl_module may consist on empty id, what i want to do is to perform a checking on it, but there are errors return to me, my query doesnt work
SET @IID = 1
SELECT t1.ID, t1.Module FROM tbl_user t1

my problem started here, i cannot begin to join my previous query,i know this is an illegal way of execute the query, but can someone correct me or enlighten me?
IF EXISTS(SELECT t2.ID FROM tbl_Module t2 where @IID = t2.id)
BEGIN
  INNER JOIN tbl_Module t2 where t1.id = t2.id
 END

A: Try this one (MS SQL) -
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT *
FROM dbo.tbl_user t1
' + CASE WHEN OBJECT_ID('dbo.tbl_Module') IS NOT NULL
        THEN 'JOIN dbo.tbl_Module t2 ON t1.id = t2.id'
        ELSE ''
    END

PRINT @SQL
EXEC sys.sp_executesql @SQL

A: As Don said, it is more common to do a LEFT JOIN, which will just put NULL in the column t1.Module if no module with that id exists:
SELECT t1.ID, t1.Module FROM tbl_user t1
LEFT JOIN tbl_Module t2 where t1.id = t2.id

But your requirements may be special?
Hope this helps!


text:
Q: Alterar cor PHP/Html estou com o seguinte problema e creio que o JS possa ajudar, mas conheco quase nada de JS.
preciso que o conteudo da tag "td" se for igual a "Montar" fique verde e se for "Aguardar" fique vermelho.
        <input type="text" id="search" placeholder="Buscar">

Operacao

                    Ativo
                    Sinal
                    Cotação

            <?php while ($linha = mysqli_fetch_assoc($result)) { ?>

                        <?= $linha['ATIVO'] ?>
                        <?= $linha['Robo PUT'] ?>
                        <?= $linha['Real Time'] ?>

            <?php } ?>

A: Experimente algo como:
<td <? if ($linha['Robo PUT'] == 'Montar'): echo "style='color: red;'"; endif; ?>>
   <?= $linha['Robo PUT'] ?>


text:
Q: Gravitational force exerted by a light beam vs an infinite rod Imagine an infinite laser beam (at both ends) that passes from the vicinity of an object with some rest mass. The laser beam should bend in a specific way due to gravitational interaction with the object. Now, replace the the laser beam with a rigid material rod of density that corresponds to the the power of the laser so that equivalent energy/mass in the unit volume of the rod is the same as that of laser beam. Furthermore, rod is not straight but it exactly follows the trajectory of the initial laser beam...
My question is that from the view point of the reference object, are there any observable differences between the laser beam and material rod and if there is any, how to justify it? I wonder if "flow of energy" (via the laser beam) makes any difference to the reference object compared to static rod.
Note that an observer in the reference object does not "see" the light beam. No photons from the beam is hitting the object, they simply pass-by. A natural extension of the question is what if the rod is actually a pipe-like construct and the matter inside does flow with some velocity like a laser beam (but with some finite speed of course).


text:
Q: Whole page goes to the left when PHP code is inserted? Is there a reason the back-end PHP code could affect the layout of a page? This only happens in IE. In Firefox and Chrome, everything looks fine.
Thing is, we have this HTML code, then a back-end code for the functions on that page is inserted by <?php include "[name of file]";?>. The php file we included has no styling in it whatsoever but it mysteriously makes the whole page go to the left edge (instead of centered). If we remove that file from the page, it renders normally.
We have learned that if we comment out a certain part of the code on that file (view below), the layout gets fixed:
//function position_list() {
    global $db, $core, $global;
    ob_start('ob_gzhandler');
    include ROOT.'templates/listing.php';
    ob_flush();
//}

I'm just wondering if anybody has encountered a similar problem? What could be wrong?

A: There is probably a problem with the included code, not with styles but with broken tags. Some nesting is going on and a tag is being closed by something other than what opened it or something is being left open. You should try running the output code through a strict html validator to find the error.

A: Compare the source in IE with and without the include line. Is it what you expect? Are there any PHP warnings?
Quite odd to see you comment out the function {} part without commenting out the body of the function. You're effectively now calling position_list(); whatever. Which of the lines is it that is causing the rendering to change?
If this is all before the doctyle and <html> tag then it could be that the output is triggering the browser to render in quirks mode, rather than standard compliance mode.

A: Sounds like you are putting IE into quirks mode. If you are using margin:auto; on an element, IE tends to ignore it in quirks mode.
Make sure that the doctype is the very first thing in the file being outputted (no line breaks, spaces, comments, etc.). Also, make sure your page validates against the given doctype.
If the above doesn't work, please post more code.


text:
Q: How to get the theoretic serial number of list elements if they were sorted by the sum in Python? I have a list given filled with numpy arrays such as:
lst = [np.array([1, 2, 3, 4, 5]),
       np.array([16, 17, 18, 19, 20]),
       np.array([6, 7, 8, 9, 10]),
       np.array([11, 12, 13, 14, 15])]

I have already tried sort and sorted functions, but I did not find the proper key to monitor serial numbers.
I would like to find out which place would the elements (numpy arrays) of the list take if I sorted them based on their sum.
Considering the example, my expected output would be:
output = [0, 3, 1, 2]

Thank you very much in advance.

A: Update: For efficiency, you may want to call np.argsort only once. Then use the result as indices for the final output.
ind = np.argsort(np.sum(lst, 1))
output = ind[ind]

Use np.argsort twice on the sum of elements:
import numpy as np

lst = [np.array([1, 2, 3, 4, 5]),
       np.array([16, 17, 18, 19, 20]),
       np.array([6, 7, 8, 9, 10]),
       np.array([11, 12, 13, 14, 15])]

print(np.argsort(np.argsort(np.sum(lst, 1))))

Output:
[0 3 1 2]

A: You can use scipy.stats.rankdata:
import numpy as np

lst = [np.array([1, 2, 3, 4, 5]),
       np.array([16, 17, 18, 19, 20]),
       np.array([6, 7, 8, 9, 10]),
       np.array([11, 12, 13, 14, 15])]

from scipy.stats import rankdata
out = (rankdata(np.sum(lst, 1))-1).astype(int)

# array([0, 3, 1, 2])

A: I think expected output should be [0,2,3,1]
You can use sorted
import numpy as np
list_ = [np.array([1, 2, 3, 4, 5]), np.array([16, 17, 18, 19, 20]), np.array([6, 7, 8, 9, 10]), np.array([11, 12, 13, 14, 15])]
print([i for i, _ in sorted(zip(range(len(list_)), list_), key=lambda x: sum(x[1]))])


text:
Q: How to run unit test which testing the script with argparse attributes? I have got a simple program my_code.py with argparse and test_code.py with the test code. Please help me with how I should run correctly the test_code.py. When I try basic commands I get an error like below:
test: python -m unittest test_code.py

AttributeError: 'module' object has no attribute 'py'

test case: python -m unittest test_code.Test_Code

python -m unittest: error: too few arguments

test method: python -m unittest test_code.Test_Code.test_double_name

python.exe -m unittest: error: the following arguments are required: name

    # my_code.py
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("name")
    parser.add_argument('-d', '--double', action="store_true")

    def double_name(new_name):
      if args.double:
        return new_name + new_name
      else:
        return new_name

    if __name__ == "__main__":
        args = parser.parse_args()
        print(double_name(args.name))

    # test_code.py
    import unittest
    import my_code

    class Test_Code(unittest.TestCase):

      def test_double_name(self):
        my_code.args = my_code.parser.parse_args([])
        self.assertEqual(my_code.double_name('test-name'), 'test-name')

        my_code.args = my_code.parser.parse_args(["test-name", "-d"])
        self.assertEqual(my_code.double_name('test-name'), 'test-nametest-name')

    if __name__ == "__main__":
      unittest.main()

A: Hello your parser usage is not correct for calling variable

code.py

code.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "--name",
    metavar="name",
    type=str,
)
parser.add_argument(
    "--double",
    metavar="double",
    type=str,
)

def double_name(new_name):
    if args.double:
        return new_name + new_name
    else:
        return new_name

if __name__ == "__main__":
    args = parser.parse_args()
    print(double_name(args.name))

For Testing argparse, You can review This Post


text:
Q: Button image not aligned with text when the button is clicked? I'm having a rather irritating problem with images on buttons in .NET. They don't behave as you would expect an image on a button to behave.
In the properties of a button you can set Image. So I select an image and the image shows up on the button! So far so good.
When a button is clicked, or in a pressed state, the text of the button will move down and right one pixel to create a depth. But not the image! It will stay in the same position, and it will look weird.
There is also the BackgroundImage property, but that's even worse! Because if I set BackgroundImageLayout to None instead of Center, the image will move up and left when pressed, the complete opposite direction of the text! What's up with that?
Anyway, what I want to achieve is a button image that moves just like the text would move when the button is in a pressed state. Is there a way to do this?

A: Just make a new image and paste the original one at an offset. Then set that as the Button's Image.
Example:
private void button1_MouseDown(object sender, MouseEventArgs e)
{
    // replace "button_image.png" with the filename of the image you are using
    Image normalImage = Image.FromFile("button_image.png");
    Image mouseDownImage = new Bitmap(normalImage.Width + 1, normalImage.Height + 1);
    Graphics g = Graphics.FromImage(mouseDownImage);
    // this will draw the normal image at an offset on mouseDownImage
    g.DrawImage(normalImage, 1, 1); // offset is one pixel each for x and y
    // clean up
    g.Dispose();
    button1.Image = mouseDownImage;
}

private void button1_MouseUp(object sender, MouseEventArgs e)
{
    // reset image to the normal one
    button1.Image = Image.FromFile("button_image.png");
}

EDIT: The following function fixes a problem where the image would not 'pop' back up when the cursor leaves the button area while the mouse button is still pressed (see Labor's comment below):
private void button1_MouseMove(object sender, MouseEventArgs e)
{
    Point relMousePos = e.Location;
    bool mouseOverButton = true;
    mouseOverButton &= relMousePos.X > 0;
    mouseOverButton &= relMousePos.X < button1.Width;
    mouseOverButton &= relMousePos.Y > 0;
    mouseOverButton &= relMousePos.Y < button1.Height;
    if (mouseOverButton != MouseButtons.None)
    {
        button1_MouseDown(sender, e);
    }
    else
    {
        button1_MouseUp(sender, e);
    }
}


text:
Q: Updating the same instance variables from different processes Here is a simple secinaro:
class Test:
    def __init__(self):
        self.foo = []

    def append(self, x):
        self.foo.append(x)

    def get(self):
        return self.foo

def process_append_queue(append_queue, bar):
    while True:
        x = append_queue.get()
        if x is None:
            break
        bar.append(x)
    print("worker done")

def main():
    import multiprocessing as mp
    bar = Test()
    append_queue = mp.Queue(10)
    append_queue_process = mp.Process(target=process_append_queue, args=(append_queue, bar))
    append_queue_process.start()

    for i in range(100):
        append_queue.put(i)
    append_queue.put(None)
    append_queue_process.join()

    print str(bar.get())

if __name__=="__main__":
    main()

When you call bar.get() at the end of the main() function why does it still return an empty list? How can I make it so that the child process also works with the same instance of Test not a new one?
All answers appreciated!

A: Objects are copied between processes by pickling them and passing the string over a pipe. There is no way to achieve true "shared memory" for pure Python objects between processes. To achieve precisely this type of synchronization, take a look at the multiprocessing.Manager documentation (https://docs.python.org/2/library/multiprocessing.html#managers) which provides you with examples about synchronized versions of common Python container types. These are "proxied" containers where operations on the proxy send all arguments across the process boundary, pickled, and are then executed in the parent process.

A: In general, processes have distinct address spaces, so that mutations of an object in one process have no effect on any object in any other process.  Interprocess communication is needed to tell a process about changes made in another process.
That can be done explicitly (using things like multiprocessing.Queue), or implicitly if you use a facility implemented by multiprocessing for this purpose.  For example, a great deal of work is done under the covers to make changes to a multiprocessing.Queue visible across processes.
The easiest way in your specific example is to replace your __init__ function like so:
def __init__(self):
    import multiprocessing as mp
    self.foo = mp.Manager().list()

It so happens that an mp.Manager instance supports a list() method that creates a process-aware list object (really a proxy for a list object, which forwards list operations to an under-the-covers server process that maintains a single copy of "the real" list - the list object isn't really shared across processes, because that's impossible - but the proxies make it appear to be shared).
So if you make that change, your code will display the results you expect - and there is no simpler way.
Note that multiprocessing works better the less IPC (interprocess communication) you need, and that's true pretty much regardless of application or programming language.


text:
Q: Change value of PHP variable in a CSS file using JavaScript I've searched around but nothing specific about this topic shows up. I know you can't change php variables with javascript due to the server side/client side difference.
I am trying to figure out if I have a php variable in a CSS file that holds the value of HEX code for a color which is applied through out the css file. Is there a way to use JavaScript to change the value of the hex code defined inside the  tags?
for example:
<?php
    $clabel = '#330099'; //purple 51:0:153
?>
.text2
{
    color:                       <?=$clabel?>; /* font change*/
    font-size:                  14px;
    font-weight:                bold;
    font-family:                Trebuchet MS, arial, verdana;

I want to know how to change the $clabel value so that it would than affect all the other instances of the clabel variable in the css file.

A: No, this is not possible. The whole PHP-Code is executed on server side, and the client gets to see nothing but its output. JavaScript is completely client side, and has no clue if even any PHP Code existed on the page in the first place.
Alternatively, you can create two CSS-classes, one with the normal font and one with the changed font, and then change the class of the needed HTML tags via JavaScript. That's possible.

A: Like other answers already said it, you can't change a PHP variable from Javascript or CSS.
But if you are trying to dynamically (meaning after the page rendering) change the color of all elements that have the "text2" class with an arbitrary color, you can actually do it with Javascript. And again, this has nothing to do with PHP.
You have to edit the CSS stylesheet with some Javascript :

var changeColor = function()
{
    var newColor = document.getElementById('color').value;

    // Iterate over all the stylesheets in the page
    for (var i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].cssRules) {
            // Iterate over all the rules in a stylesheet
            for (var j = 0; j < document.styleSheets[i].cssRules.length; j++) {
                // Search for the selector you want to change
                if (document.styleSheets[i].cssRules[j].selectorText == '.text2') {
                    // Change the color rule of that selector
                    document.styleSheets[i].cssRules[j].style.color = newColor;
                }
            }
        }
    }
}

document.getElementById('btn').addEventListener('click', changeColor);
.text2 {
  color: #0000FF;
}

Bla bla

<input type="text" value="#FF0000" id="color">
<button type="button" id="btn">Change</button>

You may have to adapt the script for it to work in every browser, but i tested it successfully in Firefox.

A: Like you yourself have mentioned in your own question, javascript in this context is performed in the client side, even if you change the value at client side a new request will get the value that has been set to the variable $clabel in the server. A good strategy would be to create css classes to the colors and classes to format the text intended and then combine them. Whenever you want you can change the class using jquery for example or even pure javascript.
.color1 { color : #000; }
.color2 { color : #555; }
.color2 { color : #fff; }

.text2
{
  font-size:                  14px;
  font-weight:                bold;
  font-family:                Trebuchet MS, arial, verdana;
}

HTML

some text

if you want to apply the color2 in the client side, so you can do by using:
$('#p1').removeClass('color1').addClass('color2')


text:
Q: Closest distance + vertices of two meshes I would like to find two vertices of two meshes (1 vertex per mesh) that define the closest distance between them. Or the two triangles would be fine I guess.
However I'm not sure how to search for this in CGAL's documentation, I'm sure that this is doable with some existing tool (probably based on a 3d distance field and/or AABBs). Could I please get a hint (keywords/link) on what to look for?
I've been pointed to the Optimal Distances CGAL package, but it's not exactly what I want, since it outputs the distance and the coordinates, so finding the vertex ID is an additional computational overhead.
I've already implemented a collision detection with CGAL to find the triangle-triangle intersection in a triangle-soup, using AABB-trees. I guess that I should be somehow close to this, although now a simple soup with all me object-triangles wouldn't do the job.

A: The solution found was this:
CGAL's Optimal Distances package can give an approximation of the closest distance between the convex hulls of two meshes, without explicitly computing the hulls. As a result one gets the shortest distance between these hulls, and the coordinates of the 2 points that lie on them and define this distance.
Then these coordinates can be used as a search-query in kd-trees that contains the original vertices of the meshes in order to find the closest vertices.
In case one mesh is non-convex, the hull that CGAL is using is very approximate, so convex decomposition might be necessary. In such a case one would have to check distances for each convex part and then take the shortest distance.
The above would result in something like this:
enter link description here


text:
Q: JS/React How to prevent data from being fetched if URL doesn't exist? I'm writing an APP that fetches data from an API - based on user's actions.
I have a problem, because I have a search bar that changes the value of state. Then I use that state in the place of ${search} in this link
var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=demo`;
using that link I then fetch data based on user's input which is stored in search/setSearch state..
However the app completely crashes quite often.. because the app starts to pull data from the API whenever state changes.. for example if user wants to check data for "MSFT" ( Microsoft company ), and starts typing M-S-F-T.. the app will crash as it's trying to fetch data for every single letter that the user enters
so it goes to:

`alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=M&apikey=demo`; // M

`alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MS&apikey=demo`; // MS

`alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSF&apikey=demo`; // MSF

`alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo`; // MSFT

and tries to fetch data for every letter entered in the search bar
If the link doesn't exist, the app will crash ( this is the PROBLEM! )
and give me an error saying! "Cannot convert undefined or null to object" - of couse.. the link doesnt exist so its undefined/null as there's nothing to get
Anyways, I need to find a way to handle the app in a way that at least it doesn't crash, and only fetches data if the link is correct.. I tried to use lodash.debounce ( something like setTimeout ) to wait a few seconds to allow the user to finish writing a full name of the stock.. however if the user erases the search, then the app tries to fetch data for an empty string
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=&apikey=demo;
(after symbol= it passes nothing, there's no such link so the app crashes after failing to fetch proper data )
I thought this could potentially be fixed with conditional rendering - and I tried to render the data conditionally (if chart == undefined then ... ).. but if the link is wrong - the app crashes as always, whether its rendered conditionally or not!
Just for reference, here's the component in which I'm rendering the search bar //
const StockSearchBar = () => {
  const { search, setSearch } = useContext(SearchContext); // state is stored in context API in another file

  function handleButtonEvents(e) {
        handleClick();
    setTimeout(() => window.location.reload(), 3000);
    }

  const handleSearch = (e) => { // searchbar functionality
    e.preventDefault();
    setSearch(e.target.value.toUpperCase());
    debounce(() => setSearch(e.target.value.toUpperCase()), 2000); // debounce 2000 milliseconds
    // setTimeout(() => setSearch(e.target.value.toUpperCase()), 2500);
  };

  const handleClick = (e) => { // this is for backend - ignore it

    if (setSearch !== '') {

      const options =
      {
        method: 'POST',
        headers: {
          'Content-Type':  'application/json'
        },
        body: JSON.stringify({search}),
      };

      const response = fetch(`http://localhost:3001/api/search`, options);
      console.log("search entered");
      console.log(response)
    };
}

  return (

      <>

      Look for Stocks or Cryptos:

// this is the searchbar
<input type='text' onChange={handleSearch} onKeyPress={(ev) => {
if (ev.key === "Enter") {
handleButtonEvents();
}}}
placeholder={search} required/>
      <Button variant="success" type="submit" onClick={handleButtonEvents}  >Search</Button>

{search}

    </>
  );
};

export default StockSearchBar;

Basically, I need to figure out a way to prevent data from being fetched if the link (based on state) isn't a proper link. Or at least that's what I think my problem is.
import { createContext, useEffect, useState } from "react";

const SearchContext = createContext();

export function SearchProvider({ children }) {
    const [search, setSearch] = useState("AAPL")
    return (
        <SearchContext.Provider value={{ search, setSearch }}>{children}</SearchContext.Provider>
    )
}

export default SearchContext;

^ This is my context api file - it's where state is stored and shared across the app
One solution I think could possibly help is switching onChange with onSubmit or onClick and then saving state to localStorage ( because onClick/onSubmit refreshes the whole page including state.. I tried e.preventDefault but for some reason it refuses to work in the browser giving me an error that "preventDefault(); is not a function"...) however, I'm still trying to figure out how to do it.. but logically it makes sense
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo  --> demo link to the API for public use
EDIT // UPDATE
ok, so I got the app to work a lot better with an if (searchbar is empty then dont set state) - thanks to Robert's comment..
  const handleSearch = (e) => {
    e.preventDefault();
    if (e.target.value !== ``) {
    setSearch(e.target.value.toUpperCase())
    }
  };

I have not added this file (component), however I think it's important to include it for obvious reasons as the error is coming from here
function LineChart(props) {
  const { search, setSearch } = useContext(SearchContext);

  var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=demo`;

  const [chart, setChart] = useState();

  useEffect(() => { // fetching data from api
      axios.get(baseUrl)
      .then(res => {

        setChart(res.data);

      })
  }, [baseUrl]);

   useEffect(()=>{}, [chart]);

     const stockPrices = useMemo(() => chart && Object.values(chart['Time Series (Daily)']).map(i => i['1. open']).reverse(), [chart]); // store stock prices in stockPrices

     const stockDates = useMemo(() => chart && Object.keys(chart['Time Series (Daily)']).map(x => x.replace(/\d{4}-/, "")).reverse(), [chart]); // store dates in stockDates

// display stock chart + settings using chart.js
  var data = {
    labels: stockDates,
    datasets: [{
      label: `${search}`,
      data: stockPrices,
      backgroundColor: "rgba(255,116,89,0.05)",
      borderColor: "rgba(255,105,75,1)",
      borderWidth: 2,
      pointBorderColor: "#2984c5",
      pointBackgroundColor: "#fff",
      pointHoverRadius: 5,
      pointHoverBackgroundColor: 'black',
      fill: true,
      pointHoverBorderColor: "rgba(41, 132, 197, 1)",
      pointHoverBorderWidth: 7,
      pointRadius: 0,
      pointHitRadius: 30,
      tension: 0.3,
    }]
  };

  var options = {
    plugins: {
    legend: {
      display: '',
      labels: {
        color: 'white',
        font: {
          size: 30,
          family: 'verdana',
        },
      }
    }
  },
    maintainAspectRatio: true,
    responsive: false,
    radius: 3,
    scales: {
      y: {
        ticks: {
          callback: function (value) {
            return "$" + value;
          },
          color: 'rgba(210,230,244,1)',
          font: {
            size: 12,
            family: "Verdana" // Add your font here to change the font of your legend label
          }
        },
        grid: {
          color: 'rgba(255,255,255,0.02)',
        }
      },
      x: {
        grid: {
          color: 'rgba(255,255,255,0.02)',
        },
        ticks: {
          color: 'rgba(210,230,244,1)',
          font: {
            family: "Verdana" // Add your font here to change the font of your legend label
          }

        }
      },
    },

  }

  return (

    <>

          <Line data={data} height={800} width={1200} options={options} /> {/* DISPLAY CHART BASED ON THE FETCHED DATA */}

      <button onClick={() => setSearch("NIO")}>CLICK ME</button>

{search}
 {/* ADDED THIS FOR TESTING PURPOSES */}

    </>
    );
  }
export default LineChart;

A: There are two types of error that might defeat a fetch request, either the link doesn't exist, or a link exists but doesn't have data to be read. A error-catch block can be used to log the error without crashing the programme. I have used the following structure to fetch from a few thousand generated links where every now and then, one of the links is bad or the json data not present. It prevented crashes and reported silently to console.
fetch(`${url}`)
  .then(response => {
     if (!response.ok){throw new Error ('Bad Response');}
     else { return response.json()};
  })
  .then(data => {
      // process data here or pass to processing function;
      parseData(data)
  })
  .catch(error => {
     // if in a loop can also log which url failed;
     console.log('error made: ', error);
  });


text:
Q: Need a working Example of Handling large and small screens on Android I tried a lot for handling multiple Tablet and handset screens on Android but could not get right way of doing this. In some cases I am getting errors and some does not work. I also posted Stack Question but did not receive satisfied result. I want to show a list and discription side by side on tablet screen whereas only list in mobile screen. Is there any good and easy way of doing this? I also tried to this but could not get the goal.

A: yes you can do this. There is a way where you can select layout based on the device.
res/layout/my_layout.xml              // layout for normal screen size ("default")
res/layout-large/my_layout.xml        // layout for large screen size
res/layout-xlarge/my_layout.xml       // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml  // layout for extra-large in landscape orientation

res/drawable-mdpi/graphic.png         // bitmap for medium-density
res/drawable-hdpi/graphic.png         // bitmap for high-density
res/drawable-xhdpi/graphic.png        // bitmap for extra-high-density
res/drawable-xxhdpi/graphic.png       // bitmap for extra-extra-high-density

res/mipmap-mdpi/my_icon.png         // launcher icon for medium-density
res/mipmap-hdpi/my_icon.png         // launcher icon for high-density
res/mipmap-xhdpi/my_icon.png        // launcher icon for extra-high-density
res/mipmap-xxhdpi/my_icon.png       // launcher icon for extra-extra-high-density
res/mipmap-xxxhdpi/my_icon.png      // launcher icon for extra-extra-extra-high-density

in case of 10' tab create a layout in
res/layout-sw720dp/my_layout.xml

in case of 7' tab create a layout in
res/layout-sw600dp/my_layout.xml

 <?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/title_detailfragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/detail_fragment"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <fragment
        android:name="com.example.fyp_awais.tab.MainActivity$MyListFragment"
        android:id="@+id/list_fragment"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="1" />
    <fragment
        android:name="com.example.fyp_awais.tab.MainActivity$MyDetailFragment"
        android:id="@+id/detail_fragment"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="1" />

</LinearLayout>


text:
Q: Why does sprite size affect performance in OpenGL ES 2.0/3.0? There is a particle system for an explosion:

Vertex shader:
#version 300 es
uniform float u_lastTimeExplosion; // time elapsed since the explosion
// explosion center (particle coordinates are set relative to this center
uniform vec3 u_centerPosition;
uniform float u_sizeSprite;
layout(location = 0) in float a_lifeTime; // particle lifetime in seconds
// initial position of the particle at the time of the explosion
layout(location = 1) in vec3 a_startPosition;
layout(location = 2) in vec3 a_endPosition; // final position of the particle
out float v_lifeTime; // remaining particle lifetime
void main()
{
    gl_Position.xyz = a_startPosition + (u_lastTimeExplosion * a_endPosition);
    gl_Position.xyz += u_centerPosition;
    gl_Position.w = 1.0;
    // calculate the remaining particle lifetime
    v_lifeTime = 1.0 - (u_lastTimeExplosion / a_lifeTime);
    v_lifeTime = clamp(v_lifeTime, 0.0, 1.0);
    // calculate sprite size based on remaining life time
    gl_PointSize = pow(v_lifeTime, 5.0) * u_sizeSprite;
}

Fragment shader:
#version 300 es
precision lowp float;
in float v_lifeTime;
uniform vec4 u_color;
out vec4 fragColor;
uniform sampler2D s_texture;
void main()
{
    vec4 texColor = texture(s_texture, gl_PointCoord);
    fragColor = u_color * texColor;
    fragColor.a *= v_lifeTime; // increase sprite transparency
}

If the size of the sprite is less than 10, then everything is fine:
GLES20.glUniform1f(sizeSpriteLink, 10f);

If the size of the sprite increases, then is a slowdown in rendering (FPS reduction):
GLES20.glUniform1f(sizeSpriteLink, 150f);

Strangely - the number of sprites affects performance less than their size.
Question: Why does sprite size affect performance? Would be grateful for any anwer/comment.
Note: mipmap for particle texture used.

A: Not sure, but it seems that increasing the size of the sprite greatly affects the consumption of graphic memory resources. Maybe someone knows about this?
It is also better to use this type of filtering to increase performance:
// one value is taken from the nearest pyramid level
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,
        GLES20.GL_NEAREST_MIPMAP_NEAREST);


text:
Q: javascript modal is not working I am using bracket tool to study about javascript.
When I see preview, I can see a button. However, even though I click the button several times and changed codes, nothing happen. Modal does not show up.
I know there are so many similar questions about modal.
I read some answers but I couldn't solve this problem.
Can somebody please give me advice how I can solve this issue?
<!DOCTYPE html >

     <link rel="stylesheet" href="modal.css">

    <button id="myBtn">Open Modal</button>

     x

Some text in the Modal..

A: Browser is loading a page from top to bottom. Therefore your script runs before html elements are loaded and can not find them.
Solution is to put your

           <button id="myBtn">Open Modal</button>

                   x

Some text in the Modal..


text:
Q: Storing input values in structs for fastest comparison later I'm sampling eight input ports and comparing the values up to ten times a second.
These inputs will be XOR'd against a similar field, indicating which signals are set to "Active Low", then an AND operation to mask out input signals that are not going to be compared (though all signals are sampled, whether compared or not).
So this is an example for the sampling. I've created a struct where the signals will be stored and then saved in memory. This struct contains a lot of other values, so replacing the whole struct is not an option. Anyway, these input values need to be saved in a efficient way so I later on can perform fast XOR and AND operations with my masks.
void SampleData(){
   // These are not all values o be sampled, only inputs
   currentSample.i0       = RD13_bit;
   currentSample.i1       = RD12;
   currentSample.i2       = RD11;
   currentSample.i3       = RD10;
   currentSample.i4       = RE12;
   currentSample.i5       = RE13;
   currentSample.i6       = RF8;
   currentSample.i7       = RF9;
}

This is an example of the comparison I need
checkInputSignals(){
  activated = ((inputValues ^ activeLowInputs) & activeInputsMask);

  if(activated ){
    importantMethod();
  }

 }

I've tried a bitfield, but I couldn't get the operators to work, and I've no knowledge about the effiency using bitfield. Efficiency in this project is not focused on memory, but speed and comfort. How should I store my three fields? If it helps, I am using a dsPic33EP microprocessor.
If using a 'char' or 'uint_8', my sample method would look like this, right? And this does not seem to be the most elegant solution.
    unsigned char inputValues;

    void SampleData(){
       currentSample.i0       = RD13_bit;
       currentSample.i1       = RD12;
       currentSample.i2       = RD11;
       currentSample.i3       = RD10;
       currentSample.i4       = RE12;
       currentSample.i5       = RE13;
       currentSample.i6       = RF8;
       currentSample.i7       = RF9;
       // For the masking
       inputValues += currentSample.i7;
       inputValues  = (inputValues << 1) + currentSample.i6;
       inputValues  = (inputValues << 1) + currentSample.i5;
       inputValues  = (inputValues << 1) + currentSample.i4;
       inputValues  = (inputValues << 1) + currentSample.i3;
       inputValues  = (inputValues << 1) + currentSample.i2;
       inputValues  = (inputValues << 1) + currentSample.i1;
       inputValues  = (inputValues << 1) + currentSample.i0;
    }

And I would have to do the same for my masks, for example.
void ConfigureActiveLowInputs(){
  activeLowInputs += currentCalibration->I0_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I1_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I2_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I3_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I4_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I5_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I6_activeLow;
  activeLowInputs  = (activeLowInputs << 1) + currentCalibration->I7_activeLow;
}

There must be a better solution than bit shifting?

A: Some things I think you need to know.

*

*Don't use bit fields. Apart from being non-portable, they make this kind of bit-twiddling harder, not easier.

*Don't use run-time shifts. Get the compiler to do your work.

*Do read code, study and practice. Learning bit-twiddling can be hard, and from your code I don't think you're quite there yet.

If we're going to help there are some things we need to know.

*

*You mention 8 ports. Are they single bit ports, or single ports with multiple bits?

*You mention 3 fields. What are they?

*Your sample code uses + operators, which are rarely used in bit operations. Why?

In C the code usually ends up with a set of macros and defines, plus a few small functions. It's all quite simple, generates good code, and runs fast without too much effort. If we only knew what you were trying to do.

A: You seem to be storing individual bits is separate structure members, and then packing them to word on the fly to be able to apply masks; but it is probably more efficient to pack them into a word, and use a mask to access the individual bits when necessary.
The members i0, i1 etc. are probably unnecessary. It would be simpler to pack the bits directly into a uint8_t member, then write functions or macros to return individual bits where necessary.
uint8_t void SampleData()
{
    return (RD13_bit << 7 ) |
           (RD12 << 6) |
           (RD11 << 5) |
           (RD10 << 4) |
           (RE12 << 3) |
           (RE13 << 2) |
           (RF8 << 1) |
           RF9 ;
}

Then:
currentSample.i = SampleData() ;

Then you can apply masks to that directly. If you need to access individual bits (and if you don't, why make then separate members in the first case?) then for example:
#include <stdbool.h>
#define GETBIT( word, bit ) (((word) & (1<<bit) != 0)

bool i6 = GETBIT( currentSample.i, 6 ) ;


text:
Q: I am having a column like this 9(05),X(05),X(15). I want to separate this 9,X,X into one column and data in () into another column. How can I do that? I am having a column like this 9(05),X(05),X(15). I want to separate this 9,X,X into one column and data in () into another column. How can I do that?
input column is
9(05)
x(05)
x(15)
x(15)
s9(07)

A: Use extract:
pat = r'(.*?)\((.*?)\)'
df[['a','b']] = df['col'].str.extract(pat, expand=True)
print (df)
      col   a   b
0   9(05)   9  05
1   x(05)   x  05
2   x(15)   x  15
3   x(15)   x  15
4  s9(07)  s9  07