text:
Q: Получение min,max значения object(Illuminate\Database\Eloquent\Collection)#175 (1) { ["items":protected]=> array(10) { [0]=> object(App\Models\Price)#205 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(1) ["store_id"]=> int(1) ["product_id"]=> int(1) ["price"]=> string(3) "500" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["original":protected]=> array(6) { ["id"]=> int(1) ["store_id"]=> int(1) ["product_id"]=> int(1) ["price"]=> string(3) "500" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [1]=> object(App\Models\Price)#206 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(2) ["store_id"]=> int(2) ["product_id"]=> int(1) ["price"]=> string(4) "2000" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["original":protected]=> array(6) { ["id"]=> int(2) ["store_id"]=> int(2) ["product_id"]=> int(1) ["price"]=> string(4) "2000" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [2]=> object(App\Models\Price)#207 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(3) ["store_id"]=> int(3) ["product_id"]=> int(1) ["price"]=> string(4) "3000" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["original":protected]=> array(6) { ["id"]=> int(3) ["store_id"]=> int(3) ["product_id"]=> int(1) ["price"]=> string(4) "3000" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [3]=> object(App\Models\Price)#208 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(4) ["store_id"]=> int(4) ["product_id"]=> int(1) ["price"]=> string(4) "4000" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["original":protected]=> array(6) { ["id"]=> int(4) ["store_id"]=> int(4) ["product_id"]=> int(1) ["price"]=> string(4) "4000" ["created_at"]=> string(19) "2016-04-05 12:57:17" ["updated_at"]=> string(19) "2016-04-05 12:57:17" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [4]=> object(App\Models\Price)#209 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(5) ["store_id"]=> int(5) ["product_id"]=> int(1) ["price"]=> string(4) "5000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["original":protected]=> array(6) { ["id"]=> int(5) ["store_id"]=> int(5) ["product_id"]=> int(1) ["price"]=> string(4) "5000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [5]=> object(App\Models\Price)#210 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(6) ["store_id"]=> int(6) ["product_id"]=> int(1) ["price"]=> string(4) "6000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["original":protected]=> array(6) { ["id"]=> int(6) ["store_id"]=> int(6) ["product_id"]=> int(1) ["price"]=> string(4) "6000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [6]=> object(App\Models\Price)#211 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(7) ["store_id"]=> int(7) ["product_id"]=> int(1) ["price"]=> string(4) "7000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["original":protected]=> array(6) { ["id"]=> int(7) ["store_id"]=> int(7) ["product_id"]=> int(1) ["price"]=> string(4) "7000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [7]=> object(App\Models\Price)#212 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(8) ["store_id"]=> int(8) ["product_id"]=> int(1) ["price"]=> string(4) "8000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["original":protected]=> array(6) { ["id"]=> int(8) ["store_id"]=> int(8) ["product_id"]=> int(1) ["price"]=> string(4) "8000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [8]=> object(App\Models\Price)#213 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(9) ["store_id"]=> int(9) ["product_id"]=> int(1) ["price"]=> string(4) "9000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["original":protected]=> array(6) { ["id"]=> int(9) ["store_id"]=> int(9) ["product_id"]=> int(1) ["price"]=> string(4) "9000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } [9]=> object(App\Models\Price)#214 (23) { ["table":protected]=> string(6) "prices" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(6) { ["id"]=> int(10) ["store_id"]=> int(10) ["product_id"]=> int(1) ["price"]=> string(5) "10000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["original":protected]=> array(6) { ["id"]=> int(10) ["store_id"]=> int(10) ["product_id"]=> int(1) ["price"]=> string(5) "10000" ["created_at"]=> string(19) "2016-04-05 12:57:18" ["updated_at"]=> string(19) "2016-04-05 12:57:18" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) } } }

Имеется вот такой вот вар_дамп.
При выполнении данного кода:
    $min_price = Price::where('product_id','=',$id)->min('price');
    $max_price = Price::where('product_id','=',$id)->max('price');

Вместо минимального значение 500 возвращает 10000, а вместо 10000 возвращает 9000.
Как из этого дампа получить min,max значения?


text:
Q: How do I reference another component's styled-components generated className while creating a (hover) rule in a different component? I'm creating a menu with styled-components and React, and want the color of the icon to change on hover, but I need it to change when the icon's parent is hovered, so that hovering the text next to the icon also activates the icon's hover styles. Here is the code I'm using to get close:
import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

const Menu = styled.div`
  display: flex;
  flex-direction: column;
`;

const LinkContainer = styled.div`
  display: flex;
  flex-direction: row;
`;

const FontAwesomeIconExtended = styled.div`
  flex: 1;

  display: grid;
  place-items: center;
  height: 40px;
  width: 40px;
  padding: 10px 2px;
  border-radius: 10px;
  transition: color 0.5s ease;

  color: ${(props) => (props.$isactive ? '#fff' : '#CBE3EB')};
  background: ${(props) =>
    props.$isactive
      ? 'linear-gradient(96.34deg, #004157 0%, #0090b2 100%)'
      : '#fff'};

  ${LinkContainer}:hover & {
    color: ${(props) => (props.$isactive ? '#fff' : 'green')};
  }                                                 /* Problem occurring here */
`;

const LinkText = styled.div`
  flex: 1 0 100px;
`;

function NavLink({ ...props }) {
  return (
    <Link to={props.path}>
      <LinkContainer $isactive={props.$isactive}>
        <FontAwesomeIconExtended
          $isactive={props.$isactive}
          icon={props.icon}
          size='2x'
          as={FontAwesomeIcon}
        />
        <LinkText $isactive={props.$isactive}>{props.name}</LinkText>
      </LinkContainer>
    </Link>
  );
}

export default function NavMenu() {
  return (
    <Menu>
      <NavLink path='/' name='Home' icon='house' $isactive />
      <NavLink path='/profile' name='Profile' icon='user' />
      <NavLink path='/payments' name='Payments' icon='credit-card-front' />
      <NavLink path='/contracts' name='Contracts' icon='file-contract' />
      <NavLink path='/messages' name='Messages' icon='mail-bulk' />
      <NavLink path='/messages' name='Documents' icon='folders' />
      <NavLink path='/locations' name='Transfer' icon='truck-moving' />
    </Menu>
  );
}

The way you reference another styled component in a later component is very clever, but in this case when it creates the hover rule, it creates without consideration of the different type of parent container ($isactive === true, or $isactive === false), so all LinkContainers have two rules for hovering, and use the last defined rule. This can be seen by moving $isactive to the last NavLink component.
Here is a screenshot of the devtools showing what I mean about the two hover rules not taking into consideration the parents class, just the general type of the parent.
I think the solution might involve being specific about the two types of LinkContainer's classNames while creating the hover rule, but that doesn't seem well supported. Thanks for taking a look.

A: Increase the specificity by repeating the class name, using another '&'
${LinkContainer}:hover && {

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an alternative/customizer app for Cmd+Tab that does not show minimized/hidden windows and apps? Is there an alternative/customizer app for cmd+tab that does not show minimized/hidden windows and apps?
Sometimes I have many apps running (Calendar, Mail, Twitter, etc.), but all of them are minimized and my focus is on, say, two apps: my IDE and the browser.
So I want cmd+tab to only show my browser and IDE.
Is there a way to achieve this?

A: If you hold command and quickly tap tab you will cycle between your two most recently used applications without bringing up the heads up display.
If you want to use a third party app Witch has options to ignore minimized windows.


text:
Q: How to set Class-Path header with dependencies? I'm using latest version of sbt 0.13.7, and I'd like to set Class-Path header of my MANIFEST.MF file with all the project dependencies, and I don't really know how. I did read Configure packaging.
I do know how to set other headers like Main-Class:
mainClass in (Compile, packageBin) := Some("mypackage.MyClass")

I know it can be done with the sbt-assembly plugin, but I don't want to create one big jar, just a small jar, that includes all the dependencies.
I found I could set Class-Path with *.jar, as shown in this snippet:
packageOptions in (Compile, packageBin) +=
  Package.ManifestAttributes(java.util.jar.Attributes.Name.CLASS_PATH -> "*.jar")

It appears a kind of workaround not a final solution. Any guidance very welcome.


text:
Q: Javascript dialog is programmed to move when the page scrolls, but it flickers. Can this be fixed? I've written some jQuery code to display a box with data in the corner of the users' web browser.  I'm using the .scroll event to make the box stay in the corner as the user scrolls up and down the page.  Let me emphasize that I am not using jquery-ui dialog.
The only problem is that the box flickers as the page scrolls.  I'm afraid that there will be no cross-browser solution to this problem as the different browsers seem to behave differently with scrolling.  Barring a cross-browser solution, an IE solution would be nice (My web application is designed to be used by a specific group of about 100 users in my organization.)
Here are snippets of the relative code:
ExternalScroll: function () {
            LittleBlackBook.setPosition();
        }

    setPosition: function () {
        var scrollPosition = $(self).scrollTop();
        var cssTop = LittleBlackBookStatic.determineCssTop(this.height, this.isTop, this.vOffset, scrollPosition);
        var cssHeight = LittleBlackBookStatic.determineCssHeight(this.height);
        var cssLeft = LittleBlackBookStatic.determineCssLeft(this.width, this.isLeft, this.hOffset);
        var cssWidth = LittleBlackBookStatic.determineCssWidth(this.width);
        this.jQueryObj.css('top', cssTop);
        this.jQueryObj.css('height', cssHeight);
        this.jQueryObj.css('left', cssLeft);
        this.jQueryObj.css('width', cssWidth);
    }

var LittleBlackBookStatic = {
    determineCssTop: function (height, isTop, vOffset, vScroll) {
        var windowHeight = $(self).height();
        var scrollPosition = $(self).scrollTop();
        var newModalTop = isTop ? vOffset + vScroll : windowHeight - height + vScroll - vOffset;
        return newModalTop + 'px';
    },

    determineCssHeight: function (height) {
        return height + 'px';
    },

    determineCssLeft: function (width, isLeft, hOffset) {
        var windowWidth = $(self).width();
        var newModalLeft = isLeft ? hOffset : windowWidth - width - hOffset;
        return newModalLeft + 'px';
    },

    determineCssWidth: function (width) {
        return width + 'px';
    }
} // end LittleBlackBookStatic

I'm using jQuery to look up the scroll position as the page scrolls and change the CSS.
Is there a better way; a way that will make it scroll without flickering?  If no, then why not?

A: You should use fixed positioning for that box instead instead of animating it to keep it in the corner.
You'll use less javascript and avoid flickering that comes with animation.


text:
Q: hide values in tables if the length of data is less than criteria I am looking to hide values from the output table if the frequency of data in the respective variable is less than 4 .
lets say if the number of records in column hp, mpg, qsec is less than 4 than the mean or median should be masked with "--"
i am trying like below but not working.
In this case if valid_n is less than 4 than mean , median should be shown as "--"
library(expss)
data <- data.frame(
  gender = c(1, 2, 1),
  sector = c(3, 3, 1),
  col1 = c(12, 15, 22),
  col2 = c(33, NA, 41),
  col3 = c(1, 1, 0),
  col4 = c(1, 0, 0),
  col5 = c(1, 2, 1)
)

data$col3 <- factor(data$col3, levels = 1, labels = "Management")
data$col4 <- factor(data$col4, levels = 1, labels = "HR")

lst <- list(data$col4,data$col3)
mean_mask =3
median_mask =3

fun1 <- function(dataset,var_list,banner1){
  perc_25 <- function(x, ...){unname(quantile(x, .25, na.rm=TRUE))}
  perc_75 <- function(x, ...){unname(quantile(x, .75, na.rm=TRUE))}
  mask_m<-function(x,N){
    x= ifelse(N<mean_mask,"--",x)
  }

  mask_me<-function(x,N){
    x= ifelse(N<median_mask,"--",x)
  }

  dataset<-dataset[var_list] %>% as.data.frame()
  first_col_param <- head(var_list,1)
  second_col_param <- tail(var_list,1)
  var_lab(colnames(dataset)[ncol(dataset)]) <- ""
  mr <- parse(text=paste0("mrset(",
                          first_col_param ," %to% ",second_col_param,")"))
  t1<- cross_fun(dataset,
                 eval(mr),
                 col_vars = banner1,
                 fun = combine_functions("Mean" = mask_m(mean,5),
                                         "Median" = mask_me(median,5),
                                         "Max"= max,
                                         "Min"=min,
                                         "25th Perc" = perc_25,
                                         "75th Perc" = perc_75,
                                         "Valid N" = valid_n
                 ))

  t1
}

mask = 5
t1 <- fun1(dataset=data,"col1",banner1=lst)

the required output should be look like below

A: Perhaps this helps

fun1 <- function(dataset,var_list,banner1){
  perc_25 <- function(x, ...){unname(quantile(x, .25, na.rm=TRUE))}
  perc_75 <- function(x, ...){unname(quantile(x, .75, na.rm=TRUE))}

  dataset<-dataset[var_list] %>% as.data.frame()
  first_col_param <- head(var_list,1)
  second_col_param <- tail(var_list,1)
  var_lab(colnames(dataset)[ncol(dataset)]) <- ""
  mr <- parse(text=paste0("mrset(",
                          first_col_param ," %to% ",second_col_param,")"))
  fun_replace_valid_n <- function(x, n) {
        dat <- cur_data_all()
        func_name <- dat$func_name
        if(x[func_name == "Valid N"] < n) {
       replace(x, func_name %in% c("Mean", "Median"), "--")

  } else x
  }

  t1<- cross_fun(dataset,
                 eval(mr),
                 col_vars = banner1,
                 fun = combine_functions("Mean" =  mean,
                                         "Median" = median,
                                         "Max"= max,
                                         "Min"=min,
                                         "25th Perc" = perc_25,
                                         "75th Perc" = perc_75,
                                         "Valid N" = valid_n
                 ))

  t1 <- as.data.frame(t1) %>%
    tidyr::separate(row_labels, into = c('grp', 'func_name'), sep = "\\|") %>%
      dplyr::group_by(grp) %>%
      dplyr::mutate(across(where(is.numeric), fun_replace_valid_n, n = 4)) %>%
      dplyr::ungroup() %>%
      tidyr::unite(row_labels, grp, func_name, sep = "|") %>%
      as.etable
  t1

}

-testing
> fun1(dataset=data,"col1",banner1=lst)

 |      |           | HR | Management |
 | ---- | --------- | -- | ---------- |
 | col1 |      Mean | -- |         -- |
 |      |    Median | -- |         -- |
 |      |       Max | 12 |         15 |
 |      |       Min | 12 |         12 |
 |      | 25th Perc | 12 |      12.75 |
 |      | 75th Perc | 12 |      14.25 |
 |      |   Valid N |  1 |          2 |


text:
Q: Не добавляется объект в RecyclerView У меня есть long переменные и я хочу заполнять RecyclerView объектами и количество объектов должно равняться значению long для этого я сделал легкий цикл
for (int i = 0; i < petiarochkaAmount100; i++) {
                couponss.add(new Coupons(R.drawable.petiarochka));
            }

Но объекты не добавляются.
Вот весь код
public class LibraryActivity extends BaseActivity {
private static final String TAG = "LibraryActivity";

List<Coupons> couponss = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_library);
    setInitialData();

    RecyclerView recyclerView = findViewById(R.id.list);
    RecyclerAdapter adapter = new RecyclerAdapter(this,couponss);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

}
public void setInitialData(){
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef = rootRef.child("users").child(getUid()).child("coupons");

    ValueEventListener valueEventListener = new ValueEventListener() {
        @SuppressWarnings("ConstantConditions")
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            long petiarochkaAmount100 = dataSnapshot.child("petiarochka").child("petiarochka100").getValue(Long.class);
            long petiarochkaAmount300 = dataSnapshot.child("petiarochka").child("petiarochka300").getValue(Long.class);
            long petiarochkaAmount500 = dataSnapshot.child("petiarochka").child("petiarochka500").getValue(Long.class);
            long lentaAmount100 = dataSnapshot.child("lenta").child("lenta100").getValue(Long.class);
            long lentaAmount300 = dataSnapshot.child("lenta").child("lenta300").getValue(Long.class);
            long lentaAmount500 = dataSnapshot.child("lenta").child("lenta500").getValue(Long.class);

            Log.v("JAJJAJAJAJA",""+petiarochkaAmount100);
            for (int i = 0; i < petiarochkaAmount100; i++) {
                couponss.add(new Coupons(R.drawable.petiarochka));
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };
    uidRef.addValueEventListener(valueEventListener);

}`

A: В данном цикле
for (int i = 0; i < petiarochkaAmount100; i++) {
            couponss.add(new Coupons(R.drawable.petiarochka));

Надо оповещать адаптер, следовательно цикл должен выглядеть так
for (int i = 0; i < petiarochkaAmount300; i++) {

                couponss.add(new Coupons(R.drawable.petiarochka));
                recyclerView.getAdapter().notifyDataSetChanged();

            }

И тогда все будет работать


text:
Q: The area enclosed by the locus of point C Triangle ABC is such that AB = 4, BC = 2, and AC = 3. If vertex A is confined to the x-axis and vertex B is confined to the y-axis, what is the area of the region enclosed by the locus of all points point C could possibly be?

A: You have some sort of a "do-nothing machine"
The midpoint of $AB$ traces a circle.
Lets start with $B = (0,0), A = (4,0)$  Where is $C$
Area  $= \sqrt {(\frac 92)(\frac 52)(\frac 32)(\frac 12)} = \frac {\sqrt {135}}{4}$
$h = \frac {\sqrt {135}}{8}$
And from Pythagoras theorem we get that the altitude splits the base into segments $\frac {11}{8},\frac {21}{8}$
Note there are 2 ways we can orient the triangle at this time.
$(\frac {11}{8},\frac  {\sqrt {135}}{4})\\
(\frac {11}{8},-\frac  {\sqrt {135}}{4})\\
$
Lets pick $C = (\frac {11}{8},\frac  {\sqrt {135}}{4})$ for now.
$A = (4\cos\theta, 0)\\
B = (0, 4\sin\theta)\\
C = (\frac {11}{8}\cos\theta + h\sin\theta, \frac {21}{8}\sin\theta + h\cos\theta)$
$C = (2\cos(\theta - \arctan\frac {\sqrt{135}}{11}), 3\sin (\theta + \arctan \frac{\sqrt {135}}{21}))$
That will trace out something that is roughly an ellipse.  I don't think it will be exactly an ellipse.
And swapping the different starting position of $C$ will change the sign on the angle of orientation.

A:
Special Note

Just found out that this is also known as Van Schooten's Locus Problem. Some good references here, here and here. The second references contains a neat solution using a purely geometrical approach.

Additional Note VI (based on Van Schooten's solution)

Refer to diagram above.
See Desmos implementation here.
Let $L,M,N$ be the lengths of $AB, AC, BC$ respectively.
Let $Z$ be the midpoint of $AB$.
Note that $ZO=ZA=ZB$.
Let $ZO=ZA=ZB=R(=L/2)$.
Draw a circle centred passing through $A,B,O$. This circle has $Z$ as its centre.
Let $P$ be the point where the line $CZ$ extended meets the circle.
Let $Q$ be the point where the line $ZC$ extended meets the circle.
Hence $ZP=ZQ=R$.
Since the arc $AQ$ is fixed, $\angle AOQ=\angle ABQ $ (fixed). Hence the locus of $Q$ is a straight line $OQ$.
Since the arc $AP$ is fixed, $\angle AOP=\angle ABP $ (fixed). Hence the locus of $Q$ is a straight line $OP$.
And since $PQ$ is a diameter of the circle, $\angle POQ$ is a right angle, i.e. $OP,OQ$ are perpendicular.
Hence the $C$ can be viewed as a point on $PQ$, with $P,Q$ constrained to move along perpendicular lines $OP, OQ$.
Hence $PCQ$ is a Trammel of Archimedes.
Therefore, the locus of $C$ is an ellipse with semi-major/minor axes $CP, CQ$.
Let $w=CZ$. Hence semi-major/minor axes are $$r^*_1=CP=R+w\\r^*_2=CQ=R-w$$
Area enclosed by the locus of $C$ (i.e. the ellipse) is
$$\pi \ r^*_1 r^*_2 = \pi (R^2-w^2)\tag{1}$$
Applying the cosine rule on triangles $ZAC, ZBC$:
$$\begin{align}
w^2&=M^2+R^2-2MR\cos\alpha\\
w^2&=N^2+R^2-2NR\;\cos\beta\\
\text{Adding:}\hspace{3cm}\\
2w^2&=M^2+N^2-2R(\underbrace{M\cos\alpha+N\cos\beta}_{=L=2R})\\
&=M^2+N^2-2R^2\\
w^2&=\frac {M^2+N^2}2-R^2\\
&=\frac {M^2+N^2}2-\frac {L^2}4\\
\therefore
R^2-w^2&=\frac {L^2}2-\left(\frac {M^2+N^2}2-\frac {L^2}4\right)\\
&=\frac {L^2-M^2-N^2}2
\end{align}$$
From $(1)$,
 area enclosed by the locus of $C$ (i.e. the ellipse) is
$$\pi \ r^*_1 r^*_2 = \pi (R^2-w^2)=\color{red}{\pi \left(\frac{L^2-M^2-N^2}2\right)}$$

Preamble from Original Answer

Interesting problem (+1).
Assuming $A,B$ are confined to the positive $x,y$ axes respectively, this gives two possible positions for $C$, labelled $C, C'$, where $ACBC'$ forms a kite with centre $P$, which divides $AB$ into $p, q$, where $p+q=4$, and semi-wingspan $h$.

Define $\alpha=\angle CAB,\;\; \beta=\angle CBA,\;\; \theta=\angle BAO$.
Using geometry, it can be deduced that, using parameter $\theta$, the coordinates of $C$ are
$$(x,y)=\big(N\cos (\beta\pm\theta),\;\;M\sin(\pm\alpha\mp\theta)\big)$$
where $N=2, M=3$.

Additional Note III

Here's a more straightforward derivation.
$$\begin{align}
r^2
&=N^2\cos^2(\beta-\theta)+M^2\sin^2(\alpha+\theta)\\
&=\tfrac12 \big(N^2(1+\cos2(\beta+\theta))+M^2(1-\cos 2(\alpha+\theta))\big)\\
&=\tfrac12 \big(N^2+M^2+N^2\cos2(\beta+\theta)-M^2\cos 2(\alpha+\theta)\big)\\
&=\tfrac 12
\big(N^2+M^2+N^2(\cos 2\beta\cos2\theta+\sin2\beta\sin2\theta)-M^2(\cos2\alpha\cos2\theta-\sin2\alpha\sin2\theta)\big)\\
&=\tfrac12 \big(N^2+M^2+\overbrace{(N^2\cos2\beta-M^2\cos2\alpha)}^A\cos2\theta+\overbrace{(N^2\sin2\beta+M^2\sin2\alpha)}^B\sin2\theta\big)\\
&=\tfrac12 \big(N^2+M^2+\sqrt{A^2+B^2}(\sin\gamma\cos2\theta+\cos\gamma\sin2\theta)\big)
\qquad\qquad\qquad\color{grey}{\big(\tan\gamma=\tfrac AB\big)}\\
&=\tfrac12 \big(N^2+M^2+\sqrt{A^2+B^2}\underbrace{\sin(\gamma+2\theta)}_
{ \substack{ \text{max: $+1$}\\ \text{min: $-1$} } } \big)\\
{r^*}^2
&=\tfrac12\big(M^2+N^2\pm\sqrt{A^2+B^2}\big)\\
{r_1^*}^2 {r_2^*}^2&=\tfrac14 \big(M^2+N^2-\sqrt{A^2+B^2}\big)\big(M^2+N^2+\sqrt{A^2+B^2}\big)\\
&=\tfrac14 \big((M^2+N^2)^2-(A^2+B^2)\big)\\
&=\tfrac14 \big((M^2+N^2)^2-2(M^2+N^2)L^2+L^4\big)
\qquad \text{(see below)}\\
&=\tfrac14 \big((L^2-M^2-N^2\big)^2\\
r_1^*r_2^*
&=\frac {L^2-M^2-N^2}2\\
\text{Area of Ellipse}=\pi r_1^*r_2^*
&=\color{red}{\pi\left(\frac {L^2-M^2-N^2}2\right)}\\
&=\color{red}{\pi\left(\frac {4^2-3^2-2^2}2\right)}\\
&=\color{red}{\tfrac32\pi}\\\\
\text{NB:}\hspace{3cm}\\
A^2+B^2
&=(N^2\cos2\beta-M^2\cos2\alpha)^2+(N^2\sin2\beta+M^2\sin2\alpha)^2\\
&=M^4+N^4-2M^2N^2(\cos2\alpha\cos2\beta-\sin2\alpha\sin2\beta)\\
&=M^4+N^4-2M^2N^2\cos2(\alpha+\beta)\\
&=(M^2+N^2)^2-4M^2N^2\cos^2(\alpha+\beta)\big)\\
&=\big(M^2+N^2\underbrace{-2MN\cos(\alpha+\beta)}_{M^2+N^2-L^2}\big)\cdot \big(\underbrace{M^2+N^2+2MN\cos(\alpha+\beta)}_{L^2})\big)\\
&=\big(2(M^2+N^2)-L^2\big) L^2\\
\end{align}$$
It can also be shown that the optimal $\theta (\theta^*)$ (i.e. when $C$ is at end of semi-major/minor axes) is given by
$$\tan\theta^*=\frac{M^2-N^2\pm L\sqrt{2(M^2+N^2)-L^2}}{\sqrt{(L+M-N)(L-M+N)(-L+M+N)(L+M+N)}}=\frac {\sqrt{15}\pm 4\sqrt{6}}9$$
It is interesting to note that at these positions, the polar angle $\phi$ is the same value as $\theta$, i.e. $$\phi^*=\theta^*$$

Additional Note V (Cartesian Form)

The parametric form for the locus of $C$ is
$$\big(N\cos(\beta-\theta),\; M\sin(\alpha+\theta)\big)$$
Eliminating parameter $\theta$ gives the Cartesian equation
$$\frac {\big(-xM\sin\alpha+yN\cos\beta\big)^2}{\big(MN\cos(\alpha+\beta)\big)^2}+\frac {\big(xM\cos\alpha-yN\sin\beta\big)^2}{\big(MN\cos(\alpha+\beta)\big)^2}=1$$
which can be transformed into the standard Cartesian form of a rotated ellipse
$$\frac{\big(x\cos\gamma+y\sin\gamma\big)^2}{P^2}+\frac {\big(x\sin\gamma-y\cos\gamma\big)^2}{Q^2}=1$$
where angle of rotation
$$\gamma=\arctan\left(\frac{M^2-N^2\pm\sqrt{(M^2+N^2)^2-(2MNcos(\alpha+\beta))^2}}{2MN\sin(\alpha+\beta)}\right)$$
and square of semimajor/minor axes
$$P^2, Q^2=\frac12\left(M^2+N^2\mp\sqrt{(M^2+N^2)^2-(2MN\cos(\alpha+\beta))^2}\right)$$

Original Answer (cont'd)

The loci of $C, C'$ are rotated ellipses. The locus of $P$ is an ellipse.
For the loci of $C, C'$, using ideas in the solutions here, it can be further shown that the semi-minor and semi-major axes occur when $r^2 (=x^2+y^2)$ is at a minimum/maximum correspondingly. This occurs when $\theta$ takes on the values $\theta^*_{min}$ and $\theta^*_{max}$ $(=\theta^*_{min} + \frac {\pi}2)$ respectively, where
$$\tan 2\theta^*_{min}=-\dfrac {2h}{p-q}=-\tfrac 35\sqrt{15}$$
This gives
$$\begin{align}
{r^*}^2
&=2^2\cos^2 (\beta-\theta^*)+3^2\sin^2 (\alpha+\theta^*)\\
&=2^2\cdot \tfrac12 (1+\cos2(\beta-\theta))+3^2\cdot\tfrac12 (1-\cos 2(\alpha+\theta))\\
&=\tfrac 12 \big[(2^2+3^2)\mp(p+q)\sqrt{4h^2+(p-q)^2}\big]\\
&=\tfrac 12 \big[13\mp 4\sqrt{10}\big]\\
r^*&=\sqrt{\tfrac{13\mp4\sqrt{10}}2}\\
&=2\pm \sqrt{\tfrac 52}\\
\text{Area of ellipse}\\
\text{ (region enclosed by locus of $C$)}
&=\pi \;r^*_1\; r^*_2\\
&=\pi \left(2^2-\tfrac 52 \right)\\
&=\color{red}{\tfrac 32 \pi} \qquad \blacksquare
\end{align}$$
Note that the area can also be calculated using $\pi (pq-h^2)$.
See Desmos implementation here.

(NB: note that $p=\frac {21}8, q=\frac {11}8, h=\frac 38\sqrt{15}$, $\alpha=\arctan (h/p), \beta=\arctan(h/q)$)
Here's an interesting wikipedia entry on the Trammel of Archimedes, an ellipsograph used for drawing ellipses.

Additional Note I

It is interesting to note that, for the general case,  the area of the ellipse, i.e. area bounded by the locus of $C$, is given by
$$\color{red}{\pi \left(\frac{L^2-M^2-N^2}2\right)}$$
 where $L=AB, M=AC, N=BC$, and the semi-minor/major axes lengths are given by
$$r^*=\frac {L\pm \sqrt{2(M^2+N^2)-L^2}}2$$
Also, if $\angle ACB$ is a right angle, i.e. $L^2=M^2+N^2$, then the area is zero, i.e. the locus is a line segment (on the line $y=x$).

Additional Note II

This note here shows an alternative derivation.
Let $u=\alpha+\theta, v=\beta-\theta$. Hence $u+v=\alpha+\beta$.
Also, let $m_1=M\sin u,\;\; m_2=M\cos u, n_1=N\sin v,\;\; n_2=N\cos v$.
From above, we have
$$\begin{align}
r^2&=N^2 \cos^2 (\beta -\theta)+M^2 \sin^2 (\alpha+\theta)\\
\frac {dr^2}{d\theta}&=2N^2\cos(\beta-\theta)\sin(\beta-\theta)+2M^2\sin(\alpha+\theta)\cos(\alpha+\theta)\\
&=2n_1n_2+2m_1m_2\\
&=0\qquad\qquad\qquad \;\;\text{at max/min }r^2\\
n_1n_2+m_1m_2&=0\\
(n_1n_2+m_1m_2)^2&=0\\
\color{\lightgrey}{m_1^2n_1^2+m_2^2n_2^2}+n_1^2n_2^2+m_1^2m_2^2&=-2m_1m_2n_1n_2+\color{\lightgrey}{m_1^2n_1^2+m_2^2n_2^2}\\
(n_2^2+m_1^2)(n_1^2+m_2^2)&=(m_2n_2-m_1n_1)^2\\\\
\color{\lightgrey}{(n_2^2+m_1^2)^2+2(n_2^2+m_1^2)(m_2n_2-m_1n_1)}\\
+(n_2^2+m_1^2)(n_1^2+m_2^2)&=(m_2n_2-m_1n_1)^2\\
&\;\;\;\color{\lightgrey}{+(n_2^2+m_1^2)^2+2(n_2^2+m_1^2)(m_2n_2-m_1n_1)}\\\\
(\underbrace{n_2^2+m_1^2}+\underbrace{m_2n_2-m_nn_1})^2
&=\big[\underbrace{m_1^2+m_2^2}+\underbrace{n_1^2+n_2^2}+\underbrace{2(m_2n_2-m_1n_1)}\big](\underbrace{n_2^2+m_1^2})\\
\big({r^*}^2+MN\cos(u+v)\big)^2
&=\big(\underbrace{\;\;\;M^2\;\;\;\;\;+N^2+2MN\cos(u+v)}_{L^2}\big)\;\;\;\;\;{r^*}^2\\
\big({r^*}^2+\tfrac {L^2-M^2-N^2}2\big)^2
&=L^2{r^*}^2\\
{r^*}^2-L{r^*}+\underbrace{\tfrac {L^2-M^2-N^2}2}_{\text{Product of roots, }r_1 r_2}&=0\\
\text{Area of ellipse}=\pi\; r_1^* r_2^*
&=\color{red}{\pi\bigg(\frac {L^2-M^2-N^2}2\bigg)}\qquad\blacksquare
\end{align}$$
NB:
$$\small r^*=\frac {L\pm \sqrt{L^2-2(L^2-M^2-N^2)}}2
=\frac {L\pm \sqrt{2(M^2+N^2)-L^2}}2\\$$

Additional Note IV (Area of Union of Both Ellipses)
  (per OP's additional question in the comments)

The union of the two ellipses (which are of equal area) is twice the area of one ellipse less the area of intersection - the near-diamond-shaped area. The area of one of four equal quadrants is given by
$$Q=\tfrac12r_1r_2\left[\tan^{-1} \big(\tfrac {r_1}{r_2}\cdot\tan\psi_2^*\big)-\big(\tfrac {r_1}{r_2}\cdot\tan\psi_1^*\big)\right]$$
where $\psi_1^*, \psi_2^*$ are the angle between the semimajor-axis in the positive quadrant and the positive $y$-axis and negative $x$-axis respectively. Since $\psi^*=\tfrac \pi 2-\phi^*=\tfrac\pi 2-\theta^*$, this is equivalent to
$$Q=\tfrac12r_1r_2\left[\tan^{-1} \big(\tfrac {r_1}{r_2}\cdot(-\tan\theta^*)\big)-\big(\tfrac {r_1}{r_2}\cdot\cot\theta^*\big)\right]$$
The area of intersection is $4Q$.If $E=$ is the area of one ellipse, the the area of the union of both ellipses is given by $2E-4Q$.


text:
Q: Какими технологии пользоваться для установки будильника на Swift для iOS Я делаю приложение будильника. Так выглядит моя вьюха:

Что уже работает:
Я нажал на кнопку «6:00» одиночным тапом, сработала моя функция addAlarm("6:00", "unstable"). Кнопка «6:00» стала выделена зелёным. Само время было запомнено в моделе данных приложения, чтобы кнопка с соответствующим временем осталась подсвеченной после закрытия и повторного открытия приложения.
Кнопка «8:00» горит красным, потому что я тапнул на неё дважды и сработала функция addAlarm("6:00", "stable"). Информация так же была записана в модель данных.
Чего я хочу:
Зелёный цвет кнопки «6:00» значит, что будильник должен сработать один раз в 6 утра, а затем должен деактивироваться, то есть кнопка снова должна стать синей.
Красный цвет кнопки «8:00» значит, что будильник должен срабатывать каждый день в 8 утра, но после этого кнопка должна также оставаться красной.
Под срабатыванием будильника я имею ввиду следующее. На экране устройства появляется уведомление с текстом «Проснись», и начинает играть мелодия. Файл с мелодией длится 20 секунд, но я хочу, чтобы мелодия длилась 3 минуты, постоянно повторяя 20 секундный файл с мелодией.
Будильник должен срабатывать даже когда приложение свёрнуто, телефон находится в спящем режиме или установлен режим «не беспокоить».
Чего я не понимаю:
Ну разумеется, как сделать то, чего я хочу :–) Если серьёзно, то мне не ясно какими методами пользоваться. Мне удалось найти следующее.
Можно использовать NSTimer, чтобы вызвать какой-то колбэк через назначенное время, но таймеры перестают работать через 10 минут после сворачивания приложения.
Можно и нужно использовать UIApplication.sharedApplication().scheduleLocalNotification(notification) для появления уведомления, но мелодия сопровождающая уведомление не может превышать 30 секнуд, также мне не ясно, как мне вызвать мою функцию removeAlarm(time) для будильников установленных однократно, если пользователь никак не отреагирует на уведомление, например, не проснётся.
Можно использовать Background Modes.
В общем, вопрос:
Какой или какие методы использовать, как их совместить, и вообще в какую сторону капать?

A: Использовать

UIApplication.sharedApplication().scheduleLocalNotification(notification)

Просто чередовать его несколько раз подряд,т.е. ставить не одну нотификацию а пачку подряд. Причем можно вызвать просто нотификацию со звуком, не выводя ее на экран.
Т.е первую мы можем вывести, а последующие просто проигрывать звук.


text:
Q: Convert datetime stored as char the YYYMMDDHHmmSS format to datetime I'm working with a table where the date and time of an event is stored as a char in the format YYYMMDDHHmmSS or '20120606122012'. I need to compare this to the current timestamp to see if it's been more than 20 minutes since the event happened, but that seems to be more difficult than I anticipated.
Is it possible to do this, or if not: is there a different approach that works?

A: Do some string manipulation to get your string to the format YYYYMMDD HH:mm:SS and you can cast/convert to datetime.
Something like this:
declare @S varchar(50)
set @S = '20120606122012'

select cast(left(@S, 8)+' '+substring(@S, 9, 2)+':'+substring(@S, 11, 2)+':'+substring(@S, 13, 2) as datetime)

A: You could also add this as a computed column or make it part of a view, so that you don't have to perform the calculation over and over in every query.
As a computed column:
ALTER TABLE dbo.whatever ADD dt
AS CONVERT(DATETIME, STUFF(STUFF(STUFF(col,9,0,' '),12,0,':'),15,0,':'), 120);

Since the calculation is deterministic, it can be persisted and/or indexed.
Using a view:
CREATE VIEW dbo.view_whatever
AS
    SELECT /* other columns, */
      dt = CONVERT(DATETIME, STUFF(STUFF(STUFF(col,9,0,' '),12,0,':'),15,0,':'))
    FROM dbo.whatever;

Then you can simply say:
WHERE dt < DATEADD(MINUTE, -20, CURRENT_TIMESTAMP)

Though I have to agree with the others - you need to fix the model. There is no advantage whatsoever to storing this as a string, except that your users don't get pesky error messages when they enter non-date junk like whosawatsa or even 20120230000000.


text:
Q: I want to calculate completion percentage through SQL query I have scenario where I want to get the percentage of completion.
I have two columns and have to calculate third.
 vCompletedTasks | vTotalTasks | vPercentageCompleted

  63               66
  55               70
  35               50
  24               48                 50%

I need to write a query which calculates third column, which is percentage.

A: select vCompletedTasks,vTotalTasks,convert(varchar(2),

((vCompletedTasks * 100) / vTotalTasks))+'%' as vPercentageCompleted

from TableName


text:
Q: Custom MediaTypeFormatter (Serializer) for ApiController specific method I have ApiController in place and one of methods needs have custom serialization.
    public async Task<Session> PostSession([FromBody] Session session)

There is massive Session object that holds everything and consumer does not want do get more than half of it, normally I could just decorate properties with [XmlIgnore()] and be done, however this object is being passed internally across many APIs and removing these would break these mechanisms.
Another solution would be to just replace that object with different one like CastratedSession and return that. I can't do this since same endpoint is being called by existing 3rd party APIs that expect to get Session or they would have to rewrite their stuff (not going to happen).
I then proposed to create a different endpoint that this 3rd party could call - but architect objected and said to do the custom MediaTypeFormatter based on specific content-type value they will set in header, problem is we already are using in this same controller custom MediaTypeFormatter, and the way I understand out of the box one can only set them in configuration per controller
public static void ConfigureApis(HttpConfiguration config)
{
    config.Formatters.Add(new CustomJsonFormatter());
    config.Formatters.Add(new CustomXmlFormatter());
}

Which sorta paints me into the corner.
How (Can) I setup a custom MediaTypeFormatter per method on ApiController?

A: you could write a custom action filter, override the OnActionExecuting method to inspect the target action, then add the proper formatter to the configuration.
internal class DecisionMakingFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var actionName= actionContext.ActionDescriptor.ActionName;
        if(actionName == "Some Foo")
        {
            actionContext.RequestContext.Configuration.Formatters.Add(new CustomMediaFormatter());
        }
        base.OnActionExecuting(actionContext);
        actionContext.RequestContext.Configuration.Formatters.Remove(new CustomMediaFormatter());
    }
}

A: figured out a workaround myself
I inherited and replaced CustomXmlFormatter() with EvenMoreCustomXmlFormatter()
then in WriteToStreamAsync did this:
  public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        if (content.Headers.ContentType.MediaType == "text/sessionXml") // this was agreed with 3rd party
        {
            //do my serialization stuff
        }
        else
        {
            return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
        }
    }

hope this saves you some time.


text:
Q: Laravel/Vue - JWT Token Remember-me I'm doing my authentication system with Laravel & JWT, but I have some questions.
I use the tymon jwt package

*

*I have a token generated at login, for 24 hours, and if the remember-me box is checked, it is valid for 2 years.
Except that how should I proceed to renew the token during these 2 years, I guess I don't have to keep the same one, for security reasons?

*Do I have to store something in a database ? like a remember-me token for example, or a refresh-token ?
I'm a bit lost with all this, and I'd like to understand how to proceed.
I've already searched quite a bit on the internet, but I can't find what I want, or it's incomplete.
public function login()
    {
        $credentials = request(['email', 'password']);
        $ttl = env('JWT_TTL');

        if (request(['remember_me']) == true) {
            $ttl = env('JWT_REMEMBER_TTL');
        }

        if (!$token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Wrong credentials'], 401);
        }

        return $this->respondWithToken($token, $ttl);
    }

protected function respondWithToken($token, $ttl)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $ttl
        ]);
    }

JWT_TTL=1440
JWT_REMEMBER_TTL=1051200

Thanks in advance,

A: You don't have to store anything in a database.
Create two JWTs, one as the access token (login) and one for remember me. Set the access token to expire for 24 hours as usual, and the remember me token to expire for 2 years.
On your protected route, check if the access token is expired, and if it is, check for the remember me token. If the remember me token is present, issue a new access token.

A: You can handle it in this way as well and its working fine with JWT package using setTTL function and define two different time in .env file.
$ttl = ($request->remember_me === true) ? env('JWT_REMEMBER_TTL') : env('JWT_TTL'); if (! $token = auth()->setTTL($ttl)->attempt($credentials)) {}


text:
Q: Sql Server : Using CASE with three conditions I want to use CASE with three conditions. It is showing error.
My query :
 select distinct a.phone, other,starttime,duration,imeinumber,
 imsinumber,call_type,a.provider_key, a.celltowerid, siteaddress,
 lat, long, azimuth from cdat a
 left join cdatdupl.dbo.cdatcelltowerareanew b on
    case
    when a.provider_key!='9' then a.tower_key=b.tower_key
    else a.celltowerid = b.celltowerid
        and a.provider_key=b.provider_key
        and a.state_key end=b.state_key

A: You have to close the CASE expression with end keyword
syntax
CASE { simple_case_expression
     | searched_case_expression
     }
     [ else_clause ]
     END

Updated Query
 select distinct a.phone, other,starttime,duration,imeinumber,
 imsinumber,call_type,a.provider_key, a.celltowerid, siteaddress,
 lat, long, azimuth from cdat a
 left join cdatdupl.dbo.cdatcelltowerareanew b on
    case
        when a.provider_key!='9' then a.tower_key=b.tower_key
        else (a.celltowerid = b.celltowerid
            and a.provider_key=b.provider_key
            and a.state_key end=b.state_key)
    end


text:
Q: uwsgi and django: ImportError: No module named __future__ when I try to deploy my django page uWSGI tells:
...
added /env/project/ to pythonpath.
Traceback (most recent call last):
  File "/env/project/project/wsgi.py", line 27, in <module>
    from django.core.wsgi import get_wsgi_application
  File "/env/lib/python2.7/site-packages/Django-1.5.1-py2.7.egg/django/core/wsgi.py", line 1, in <module>
from django.core.handlers.wsgi import WSGIHandler
  File "/env/lib/python2.7/site-packages/Django-1.5.1-py2.7.egg/django/core/handlers/wsgi.py", line 1, in <module>
    from __future__ import unicode_literals
ImportError: No module named __future__
unable to load app 0 (mountpoint='') (callable not found or import error)

i tried
django-admin.py startproject project

to test with a fresh project, but it doesnt work either. I also played arround with the project.ini and reinstalled the virtualenv (tried: 2.7 3.0 3.3). Nothing helps.
Nginx and uWSGI are running in a chrooted jail. Django is installed with easy_install-2.7 in a virtualenv-2.7.
I dont really understand what is happening here. I think it has to do with the update to django version 1.5.
Does someone has an idea?

A: There could be several reasons for this. Most likely it is a permissions issue. uwsgi is running as a user that doesn't have read access to the python files in the virtualenv.
Check the virtualenv
In any case, the first step is to source the virtualenv and check that the import works.
. /path/to/venv/activate/script
python -c 'import __future__'

If that works, then you know your virtualenv is in good shape.
Check that the module is in python's module search path
Now the error is isolated to uwsgi's use of that virtualenv. Run the following snippet to find the location of the __future__ module.
python -c 'import __future__; print __future__.__file__'

When uwsgi runs python, it must run it as a user and with an environment. If the environment is wrong, python won't be able to find its modules. Ensure that the location of the __future__ module is in python's module search path.
# Open /env/project/project/wsgi.py and add the following lines to the
# beginning.
import sys; print sys.path

Restart uwsgi and look for that printed list of directories. You should find that one of those directories contains the path to __future__'s module. If it doesn't then you'll need to figure out how to correct that path.
Check that uwsgi has permissions to read/access the module
Granted that the directory is present, you need to ensure that the file permissions would allow uwsgi to load that module.
sudo -u <uwsgi user> -c python /path/to/__future__/module.py

Likely the culprit is the uwsgi user doesn't have permissions.


text:
Q: How to Pass dictionary as the value of another dictionary? var for_cat_dict = new Dictionary<string, string>();
var category_Dict = new Dictionary<string,Dictionary<string,string>>();

for_cat_dict.Add(bean.getId(), bean.getId());

Now I want to add elements to the category_dict. So I tried..
category_Dict.Add(bean.getId(),[for_cat_dict]);

But it doesnt work... any solutions??

A: It's not really clear what you're trying to do, but
Category_Dict.Add(bean.getId(), for_cat_dict);

should at least compile. Whether it'll do what you want is another matter - it's not clear whether these are local variables, fields etc. (It also looks like you're not following .NET naming conventions in various ways...)

A: Dictionary<string, string> for_cat_dict = new Dictionary<string, string>();
Dictionary<string, Dictionary<string, string>> Category_Dict = new Dictionary<string, Dictionary<string, string>>();

Category_Dict.Add("somekey", for_cat_dict);


text:
Q: Entity Framework 6 DB first with multiple data models for huge Database I have an MSSQL DB with more than 1000 tables, and I wanted to use EF 6 in my project as DB is large and already running with another system so I will go with DB first approach.

*

*My question is that what is the best practice to use multiple EF data models(each will contain 10 or less tables) will communicate with each other as it will be in different context (e.g. getting data from product table in sales model).

*How to manage same Tables in different models e.g. users table probably will be in each model.

*Is there anyway that I can use for updating all models at once or is there any post-build option to automate updating all models from db and what will be the affect on customized tables.

Already done: Created multiple data models in the same project with the same DB in different folders(working fine).
Thanks.

A: The answer to all of your questions is Domain Driven Design.
Go through Julie Lerman's DDD Bounded Context. She has explained everything in an obvious and comprehensive way.
For data sharing she has another article. Have a look at this too


text:
Q: PayPal API QueryParameters not found
I copied and pasted a section from here (You will have to scroll to the top - click C# on the right and scroll down/refresh) and have installed the PayPal API into the project Install-Package PayPal but QueryParameters is not found - is there a second part or something I should already know about?

Code from site
OAuthTokenCredential tokenCredential =new OAuthTokenCredential("<CLIENT_ID>", "<CLIENT_SECRET>");

string accessToken = tokenCredential.GetAccessToken();
var parameters = new QueryParameters();
parameters.SetCount("10");

PaymentHistory paymentHistory = Payment.Get(accessToken, parameters);

A: AFAICS are the PayPal QueryParameters part of PayPal.Util. Please try if you can access this namespace.
If not you can add it manually (as a class) using this link.
You should also consider downloading the whole SDK if the above does not work using nuget.

A: Some of the language tabs on the PayPal REST API Reference page have sample code that is woefully out-of-date (and in this case, completely incorrect since Payment.Get(...) is intended to return a single payment resource, not a list).  The PayPal docs team is well aware of this issue and will be removing the language tabs in the near future in favor of the SDKs providing their own samples via GitHub.
I'd recommend checking out the PayPal .NET SDK samples project on GitHub, which does a much better job of showing you not only the code, but displaying the request/response details for each API operation.
Regarding getting the payment history, you'll want to do the following using the PayPal .NET SDK:
using PayPal.Api;

// Authenticate with PayPal and setup the APIContext object.
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken)
{
    Config = config
};

// Get the payment history
var paymentHistory = Payment.List(apiContext, count: 10, startIndex: 5);


text:
Q: How to delete a row from a WordPress custom database? I have a custom database and a code that displays the table data and I want a button on the right side of the table that will delete a row that it's attached to from the table.
<?php //get_header();

global $wpdb;
$table_name = $wpdb->prefix . "hubaya_wallet_users";
$result = $wpdb->get_results("SELECT * FROM $table_name");

echo '
PAY USERS

  ID
  ROLE
  BALANCE
  REG DATE
  Mobile Number	 ';

  foreach ( $result as $print ) { ?>

    <?php echo $print->user_id; ?>
    <?php echo $print->user_role; ?>
     <?php echo $print->balance ; ?>
     <?php echo $print->created_date; ?>
    <?php echo $print->phone_no; ?>

  <?php }
  ?>

I want a button attached to each row that on click will delete the row. I tried adding a table like this:
<input name="del" type="submit" value= "echo $print->user_id; ?>">

Now I don't know how to set its action to a function below.
function del(){
    global $wpdb;
    $table_name = $wpdb->prefix . $_POST['table'];
    $mss = intval($_POST['del']);
    $wpdb->delete( $table_name, [ 'id' => $mss] );
}

I've also tried creating a separate form where I will have to type in everything and then submit but still failed.


text:
Q: How to use date-pipe inside for loop in angular? I want to use date-pipe for the values of my dictionary. So I tried this.
<div *ngFor="let field of watchlist | keyvalue">
<li *ngIf="field.value  && field.key">{{field.key}}: {{field.value | date:'d MMM y'}}

but got an error
    Error: src/app/update-watchlist/update-watchlist.component.html:45:76 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(value: string | number | Date, format?: string | undefined, timezone?: string | undefined, locale?: string | undefined):
string | null', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'string | number | Date'.
      Type 'unknown' is not assignable to type 'Date'.
  Overload 2 of 3, '(value: null | undefined, format?: string | undefined, timezone?: string | undefined, locale?: string | undefined): null', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'null | undefined'.
      Type 'unknown' is not assignable to type 'null'.
  Overload 3 of 3, '(value: string | number | Date | null | undefined, format?: string | undefined, timezone?: string | undefined, locale?: string | undefined): string | null', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'string | number | Date | null | undefined'.
      Type 'unknown' is not assignable to type 'Date'.

45                     <li *ngIf="field.value  && field.key">{{field.key}}: {{field.value | date:'d MMM y'}}

A: Make sure field.value is a string or a number or a Date. It currently is seen as unknown.
To do that, you'll either have to better type watchlist or explicitly field.value.


text:
Q: Mechanical relay replacement for mosfet bias This question is derived from this question after additional experimenting how to avoid power up and power down overshoot with or without load connected to power supply. With my present level of knowledge I resolve this issue effectively using the following circuit (see "dashed" frame section):

It's very simple: LM555 is used for power up delay until bias supply (+/-15 for CC and CV logic) is stabilized as shown below (Vout=yellow, +15V=magenta, -15V=blue).

When power is switched off, then relay is demagnetized while valid bias (+/-15V) is still present and make clean cut by connecting the gate to the ground and no overshoot in CV mode is present. That is nicely visible on the following image:

So far so good. My question is: since this solution with relay is a little too "mechanical" is there a replacement for such functionality?
I spent some time experimenting with MOSFET and BJT as a switch but the problem is that we are working here with marginal situations where power for the switch is also coming in and going away. I found some workable solution for power up case but "grounding" Q1 gate in case of power down to inhibit any residual control voltage what results in appearing undesired (uncontrolled) DCIN to the OUT+ is beyond my expertise.
EDIT 2015-02-26: I spent some time to use different type of bias supply with proper power sequencing. That made this question and one from which this one is derived not relevant anymore. Used solution is mentioned here and here.

A: Option 2: Replace the analog circuit with a microcontroller

simulate this circuit – Schematic created using CircuitLab
Without external input, pull-down R1 firmly applies ground to Vgate through Q2.
(Existing)R2 is large-ish since FET gate does not need large current.
R3 is current protection for the LED inside the opto. A 380ohm resistor with a 1.2V drop across the LED yields about 10mA.
When uC_PowerEnable becomes high, Q2's gate is biased at DCIN, allowing Vgate to rise.
The recommended capacitor across the ATTiny power supply pins can be up-sized to ensure the Tiny is the last thing that turns off. Without signal from the uC, R1 resumes its original role of 'permanently' grounding Vgate. In this setup, the uC can shut down Vout for any reason(s) and can be reprogrammed, instead of redesigned and/or resoldered.
SetPin(uC_PowerEnable, VinPlus15Good && VinMinus15Good); //Shut down if either input rail fails

A: Option 1) Remain analog

simulate this circuit – Schematic created using CircuitLab
With DCIN applied, the opto-isolator is activated and conducts DCIN to the gate of Q2, switching it off, and allowing Vgate to rise.
When DCIN is disconnected, the opto blocks and R6 biases Q2 into conduction, thereby grounding Vgate.
R9 should be sized to drop the voltage that is not dropped by the LED and limit the LED current to about 10mA.
ZD1 is to protect the LED from accidents.


text:
Q: Selenium script read js file embedded in html We are planning to automate with selenium the process to get all js from html page and to find whether a method is called inside the js script, can anyone suggest the approach to do so

A: One approach would be to use WebDriver.getPageSource and parse the code according to your needs, e.g. by using a regular expression.


text:
Q: When solving an equation with absolute value on both sides, how to choose the side to work with? When solving an equation with absolute value on both sides, such as
$$|2x-1|=|4x+3|$$
how to choose one side of which to use the definition of absolute value?
For example, if we apply absolute value just for right side
so we have $2x-1=-(4x+3)$ and $2x-1=(4x+3)$. But why we don't solve for left hand $-(2x-1)=4x+3$ and $(2x-1)=4x+3$?
I know how to solve these but I don't understand the logic.

A: The  argument of the LHS module changes sign at $x=\frac{1}{2}$. The argument in RHS changes sign at $x=-\frac{3}{4}$, so we have three systems:
$$
\begin{cases}
x<-\frac{3}{4}\\
1-2x=-(4x+3)
\end{cases}
\quad \lor \quad
\begin{cases}
-\frac{3}{4}\le x<\frac{1}{2}\\
1-2x=4x+3
\end{cases}
\quad \lor \quad
\begin{cases}
x\ge\frac{1}{2}\\
2x-1=4x+3
\end{cases}
$$
can you solve these?

A: The logic is that, faced with something like $\lvert X \rvert = \lvert Y \rvert$ where $X$ and $Y$ are any expressions, we know that $X$ and $Y$ are both the same distance from $0$.
In other words, if they have the same absolute value, then either they're the same so that $X = Y$ or they're negatives of each other (think $\lvert 3 \rvert = \lvert -3\rvert$) so that $X = -Y$, and both cases are perfectly valid.
But multiplying each of the above equations by $-1$, we have a total of four equations
\begin{align*}
X = Y\quad &\text{ is equivalent to} \quad-X = -Y \\
X = -Y \quad &\text{ is equivalent to}\quad -X = Y
\end{align*}
that form two pairs: As long as you pick one equation from each set of equivalent pairs, you'll get all possible solutions. With your method, whether we choose $X = -Y$ or $-X = Y$ depends on who we keep the absolute value with:
$|X| = Y$ gives $X = Y$ or $X = -Y$, while $X = |Y|$ gives $X = Y$ or $-X = Y$.
But remember, multiplying an equation by a negative doesn't change the solutions at all, so either one is perfectly good.


text:
Q: Como fazer busca e ordenação de TemplateFields em um GridView? Basicamente, tenho uma tabela (GridView) em uma página aspx cujos dados estão definidos por TemplateFields. Por exemplo:
<asp:GridView runat="server" ID="grdProdutos">
    <Columns>
        <asp:TemplateField HeaderText="Produto">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblProduto" Text='<%# Eval("NomeProduto")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Tipo">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblTipo" Text='<%# Eval("TipoProduto")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Preço">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblPreco" Text='<%# Eval("PrecoProduto")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Os métodos usados no code behind são os seguintes:
RepositorioProdutos banco = new RepositorioProdutos();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CarregarGridView();
    }
}

public void CarregarGridView()
{
    var produtos = banco.ObterProdutos();

    if (produtos != null)
    {
        grdProdutos.DataSource = produtos;
        grdProdutos.DataBind();
    }
    else
    {
        throw new Exception("Nenhum produto encontrado.");
    }
}

Gostaria de saber como poderia implementar uma busca por produtos (procurando um termo em qualquer campo) e como poderia implementar uma ordenação clicando no nome da coluna que eu gostaria de ordenar (como no Explorer do Windows), sem precisar fazer uma nova consulta ao banco (ou seja, sem precisar acessar o método banco.ObterProdutos() novamente).
Obs.: para a busca, estou considerando o uso de um textBox que será usado para inserir a palavra-chave da busca, e um botão que acionará a busca.

A: São duas perguntas distintas, na minha opinião não é uma tarefa tão simples quando parece, portanto essa resposta não pretende ser definitiva, mas apenas tentar mostrar um ponto de partida.
Sobre o sorting:
O GridView possui um evento OnSorting que fornece um parâmetro com uma propriedade SortExpression que contém uma string normalmente com o nome do campo a ser ordenado.
Ocorre que com Linq não conseguimos ordernar os campos a partir de uma string, para isso precisamos de uma library System.Linq.Dynamic que permite utilizarmos strings em vez das lambda expressions.
Portanto, instale a library System.Linq.Dynamic pelo nuget, depois certifique-se de fazer referência no seu código:
using System.Linq.Dynamic;

Agora altere seu gridView para aceitar sorting:
<asp:GridView ID="grdProdutos" AllowSorting="true" OnSorting="gridView_Sorting" runat="server">

Nas colunas do gridView precisamos definir a SortExpression que informa por qual campos queremos ordenar:
<asp:TemplateField HeaderText="Produto" SortExpression="Produto">

E no seu codebehind:
protected void grdProdutos_Sorting(object sender, GridViewSortEventArgs e)
{
    var gridView = (GridView)sender;

    for (int i = 0; i < gridView.Columns.Count; i++)
        if (gridView.Columns[i].SortExpression == e.SortExpression)
            if (e.SortExpression.EndsWith(" desc"))
                gridView.Columns[i].SortExpression = e.SortExpression.Replace(" desc", "");
            else
                gridView.Columns[i].SortExpression = e.SortExpression + " desc";

    gridView.DataSource = banco.ObterProdutos().OrderBy(e.SortExpression);
    gridView.DataBind();
}

Lembrando que o Dynamic Linq funciona com tipos IQueryable<T>, portanto se seu método ObterProdutos retorna um IEnumerable<T> modifique o mesmo, provavelmente evitando fazer uma chamada para ToList().
Para pesquisar você pode fazer com o input e um botão parar disparar e usar o valor do input para pesquisar em seguida define novamente o DataSource, por exemplo:
gridView.DataSource = banco.ObterProdutos().Where(m => m.Produto.StartsWith(valordoinput);
gridView.DataBind();

A parte chata vai ser manter a busca e o sort juntos. Você precisaria criar um método que vai buscar o SortExpression de cada uma das colunas do gridView assim como a expressão de pesquisa que retorne uma lista de produtos com Where e OrderBy.

A: Se o Grid já estiver populado você pode usar o próprio ds da grid para retomar as informações sem a necessidade de buscar novamente na base.. Acredito que isso daria certo..
 IList<seuObj> variavel = this.GridView1.DataSource as IList<seuObj>;

 if (variavel != null){
     GridView1.DataSource = variavel.OrderBy(x => x.campo).ToList();
     GridView1.DataBind();
 }


text:
Q: My flash preloader works in IE7 to IE10 but not in IE11 So I made a custom preloader for a flash game of mine. Im using the swfObject library to embed the flash game.
The preloader shows up in Firefox, Chrome and IE7-10 but it doesn't show up in IE11. It shows a white screen until the game is loaded, the flash game is receiving the parameters OK and the callback function tells the flash object is created (in IE11 it is created when the white screen starts). Ive already tried to change IE11 user agent to other IEs and it didnt work.
Javascript Code: (swfObject)
<script type="text/javascript">

var flashvars = {};
flashvars.idSessao = "<?php echo $idSessao; ?>";
flashvars.sessionPHP = "<?php echo session_id(); ?>";
flashvars.lingua = "pt";

var params = {};
params.menu = "false";
params.wmode = "transparent";
params.allowFullScreen = "true";
params.allowScriptAccess = "always";
params.type = "application/x-shockwave-flash";
params.pluginspage = "http://www.macromedia.com/go/getflashplayer";
params.bgcolor = "#FFFFFF";

var attributes = {};
attributes.id = "as3_js";
attributes.name = "jogo";
attributes.align = "middle";

swfobject.embedSWF('jogos/novo<?php echo $rowPresGame['GameRefID']; ?>.swf', 'flash', '900', '600', '9.0.0',  false, flashvars, params, attributes,swfCallback);

function swfCallback( event )
{
      console.log(event.success);
}
</script>

AS3 Code
loadGame()

function loadGame()
{
    loadbar.visible = false;

    lang = root.loaderInfo.parameters.lingua;
    idSession = root.loaderInfo.parameters.idSessao;
    phpSession = root.loaderInfo.parameters.sessionPHP;

    addEventListener(Event.ENTER_FRAME,  loadGameProgress);

}

function loadGameProgress(e:Event):void
{
    var totalload = loaderInfo.bytesTotal;
    var currentload = loaderInfo.bytesLoaded;

    loadbar.scaleX = currentload/totalload
    loadbar.visible = true;

    if (loaderInfo && currentload == totalload)
    {
        this.removeEventListener(Event.ENTER_FRAME,  loadGameProgress);
        play();
    }
}

Thanks in advance


text:
Q: Making a scrollable div without knowing the available height of the container Disclaimer: I'm not the most experienced person when it comes to HTML, so this may be an obvious fix.
Here's my predicament: I'm working on a web page designed for smartphones and tablets, so the dimensions of the screen varies a lot. I have a div on the right side of my page which has a width of 60% and a height of 85%. Inside this there is a square image with width: 100% and another div with a few buttons that I would like to make scrollable. NOTE: I do not want to have the outermost of these two divs be scrollable, only the innermost one.
Because of this setup I can't know for sure where on the page the inner div begins, but I do know where it ends.
I looked through some old questions but I wasn't able to find anything too similar, but I did find a question where someone knows the size of the outermost div in a simplified version of the problem. I adapted the simplified HTML so that it represents my problem.
Here's the jsfiddle: http://jsfiddle.net/s9Zfx/8/
Basically, I need to make it so that everything stays inside the blue box, the green box stays as is, and the red box is scrollable and contains the yellow box.
Thanks.

A: I have done with some row of jquery
http://jsfiddle.net/s9Zfx/9/

some scrollable

content here

css
    div{ display: table-cell;float:left;}
#div1 {
    height: 500px;
    width: 400px;
    border:5px solid blue;

}
#div2 {
    overflow:auto;
    border:5px solid red;
    height:100%;
    width:100%;
}
#div3 {
   height:1000px;
   border:5px solid yellow;
    white-space: nowrap;
    width:100%;
}
#image-container {

    width: 100%;
    border:5px solid green;
}

jquery
var result1 = $("#image-container").height();

var result2 = $("#div1").height();

 $("#div2").height(result2-result1);

or if you want all in one line
$("#div2").height($("#div1").height() - $("#image-container").height());

without jquery I think it's impossible. Hope this solution may help you


text:
Q: How do i set sate based on the condition in checkbox Change function reactjs In the checkbox the default value is null and I am setting it as true when required
but also I thought of one more condition that needs to be set when the checkbox is already selected I want to unselect it and set the value as false instead of null.
Assume alwaysSelected -if this is selected it is true(onload) based on this condition i should update the state
this.state = {
checkbox: null,
}
this.props.alwaysSelected=true

<Checkbox
onChange={this.ChangeValue}
/>

ChangeValue= (event) => {
this.setState(checboxState=> ({
checkbox: checboxState.checkbox ? null : true
});
})

Just say prevState.checkbox -true on a load of the page then it just gives null but need to set it as false
Option tried is setState callback and componentDidUpdate but failed to acheive.
can we do this in another approach??

A: You can pass the checkbox state to the Checkbox component as value and change the event:
ChangeValue = () => this.setState({checkbox:!checkbox});

or if event returns true/false
 ChangeValue = event => this.setState({checkbox:!event});


text:
Q: Convert only the nans between the first and the last populated value of each column I have a number of dataframes that look like the example below:

*

*each row is a period of observation each column is a quantity I am measuring (e.g. rainfall in New York)

*some columns starts and end with some nans

*most columns have nans in between the first and the last populated value

Desired output: for each column, convert the nans between the first and the last value to 0, without modifying the nans at the beginning and at the end
Example: convert [nan,7,6,nan,9,nan] to [nan,7,6,0,9,nan]
What I have tried:
based on Locate first and last non NaN values in a Pandas DataFrame it's easy to find the first and the last not-null value for each column
I can therefore loop through each column, then for each column loop between first and last not-null values, and replace nans with zero. It works, but it is of course not vectorised, slow and inefficient.
Can you think of a better alternative?
I could, for each column, query the dataframe to find the nans between the first and last, but I would still have to loop through all the columns.
import numpy as np

np.random.seed(5)
import pandas as pd

rows = 20
df =pd.DataFrame(index = np.arange(0,rows), columns =['New York', 'London','Paris'], data = np.random.rand(rows,3))

df.iloc[0:2,0] = np.nan
df.iloc[0:3,1] = np.nan

df.iloc[-3:,0] = np.nan
df.iloc[-2:,1] = np.nan

df.iloc[7,0] = np.nan
df.iloc[10,0] = np.nan

df.iloc[9,1] = np.nan

df.iloc[11,2] = np.nan

first_notna = df.apply(pd.Series.first_valid_index)
last_notna = df.apply(pd.Series.last_valid_index)

out = df.copy()

for numcol, col in enumerate(df.columns):
    for r in np.arange( first_notna.loc[col], last_notna.loc[col] + 1 ):
        if np.isnan( df.iloc[r,numcol]):
            out.iloc[r,numcol] = 0

A: Copying a solution from another stack overflow answer: Filling missing middle values in pandas dataframe
Uses a combination of bfill and ffill to first get a boolean df of whether the row is NOT a trailing or leading nan. It then fills those with 0
df[df.bfill().notnull() & df.ffill().notnull()] = df.fillna(0)


text:
Q: MS Access Parameter Query Results in Error I have a query that used a field from a form as a parameter in a crosstab query and it worked fine, the contents of the field are like 2017-18 etc. But now I have 2 forms that run the same query and have used TempVars, I have dim/defined the TempVars in the VBA before the query launches and have used the following as a parameter in the query;
[Tempvars]![varFinDate]

But when the query runs I get the error message;

The expression is typed incorrectly, or is too complex to be
  evaluated. For example, a numeric express may contain too many
  complicated elements. Try simplifying the expression by assigns parts
  of the express to variables.

I have used the same principle on many queries without issue.

A: A crosstab has to have the parameters predefined. Have you declared the parameters in the crosstab query?
If not you can set them in the Query editor by right click and select Parameters property in the designer.


text:
Q: Flutter card elevation not applying on card top When adding a container inside a card widget then elevation of card is not applying on top of card.
Card(
  elevation: 10,
  shadowColor: Colors.green,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(12.0),
  ),
  child: Column(
    children: <Widget>[
      Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // widget goes here
          ],
        ),
      ),
      SizedBox(
        height: 20,
      ),
      // some more widgets
    ],
  ),
);

A: Consider using Container decoration instead of Card elevation
return Container(
  margin: EdgeInsets.all(50),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.all(Radius.circular(12)),
    boxShadow: [
      BoxShadow(
        color: Colors.green.withOpacity(0.5),
        spreadRadius: 5,
        blurRadius: 7,
        offset: Offset(0, 3), // changes position of shadow
      ),
    ],
  ),
child:Column(), //your widget here
)

A:       @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Align(
        alignment: AlignmentDirectional.topCenter,
        child: Container(
          height: 200,
          width: 200,
          child: Card(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  color: Colors.cyan,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("SOMETHING")
                      // widget goes here
                    ],
                  ),
                ),
              ],
            ),
            color: Colors.orange,
            elevation: 10,
            shadowColor: Colors.green,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.0),
            ),
          ),
        ),
      )),
    );
  }


text:
Q: Rotate object around z axis, depending on a point I have an object like a HUD on the front of a tube in Three.js however this Hud needs to align its self always depending on a vector point. This vector point is the high side of this point so the object has to be facing aligned with that point all the time regardless of the direction and position of the tube. To illustrate a problem I am attaching an image.
https://imgur.com/a/QNtz25E
In the image the green arrow represents the pipe, the red line represents the vector point to with the circle image has to rotate around the z-axis to be aligned.
I tried calculating the angle of the vector point and its center point to calculate how much I have to rotate in z the axis to align it to the point. which works in some scenarios where the object is not upside down for example. To place the object I am using the last point of the tube and using the previous as look at to keep it always perpendicular.
rotateobject() {
    //set the object perpendicular to the pipe
      this.hudObj.lookAt(this.previouspoint);
      let zerovector = new THREE.Euler();
      //reset the rotation
      this.hudObj.rotation.copy(zerovector);
      this.hudObj.lookAt(this.previousActualPoint);

      //Line to be able to see if the object is aligned

      var material = new THREE.LineBasicMaterial({
        color: 0x0000ff
      });
      var geometry = new THREE.Geometry();
      geometry.vertices.push(
        new THREE.Vector3( this.previouspoint.x , this.previouspoint.y, this.previouspoint.z),
        new THREE.Vector3( ((this.previouspoint.x) + this.previouspointdata.highSide.x), ((this.previouspoint.y) + this.previouspointdata.highSide.y), ((this.previouspoint.z) + this.previouspointdata.highSide.z) ),
      );
      var line = new THREE.Line( geometry, material );
      this.scene.add( line );
        /// calculate angle and rotate in z axis
      var angleRadians = Math.atan2(parseFloat(this.previouspointdata.highSide.y.toFixed(1)), parseFloat(this.previouspointdata.highSide.x.toFixed(1)));
      if (angleRadians > 0 && angleRadians < Math.PI / 2) {
        this.hudObj.rotateZ(-(Math.PI / 2 - angleRadians) );
      }//0-90
      else if (angleRadians < Math.PI && angleRadians > Math.PI / 2) {
        this.hudObj.rotateZ((angleRadians - Math.PI / 2) );
      }//90-180
      else if (angleRadians > -Math.PI && angleRadians < -Math.PI / 2) {
        this.hudObj.rotateZ((-Math.PI/2  + angleRadians) );
      }//-180-90
      else if (angleRadians < 0 && angleRadians > -Math.PI / 2) {
        this.hudObj.rotateZ(-(Math.PI / 2 - angleRadians));
      }//-0-90
      else if (angleRadians === 0) {

      } //0
      else if (angleRadians === Math.PI || angleRadians === -Math.PI) {
        this.hudObj.rotateZ(-(Math.PI / 2) );
      }//180
      else {
        if(Math.sign(angleRadians) === -1){
         this.hudObj.rotateZ( Math.PI );
        }
       }

    }

I really appreciate the help I am very stuck in this. thank you all for your help

A: I think what you're looking for are cartesian coordinates of a point on a sphere. If so, you need to know:
Coordinates of center of the sphere - Xc, Yc and Zc - radius of the sphere - r - and two angles - phi and omega, then you can get coordinates of that point - Xp, Yp and Zp - like this:
Xp = Xc + (r * cos(omega) * sin(phi))
Yp = Yc + (r * cos(phi))
Zp = Zc + (r * sin(omega) * sin(phi))

see this image
Then, if you'd need object on that point facing the center, you can use lookAt function from THREE.js
object.lookAt( Xc, Yc, Zc );

https://threejs.org/docs/#api/en/core/Object3D.lookAt


text:
Q: Javascript singleton: How to access private variables? I have this singleton. The public functions allow to set private variables but I am not able to set them in the way that I am able to use them in the private methods:
var ServiceInterface = (function () {
  // Instance stores a reference to the Singleton
  var instance;

  function init() {
    // Singleton
    // Private methods and variables
    var m_action;

    function performAction() {
      alert(m_action);
    }

    return {
      // Public methods and variables
      callBackend: function (sAction) {
        m_action = sAction;
      }
    };
  };
})

m_action is not available throughout the public and private section of the singleton. What am I doing wrong?

A: I think you're referring to this
var ServiceInterface = (function () {
    var m_action;

    function performAction() {
      alert(m_action);
    }

    return {
      // Public methods and variables
      callBackend: function (sAction) {
        m_action = sAction;
        performAction();
      }
    };
})()

ServiceInterface.callBackend("Hello world");

You need to execute anonymous function. Running it enables to create variables and functions defined with the anonymous function and these cannot be seen outside. Most of js libraries use this convention to create modules and to avoid infecting the global scope
var ServiceInterface = (function () {
   // code inside
})()

These are the variables and functions confined within the scope of anonymous function executed
// var ServiceInterface = (function () {
    var m_action;

    function performAction() {
      alert(m_action);
    }

// })()

Finally, return a javascript object that will expose functions that can be accessible outside the anonymous function scope
//var ServiceInterface = (function () {
//  var m_action;
//
//  function performAction() {
//       alert(m_action);
//  }

    return {
      // Public methods and variables
      callBackend: function (sAction) {
        m_action = sAction;
        performAction();
      }
    };
//})()

However, why go through the trouble of making private variable and method for a singleton?

A: This is how you create a singleton with a private member variable.
ServiceInterface = new (function() {
    var m_action = false;

    this.setAction = function(s) {
        m_action = s;
    };
    this.getAction = function() {
        return m_action;
    };

    this.performAction = function() {
        alert(ServiceInterface.getAction());
    };

    this.createCallback = function() {
        return function(sAction) {
            ServiceInterface.setAction(sAction);
        };
    }
})();
ServiceInterface.setAction("secret");
ServiceInterface.performAction();

ServiceInterface becomes a singleton because the constructor function is thrown away after it's created. ServiceInterface = new (.....)(); is how it's executed right after being declared. It's a singleton because there is no way for someone to create another instance.
I don't use var to create the instance. When you exclude var and you're not inside a function the new variable will be attached to the prototype of the parent object. In the browser this will be window. window is like a global singleton in javascript.
The local variable m_action is persisted because setAction and getAction reference it as closure functions, and the variable is attached to their scope. So they can be used as setter/getter methods.
You can now use ServiceInterface.setAction(sAction); in your callbacks to set the private member.
http://jsfiddle.net/thinkingmedia/w7DdE/6/


text:
Q: How to use mapreduce to count the same values in MongoDB? I am new to MongoDB and am trying to learn how to use mapreduce to count entries with the same value. Here is my example schema I am trying to learn from:
{
    "id" : ObjectId("5913et2s059f950g9b799867"),
    "name" : "Sam's Hotdog Stand",
    "country" : "USA",
    "location:" {
        "longitude" : 104.9903,
        "latitude" : 39.7392
    }
}

I am trying to count the number of restaurants with the same longitude (truncating the decimal).
I have my map function:
map = function() {
    emit({
        longitude: Math.floor(this.location.longitude),
        name: this.components.name
    }, {
        count : 1
    });
}

but am a little lost on the reduce part. I know I need to compare each value, but am confused on how to do it. This is what I have so far, I understand how to count each value, but not check if the longitudes are the same:
reduce = function(key, values) {
    var total = 0;
    for (var i = 0; i < values.length; i++) {
        total += values[i].count;
    }
    return { count : total };
}

How do I count each restaurant with the same longitude, and how do I separate them to each longitude?


text:
Q: iOS: Touch Event in UIScroll view I have tried so many thing to get touch inside a UIScrollView but I'm not getting how to do it.
Actually I want to touch inside a UIScrollView and get the location of subview (which i have touched).

A: You can do it with gesture recognizers. For detect single tap location use UITapGestureRecognizer
UITapGestureRecognizer *tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)] autorelease];
[myScrollView addGestureRecognizer:tapRecognizer];

- (void)tapAction:(UITapGestureRecognizer*)sender{
    CGPoint tapPoint = [sender locationInView:myScrollView];
    CGPoint tapPointInView = [myScrollView convertPoint:tapPoint toView:self.view];
}

To convert that tapPoint to self.view you can use convertPoint:toView: method in UIView class


text:
Q: Finding visible elements on webapp using selenium I need help to find visible elements on a webapp page using selenium.
For example, I need to find a row that is click-able and click on it.
The problem is that the elements are visible but not present in the page source as they are generated. Also, I'm coding in Java to find the elements. I tried using xpath and css path which I found using Firefox Firebug, but it didn't work. The click-able rows in the table all have the same class. They have different text though. Any help? Thanks!

A: You can use isDisplayed() method for same
boolean aa = driver.findElement(By.xpath("YOUR Element")).isDisplayed();
boolean ab = driver.findElement(By.xpath("YOUR Element")).isEnabled();
boolean ac = driver.findElement(By.xpath("YOUR Element")).isSelected();

For more detail info please refer the below URL:-
http://www.softwaretestinghelp.com/webdriver-commands-selenium-tutorial-14/
Hope it will help you :)


text:
Q: How to concatenate multiple lines of output to one line? If I run the command cat file | grep pattern, I get many lines of output. How do you concatenate all lines into one line, effectively replacing each "\n" with "\" " (end with " followed by space)?
cat file | grep pattern | xargs sed s/\n/ /g
isn't working for me.

A: The fastest and easiest ways I know to solve this problem:
When we want to replace the new line character \n with the space:
xargs < file

xargs has own limits on the number of characters per line and the number of all characters combined, but we can increase them. Details can be found by running this command: xargs --show-limits and of course in the manual: man xargs
When we want to replace one character with another exactly one character:
tr '\n' ' ' < file

When we want to replace one character with many characters:
tr '\n' '~' < file | sed s/~/many_characters/g

First, we replace the newline characters \n for tildes ~ (or choose another unique character not present in the text), and then we replace the tilde characters with any other characters (many_characters) and we do it for each tilde (flag g).

A: Here is another simple method using awk:
# cat > file.txt
a
b
c

# cat file.txt | awk '{ printf("%s ", $0) }'
a b c

Also, if your file has columns, this gives an easy way to concatenate only certain columns:
# cat > cols.txt
a b c
d e f

# cat cols.txt | awk '{ printf("%s ", $2) }'
b e

A: I like the xargs solution, but if it's important to not collapse spaces, then one might instead do:
sed ':b;N;$!bb;s/\n/ /g'

That will replace newlines for spaces, without substituting the last line terminator like tr '\n' ' ' would.
This also allows you to use other joining strings besides a space, like a comma, etc, something that xargs cannot do:
$ seq 1 5 | sed ':b;N;$!bb;s/\n/,/g'
1,2,3,4,5

A: Here is the method using ex editor (part of Vim):

*

*Join all lines and print to the standard output:
$ ex +%j +%p -scq! file

*Join all lines in-place (in the file):
$ ex +%j -scwq file

Note: This will concatenate all lines inside the file it-self!

A: Use tr '\n' ' ' to translate all newline characters to spaces:
$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!
Edit:
tr can only handle single character translations. You could use awk to change the output record separator like:
$ grep pattern file | awk '{print}' ORS='" '

This would transform:
one
two
three

to:
one" two" three"

A: This could be what you want
cat file | grep pattern | paste -sd' '

As to your edit, I'm not sure what it means, perhaps this?
cat file | grep pattern | paste -sd'~' | sed -e 's/~/" "/g'

(this assumes that ~ does not occur in file)

A: This is an example which produces output separated by commas. You can replace the comma by whatever separator you need.
cat <<EOD | xargs | sed 's/ /,/g'
> 1
> 2
> 3
> 4
> 5
> EOD

produces:
1,2,3,4,5

A: Piping output to xargs will concatenate each line of output to a single line with spaces:
grep pattern file | xargs

Or any command, eg. ls | xargs. The default limit of xargs output is ~4096 characters, but can be increased with eg. xargs -s 8192.
grep xargs

A: In bash echo without quotes remove carriage returns, tabs and multiple spaces
echo $(cat file)

A: Probably the best way to do it is using 'awk' tool which will generate output into one line
$ awk ' /pattern/ {print}' ORS=' ' /path/to/file

It will merge all lines into one with space delimiter

A: paste -sd'~' giving error.
Here's what worked for me on mac using bash
cat file | grep pattern | paste -d' ' -s -

from man paste .
-d list     Use one or more of the provided characters to replace the newline characters instead of the default tab.  The characters
                 in list are used circularly, i.e., when list is exhausted the first character from list is reused.  This continues until
                 a line from the last input file (in default operation) or the last line in each file (using the -s option) is displayed,
                 at which time paste begins selecting characters from the beginning of list again.

                 The following special characters can also be used in list:

                 \n    newline character
                 \t    tab character
                 \\    backslash character
                 \0    Empty string (not a null character).

                 Any other character preceded by a backslash is equivalent to the character itself.

     -s          Concatenate all of the lines of each separate input file in command line order.  The newline character of every line
                 except the last line in each input file is replaced with the tab character, unless otherwise specified by the -d option.
                 If '-' is specified for one or more of the input files, the standard input is used; standard input is read one line at a time,

circularly, for each instance of '-'.

A: On red hat linux I just use echo :
echo $(cat /some/file/name)
This gives me  all records of a file on just one line.


text:
Q: Exact diagonalisation by Bogoliubov-Valatin Rotation in the 'real -particle' space I have a question about the random ising model, where the model is no longer translationally invariant, and one has to resort to diagonalizing the full hamiltonian rather than solve for decoupled $2X2$ matrices in the $(k,-k)$ subspace.
To be precise, consider the Hamiltonian in terms of spinless fermions on site with open boundary conditions

I write a matrix that gives me the correct eigenvalues and other properties, but I do not know what to make of the eigenvectors.
If I have $N$ sites, I get $2N$ eigenvectors, each of length $2N$, how do I map them to the $\bf{u}$ and $\bf{v}$ given below, especially since all elements are real.

EDIT - I think I now understand the above construction. My question is - If I want to calculate correlators like $<c^{\dagger}_{i}c_{j}>$ and $<c^{\dagger}_{i}c^{\dagger}_{j}>$, say in the ground state, what is my eigenvector(column vector)) i.e $\psi_{0}$
Note : Images taken from http://www.statphys.sissa.it/statistical/tesi_phd/canovi.pdf
Please see this for reference as well, pages 51 - 54.


text:
Q: uwsgi: no app loaded. going in full dynamic mode In my uwsgi config, I have these options:
[uwsgi]
chmod-socket = 777
socket = 127.0.0.1:9031
plugins = python
pythonpath = /adminserver/
callable = app
master = True
processes = 4
reload-mercy = 8
cpu-affinity = 1
max-requests = 2000
limit-as = 512
reload-on-as = 256
reload-on-rss = 192
no-orphans
vacuum

My app structure looks like this:
/adminserver
   app.py
   ...

My app.py has these bits of code:
app = Flask(__name__)
...

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5003, debug=True)

The result is that when I try to curl my server, I get this error:
Wed Sep 11 23:28:56 2013 - added /adminserver/ to pythonpath.
Wed Sep 11 23:28:56 2013 - *** no app loaded. going in full dynamic mode ***
Wed Sep 11 23:28:56 2013 - *** uWSGI is running in multiple interpreter mode ***

What do the module and callable options do? The docs say:

module, wsgi Argument: string
Load a WSGI module as the application. The module (sans .py) must be
  importable, ie. be in PYTHONPATH.
This option may be set with -w from the command line.
callable Argument: string Default: application
Set default WSGI callable name.

A: For anyone else having this problem, if you are sure your configuration is correct, you should check your uWSGI version.
Ubuntu 12.04 LTS provides 1.0.3. Removing that and using pip to install 2.0.4 resolved my issues.

A: Module
A module in Python maps to a file on disk - when you have a directory like this:
/some-dir
    module1.py
    module2.py

If you start up a python interpreter while the current working directory is /some-dir you will be able to import each of the modules:
some-dir$ python
>>> import module1, module2
# Module1 and Module2 are now imported

Python searches sys.path (and a few other things, see the docs on import for more information) for a file that matches the name you are trying to import.  uwsgi uses Python's import process under the covers to load the module that contains your WSGI application.
Callable
The WSGI PEPs (333 and 3333) specify that a WSGI application is a callable that takes two arguments and returns an iterable that yields bytestrings:
# simple_wsgi.py
# The simplest WSGI application
HELLO_WORLD = b"Hello world!\n"

def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return [HELLO_WORLD]

uwsgi needs to know the name of a symbol inside of your module that maps to the WSGI application callable, so it can pass in the environment and the start_response callable - essentially, it needs to be able to do the following:
wsgi_app = getattr(simple_wsgi, 'simple_app')

TL;PC (Too Long; Prefer Code)
A simple parallel of what uwsgi is doing:
# Use `module` to know *what* to import
import simple_wsgi

# construct request environment from user input
# create a callable to pass for start_response
# and then ...

# use `callable` to know what to call
wsgi_app = getattr(simple_wsgi, 'simple_app')

# and then call it to respond to the user
response = wsgi_app(environ, start_response)

A: First, check your configuration whether is correct.
my uwsgi.ini configuration:
[uwsgi]
chdir=/home/air/repo/Qiy
uid=nobody
gid=nobody
module=Qiy.wsgi:application
socket=/home/air/repo/Qiy/uwsgi.sock
master=true
workers=5
pidfile=/home/air/repo/Qiy/uwsgi.pid
vacuum=true
thunder-lock=true
enable-threads=true
harakiri=30
post-buffering=4096
daemonize=/home/air/repo/Qiy/uwsgi.log

then use uwsgi --ini uwsgi.ini to run uwsgi.
if not work, you rm -rf the venv directory, and re-initial the venv, and re-try my step.
I re-initial the venv solved my issue, seems the problem is when I pip3 install some packages of requirements.txt, and upgrade the pip, then install uwsgi package. so, I delete the venv, and re-initial my virtual environment.