text:
Q: Remove a life from my game when dot passes certain point? I'm designing a game for a class where:

*

*A colored dot appears from the right side of the screen and moves across the screen to the left on a fixed horizontal axis.

*When the dot reaches the middle, the player needs to press a key corresponding to its color. If done at the right time, the score increases by one.

*If not, the player loses one life.

I'm having trouble with the following:

*

*[SOLVED] Adding a new dot to the list of dots at random intervals in the game. This will make it so the dots don't appear linearly, and two dots can be generated right after one another.

*[SOLVED] Moving the dots across the screen left to right.

*[SOLVED] Removing the correct dot when it's in the hitbox area.

*Removing a life if a dot goes offscreen.

The language used here is intermediate student with lambda.
Currently, when I press 1 for red, it will remove it as long as a red dot is the first in the list. I need a function that removes that specific red dot.
Here's the code so far; know that it's not finished and thus not working as I intend it to.
; Color Match

; Game structures
(define-struct dot [x color])
(define-struct cm [dots score lives state])

; Constants
(define width 800)
(define height (/ width (/ 16 9)))
(define h-w (/ width 2))
(define h-h (/ height 2))
(define arrow (beside (rectangle 25 10 "solid" "black")
                                             (rotate 135 (right-triangle 18 18 "solid" "black"))))

(define background (empty-scene width height))
(define bars (place-images
    (list
     (circle (/ width 25) "outline" "black")
     (rectangle (+ width 2) (- height 375) "outline" "black"))
    (list
     (make-posn h-w h-h)
     (make-posn h-w h-h))
  background))

; Game
(define (main ws)
  (big-bang (make-cm empty 0 3 "start")
            [on-tick tock]
            [to-draw render]
            [on-release interact]
            ))

;; random-color: number -> string
;; consumes a number and returns a color
;; string for the given number
(define (random-color n)
  (cond
    [(= n 0) "red"]
    [(= n 1) "blue"]
    [(= n 2) "green"]
    [(= n 3) "yellow"]
    [else (error "Invalid color chosen.")]))

;; draw-dot: structure -> image
;; consumes a dot structure and draws it as an image

(define (draw-dot struct)
  (cond
    [(string=? (dot-color struct) "red") (overlay
                                    (rotate 90 arrow)
                                    (circle (/ width 25) "outline" "black")
                                    (circle (/ width 25) "solid" (dot-color struct)))]
    [(string=? (dot-color struct) "blue") (overlay
                                    (rotate 270 arrow)
                                    (circle (/ width 25) "outline" "black")
                                    (circle (/ width 25) "solid" (dot-color struct)))]
    [(string=? (dot-color struct) "green") (overlay
                                    (flip-horizontal arrow)
                                    (circle (/ width 25) "outline" "black")
                                    (circle (/ width 25) "solid" (dot-color struct)))]
    [(string=? (dot-color struct) "yellow") (overlay
                                    arrow
                                    (circle (/ width 25) "outline" "black")
                                    (circle (/ width 25) "solid" (dot-color struct)))]))

;; tock: color-match -> color-match
;; placeholder for later worldstate
(define (tock ws)
  (cond
    [(string=? (cm-state ws) "play")
     (make-cm (move-dots (add-dot? (random 50) (cm-dots ws)))
              (+ (cm-score ws) 1)
              (cm-lives ws)
              "play")]
    [else ws]))

;; add-dot?: number, list of dots -> list of dots
;; consumes list of dots and number and adds a new dot
;; to the list of dots
(define (add-dot? n lod)
  (cond
    [(= n 1) (cons (make-dot (+ width 25) (random-color (random 4))) lod)]
    [else lod]))

;; render: color-match -> image
;; consumes the current color-match structure and calls the appropriate
;; helper function.
(define (render ws)
  (cond
    [(string=? (cm-state ws) "start") (render-start ws)]
    [(string=? (cm-state ws) "play") (render-play ws)]
    [(string=? (cm-state ws) "pause") (render-pause ws)]
    [else (error "Invalid gamestate chosen.")]))

;; render-start: color-match -> image
;; helps the render function by displaying the current state
;; as an image.
(define (render-start ws)
  (place-image
   (above
    (text "Instructions" (/ width 20) "red")
    (text "Colored shapes will begin appearing from the right of the screen." (/ width 50) "black")
    (text "Once they reach the bar in the middle, press the appropriate key." (/ width 50) "black")
    (text "1: Red" (/ width 50) "red")
    (text "2: Blue" (/ width 50) "blue")
    (text "3: Green" (/ width 50) "green")
    (text "4: Yellow" (/ width 50) "yellow"))
   h-w
   h-h
   background))

;; draw-dots: list of dots -> image
;; consumes a list of dots and draws them
;; according to their color
(define (draw-dots lod)
  (cond
    [(empty? lod) bars]
    [else (place-image (draw-dot (first lod))
                       (dot-x (first lod))
                       h-h
                       (draw-dots (rest lod)))]))

;; is-visible?: dot -> boolean
;; consumes a dot and determines if it is currently visible
;; on the canvas
(define (is-visible? dot)
  (cond
    [(> (dot-x dot) -25) #true]
    [else #false]))

;; move-dot: dot -> number
;; consumes a dot and returns its new
;; x coordinate
(define (move-dot dot)
  (- (dot-x dot) 10))

;; new-dot: dot -> dot
;; consumes a dot and returns a new dot by calling
;; the move-dot function
(define (new-dot dot)
  (make-dot (move-dot dot) (dot-color dot)))

;; move-dots: list of dots -> list of dots
;; consumes a list of dots and moves them across the
;; canvas as long as they are in view
(define (move-dots lod)
  (cond
    [(empty? lod) empty]
    [(not (is-visible? (first lod))) (rest lod)]
    [else (cons (new-dot (first lod)) (move-dots (rest lod)))]))

;; draw-bars: cm -> image
;; consumes the world state and returns the image of bars
(define (draw-bars ws)
  (place-image (draw-dots (cm-dots ws))
               h-w
               h-h
               bars))

;; render-play: color-match -> image
;; helps the render function by displaying the current state
;; as an image.
(define (render-play ws)
  (overlay/align "left" "top" (current-lives ws)
  (underlay/align "right" "top" (place-image (draw-bars ws)
                                             h-w
                                             h-h
                                             background)
                  (current-score ws))))

;; current-lives: cm -> image
;; consumes the worldstate and displays the
;; current life count
(define (current-lives ws)
  (text (string-append "Lives: " (number->string (cm-lives ws))) 18 "red"))

;; current-score: cm -> image
;; consumes the worldstate and shows the
;; current score
(define (current-score ws)
  (text (string-append "Score: " (number->string (cm-score ws))) 18 "black"))

;; render-pause: color-match -> image
;; helps the render function by displaying the current state
;; as an image.
(define (render-pause ws)
  (place-image
  (text "paused" (/ width 20) "red")
  h-w
  (- h-h 75)
  (render-play ws)))

; (define (check-dot lod key)
;   (cond
;     [(empty? lod) empty]
;     [(and (< (- h-w (+ (/ width 25) 25)) (dot-x (first lod)) (+ h-w (+ (/ width 25) 25))) (string=? (dot-color (first lod)) "red") (key=? key "1")) (remove (make-dot (dot-x (first lod)) "red") lod)]
;     [(and (< (- h-w (+ (/ width 25) 25)) (dot-x (first lod)) (+ h-w (+ (/ width 25) 25))) (string=? (dot-color (first lod)) "blue") (key=? key "2")) (remove (make-dot (dot-x (first lod)) "blue") lod)]
;     [(and (< (- h-w (+ (/ width 25) 25)) (dot-x (first lod)) (+ h-w (+ (/ width 25) 25))) (string=? (dot-color (first lod)) "green") (key=? key "3")) (remove (make-dot (dot-x (first lod)) "green") lod)]
;     [(and (< (- h-w (+ (/ width 25) 25)) (dot-x (first lod)) (+ h-w (+ (/ width 25) 25))) (string=? (dot-color (first lod)) "yellow") (key=? key "4")) (remove (make-dot (dot-x (first lod)) "yellow") lod)]
;     [else lod]))

;; correct-dot? cm, lod, string -> list of dots
;; consumes the world state, its list of dots, a string, and sorts
;; out dots that have been correctly selected
(define (correct-dot? lod c)
  (cond
    [(empty? lod) empty]
    [(and (< (- h-w (+ (/ width 25) 1)) (dot-x (first lod)) (+ h-w (+ (/ width 25) 1))) (string=? (dot-color (first lod)) c)) (correct-dot? (rest lod) c)]
    [else (cons (first lod) (correct-dot? (rest lod) c))]))

;; is-it?: list of dots, key -> list of dots
;; consumes a list of dots and a key and returns
;; a new list of dots with one removed if the
;; conditions are met for it
(define (is-it? lod key)
  (cond
    [(empty? lod) empty]
    [(key=? key "up") (correct-dot? lod "red")]
    [(key=? key "down") (correct-dot? lod "blue")]
    [(key=? key "left") (correct-dot? lod "green")]
    [(key=? key "right") (correct-dot? lod "yellow")]
    [else lod]))

;; interact: color-match, key -> color-match
;; consumes the current color-match state and returns
;; a new one depending on which key is pressed.
(define (interact ws key)
  (cond
    [(string=? (cm-state ws) "play")
     (cond
       [(key=? key "p") (make-cm (cm-dots ws)
                                 (cm-score ws)
                                 (cm-lives ws)
                                 "pause")]
       [else (make-cm (is-it? (cm-dots ws) key)
                      (cm-score ws)
                      (cm-lives ws)
                      (cm-state ws))])]
    [(and (string=? (cm-state ws) "start") (key=? key "p")) (make-cm (cm-dots ws)
                                                                     (cm-score ws)
                                                                     (cm-lives ws)
                                                                     "play")]
    [(and (string=? (cm-state ws) "pause") (key=? key "p")) (make-cm (cm-dots ws)
                                                                     (cm-score ws)
                                                                     (cm-lives ws)
                                                                     "play")]
    [else ws]))

(main 200)

A: In ISL lists are not mutable so the only thing that you are able to do is create a new list with everything except what you want to remove. You could possibly filter through the list with your procedure only accepting the elements you want to keep


text:
Q: how to handle http request error in blade? I am getting an HTTP request in my controller like this:
try {
    $cards = $client = Http::acceptJson()->get('www.my.local', $request->input());
    $response = $client->json();

    if ($client->clientError()) {
        throw new HttpException(400, $error['errors'][0]['detail'] ?? 'Server busy');
    }

    return view('card::cards.index')
        ->with([
            'items' => $cards['data'],
            'meta' => $cards['meta'],
        ]);
} catch (\Exception $exception) {
    return back()->withErrors($exception->getMessage())->withInput();
}

The error response:
[
   "error" => "validate error",
   "fields" => [
      "id" => "init",
      ......
   ]
]

And somethings like this:
[
    "error" => "server error"
]

I want to show all of the errors array in my blade but I can't.

A: You can get errors in blade file and showing them using $errors variable which is available in your blade. More info in laravel doc
@if($errors->any())

    @foreach($errors->all() as $error)

{{ $error }}

    @endforeach

@endif

redpajama_set_name: RedPajamaStackExchange


text:
Q: React Native FlatList is not scrolling I am developing a React Native application for Learning purposes. Now I am using FlatList in my application. But I am having a problem. My flat list is not scrolling to see all the items. It bounces back when I tried to scroll it out of screen size. I used the solutions I found online adding the flex to 1 on the root, but it is not working.
Here is my code:
class Events extends React.Component {
  static navigationOptions = {
    title: "Events"
  };

  constructor(props) {
    super(props);
    this.state = {
      data: [
        {
          id: 1,
          name: "Name 1"
        },
        {
          id: 2,
          name: "Name 2"
        },
        {
          id: 3,
          name: "Name 3"
        },
        {
          id: 4,
          name: "Name 4"
        },
        {
          id: 5,
          name: "Name 5"
        },
        {
          id: 6,
          name: "Name 6"
        },
        {
          id: 7,
          name: "Name 7"
        },
        {
          id: 8,
          name: "Name 8"
        },
        {
          id: 9,
          name: "Name 9"
        },
        {
          id: 10,
          name: "Name 10"
        },
        {
          id: 11,
          name: "Name 11"
        },
        {
          id: 12,
          name: "Name 12"
        },
        {
          id: 13,
          name: "Name 13"
        },
        {
          id: 14,
          name: "Name 14"
        },
        {
          id: 15,
          name: "Name 15"
        },
        {
          id: 16,
          name: "Name 16"
        },
        {
          id: 17,
          name: "Name 17"
        },
        {
          id: 18,
          name: "Name 18"
        },
        {
          id: 19,
          name: "Name 19"
        },
        {
          id: 20,
          name: "Name 20"
        },
        {
          id: 21,
          name: "Name 21"
        },
        {
          id: 22,
          name: "Name 22"
        },
        {
          id: 23,
          name: "Name 23"
        },
        {
          id: 24,
          name: "Name 24"
        }
      ]
    };
  }

  _handleLoadMore() {}

  renderItem(item) {
    return (
      <Card>
        <CardItem>
          <Left>
            <Thumbnail source={{ uri: "https://www.vkguy.co.uk/images/slideshow/05.jpg" }} />
            <Body>
              <Text>NativeBase</Text>
              <Text note>GeekyAnts</Text>
            </Body>
          </Left>
        </CardItem>
        <CardItem cardBody>
          <Image
            source={{ uri: "https://www.vkguy.co.uk/images/slideshow/05.jpg" }}
            style={{ height: 200, width: null, flex: 1 }}
          />
        </CardItem>
        <CardItem>
          <Left>
            <Button transparent>
              <Icon active name="thumbs-up" />
              <Text>12 Likes</Text>
            </Button>
          </Left>
          <Body>
            <Button transparent>
              <Icon active name="chatbubbles" />
              <Text>4 Comments</Text>
            </Button>
          </Body>
          <Right>
            <Text>11h ago</Text>
          </Right>
        </CardItem>
      </Card>
    );
  }

  render() {
    return (
        <FlatList
        contentContainerStyle={{
          flex: 1,
          flexDirection: "column",
          height: "100%",
          width: "100%"
        }}
        data={this.state.data}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => this.renderItem(item)}
        onEndReached={this._handleLoadMore}
      />
    );
  }
}

export default Events;

But it is not scrolling to see the items off the screen. How can I fix it?
Here is the screenshot. I cannot scroll down more than that.

A: Change some styling in FlatList view and add View as main container
render() {
    return (
        <View style={{ flex: 1, width: '100%' }}>
            <FlatList
                data={this.state.data}
                keyExtractor={item => item.id.toString()}
                renderItem={({ item }) => this.renderItem(item)}
                onEndReached={this._handleLoadMore}
            />
        </View>
    );
  }

A: Try with
<FlatList
    contentContainerStyle={{ flexGrow: 1, paddingBottom: 5 }}
    data={this.state.data}
    keyExtractor={item => item.id.toString()}
    renderItem={({ item }) => this.renderItem(item)}
    onEndReached={this._handleLoadMore}
    onEndReachedThreshold={0.5}
  />


text:
Q: Mysql root user password set to empty string I've repeatedly tried to set a password for the root mysql user, originally there was no password at all. However, after resetting it, via code I found from tutorials on the subject:
mysqld_safe --skip-grant-tables &
UPDATE user SET authentication_string=PASSWORD("mypasswordhere") where User='root';
FLUSH PRIVILEGES;

The terminal says I set the password correctly, but when I try to log back in with the password, it doesn't work. What I found is that it's setting the password to an empty string, does anyone know why?

A: I had some problems to set the password using PASSWORD() function because the validate_password plugin was activated, to bypass this plugin, I created the authentication_string value before setting the new password.
You don't need run mysql in safe mode mysql_safe --skip-grant-tables to change a password, just start normally and try this:
# mysql -uroot

mysql> SELECT PASSWORD('HELLO');
+-------------------------------------------+
| PASSWORD('HELLO')                         |
+-------------------------------------------+
| *C1BCFD6877BB358C0518ECCD6D5A70BFF7D0A174 |
+-------------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> use mysql;

mysql> update user set authentication_string="*C1BCFD6877BB358C0518ECCD6D5A70BFF7D0A174" where User='root';
mysql> flush privileges;
mysql> quit

# mysql -uroot -pHELLO

mysql>

Another simple solution is the ALTER USER command:
ALTER USER 'root'@'localhost' IDENTIFIED BY '*C1BCFD6877BB358C0518ECCD6D5A70BFF7D0A174';

If these solutions not work, please show the output from the commands and which MySQL version you using to test.


text:
Q: Is there a case statement in Haml-Coffee? I'd like to do the following in Haml-Coffee:
- case msg.type
- when "usertext"
    = msg.body
- when "direct"
    = msg.content.kbcontent_body

But I get an error "Reserved word "case""
I suspect it's not supported by Haml-Coffee actually.

A: Before the question was edited, it's main phrase had been:
Is there a case statement in HAML?
The answer is: in vanilla Haml there indeed is case!
%p
  - case 2
  - when 1
    = "1!"
  - when 2
    = "2?"
  - when 3
    = "3."

A: There isn't a case statement in CoffeeScript. You want switch — the case keyword is the JavaScript equivalent of when, and like many dropped JavaScript keywords is reserved in CoffeeScript. Also, I'm not 100% positive and don't have Haml-Coffee to test right now, but I think you'll need to indent the body of the switch.

A: You can use any complex ruby code in haml using :ruby syntax when it is extremely necessary. Keep this on top level and use the resulting variable in your coffee haml
:ruby
  x = case a
  when 2
     "two"
  when 3
     "three"
  end


text:
Q: iOS / Swift 3: UIView too big within UIPageController I embedded a PageController within a ContainerView.
Why are the Views I display in the PageController not scaled to fit the PageController? How can I achieve "scale to fit"?
(At least the PageController itself adapts its size to the ContainerView)
My classes are:
import UIKit

class YellowController : UIViewController

{

}

class GreenController : UIViewController
{

}

//from a tutorial:
class PageController : UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate
{
// from stackoverflow to avoid the black box at the bottom of the pagecontroller
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    for view in self.view.subviews
    {
        if view is UIScrollView
        {
            view.frame = UIScreen.main.bounds
        }
        else
        {
            view.backgroundColor = UIColor.clear
        }
    }
}

lazy var VCArray: [UIViewController] =
{
    return [self.VCInstance(name: "InfoPage"),
            self.VCInstance(name: "FragePage"),
            self.VCInstance(name: "AntwortPage") ]
}()

private func VCInstance (name: String) -> UIViewController
{
    let VCC = UIStoryboard(name: "Lerneinheit", bundle: nil).instantiateViewController(withIdentifier: name)

    return VCC
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.dataSource = self
    self.delegate = self
    if let InfoPage = VCArray.first
    {
        setViewControllers([InfoPage], direction: .forward, animated: true, completion: nil)
    }
}

public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
{
    guard let viewControllerIndex = VCArray.index(of: viewController)
    else
    {
        return nil
    }

    if (viewControllerIndex<1)
    {
        return nil
    }

    return VCArray[viewControllerIndex - 1]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
{
    guard let viewControllerIndex = VCArray.index(of: viewController)
        else
    {
        return nil
    }

    if viewControllerIndex == VCArray.count-1
    {
        return nil
    }

    return VCArray[viewControllerIndex + 1]
}

public func presentationCount(for pageViewController: UIPageViewController) -> Int
{
    return VCArray.count
}

public func presentationIndex(for pageViewController: UIPageViewController) -> Int
{
    guard let firstViewController = viewControllers?.first, let firstViewControllerIndex = VCArray.index(of: firstViewController)
    else
    {
        return 0
    }

    return firstViewControllerIndex
}

IB:

Result wth the yellow view beeing cut instead of scaled to fit the PageController:

Constraints for the yellow view:

A: The code below is redundant, remove it:
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    for view in self.view.subviews
    {
        if view is UIScrollView
        {
            view.frame = UIScreen.main.bounds
        }
        else
        {
            view.backgroundColor = UIColor.clear
        }
    }
}


text:
Q: How to change private @mobx.observable.ref mobx state via props? Currently my class is defined this way:
type ClapWidgetProps = {
  animate: boolean,

};

export class Widget extends React.Component<WidgetProps> {
  @mobx.observable.ref private animate: boolean = this.props.animate || false;

This observable animate controls some animation effect inside the widget.
As you can see the internal state animate is initialised by this.props.animate.
What I want to achieve is that I wish to able to change the value of the observable animate via this.props.animate continuously even after initialisation.
How can I let this.props.animate override observable animate when the property is changed?

A: In case you need to control animation both from inside and from outside component you need to benefit from the React lifecycle methods
@observer
export class Widget extends React.Component<WidgetProps> {
  @observable private animate: boolean = this.props.animate || false;

  toggleAnimate = () => {
    this.animate = !this.animate;
  }

  componentDidUpdate(prevProps) {
    if (prevProps.animate !== this.props.animate) {
      this.animate = this.props.animate;
    }
  }

  render() {
     // call  this.toggleAnimate to change animate from inside component
  }
}

And from outer
// some jsx

<Widget animate={this.state.animate} />

// and if outer component this.state.animate changes - it will cause a change of Widget animate prop

A: MobX is all about  the stores which are state of your application. In your example you have 2 sources of animate property which (within your Widget component and somewhere outside which you pass to Widget as prop) isn't really a good practice.
This would be a much better way to setup your application
class Store {
    @observable animate = false;

    @action
    setAnimate(animate) {
        this.animate = animate;
    }
}

@inject('store')
class Widget extends React.Component {
    toggleAnimate = () => {
        const { store } = this.props;
        store.setAnimate(!store.animate);
    }

    render() {
        const { animate } = this.props.store;
        // whenever animate changes in your store render method will trigger
    }
}

Please note that this is not working example since you'll have to setup your Provider at root level of your application. Please see section Provider and inject https://github.com/mobxjs/mobx-react for more info.
You can find more about defining stores at https://mobx.js.org/best/store.html.


text:
Q: Yii2 - Renderizar una vista desde una subcarpeta Estoy trabajando en Yii2. Quería saber cuál es la forma correcta de renderizar desde el controlador una vista que se encuentra dentro de una subcarpeta en el directorio views. Por ejemplo, tengo la siguiente situación:
views
-campus (carpeta)
--actividad (subcarpeta)
---2020.php (vista)

Intenté las siguientes opciones pero sin resultado:

*

*$this->render('/actividad/2020',[]); return

*$this->render('/actividad/2020',[],$this->context); return

*$this->render('2020',[],$this->context); return

*$this->render('@app/views/campus/actividad/2020',[]); return

*$this->render('//actividad/2020',[]);

Desde ya gracias!

A: Recuerda que la ruta principal viene con el mismo nombre que tu controller y es a partir de ahi que puedes ir construyendo la ruta. Ejemplo
CampusController
  actionIndex
   $this->render('index');

Ira a la ruta views/campus/index.php
Si tu quieres ir a otra carpeta debe ser a partir de campus por ejemplo si quieres ir a

campus/actividad/2020.php

La ruta del render debería ser
$this->render('actividad/2020');

Lo que te sobra es la "/" del principió en tus intentos , es decir tu intento 1 ha de cambiar de
$this->render('/actividad/2020',[]); return

a
$this->render('actividad/2020',[]); return


text:
Q: Is possible SWAP sol to USDC? I am trying to SWAP from SOL to USDC, this is what I have tried with web3js, Raydium and even Jupiter, none of these integrations have returned a positive result, on the other hand I do not find much documentation on the subject, I know how to send TOKEN -> TOKEN but no CRYPTO (SOL) -> STABLE-COIN (USDC)
What I am trying to do is make the SWAP work now with Jupiter, this has been impossible, there is a way to make SWAP between SOL and USDC?
Code Example
const jupiter = await Jupiter.load({
            connection: this.connection,
            cluster: "mainnet-beta",
            user: wallet,
        });

        const tokens = await this.getTokens();

        console.log(tokens);

        const routeMap: Map<string, string[]> = jupiter.getRouteMap();
        const outputToken = tokens.find((t) => t.address == "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
        const inputToken = tokens.find((t) => t.address == environment.swap.WrappedSolAddress);

        const routes = await jupiter.computeRoutes({
            inputMint: new PublicKey(inputToken.address),
            outputMint: new PublicKey(outputToken.address),
            inputAmount: LAMPORTS_PER_SOL * 1,
            slippage: 1,
        });

        const { execute } = await jupiter.exchange({
            routeInfo: routes.routesInfos[0],
        });

        const swapResult: any = await execute();

Error
TypeError: Cannot read properties of undefined (reading 'address')
at SolanaService.<anonymous> (/home/foo/GitHub/foo/dist/apps/foo/webpack:/doo/apps/foo-api/src/app/services/solana/solana.service.ts:208:55)

A: The way you're fetching tokens might be wrong
import {Jupiter,TOKEN_LIST_URL} from "@jup-ag/core"

const tokens = await (await fetch(TOKEN_LIST_URL["devnet"])).json();
console.log(tokens.find((t)=> t.address == "7duMWSNdYMof6WKZHs5X1wdmmxUa6cDGqqKShhMSGkgg"))


text:
Q: Why the gradient generated doesn't get displayed? As I copy the generated gradient :
background: #e4f5fc; /* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2U0ZjVmYyIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjQyJSIgc3RvcC1jb2xvcj0iI2JmZThmOSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjQ2JSIgc3RvcC1jb2xvcj0iI2JmZThmOSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjY3JSIgc3RvcC1jb2xvcj0iIzlmZDhlZiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiMyYWIwZWQiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(top,  #e4f5fc 0%, #bfe8f9 42%, #bfe8f9 46%, #9fd8ef 67%, #2ab0ed 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e4f5fc), color-stop(42%,#bfe8f9), color-stop(46%,#bfe8f9), color-stop(67%,#9fd8ef), color-stop(100%,#2ab0ed)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #e4f5fc 0%,#bfe8f9 42%,#bfe8f9 46%,#9fd8ef 67%,#2ab0ed 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #e4f5fc 0%,#bfe8f9 42%,#bfe8f9 46%,#9fd8ef 67%,#2ab0ed 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #e4f5fc 0%,#bfe8f9 42%,#bfe8f9 46%,#9fd8ef 67%,#2ab0ed 100%); /* IE10+ */
background: linear-gradient(to bottom,  #e4f5fc 0%,#bfe8f9 42%,#bfe8f9 46%,#9fd8ef 67%,#2ab0ed 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e4f5fc', endColorstr='#2ab0ed',GradientType=0 ); /* IE6-8 */

to my css file, the gradient in the background is not generated and the background remains as it was. What could be the reason for this ? Is there anything else that needs to be done before ?

A: Did you set any selector, to which this style shall be applied to?
E.g.
body{
     background: .... /* all the stuff in here*/
}


text:
Q: Links to change colour with css not working properly I have some code for which  I am trying to make a navbar. I have links in the code and I changed them when the page is scrolled up a little. I change the colours ok but cant change on hover to stay permanent? I seem to have tried everything but its like its resetting my css all the time. It works fine with the links but cant seem to change on hover colour to stay the same.

$(document).ready(function() {
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll > 10) {
      $(".white").css("background", "#362c6e");
      $(".white").css("color", "#ffffff");
      $(".nav-login").css("color", "#ffffff");
      $(".nav-big a:link").css("color", "#ffffff");
      $(".nav-more a:link").css("color", "#ffffff");
    }
    if (scroll < 10) {
      $(".white").css("background-color", "rgba(255, 255, 255, 0)");
      $(".white").css("color", "#111111");
      $(".nav-login").css("color", "#362c6e");
      $(".nav-big a:link").css("color", "#362c6e");
      $(".nav-more a:link").css("color", "#362c6e");
    }

  })
})
.image-container-left {
  margin-left: 40px;
  margin-top: 0px;
}

#nav {
  overflow: hidden;
  width: 100%;
  /* Full width */
  border: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  float: left;
  list-style: none;
}

.nav-image-left {
  border: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
  margin-right: 5px;
  margin-top: 17px;
  margin-left: 5px;
  float: left;
  list-style: none;
}

.nav-big {
  border: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
  margin-right: 5px;
  margin-top: 37px;
  float: left;
  list-style: none;
  margin-left: 5%;
}

.nav-more {
  border: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
  margin-top: 37px;
  margin-left: 30px;
  ;
  float: left;
  list-style: none;
}

.nav-login {
  list-style-type: none;
  float: right;
  margin-top: 37px;
  margin-right: 40px;
  color: 362c6e;
}

.nav-big a:hover,
a:visited,
a:link,
a:active {
  text-decoration: none;
}

.nav-more a:hover,
a:visited,
a:link,
a:active {
  text-decoration: none;
}

.nav-big a:link {
  color: #362c6e;
}

.nav-more a:link {
  color: #362c6e;
}

.nav-more a:hover {
  color: #e73972;
)
.nav-big a:hover {
    color: #e73972;
)

 About us

 Register new job

 Register business

 Contact us

 Login

0800 038 6210

A: Is this what you need?

$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();

            $('#nav').toggleClass('before10',!(scroll > 10)); // toggle Class ad or remove a class considering the second parameter being true or false
            $('#nav').toggleClass('after10',(scroll > 10));// toggle Class ad or remove a class considering the second parameter being true or false

  })
})
body{
 min-height:700px;
}
.image-container-left {

  margin-left:40px;
  margin-top:0px;
}

#nav {
 overflow: hidden;
 width: 100%; /* Full width */
 border:0;
 list-style-type: none;
 margin: 0;
 padding: 0;
 overflow: hidden;
 float: left;
 list-style: none;
}

.nav-image-left {
 border:0;
 list-style-type: none;
 margin: 0;
 padding: 0;
 margin-right: 5px;
 margin-top: 17px;
 margin-left: 5px;
 float: left;
 list-style: none;
}

.nav-big {
 border:0;
 list-style-type: none;
 margin: 0;
 padding: 0;
 margin-right: 5px;
 margin-top: 37px;
 float: left;
 list-style: none;
 margin-left:5%;
}

.nav-more {
 border:0;
 list-style-type: none;
 margin: 0;
 padding: 0;
 margin-top: 37px;
 margin-left: 30px;;
 float: left;
 list-style: none;
}

.nav-login {
   list-style-type: none;
   float: right;
   margin-top: 37px;
   margin-right:40px;
   color:362c6e;
}

#nav ul li a{
 color:blue;
 text-decoration:none;
}

#nav.before10 ul li a{
 color:blue;
 text-decoration:none;
}
#nav.before10 ul li a:hover{
 color:grey;
}
#nav.after10{
 background:teal;
}
#nav.after10 ul li a{
 color:red;
 text-decoration:none;
}
#nav.after10 ul li a:hover{
 color:white;
}

 About us

 Register new job

 Register business

 Contact us

 Login

0800 038 6210

A: I think the problem is how you are trying to set the css properties.
$(".nav-big a:link") selects the actual elements in the DOM tree, nit the corresponding rule in your .css file. Then, when you call ".css("property", "value")" on those elements, you effectively change their element.style property, which is equivalent to setting that property inline (i.e. `).
Since the specificity of inline styles is higher that that of styles defined in a .css file, your :hover rule in a .css file will not be applied anymore.
There isn't really a way to edit you .css files from either JavaScript or JQuery (which is still just a JavaScript library), so what you should do instead is dynamically add and remove classes as described here.
As a side note, you honestly don't need jQuery for such tasks in 2018. It has its uses, but those are all either advanced or obsolete. Loading a external library bloats your page and is overall frowned upon. .ready can be replaced by just placing your


text:
Q: AngularJS ng-table filter not working on nested fields I have a problem with filter in ng-table AngularJS
when I use it, it's work for

{{p.quantite}},
  {{p.montant}}, {{p.date | date:'dd/MM/yyyy'}}

but not working for others

{{p.produitEspece.produitFamille.libelle}},
  {{p.produitEspece.libelle}},{{p.clientClient.libelle }}

this my code:
show_vente.html

Liste des ventes

                                                         {{p.produitEspece.produitFamille.libelle}}
                                                         {{p.produitEspece.libelle}}
                                                        {{p.quantite}}
                                                        {{p.montant}}
                                                        {{p.clientClient.libelle }}
                                                        {{p.date | date:'dd/MM/yyyy'}}

venteController.js
var tableData = [];
$scope.filter = {
    key: undefined,
    failed: undefined
};
$scope.tableParams = new ngTableParams({
    page: 1,
    count: 25,
},{
    dataset: tableData,
    total:tableData.length,
    getData : function($defer,params){
        $http.get(prod.url+'/vente/all').then(function(response) {
            tableData = response.data;

            tableData = params.filter() ? $filter('filter')(tableData, params.filter()) : tableData;
            $defer.resolve(tableData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
            params.total(tableData.length);
        });
    }
})

also sorting work just for "montant" and "quantite" and not working for others
help please
thanks in advance
Update
I found the solution of my problem, I did create my own filter:

filter="{ 'client': 'clienttext' }"

...

thanks :)


text:
Q: Continuously Adding SSDs to an existing PostgreSQL Server An Ubuntu 18.04 server dedicated to running a PostgreSQL 11.2 server (with TimescaleDB extension) will be running out of disk space soon so new SSD disks will need to be added to the machine to support the growing database size.
The data is expected to continue increasing at the same/higher rate, so the storage hardware will need to be increased continuously until the machine runs out of 2.5" drive bays. Only then will distributing the database over multiple machines be considered, due to the increased complexity involved.
Thoughts

*

*Union file systems like mergerfs can pool the drives together, solving the storage expansion problem easily. But this will increase the latency of database operations and are thus not recommended. Redundancy can be added by having an underlying RAID-1/5/6/10 or using SnapRAID.

*RAID-0 and RAID-10 allows expansion of the RAID array into the newly added drive, with the bonus of increased performance from striping. However every drive being added is an additional point of failure. Furthermore, numerous people claims that mirroring SSDs is of limited use as both SSDs in RAID-0 will likely fail at the same time. So maybe this means that RAID-10 is no better than RAID-0. Furthermore, failure rates increase linearly with each additional SSD added.

*RAID-5/6 reduce performance due to parity calculations and having write to 2 drives, reducing the effective IOPS by 75%. Seems to be a poor choice for databases.

*PostgreSQL TABLESPACES can be used to assign every table to a specific drive. However, using tablespaces will make recovery very complicated. Furthermore, is it possible to create new tablespaces on the new drives and let Postgres automatically decide where to write new record to?

*ZFS, BTRFS? Not familiar with them, willing to explore if they are suitable.
Question: What is the year-2020 recommended method of expanding the storage of a PostgreSQL machine, if expansion has to be done frequently (1-2X a year), performance should not be affected much, and recovery should not be so complicated that it may lead to data loss?
RAID-10 seems like a good idea to me, except that RAID-1 appears to have limited usage while causing the 'loss' of half the disk space, made worse by the increasing points of failure with increasing number of drives.
Due to budget constraints, we cannot fill up all 16 drive bays in a 2U chassis with SSDs at once, so it has to be done incrementally.
Any advice is greatly appreciated!
EDIT: After looking into ZFS, it seems like this might be one of the solutions for my case.

*

*A ZFS pool with only mirrored ZFS vdevs (2 drives per vdev) will allow storage pool expansion by adding 2 drives at a time

*Keeping 1-2 hot spares in the ZFS pool can allow automatic failover by ZFS when 1 of the drives fail

*With mirrored vdevs, the rebuild time after a drive has failed will be way faster than with RAIDZ vdevs. This also reduces the chance that the surviving drive used for the rebuild can fail during the process. The degraded mirrored vdev will have much greater performance than a degraded RAIDZ vdev during rebuild

*ZFS supports inline data compression which helps significantly (4X compression) with reducing the storage requirements of TimescaleDB data without having to use native TimescaleDB compression that prevents compressed data from being updated unless it is uncompressed. This is pretty important too as TimescaleDB is known to have poorer data compression compared to other databases like InfluexDB

*Monitor and replace the SSDs when they are about to fail, as suggested by jjanes
If I understand this correctly, using ZFS mirrored vdevs will check all my boxes: Continuously add drives, allow drive pooling which provides a single mountpoint, data redundancy and a bonus ~4X data compression.

A: Have you turned on TimescaleDB's native compression, available since v1.5?  I ask because you mention ZFS/BTRFS above, which suggests you aren't employing its compression already.
Typically see 90-98% storage savings in the wild...
https://docs.timescale.com/latest/using-timescaledb/compression
Additionally, you can use TimescaleDB's attach_tablespace command to add more disks, and then new chunks are load balanced across the available tablespaces.
https://docs.timescale.com/latest/api#attach_tablespace


text:
Q: Loss function for changing a classification network to a regression one I am trying to change a neural network that classifies pointclouds into 40 different classes, to a regression networks that predicts a specific property of them in three points(x,y,z). for the loss function I have replaced this loss value:

loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)

with this one:
mse = tf.keras.losses.MeanSquaredError()
regression_loss=mse(pred, label)
regression_loss = tf.cast(regression_loss, tf.float32)
tf.summary.scalar('regression loss', regression_loss)

I have only changed the last layer output from 40 to 3 and some minor stuff for the network to actually start the training.
I used tf.cast because there is another loss computed in the middle of network multiplied by 0.001 and added to this loss to give the mean loss and before that, it kept raising the error that x(regression_loss) is int and y(middle_loss) is float and they can't be added which was also weird. The values for 'labels' are small around zero but the loss stays at zero almost all the time except for random times. I would be thankful if anyone could help me find the problem or replace the loss function maybe.
The log looks like this:
**** EPOCH 000 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
Model saved in file: log/model.ckpt
**** EPOCH 001 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 002 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.019608
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.015625
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 003 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 004 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 005 ****
----0-----
mean loss: 0.019608
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 006 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 007 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.015625
----3-----
mean loss: 0.015625
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 008 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 009 ****
----0-----
mean loss: 0.015625
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 010 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.015625
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
Model saved in file: log/model.ckpt
**** EPOCH 011 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 012 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 013 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.000000
----2-----
mean loss: 0.000000
----3-----
mean loss: 0.000000
----4-----
mean loss: 0.000000
----0-----
----1-----
eval mean loss: 0.000000
**** EPOCH 014 ****
----0-----
mean loss: 0.000000
----1-----
mean loss: 0.015625
----2-----

I have thought about multiplying the regression_loss by 100 but I don't believe that would make much difference.

A: I figured out the reason for this the same day:) in case anyone comes across this kind of problem this is what I did wrong:
for the labels placeholder, I forgot to change the tf.int32 to tf.float32 so the labels were all transformed to int32 and it would constantly calculate zero for the loss!
labels_pl = tf.placeholder(tf.float32, shape=(batch_size,3))


text:
Q: Missing Microsoft.FailoverClusters.PowerShell in MS Virtual Machine Manager 2012 installation Im installing VMM 2012 on a virtual machine. The installer throws the error

Could not load file or assembly
  'Microsoft.FailoverClusters.PowerShell, Version=6.1.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
  dependencies. The system cannot find the file specified.

Issue is that this assembly seems very hard to find. Any advice what I possibly could have missed?

A: This was solved by restarting the computer and running the installation again!


text:
Q: Differences between onClick and onSubmit in Google Analytics Event Tracking I had a website where there was a link to a hotel booking engine and had been using onSubmit to record a form submission as an event.
However it didn't seem to be recording properly - the figures were too low.
So, I thought that maybe changing to onClick would help - so the code on the form would look like this:
<form id="bookingEngine"
      class="bookingEngine"
      name="bookingEngine"
      action="redirect.php"
      method=POST
      target="_blank"
     onClick="ga('send', 'event', 'Booking', 'Website');
     ">

This works, except now the figures are much higherand look as if maybe overreporting?
Is this right, could the onClick on a form tag be recording something other than the number of forms submitted?

A: A more simplistic explanation would be that the onclick tracks when an element is clicked, regardless of the outcome or the context in which the element was clicked, whereas the onbusmit tracks when a form button is clicked and the form successfully submitted. So if there were errors in the form that invalidated the form, and it doesn't get submitted, then the onsubmit action would not occur.


text:
Q: Exponential Shorthand for Integers So my understanding is that this: 1e3 Equates to 1000.0.
My question is, is there a similar shorthand for integers? I realize that I can do: static_cast<int>(1e3). Is there anything available to me outside of this?

A: No, there is no syntax for scientific notation integer literal in C++.
You could shorten the conversion with a user defined literal:
constexpr int operator "" _i(long double d) noexcept {
    return d;
}

int main() {
    auto big = 1e3_i; // is int
}

However, this does (at least on GCC that I tested) prevent the compiler from noticing overflow in the initialization so in those cases where possible, prefer the more conventional:
int big = 1e30; // compiler should yell at you


text:
Q: How to create two spinner for Date Picker in one class in android? I have created one class in which i want to set two different spinner for date picker. I want this because i want to set start event date and end event date, so how can i set two different spinner with date picker in one class??? thanks in advance.

A: Here is the triple number picker ive used in some of my applications. shoudl be easy to modifiy it to only use two numbers.
package com.t3hh4xx0r.nfcsecure.widgets;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.NumberPicker;

import com.t3hh4xx0r.nfcsecure.R;

public class TripleNumberPickerPreference extends DialogPreference {
    private static final String defaultPersistedString = "0:0:0";
    private NumberPicker hours = null;
    private NumberPicker mins = null;
    private NumberPicker secs = null;

    View rootView;

    public TripleNumberPickerPreference(Context ctxt) {
        this(ctxt, null);
    }

    public TripleNumberPickerPreference(Context ctxt, AttributeSet attrs) {
        this(ctxt, attrs, 0);
    }

    public TripleNumberPickerPreference(Context ctxt, AttributeSet attrs, int defStyle) {
        super(ctxt, attrs, defStyle);

        setPositiveButtonText("Set");
        setNegativeButtonText("Cancel");
    }

    @Override
    protected View onCreateDialogView() {
        String[] nums = new String[61];

        for(int i=0; i<nums.length; i++) {
           nums[i] = Integer.toString(i);
        }

        LayoutInflater lI = LayoutInflater.from(getContext());
        rootView = lI.inflate(R.layout.triple_number_picker, null);
        hours = (NumberPicker) rootView.findViewById(R.id.hours);
        mins = (NumberPicker) rootView.findViewById(R.id.minutes);
        secs = (NumberPicker) rootView.findViewById(R.id.seconds);

        hours.setMaxValue(24);
        hours.setMinValue(0);
        hours.setDisplayedValues(nums);

        mins.setMaxValue(60);
        mins.setMinValue(0);
        mins.setDisplayedValues(nums);

        secs.setMaxValue(60);
        secs.setMinValue(0);
        secs.setDisplayedValues(nums);

        deconstructPersistedData();

        return (rootView);
    }

    private void deconstructPersistedData() {
        hours.setValue(Integer.parseInt(getPersistedString(defaultPersistedString).split(":")[0]));
        mins.setValue(Integer.parseInt(getPersistedString(defaultPersistedString).split(":")[1]));
        secs.setValue(Integer.parseInt(getPersistedString(defaultPersistedString).split(":")[2]));
    }

    private String buildPersistedData() {
        StringBuilder sB = new StringBuilder();
        sB.append(hours.getValue());
        sB.append(":");
        sB.append(mins.getValue());
        sB.append(":");
        sB.append(secs.getValue());
        sB.append(":");

        long timeTillNextSecureLock = buildTimeTillSecureLock();
        Log.d("TIME TILL NEXT LOCK SET", ""+timeTillNextSecureLock);
        sB.append(timeTillNextSecureLock);
        return sB.toString();
    }

    private long buildTimeTillSecureLock() {
        double hoursSimple = hours.getValue();
        double minsSimple = mins.getValue();
        double secsSimple = secs.getValue();

        double secsToMillis = 1000;
        double minsToMillis = 60000;
        double hoursToMillis = 3600000;

        double secsAsMills = secsSimple * secsToMillis;
        double minsAsMills = minsSimple * minsToMillis;
        double hoursAsMills = hoursSimple * hoursToMillis;

        return (long) (secsAsMills + minsAsMills + hoursAsMills);
    }

    @Override
    protected void onBindDialogView(View v) {
        super.onBindDialogView(v);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        String persisted = buildPersistedData();

        if (positiveResult) {
            if (callChangeListener(persisted)) {
                persistString(persisted);
                notifyChanged();
            }
        }
    }

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return defaultPersistedString;
    }

      public static long subAndCheck(long a, long b) {
          long ret;
          String msg = "overflow: subtract";
          if (b == Long.MIN_VALUE) {
              if (a < 0) {
                  ret = a - b;
              } else {
                  throw new ArithmeticException(msg);
              }
          } else {
              ret = addAndCheck(a, -b, msg);
          }
          return ret;
      }

      private static long addAndCheck(long a, long b, String msg) {
          long ret;
          if (a > b) {
              ret = addAndCheck(b, a, msg);
          } else {
              if (a < 0) {
                  if (b < 0) {
                      if (Long.MIN_VALUE - b <= a) {
                          ret = a + b;
                      } else {
                          throw new ArithmeticException(msg);
                      }
                  } else {
                      ret = a + b;
                  }
              } else {
                  if (a <= Long.MAX_VALUE - b) {
                      ret = a + b;
                  } else {
                      throw new ArithmeticException(msg);
                  }
              }
          }
          return ret;
      }
}

And the layout -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="1"
            android:text="@string/hours"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textView1"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/minutes"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="1"
            android:text="@string/seconds"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <NumberPicker
            android:id="@+id/hours"
            android:layout_width="0dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="3dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <NumberPicker
            android:id="@+id/minutes"
            android:layout_width="0dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="3dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <NumberPicker
            android:id="@+id/seconds"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>


text:
Q: count occurrences of a string in a structure I have a structure mydata and I need to access one of its fields mydata.myfield, and within that field, access another field mydata.myfield.mysecondfield. In the last field, mydata.myfield.mysecondfield I need to check how many times a particular string ('apple') occurs.
I have tried with:
 aaa=unique(mydata.myfield.mysecondfield,'apple')
 bbb=cellfun(@(x) sum(ismember(mydata.myfield.mysecondfield,x)),aaa,'un',0)

but I get this error: Attempt to reference field of non-structure array.
The structure contains fields with both strings and numeric values.

A: The underlying problem may be due to the fact that the structure is a little bit different from how you describe it. Following your question, I created it as follows:
mydata = struct();
mydata.myfield.mysecondfield = {'apple' 'apple' 'orange' 'banana' 'apple' 'kiwi'};

and since I'm not getting the same error you get, I think the underlying types may be slightly mismatching. Anyway, given mydata defined as above, if you change your code as follows, it should work but it will return the count of every unique occurrence within the field:
aaa = unique(mydata.myfield.mysecondfield);
bbb = cellfun(@(x) sum(ismember(mydata.myfield.mysecondfield,x)),aaa,'un',0)

bbb =
      4×1 cell array
      [3]
      [1]
      [1]
      [1]

If you only want to count the number of apple occurrences, you should use the following approach instead:
apple_count = sum(strcmp(mydata.myfield.mysecondfield,'apple')); % 3


text:
Q: The Hilbert function and polynomial of $S = k[x_1, x_2, x_3, x_4]$ and $I = (x_1x_3, x_1x_4, x_2x_4)$ step clarification. My professor based on pg. 320 - 321 of Eisenbud, wrote the following:
Let $I = (m_1, \dots, m_l)$ be a minimal set of monomial generators, $I' = (m_1, \dots, m_{l-1}) \subsetneq I,$ and $d = \operatorname{deg}m_l.$
$$S\mu \xrightarrow{\varphi} S/I' \rightarrow S/I \rightarrow 0$$
$$\mu \mapsto m_l + I^{'}$$
Then we have:
$$\operatorname{ker}{\varphi} = (I': m_l) = J = (m_1/\operatorname{gcd}(m_1, m_l), \dots , m_{l-1}/\operatorname{gcd}(m_{l - 1}, m_l))$$
Therefore, $\operatorname{im}(\varphi) = S/J\mu$ and we have the s.e.s.:
$$0 \rightarrow (S/J)\mu \xrightarrow{\tilde{\varphi}} S/I' \rightarrow S/I \rightarrow 0 .$$
Regard $S\mu$ as a graded $S-$module, $\operatorname{deg}\mu = d.$ Then the s.e.s. is graded. So for each $i \in \mathbb Z,$ we get a s.e.s of vector spaces
$$0 \rightarrow (S/J)_{i - d} \rightarrow (S/I')_{i} \rightarrow (S/I)_i \rightarrow 0 $$ which implies that $H_{S/I}(i) + H_{S/J}(i -d) = H_{S/I'}(i)$ and this gives us an algorithm to find $H_{S/I}(i).$
Now, here is her solution to the question I mentioned above:
1- Put $m_l = x_2x_4, I' = (x_1x_3, x_3x_4)$ then
$J = (I': x_2x_4) = (x_1x_3/\operatorname{gcd}(x_1x_3, x_2x_4), x_1x_4/\operatorname{gcd}(x_1x_4, x_2x_4)) = (x_1x_3, x_2x_1)= (x_1)$
And $S/J = k[x_2, x_3, x_4],$ so $H_{S/J}(d) = \binom{3 + d -1}{d} = \frac{(d + 1)(d + 2)}{2}$ where $d = \operatorname{deg} m_l $ and $H_{S/J}(i - 2) = \frac{(i-1)i}{2}, i \geq 2$
2- Put $m_{l}^{'}= x_1x_4$, $I^{''} = (x_1x_3)$ then $\operatorname{deg}m_{l}^{'} = 2,$ and $J' = (I'': x_1x_4) = (x_1x_3/\operatorname{gcd}(x_1x_3, x_1x_4)) = (x_1x_3/x_1) = (x_3)$
And $S/J' = k[x_1, x_2, x_4],$ so $H_{S/J'}(d) = \binom{3 + d -1}{d} = \frac{(1 + d)(2 + d)}{2}$ where $d = \operatorname{deg} m_l^{'} $ and $H_{S/J'}(i - 2) = \frac{(i - 1)i}{2}, i \geq 2$
So,
$$H_{S/I^{'}}(i) + H_{S/J^{'}}(i - 2) = H_{S/I^{''}}(i).$$
Now, since  $H_{S/J^{'}}(i - 2) = i - 2, i \geq 2,$ it remains to find $H_{S/I^{''}}(i)$.
Since we have $S/I^{''} = \frac{k[x_1, x_3]}{(x_1 x_3)}[x_2, x_4],$ a polynomial ring over the indeterminates $ x_2, x_4,$ monomials: $x_1^a x_{2}^b x_4^c, x_3^ax_2^b x_4^c,$ then $$S/I^{''} = k[x_1, x_2, x_4] + k[x_3, x_2, x_4].$$
But then my professor wrote  $H_{S/I^{''}}(d) = 2 \frac{(d + 1)(d + 2)}{2} - (d + 1) = (d + 1)^2$.
She said that multiplication by $2$ occurs because we have $$S/I^{''} = k[x_1, x_2, x_4] + k[x_3, x_2, x_4]$$
is the addition of two polynomial rings (is that reasoning correct ?) and the subtraction of $d+1$ because we have counted $x_2x_4$ twice, but I do not understand why the number of $x_2x_4$ is $d+1,$ could someone explain this to me please?
Also, I know that $H_{S/I}(i)$ should be called Hilbert function of dimension $i$, but what should be called the Hilbert polynomial and it is polynomial in which indeterminates? Could anyone clarify this to me, please?

A: The process of counting above is a basic use of the inclusion-exclusion principle:
Step 1: The number of monomials $x_1^a x_{2}^b x_4^c$ that has degree $d$ is $d+2 \choose 2$ which is $\frac{(d+1)(d+2)}{2}$. These monomials include monomials of the form $x_2^bx_4^c$ of degree $d$ (when $a=0$).
Step 2: Similarly, he number of monomials $x_3^a x_{2}^b x_4^c$ that has degree $d$ is also $d+2 \choose 2$ which is $\frac{(d+1)(d+2)}{2}$. These monomials also include monomials of the form $x_2^bx_4^c$ of degree $d$ (when $a=0$).
So if we want to count the number of monomials $x_1^a x_{2}^b x_4^c, x_3^ax_2^b x_4^c$ of degree $d$, we have to take the total number of step 1 and step 2 and subtract the number of monomials of the form $x_2^bx_4^c$ of degree $d$ (because when we take the total, we count the number of monomials include monomials of the form $x_2^bx_4^c$ twice).


text:
Q: Bootstrap navigation - external link I got a problem with external link in my navbar.
I have added "German" to the navbar. By clicking, it should open an new window to get to the german version of the site (in this example it's google). But nothing happens.
Here is my test url: http://cc2.ngabriel.com/

A: Open the console of your browser (F12 or Ctrl+Shift+I, depending your browser) and you'll see that your javascript launch an exception in custom.js at line 296:
Uncaught TypeError: Cannot read property 'querySelector' of null

On this code:
overlay = document.querySelector( 'div#login' ),
closeBttn = overlay.querySelector( 'button.overlay-close' );

overlay is undefined because you don't have a div with a login id in your DOM.


text:
Q: Zip command in ruby block does not work without binding.pry I have a block of code that executes a zip command from another class:
def zip_up_contents path name
  Zipper.new path name
end

The problem is that it zips blank copies of all the files passed to it. But when I put a binding before the zip command like so:
def zip_up_contents path name
  binding.pry
  Zipper.new path name
  binding.pry
end

it zips the files successfully. I know this by checking the resulting file's byte size from within pry on the second binding point with and without the first binding present. Without the binding, the zip archive's byte size is half what it should be, and with the binding it's the size I would expect.
The "Zipper" class simply calls the system zip with backticks. I don't think that's the problem because I've used that class without trouble in other contexts. The zip utility is Zip 3.0 on Ubuntu 10.04.
I have no idea why the presence of the binding makes a difference. If anyone has encountered anything similar, or has thoughts about how to better debug the issue, I'd appreciate hearing about it.
EDIT: For anyone encountering anything similar, I resolved this by calling fsync on the files prior to zipping them: http://www.ruby-doc.org/core-2.0.0/IO.html#method-i-fsync

A: I had this problem with some Rspec tests last week -- turned out to be a race condition. Is there any chance that the file hasn't been saved when you pass it to be zipped? I mean, maybe the binding.pry is just giving it a chance to catch up.


text:
Q: Value classes in generics - interoperability with Java/Groovy I'm struggling with value classes in generics and interoperability with Java or Groovy. Value class are inlined: Inline classes | Kotlin 1 except for generics.
Given following value class and interface (Kotlin):
@JvmInline
value class ValueClass(val id: String)

interface ValueClassListProvider {
    @Suppress("INAPPLICABLE_JVM_NAME")
    @JvmName("values")
    fun values(): List<ValueClass>

    @Suppress("INAPPLICABLE_JVM_NAME")
    @JvmName("value")
    fun value(): ValueClass
}

how can I implement ValueClassListProvider interface in Java or Groovy?
class ValueClassListProviderImplJava implements ValueClassListProvider {
    public List<ValueClass> values() {
        return Arrays.asList(new ValueClass("1"));
    }

    public String value() {
        return "1";
    }
}

Trying to run following code:
public static void main(String[] args) {
    ValueClassListProviderImplJava provider = new ValueClassListProviderImplJava();
    System.out.println(provider.values());
}

result in:
java: cannot find symbol
  symbol:   constructor ValueClass(java.lang.String)
  location: class pl.test.valueclass.ValueClass

For Groovy implementation of ValueClassListProvider interface:
class ValueClassListProviderImplGroovy implements ValueClassListProvider {

    List<String> values() {
        return ["1", "2"]
    }

    String value() {
        return "1"
    }
}

it compiles and seems to work, but when this implementation is later used in Kotlin code (suppose this is stub used in spock tests), it blows with:
java.lang.ClassCastException: class java.lang.String cannot be cast to class pl.test.valueclass.ValueClass

Is it possible to create instance of value class in Java or Groovy (needed for generics)?


text:
Q: How can I alter the UI in a JQuery autocomplete box? I have a jquery autocomplete textbox.
http://docs.jquery.com/UI/Autocomplete#events
The spec there shows this:
Triggered when the suggestion menu is opened.
Code examples
Supply a callback function to handle the open event as an init option.
$( ".selector" ).autocomplete({
   open: function(event, ui) { ... }
});

I have that exact code and it works fine, but in the function I want to style the first list item.
$(ui).length is 1
$(ui).find('ul').length is 0
$(ui).find('li').length is 0

I can't figure out what ui is or how to use it. I can't use firebug because the popup dialogue disappears as soon as I click the firebug toolbar

A: Try to alert $(ui).html() and see what it contains, then you can use the right selector.

A: This selector should work:
ul.ui-autocomplete li:first-child

You can create a CSS rule with it.

A: When I use "Inspect Element" on an option I get
c++
, so you may want to try styling either the li or a classes.

A: If you look at the end of the documentation there is a section on theming. I believe this gives an indication of what could be done.
$( ".selector" ).autocomplete({
   open: function(event, ui) {
       $(".selector").find("li.ui-menu-item:first").css('your style here');
   }
});

A: ui will only contain the suggestion that was selected.  To get the item that was selected, you could use :
var value = ui.item.value;

To style it, you will need to think of another way, for example:
$('.ui-menu-item:first').css('color','red');

Edit:  That's why ui is null when you simply alert it without selecting anything.


text:
Q: How to redirect querystring url to subdomain url using htaccess I want to redirect query string URL to subdomain URL:
https://domainname.com/login/?_redirected=yes
to
http://subdomain.domain.com.
I tried some of htaccess code but it's not working. How can i solve this.
RewriteCond %{HTTP_HOST} =myhost.com [NC]
RewriteCond %{QUERY_STRING} ^(p=1&preview=true)
RewriteRule ^$ http://alt.myhost.com/?%1 [R=301,L]


text:
Q: Make Slide in Animation JavaScript and HTML How would one make a slide and fade in animation like in seen in the green and pink boxes on sharethis.com? In particular I like the one in the blue box with the arrows. Are there a set of JavaScript codes or CSS effects?

A: The easiest would probably be to use a library like this:
http://janpaepke.github.io/ScrollMagic/
I see that for the arrows effect the css-height property is animated when you scroll. This is done in javascript. But you can also achieve this effect through CSS3-transitions.
Update: Slide and wipe effects from the demo page:
// ani
var pinani = new TimelineMax()

// wipe
.add(TweenMax.to("#wipe", 1, {
    width: "100%"
}))
// slide
.add(TweenMax.to("#slide", 1, {
    top: "0%",
    ease: Bounce.easeOut,
    delay: 0.2
}));

// pin
new ScrollScene({
    triggerElement: "section#pin",
    duration: 1100
})
.on("progress", function () {
    // keep centered even though width changes
    $("#wipe h3").width($("#pin>h3").width());
})
    .setTween(pinani)
    .setPin("section#pin")
    .addTo(controller);


text:
Q: How to upload base64 encoded image to server I have jquery plugin which send image in base 64 encoded format which i want to store in server
here is what I've tried
$post = json_decode($_POST['file'], true); $data = $post['output']['image'];

 $data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

require('/home/example/public_html/files/image/class.upload.php');

$code = md5(time());
$handle = new upload($data);
if ($handle->uploaded) {
  $handle->file_new_name_body = "$code";
  $handle->mime_check = true;
  $handle->allowed = array('image/*');
  $handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize         = true;
  $handle->image_x              = 600;
  $handle->image_ratio_y        = 600;
  $handle->process('/home/example/public_html/files/blog/img/');
  if ($handle->processed) {
  $file_name = $handle->file_dst_name;
  } else {
  echo "error";
  }
}

My above code image upload class works on every image but i'm unable to uploade base 64 encoded image, how can i achieve that

A: The upload class you're using doesn't support feeding base64 directly into it. You're best off using this method to save a temporary version to your directory first, using the class to do what you need to do, then deleting it:
$data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

require('/home/example/public_html/files/image/class.upload.php');

$code = md5(time());
$write_dir = "/home/example/public_html/files/blog/img/";
$temp_code = "temp_".$code;

$ifp = fopen($write_dir.$temp_code, "wb");
fwrite($ifp, $data);
fclose($ifp);

$handle = new upload($write_dir.$temp_code);
if ($handle->uploaded) {
    $handle->file_new_name_body = "$code";
    $handle->mime_check = true;
    $handle->allowed = array('image/*');
    $handle->image_convert = 'jpg';
    $handle->jpeg_quality = 70;
    $handle->image_resize         = true;
    $handle->image_x              = 600;
    $handle->image_ratio_y        = 600;
    $handle->process($write_dir);
    if ($handle->processed) {
        $file_name = $handle->file_dst_name;
        unlink($write_dir.$temp_code);
    } else {
        echo "error";
    }
}


text:
Q: Flask Restplus returns a corrupted PNG file Developing a rest API using flask with flask_restplus. It successfully returns an image file, generated by the PIL library, but the file is corrupted and cannot be viewed.
@api.route('/annotate')
class Annotate(Resource):
        @api.representation('image/png')
        def post(self):
                file = io.BytesIO()
                img = Image.new('RGBA', (50, 50), (70, 0, 0, 255))
                img.save(file, 'png')
                file.seek(0)
                return send_file(file,
                                 as_attachment=True,
                                 attachment_filename='annotated.png',
                                 mimetype='image/png')

A: It seems to be working just fine. I jus tried the following and it works as expected. Here is the resulting image as well.

from flask import Flask, render_template, jsonify, send_file
from PIL import Image
import io
app = Flask(__name__)

@app.route('/image')
def image():
    file = io.BytesIO()
    img = Image.new('RGBA', (50, 50), (70, 0, 0, 255))
    img.save(file, 'png')
    file.seek(0)
    return send_file(
        file,
        as_attachment=True,
        attachment_filename='annotated.png',
        mimetype='image/png')

Start it like so FLASK_APP=f1.py flask run.

A: Please reference to this github issue.
Swagger basically messes up the encoding. If you make the call though another client it should work properly.


text:
Q: Silverlight AutoCompleteComboBox - build list asyncronously? I would like to have a textbox in a Silverlight app where the user can type in it, and after a few characters are entered the control calls a web service to retrieve a list of potential choices that the user can choose from.  Essentially it is a type-ahead combobox but I don't want to keep all of the possible choices in memory I want to load them dynamically after getting some input from the user.  I'm hoping that the AutoCompleteComboBox from the Silverlight Toolkit can provide this functionality, but all of the examples I can find use a static list that is kept fully in memory.
Can the AutoCompleteComboBox do this?  If so, how?  If not, what are my other options?

A: I ended up figuring this out based on their samples page, though it was far from obvious.  You put an event handler on the Populating event of the AutoCompleteTextBox.  Inside the handler you set e.Cancel = true and then fire off an async event.  When the async event completes you set the ItemsSource of the AutoCompleteTextBox and then call its PopulateComplete() method.  Seems to work but I haven't extensively tested it.


text:
Q: C# action block await doesnt work as expected The Problem seemed to be with await firing before some async blocks where completed.
Either because I did something, the objects do not support or more likely, i screwed somewhere up. But since the Problem needed to much code to occur, it was considered a code dump =(
I hope this helps, a little bit.
I ditched the Broadcastblock and switched to a task based pipeline.
using the task factory for crawler that needs to have write access to its own input:
https://msdn.microsoft.com/en-us/library/ff963548.aspx
solved the problems.
The sync version of these are ideal for slow producers/fast consumers
taskfactory -> create your tasks, and connect them via a BlockingCollection,
sadly you cant have a foreach consuming enumerable with a last flag (would be nice for a crawler as this)

A: The Complete method will do what you need I believe. Documentation here has a good example:
https://msdn.microsoft.com/en-us/library/hh194731%28v=vs.110%29.aspx

A: ok, try replacing your merge method with this:
 private static async Task merge(Func<ConcurrentDictionary<string,int>> getter, Action<ConcurrentDictionary<string,int>> setter, List<parserPart>list)
        {
            List<Task> tasks  = new List<Task>();
            var target = getter();
            int buffer;
            foreach (parserPart b in list)
            {
                tasks.Add(Task.Factory.StartNew( () => {
                    target.TryGetValue(b.uploader_id, out buffer);
                    target.TryAdd(b.uploader_id, (buffer + b.count));
                }
            }
            Task.WaitAll(tasks.ToArray());
            await Task.Run(() => setter(target));
            Console.Writeline("merging task");
        }
    }

also, use  the Complete method before awaiting for Completion:
splitter.Complete();
sorter.Complete();
await Task.WhenAll(svn, splitter.Completion, sorter.Completion);

P.S. .. I haven't tested this since it's too much code to replicate but you did say that your merge method keeps running after you get some of the results, so, by creating that list of  tasks, you can wait for the entire list to finish before getting the results.


text:
Q: How to copy files from host to docker named volume I started a Django app with docker with bind host to handle user uploads but now I want to migrate to named volumes but I already have files in my host, so I was wonderings how can I copy the files from the host to the volume, this is my docker-compose for my web container:
version: '3'
services:
  db:
    restart: always
    image: "postgres:13.2-alpine"
    container_name: db
    ports:
      - "5432:5432"
    env_file:
      - ./.env.dev
    volumes:
      - ./pgdata:/var/lib/postgresql/data
  web:
      container_name: web
      restart: always
      build:
        context: .
        dockerfile: ./docker/development/Dockerfile
      environment:
        DEBUG: 'true'
        DJANGO_SETTINGS_MODULE: myapp.app_settings.development
      command: sh ./docker/development/runserver.sh
      ports:
        - "8000:8000"
      env_file:
        - ./.env.dev
      volumes:
        - .:/app # Enable code reload
        - django-static:/app/run/static
        - django-media:/app/run/media
      depends_on:
        - db

volumes:
  django-static:
  django-media:

And this is my Dockerfile:
FROM python:3.8
ENV PYTHONUNBUFFERED 1
RUN mkdir /app
WORKDIR /app
COPY ./requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
# COPY . /app
ADD . /app

RUN apt-get clean && apt-get update && apt install -y netcat

COPY ./docker/development/entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

There is a way to copy my uploads from host: /home/art/myapp/run/media and /home/art/myapp/run/static to volumes django-static and django-media ?
Also, How I can backup the files from the volume?

A: You can make it this way:
docker run -d --rm --name temp -v django-media:/root alpine tail -f /dev/null
docker cp ./run/media/. temp:/root
docker stop temp
docker exec -it --user root web /bin/bash
chown -R root:root /run/media

Creates a temp container with named volume mounted
docker run -d --rm --name temp -v django-media:/root alpine tail -f /dev/null

Then copy all files to temp container volume (./run/media/. copy all  the files/folders inside to target dir /root)
docker cp ./run/media/. temp:/root

then stops the temp container
docker stop temp

Now files are copied but without right permissions, exec a terminal inside the container that mounts the named volume, move to directory and run chown to own the copied files, in this case I asume that files inside container belongs to root:root and the files copied belongs to different user, you can check that with ls -la command.
docker exec -it --user root web /bin/bash
chown -R root:root /run/media


text:
Q: Cómo puedo mostrar en un SELECT lo que está seleccionado en la base de datos Hice un select de rangos administrativos, en el cuál al elegir uno y darle al botón de enviar funciona. Pero quiero mostrar en el mismo select lo que seleccionó anteriormente al enviar como default, es decir. Si seleccionó antes 'option="1"'(que sería el rango de moderador), al recargar la página muestre esa misma selección que hizo como predeterminada. Perdonen si no me explico muy bien.
Rango

// Ya seleccionado, que muestre el <option> elegido anteriormente como default
<select name='rankc'>
<option value='1'>Usuario</option>
<option value='2'>Vip</option>
</select>

    $stmt = $db->prepare("UPDATE users SET username = ?, motto = ?, rank = ?, credits = ?, pixels = ?, points = ?, pais = ?, tarea = ? WHERE username = ?");
                    $stmt->bind_param('sssssssss', $_POST["usernamec"], $_POST["mottoc"], $_POST["rankc"], $_POST["creditsc"], $_POST["pixelsc"], $_POST["pointsc"], $_POST["paisc"], $_POST["tareaType"], $_POST["usernamec"]);
                    $stmt->execute();

Gracias de antemano. :)

A: Puedes crear una variable en el localStorage que almacene el resultado que se seleccionó en dicho select, y luego, al recargar la página, que se imprima en el  del select el valor de la variable que creaste en el localStorage, para hacer todo ésto, te recomendaría emplear Javascript, yo te daré alguna idea pero con jQuery:
$(document).ready(function(){

    var valor = localStorage.getItem("opcionEscogida");

    if(valor != null && valor != "undefined"){

    $('select[name="rankc"]').find("option[value="+valor+"]").prop('selected','selected');

    }

})

$("select[name="rankc"]").change(function(){

    var opcion = $(this).val();

    localStorage.setItem("opcionEscogida", opcion);

})

Si tienes alguna duda o algún error, me comentas.


text:
Q: TypeError: object of type 'PSKeyword' has no len() I want to convert PDF to text files to process the document. I am using python 3.x and
While I try to convert pdftotext using PDFMiner. some pdf can't be parsed and leads to the error(python 3.x)
This is the code which converts the pdf to text. onlyfiles[2] is the pdf file
name. couldn't figure out the error message.
import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
def extract_text_by_page(pdf_path):
    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh,
                                      caching=True,
                                      check_extractable=True):
            resource_manager = PDFResourceManager()
            fake_file_handle = io.StringIO()
            converter = TextConverter(resource_manager, fake_file_handle)
            page_interpreter = PDFPageInterpreter(resource_manager, converter)
            page_interpreter.process_page(page)
            text = fake_file_handle.getvalue()
            yield text
            # close open handles
            converter.close()
            fake_file_handle.close()
def extract_text(pdf_path):
    for page in extract_text_by_page(pdf_path):
        print(page)
        print()
if __name__ == '__main__':
    print(extract_text(onlyfiles[2]))

The error message is:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-7fed22ec1779> in <module>
     25         print()
     26 if __name__ == '__main__':
---> 27     print(extract_text(onlyfiles[2]))

<ipython-input-19-7fed22ec1779> in extract_text(pdf_path)
     21             fake_file_handle.close()
     22 def extract_text(pdf_path):
---> 23     for page in extract_text_by_page(pdf_path):
     24         print(page)
     25         print()

<ipython-input-19-7fed22ec1779> in extract_text_by_page(pdf_path)
     14             converter = TextConverter(resource_manager, fake_file_handle)
     15             page_interpreter = PDFPageInterpreter(resource_manager, converter)
---> 16             page_interpreter.process_page(page)
     17             text = fake_file_handle.getvalue()
     18             yield text

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdfinterp.py in process_page(self, page)
    850             ctm = (1, 0, 0, 1, -x0, -y0)
    851         self.device.begin_page(page, ctm)
--> 852         self.render_contents(page.resources, page.contents, ctm=ctm)
    853         self.device.end_page(page)
    854         return

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdfinterp.py in render_contents(self, resources, streams, ctm)
    862         self.init_resources(resources)
    863         self.init_state(ctm)
--> 864         self.execute(list_value(streams))
    865         return
    866

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdfinterp.py in execute(self, streams)
    886                         log.debug('exec: %s %r', name, args)
    887                         if len(args) == nargs:
--> 888                             func(*args)
    889                     else:
    890                         log.debug('exec: %s', name)

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdfinterp.py in do_TJ(self, seq)
    770                 raise PDFInterpreterError('No font specified!')
    771             return
--> 772         self.device.render_string(self.textstate, seq, self.ncs, self.graphicstate.copy())
    773         return
    774

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdfdevice.py in render_string(self, textstate, seq, ncs, graphicstate)
     85             textstate.linematrix = self.render_string_horizontal(
     86                 seq, matrix, textstate.linematrix, font, fontsize,
---> 87                 scaling, charspace, wordspace, rise, dxscale, ncs, graphicstate)
     88         return
     89

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdfdevice.py in render_string_horizontal(self, seq, matrix, pos, font, fontsize, scaling, charspace, wordspace, rise, dxscale, ncs, graphicstate)
     98                 needcharspace = True
     99             else:
--> 100                 for cid in font.decode(obj):
    101                     if needcharspace:
    102                         x += charspace

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\pdffont.py in decode(self, bytes)
    717
    718     def decode(self, bytes):
--> 719         return self.cmap.decode(bytes)
    720
    721     def char_disp(self, cid):

~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\pdfminer\cmapdb.py in decode(self, code)
    125
    126     def decode(self, code):
--> 127         n = len(code)//2
    128         if n:
    129             return struct.unpack('>%dH' % n, code)

TypeError: object of type 'PSKeyword' has no len()


text:
Q: How can i detect the real location of the line which cause the memory-Leak C++? i'm having a C++ application which contains memory-leak, althugh i'm using "Leakdiag" and "LDGrapher" but i can't where is the leakage is?!
i'm also using "_CrtDumpMemoryLeaks();" function which give me results like this:
etected memory leaks!
Dumping objects ->
{657} normal block at 0x00D93B98, 52 bytes long.
 Data: < N   N          > D8 4E D9 00 D8 4E D9 00 00 00 00 00 CD CD CD CD
{656} normal block at 0x00D93AF0, 108 bytes long.
 Data: <(        ;  (   > 28 F0 12 00 00 00 00 00 98 3B D9 00 28 F0 12 00
{655} normal block at 0x00D94ED8, 52 bytes long.
 Data: < ;   ;          > 98 3B D9 00 98 3B D9 00 CD CD CD CD CD CD CD CD
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\occcont.cpp(923) : {641} normal block at 0x00D92100, 12 bytes long.
 Data: <            > F6 06 0A 00 00 00 00 00 00 00 00 00

How can i know the real loaction for memory leakage?

A: You can overload the global new and delete operators, and each time you allocate with new, you store the address of the pointer in some container along with the __LINE__ and __FILE__ information. When you delete something, you remove it from the container. When your application exits, dump the contents of the container. You will then know which allocations you forgot to deallocate. You can use a map container with the memory address as key and file and line information as value.
I think this is as close as you can get to the real location of the memory leak.


text:
Q: JQuery replace two table rows based on the data attribute of one I have a table in which I have editable data. Each 'editable' section covers two table rows.

(Please note I haven't put the 	 in....)
My jQuery so far is as follows. This will replace the first row with the relevent ID. I am having trouble selecting the second row... next() seems to be looking for the next row that has the ID.
 var new_row="

    "+doc_name+"
    "+first_ins4+"
    "+job_price4+"
    "+tender4+"
    Edit | Delete

";
    var new_row2="
"+second_ins4+"
";

    var row_to_change=$("tr:[data-doc_id2='"+doc_id+"']");
    $(row_to_change).replaceWith(new_row);

A:  var row_to_change=$("tr:[data-doc_id2='"+doc_id+"']");
 $(row_to_change).closest('tr').next('tr').remove();
 $(row_to_change).replaceWith(new_row);

Instead of having new_row and new_row2 I stuck the HTML together in new_row variable replacing one of the rows with the two new rows then removed the next row by using a standard selector. Clumsy but works.


text:
Q: How to get body from a server response with code 400 in Kotlin with coroutine and retrofit? I have a xampp server connected to my android app.
When I perform an api call, it would return either a response code 200 or a response code 400.
If the response code is 200, I'm able to get the body of the response.
Here is the response body:
{"message": "User was created."}

However, I'm unable to get the response body when the code is 400.
It is null.
This is my interface:
@POST("api/user/createUser.php")
suspend fun register(@Body details : JsonObject) : Response<JsonElement>

This is how I call it:
val service = Server.ApiClient.createService(ServerInterface::class.java)

        CoroutineScope(Dispatchers.IO).launch {

            try {
                val response = service.register(details)
                Log.wtf("Message",response.body().toString())
            }
            catch (e : Exception){
                Log.wtf("Error",e.message)
            }
        }

Here is the log :
Response code 200:
E/Message: {"message":"User was created."}

Response code 400:
E/Message: null

Does anybody know how to solve this ?

A: If I remember correctly, retrofit handles response codes outside 200-399 range as errors, so the message should be available using response.errorBody() instead of response.body().


text:
Q: Implement different themes using styled components I decided to switch to styled-components and now I'm really struggling to make my dark/light theme work again. Before I used only css and relied upon css variables. I looked many tutorials and example for styled-components but the theme is always stored and changed on app/top component, while I preferably need it stored in the config component and rendered on another.
How could I do this without necessarily changing the structure ?
import * as sc from "./styles";

function App() {
  return (
    <>
      <sc.globalStyles />
      <sc.title>My app</sc.title>
      <Configuration />
    </>
  );
}

function Configuration() {
  const [config, setConfig] = useState(
    retrieveFromStorage("configuration") ?? {
      //other things
      useDarkTheme: true,
    }
  )

  useEffect(() => setToStorage(config, "configuration"), [config]);

  const handleConfig = ({ target: { type, name, value, checked } }) => {
    setConfig(prev => ({
      ...prev,
      [name]: type === "select-one" ? value : checked,
    }));
  };

  return (
    <>
      <sc.options>
        <summary title="set your config">Options:</summary>
        {/*other things*/}
      </sc.options>
      <Theme useDarkTheme={config.useDarkTheme} handleInput={handleConfig} />
    </>
  );
}

function Theme({ useDarkTheme, handleInput }) {
  React.useEffect(
    () => (useDarkTheme ? console.log("should be dark") : console.log("should be light")),
    [useDarkTheme]
  );

  return (
    <sc.theme>
      ☀
      <sc.toogleSwitch>
        <sc.toogleTheme
          type="checkbox"
          name="useDarkTheme"
          id="toogle"
          defaultChecked={useDarkTheme}
          onChange={handleInput}
        />
        <sc.themeLabel htmlFor="toogle" />
      </sc.toogleSwitch>

    </sc.theme>
  );
}

thanks!

A: Are you familiarized with React's Context API? From styled-components docs:

styled-components has full theming support by exporting a <ThemeProvider> wrapper component. This component provides a theme to all React components underneath itself via the context API.

Let's see how we could implement a ThemeProvider with styled-components.
1. First we need to create a Context to encapsulate our theming logic
We should also create a "custom hook" to ease access to our context throughout our app.
theme-context.jsx
import React from 'react'

export const ThemeContext = React.createContext({
  // our theme object
  theme: {},
  // our color modes ('dark' || 'light')
  colorMode: '',
  // a method to toggle our theme from `dark` to `light` and vice-versa
  setColorMode: () => null,
})

// export our custom hook for quick access to our context
export function useTheme() {
  return React.useContext(ThemeContext)
}

2. Now we need to extend styled-components native <ThemeProvider> to create our own ThemeProvider
Since we'll need access to our themes, I'll add two very contrived theme objects (for the sake of simplicity) as well.
theme-provider.jsx
import React from 'react'
import { ThemeProvider as StyledProvider } from 'styled-components'
import { ThemeContext } from './theme-context'

// our theme objects
const lightTheme = { colorMode: 'light', bg: '#fff', text: '#000' }
const darkTheme = { colorMode: 'dark', bg: '#000', text: '#fff' }

// our iterable theme "store"
const myThemes = [lightTheme, darkTheme]

// our default color mode
const defaultColorMode = 'light'

const ThemeProvider = ({ children, ...props }) => {
  // get fallback values from the parent ThemeProvider (if exists)
  const {
    theme: fallbackTheme,
    colorMode: fallbackColorMode,
  } = useTheme()

  // initialize our state
  const theme = props.theme ?? fallbackTheme
  const [colorMode, setColorMode] = React.useState(
    props.colorMode ?? fallbackColorMode ?? defaultColorMode,
  )

  // memoize the current theme
  const resolvedTheme = React.useMemo(() => {
    const theme = myThemes.find(t => t.colorMode === colorMode)
    if (theme) return theme
    return lightTheme
  }, [theme, myThemes, colorMode])

  // update our state if props change
  React.useEffect(() => {
    setColorMode(props.colorMode ?? fallbackColorMode ?? defaultColorMode)
  }, [props.colorMode, fallbackColorMode])

 return (
    <ThemeContext.Provider
      value={{
        theme: resolvedTheme,
        colorMode,
        setColorMode,
      }}
    >
      <StyledProvider theme={resolvedTheme}>{children}</StyledProvider>
    </ThemeContext.Provider>
  )
}

export default ThemeProvider

3. Our final step is wrapping up our main <App /> component within our ThemeProvider
app.jsx
import React from 'react'
import ThemeProvider from './theme-provider'

const App = () => {
  const [themeType, setThemeType] = React.useState('light')
  const switchThemes = () => {
    setThemeType(last => (last === 'dark' ? 'light' : 'dark'))
  }

  return (
    <ThemeProvider colorMode={themeType}>
      <MySwitch onClick={switchThemes} />
    </ThemeProvider>
  )
}

And that's it. We should now be able to toggle our theme by clicking on MySwitch. Hope that helps!
Let me know how it goes? Cheers


text:
Q: How to refetchQueries a query having an args option I would like to know how to pass an argument during a refetchQueries in Apollo.
Code:
submitForm(e) {
        e.preventDefault();
        this.props.addAppleMutation({
            variables: {
                        color: "red"
                        weight: "0.33"
            },
            // stuck here
            refetchQueries: [{ query: loadApplesQuery, variables: {//argument i want to pass} }]
        })
    }

My query:
const loadApplesQuery = gql`
    query($id: ID) {
        apple(id: $id) {
            color
            size
            id
        }
    }
`

A: Yeah you can do this, you can also have a look at the same scenario that you want to tackle at
https://www.apollographql.com/docs/react/api/react-apollo#graphql-mutation-options-refetchQueries
so for example you can do this with High Order Component (HOC), you can do something like this

const loadApplesQuery = gql`
    query($id: ID) {
        apple(id: $id) {
            color
            size
            id
        }
    }
`;

const addAppleMutation = gql`
    mutation($apple: Apple) {
        addApple(Apple: $apple)
    }
`;

export default graphql(addAppleMutation, {
  name: 'addAppleMutation',
  options: {
    refetchQueries: (mutationResult) => [{
        query: loadApplesQuery,
        variables: {
          id: mutationResult.id,
        }
      }]
  },
})(MyComponent);

and then in the submitForm method you can do something like this

submitForm(e) {
   this.props.addAppleMutation({ variables : { color: 'green', size: 'small'}});
}

Hopefully that will help you.


text:
Q: How to submit modal with ajax and send data to another modal YII2 I've got modal window and from it I call another modal. I want to close second modal and send $model to first modal (action)... I use this code http://www.yiiframework.com/wiki/690/render-a-form-in-a-modal-popup-using-ajax/
View
<?php $form = ActiveForm::begin([
 'id' => 'form-deposit',
 'action' => ' ',
 'options'=>[
    'onsubmit'=>'submitForm',
 ]
 ]);?>
 <?= $form->field($model, 'sum')->textInput() ?>

JS
function submitForm($form) {
    $.post(
        $form.attr("action"), // serialize Yii2 form
        $form.serialize()
    )
        .done(function(result) {
            //$form.parent().html(result.message);
            $('#modalreference-edit').modal('hide');
        })
        .fail(function() {
            console.log("server error");
            $form.replaceWith('<button class="newType">Fail</button>').fadeOut()
        });
    return false;
}

controller
public function actionCreatedeposit()
    {
        $model = new FinanceIncomeExpenses();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->refresh();
        }
        else {
            if(Yii::$app->getRequest()->isAjax){
                return $this->renderAjax('deposit/create', [
                    'model' => $model,
                ]);
            }else{
                return $this->render('deposit/create', [
                    'model' => $model,
                ]);
            }
        }
    }

If i disable action it close both modal windows and nothing write in db.  When i use action i've got the blank page.


text:
Q: Ruby on Rails: meta_tags gem I use the meta_tags gems to handle all the SEO meta tags.
However, when I use in my application.html.haml view, it's showing on the page itself so that the user sees it as well.
= set_meta_tags title: "app title, keywords...."

Any idea why that happens?

A: This is a behaviour of HAML rather than the meta_tags gem.
-# In a HAML file, ...
= '= will evaluate the ruby code and put the result on the page'
- '- will evaluate the ruby code but not put the result on the page'

Reference: http://haml.info/docs/yardoc/file.REFERENCE.html#ruby_evaluation