text:
Q: how create select box using Array object json in angular js? I am trying to displaying country names from json object. json data looking collection of array object, this object using ng-repeat iterating that json data and displaying into select box. i tried bellow code.
Json
----

$scope.countries = [
  {
    "AT": "Austria"
  },
  {
    "CI": "Côte d'Ivoire"
  },
  {
    "CG": "Congo"
  },
  {
    "SV": "El Salvador"
  },
  {
    "IN": "India"
  },
  {
    "SX": "Sint Maarten (Dutch part)"
  },
  {
    "SZ": "Swaziland"
  },
  {
    "CH": "Switzerland"
  },
  {
    "AE": "United Arab Emirates"
  }
]

html
----
<select ng-model="counryNames" >
          <option ng-repeat="(key,country) in countries"  value="{{key}}">{{country[key]}}</option>
     </select>

A: Change your ng-repeat as, you should access the key of countries not country
<option ng-repeat="(key, value) in countries" value="{{key}}">{{countries[key]}}</option>

DEMO

   angular.module("myapp", [])
      .controller("MyController", function($scope) {
         $scope.countries = [{
            "AT": "Austria"
          }, {
            "CI": "Côte d'Ivoire"
          }, {
            "CG": "Congo"
          }, {
            "SV": "El Salvador"
          }, {
            "IN": "India"
          }, {
            "SX": "Sint Maarten (Dutch part)"
          }, {
            "SZ": "Swaziland"
          }, {
            "CH": "Switzerland"
          }, {
            "AE": "United Arab Emirates"
          }];
      });
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
  <div ng-controller="MyController">
     <select>
    <option ng-repeat="(key, value) in countries" value="{{key}}">{{countries[key]}}</option>
</select>
  </div>
</body>


text:
Q: htlatex and subfigures Is it possible to have htlatex generate side-by-side subfigures?  The mwe tex file
\documentclass{article}

\ifdefined\HCode
\usepackage[compatibility=false]{caption}
\def\pgfsysdriver{pgfsys-tex4ht.def}
\else
\usepackage[]{caption}
\fi
\usepackage{subcaption}
\usepackage[]{graphicx}

\begin{document}

\begin{figure}[htpb]
  \centering
  \begin{subfigure}{0.45\textwidth}
    \centering
    \includegraphics[width=\textwidth]{image1.png}
    \caption{Image 1}
  \end{subfigure}
  \begin{subfigure}{0.45\textwidth}
    \centering
    \includegraphics[width=\textwidth]{image2.png}
    \caption{Image 2}
  \end{subfigure}
  \caption{Main Caption}
\end{figure}

\end{document}

together with the config file
\Preamble{html}

\Configure{@HEAD}{\HCode{<link href="basic.css" rel="stylesheet" type="text/css" />\Hnewline}}

\ConfigureEnv{figure}
   {\HCode{
}%
    \bgroup \Configure{float}{\ShowPar}{}{}%
   }
   {\egroup
    \HCode{
}\ShowPar
\par}
{}{}

\Css{div.caption {text-align:left;font-size:83\%;text-indent:0em; margin-left:2em; margin-right:2em; }}
\Css{div.caption span.id{font-variant: small-caps; white-space: nowrap; }}
\Css{.figure div.caption{text-align: center;}}
\Css{div.figure{text-align:center;clear:both;overflow:auto;width:100\%;margin-bottom:1em;}}

\begin{document}

\makeatletter
% Various helper functions
% default font size
\newcommand\emwidth{16}
\let\emwidth\f@size
% convert pt to rem
\newcommand\CalcRem[1]{\strip@pt\dimexpr(#1)/\emwidth}

\Configure{graphics*}
{png}
{% we must add the image to the list of output files
  \special{t4ht+@File: \csname Gin@base\endcsname.png}
  \Picture[pict]{\csname Gin@base\endcsname\PictExt
  \space style="width:\CalcRem{\Gin@req@width}em;"
  }%
}
\makeatother

\EndPreamble

generates

I have read this threads:

*

*Htlatex and subcaption - can htlatex be extended?

*configuring minipage in htlatex
But, I cannot piece together how I might achieve the desired result. I have included the graphics configuration in the .cfg file because it is important that I be able to scale the images.

A: Try this config file:
\Preamble{xhtml}

\Configure{@HEAD}{\HCode{<link href="basic.css" rel="stylesheet" type="text/css" />\Hnewline}}
\DeclareGraphicsRule{.png}{bmp}{.xbb}{}

\ConfigureEnv{figure}
   {\ifvmode\IgnorePar\fi\EndP\HCode{
}%
    \bgroup \Configure{float}{\ShowPar}{}{}%
   }
   {\egroup
    \ifvmode\IgnorePar\fi\EndP\HCode{
}\ShowPar
\par}
{}{}

\ConfigureEnv{subfigure}{\ifvmode\IgnorePar\fi\EndP\HCode{
}}{\ifvmode\IgnorePar\fi\EndP\HCode{
}}{}{}
\Css{.subfigure{display: inline-block;}}
\Css{.subfigure img{display:block;}}

\Css{div.caption {text-align:left;font-size:83\%;text-indent:0em; margin-left:2em; margin-right:2em; }}
\Css{div.caption span.id{font-variant: small-caps; white-space: nowrap; }}
\Css{.figure div.caption{text-align: center;}}
\Css{div.figure{text-align:center;clear:both;overflow:auto;width:100\%;margin-bottom:1em;}}

\begin{document}

\makeatletter
% Various helper functions
% default font size
\newcommand\emwidth{16}
\let\emwidth\f@size
% convert pt to rem
\newcommand\CalcRem[1]{\strip@pt\dimexpr(#1)/\emwidth}

\Configure{graphics*}
{png}
{% we must add the image to the list of output files
  \special{t4ht+@File: \csname Gin@base\endcsname.png}
  \Picture[pict]{\csname Gin@base\endcsname\PictExt
  \space style="width:\CalcRem{\Gin@req@width}em;"
  }%
}
\makeatother

\EndPreamble

The important changes are:
\DeclareGraphicsRule{.png}{bmp}{.xbb}{}

this will enable to use correct bounding box for the images. See
 this answer for details.
\ConfigureEnv{figure}
   {\ifvmode\IgnorePar\fi\EndP\HCode{
}%
    \bgroup \Configure{float}{\ShowPar}{}{}%
   }
   {\egroup
    \ifvmode\IgnorePar\fi\EndP\HCode{
}\ShowPar
\par}
{}{}

I've added \ifvmode\IgnorePar\fi\EndP for correct handling of paragraphs. See Control the
 tags inserted by tex4ht for details.
Now the actual code for subfigure:
\ConfigureEnv{subfigure}{\ifvmode\IgnorePar\fi\EndP\HCode{
}}{\ifvmode\IgnorePar\fi\EndP\HCode{
}}{}{}
\Css{.subfigure{display: inline-block;}}
\Css{.subfigure img{display:block;}}

This add
 element and needed CSS configurations. The first one will make subfigures float next themselves, the second will put caption bellow the image.
The result:

redpajama_set_name: RedPajamaStackExchange


text:
Q: IE11 shows every { display: table-cell } element at a new line I have the following HTML (JSFiddle):

        <input id="BodyContentPlaceholder_TxtCustomerId" type="text">
        <input id="BodyContentPlaceholder_BtnShowByCustomerId" type="submit" value="Show">

And the following CSS:
.tabled-contents {
    display: table;
    width: 100%;
}

.form-group input[type=text], .form-group input[type=submit] {
    display: table-cell;
    width: 200px;
}

It looks as expected in all browsers (Chrome, FF etc.): both inputs are on the same row.
But in IE11 the second input is rendered under the first one.
Does anybody know why it's so and how to make it to be shown in IE the same way as in the other browsers?

A: I submitted a bug report to the IE development team and it has been accepted as the issue.
I'll update this post upon changing the status of the bug.

A: Workaround
add an empty div

Example Codepen http://codepen.io/vinaymavi/pen/JWjxJb

   Cell-1

    Cell-2

    Cell-3

For more info please check
Microsoft bug https://connect.microsoft.com/IE/feedbackdetail/view/1263383/ie11-shows-every-html-input-element-with-display-table-cell-css-style-at-a-new-line#

A: use the 'table' display property and the 'table-row' display property for the wrapping elements, but don't use the 'table-cell' property for the input element. just don't set the display property for those inline elements. and everything will work just fine, even in ie country :)
p.s. - wrapping an input element with a div or other element contaminates the semantic structure, it should remain simple and true to meaning as much as possible.


text:
Q: When Trying to access Elastic Search get using java getting Empty Response Following the Docs of Elastic Search Was able to Set up the Java Environment for its API's.
But when Trying to access from an index called twitter, under a type called tweet, with id valued 1 the response is coming null with no error in console.
Code for the Above
Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch").build();

        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        GetResponse response = client.prepareGet("twitter", "tweet", "2").get();
        System.out.println(response.getFields());

        client.close();

Kibana Console data for the Same
{
        "_index": "twitter",
        "_type": "tweet",
        "_id": "2",
        "_score": 1,
        "_source": {
          "user": "Rahul",
          "post_date": "2009-11-15T14:12:12",
          "message": "trying out Elasticsearch"
        }
      },
      {
        "_index": "twitter",
        "_type": "tweet",
        "_id": "1",
        "_score": 1,
        "_source": {
          "user": "kimchy",
          "post_date": "2009-11-15T14:12:12",
          "message": "trying out Elasticsearch"
        }
      }

A: Please Try some thing like this hope it helps
RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http")).build();

        Response response = restClient.performRequest("GET", "/twitter/_search",
               Collections.singletonMap("pretty", "true"));

/*
        JsonObject user = new JsonObject();
        user.addProperty("user","Yash");
        user.addProperty("post_date","2009-11-15T14:12:12");
        user.addProperty("message","Checking json");

        HttpEntity entity = new NStringEntity(user.toString());

        Response indexResponse = restClient.performRequest(
                "PUT",
                "/twitter/tweet/3",
                Collections.<String, String>emptyMap(),
                entity);
*/

        System.out.println(EntityUtils.toString(response.getEntity()));

        restClient.close();

A: Make sure you are using HTTP , not HTTPs - the server may be hanging-up on you if you make a simple plain-text HTTP request?


text:
Q: Android scaling image vertically I am trying to create a mini progress bar that will indicate how much data a user has used. It doesn't even need to animate, I just need it to change in size based on a variable I have set up. So when I load up the screen, how much of the progress bar is filled up will depend on a variable I have set up in Java.
I have managed to get this working horizontally by using
scale =  new ScaleAnimation(0.0f, 1.5f, 1.0f, 1.0f,1.0f, 1.0f);

This will start the image from nothing and stretching out to its full size, so I can use it as a horizontal progress bar which is great.
Now I woulda thought doing this vertically instead would be a simple matter of just changing the fromY to 0 and the toY to the new size I want. However when I do this, by changing the fromY to 0.0f and the toY to 2.0f, the image actually moves and stretches at the same time rather than stretching. Also the image moves position for some reason. It starts off higher up than where I positioned in using XML, and moves down to the original position and stretches out to the new scale I set up.
The code I use to try and stretch it vertically is
scale =  new ScaleAnimation(1.0f, 1.0f, 0.0f, 2.0f, 1.0f, 1.0f);

So can someone please explain why it stretches horizontally fine, but when I try to stretch it vertically, it suddenly moves and stretchs at the same time.
Would be very grateful for any help.

A: I appreciate you have solved the animation issue you mentioned, but based on you saying you don't even need the bar to animate, the ClipDrawable class may make your life simpler. You can define one in an xml layout and then set the clip level from your code, which will clip the given drawable by the given amount.
Check this out for more details on how to use it:
http://developer.android.com/guide/topics/resources/drawable-resource.html#Clip
Hope that's of some help.


text:
Q: Inefficiency of Numpy Argwhere I am learning about methods like argwhere and nonzero in NumPy.  It appears that  thenumpy.nonzero(x) the function returns a tuple of one-dimensional ndarray objects so that the output of this function could be used for indexing.
I have not ready the C source code of nonzero because I don't know how to find it.  However, I imagine that the nonzero function will construct an m by ndim ndarray object (for some m that depends on the input) that will hold the indices of nonzero elements of a.  To verify that this guess is correct, I tried:
import numpy as np
from numpy.random import Generator, PCG64
rg = Generator(PCG64())
x = rg.integers(0,2,(10000,10000))
y = np.nonzero(x)
print(y[0].base is y[1].base)
z = y[0].base
print(type(z),z.shape)
print(np.array_equal(z[:,0].reshape(-1),y[0]))
print(np.array_equal(z[:,1].reshape(-1),y[1]))

which outputs:
True
<class 'numpy.ndarray'> (50005149, 2)
True
True

My interpretation of the above is that the nonzero function does construct a single m by ndim sized array.
There is also a np.argwhere(x) function.  Unlike np.nonzero, it will return an m by ndim size array, not a tuple.  Reason suggests that argwhere and nonzero would be practically the same, except that nonzero returns the output in a slightly different format.   To my surprise, argwhere seems to be implemented as follows (according to: https://numpy.org/doc/stable/reference/generated/numpy.argwhere.html):
# nonzero does not behave well on 0d, so promote to 1d
    if np.ndim(a) == 0:
        a = shape_base.atleast_1d(a)
        # then remove the added dimension
        return argwhere(a)[:,:0]
    return transpose(nonzero(a))

Because the nonzero function returns a tuple, it seems like the transpose operation in argwhere is going to require an extra copy for no reason.  A quick experiment with a timer suggested that this copy does happen.
Question
Can someone explain why the argwhere function is implemented this way?  For example, the alternative
def faster_argwhere(a):
    # nonzero does not behave well on 0d, so promote to 1d
    if np.ndim(a) == 0:
        a = shape_base.atleast_1d(a)
        # then remove the added dimension
        a=a[:,:0]
    return np.nonzero(a)[0].base

already seems better, since:
x = rg.integers(0,2,(10000,10000))
t_0 = time.perf_counter()
y = np.argwhere(x)
t_1 = time.perf_counter()
z = faster_argwhere(x)
t_2 = time.perf_counter()
print('elapsed time for argwhere:' + str(t_1-t_0) + ", and for other method:" + str(t_2-t_1))
print(np.array_equal(y,z))

yields:
elapsed time for argwhere:2.175326200000086, and for other method:1.7338391999999203
True

A: When I looked at nonzero some time ago, I saw that it performed two passes.  First a np.count_nonzero (in the c-api version) to determine the return size, and a second to actually get the indices.  I didn't pay attention as to whether it allocated n independent arrays or just one 2d.  But now that you mention it, the arrays are views of a common 2d array:
In [464]: x = np.arange(12).reshape(3,4)
In [468]: idx = np.nonzero(x%3==0)
In [469]: idx
Out[469]: (array([0, 0, 1, 2]), array([0, 3, 2, 1]))
In [470]: idx[0].__array_interface__
Out[470]:
{'data': (54070800, False),
 'strides': (16,),
  ...}
In [471]: idx[1].__array_interface__
Out[471]:
{'data': (54070808, False),
 'strides': (16,),
 ....}

The data pointer is 8 larger, and strides 16, consistent with that.
For a 3d array:
In [472]: x = np.arange(24).reshape(2,3,4)
In [473]: idx = np.nonzero(x%3==0)
In [474]: idx[0].__array_interface__
Out[474]:
{'data': (54163904, False),
 'strides': (24,),
In [475]: idx[1].__array_interface__
Out[475]:
{'data': (54163912, False),
 'strides': (24,),
In [476]: idx[2].__array_interface__
Out[476]:
{'data': (54163920, False),
 'strides': (24,),

The same thing - 24 strides etc.
I don't know the history of these functions.  Has nonzero always returned views of a common 2d array?  Recent versions have tried to ween us away from using np.where instead np.nonzero.  We don't yet have a np.arg_nonzero :)
As you note, the nonzero tuple works well as index.
x[np.nonzero(x)]

Novices often don't appreciated this, and instead think they need a list of tuples.  But to use those they have to iterate
 for tup in [(0,0),(1,0),...]: print(x[tup])

The argwhere isn't quite right for that:
In [480]: x[idx]
Out[480]: array([ 0,  3,  6,  9, 12, 15, 18, 21])
In [481]: np.transpose(idx)
Out[481]:
array([[0, 0, 0],
       [0, 0, 3],
        ....
       [1, 2, 1]])
In [482]: [x[tuple(i)] for i in np.transpose(idx)]
Out[482]: [0, 3, 6, 9, 12, 15, 18, 21]

I don't know if that worked without the tuple in earlier versions or not; it raises an error now.
So yes it might be possible to make argwhere more efficient, by accessing the nonzero base directly.  But what's the benefit?
In [487]: idx[0].base
Out[487]:
array([[0, 0, 0],
       [0, 0, 3],
         ...
       [1, 2, 1]])

In [492]: timeit x[idx]
2.46 µs ± 8.17 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [493]: timeit [x[tuple(i)] for i in idx[0].base]
21.7 µs ± 836 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [494]: timeit [x[tuple(i)] for i in np.transpose(idx)]
33.2 µs ± 94.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Ultimately why questions like this can only be answered by comments in the code or discussions in the developer's forums or the github issues.


text:
Q: How to force inputs to take on the same values across modules I'm working on a shiny dashboard that makes heavy use of shiny modules and my client has asked me to make it so that the same two inputs from my dashboard's various tabs take on the same values regardless of tab.  I'm having a huge problem doing this and was able to recreate it using a toy example that you'll find below.
#app.R

library(data.table)
library(shiny)
library(ggplot2)
library(ggthemes)
library(shinythemes)
source("Modules.R")

penguins <<- as.data.table(palmerpenguins::penguins)

ui = uiOutput("ui")
inputs <<- reactiveValues(species = NULL, island = NULL)

server <- function(input, output, session) {
  bill_species_server("tab1")
  flipper_mass_scatter_server("tab2")

  output$ui = renderUI({
    fluidPage(
      titlePanel("", "Penguin Dashboard"),
       tabsetPanel(
         tabPanel("Bill Length by Species",
                ui_code("tab1")
        ),
        tabPanel("Flipper Length by Body Mass",
                 ui_code("tab2")
        )
      )
    )
  })
}

# Run the application
shinyApp(ui = ui, server = server)

#Modules.R

ui_code = function (id) {
  ns = NS(id)

  sidebarLayout(position = "left",
    sidebarPanel(
      selectInput(ns("species"), "Choose 1+ species:", choices = penguins[, sort(unique(species))], multiple = TRUE),
      selectInput(ns("island"), "Choose 1+ islands:", choices = penguins[, sort(unique(island))], multiple = TRUE)
    ),
    mainPanel(
      plotOutput(ns("plot"))
    )
  )
}

bill_species_server = function(id) {

  moduleServer(id, function(input, output, session) {

    observeEvent(inputs$species, ignoreInit = TRUE, ignoreNULL = TRUE, {
      if (length(inputs$species) > 0) {
        updateSelectInput(session = session, inputId = "species", selected = inputs$species)
      }
    })

    observeEvent(inputs$island, ignoreInit = TRUE, ignoreNULL = TRUE, {
      if (length(inputs$island) > 0) {
        updateSelectInput(session = session, inputId = "island", selected = inputs$island)
      }

    })

    output$plot = renderPlot({

      if (length(input$species) > 0) {
        penguins = penguins[species %in% input$species]
      }

      if (length(input$island) > 0) {
        penguins = penguins[island %in% input$island]
      }

      ggplot(penguins) + geom_histogram(aes(x = `bill_length_mm`, fill = species)) + scale_fill_canva(palette = "Striking and energetic")
    })

    observeEvent(input$species, ignoreNULL = TRUE, ignoreInit = TRUE, {
      inputs$species = input$species
    })

    observeEvent(input$island, ignoreNULL = TRUE, ignoreInit = TRUE, {
      inputs$island = input$island
    })

  })
  return(inputs)
}

flipper_mass_scatter_server = function (id) {

  moduleServer(id, function(input, output, session) {

    observeEvent(inputs$species, ignoreInit = TRUE, ignoreNULL = TRUE, {
      if (length(inputs$species) > 0) {
        updateSelectInput(session = session, inputId = "species", selected = inputs$species)
      }
    })

    observeEvent(inputs$island, ignoreInit = TRUE, ignoreNULL = TRUE, {
      if (length(inputs$island) > 0) {
        updateSelectInput(session = session, inputId = "island", selected = inputs$island)
      }

    })

    output$plot = renderPlot({

      if (length(input$species) > 0) {
        penguins = penguins[species %in% input$species]
      }

      if (length(input$island) > 0) {
        penguins = penguins[island %in% input$island]
      }

      ggplot(penguins) + geom_point(aes(x = `flipper_length_mm`, y = body_mass_g, colour = species)) + scale_colour_canva(palette = "Striking and energetic")
    })

    observeEvent(input$species, ignoreNULL = TRUE, ignoreInit = TRUE, {
      inputs$species = input$species
    })

    observeEvent(input$island, ignoreNULL = TRUE, ignoreInit = TRUE, {
      inputs$island = input$island
    })
  })
  return(inputs)
}

So the two inputs that I'm trying to link in this toy example are species and island.  I've set it up so that when someone makes a new selection on either input, an observer should update a global variable which in this case I've labelled inputs.  And then if inputs is updated, the other tab should then update its own selectInput.
Weirdly, I find that with this code, if I make my selections kind of slowly, all works just fine!  However, the moment that I click 2+ choices in rapid succession, it causes an infinite loop to happen in the current tab where the second choice appears, then disappears, then appears... etc.  Conversely, when I have 3 choices selected and try to delete options in rapid succession, it just doesn't let me delete all choices!!
So weird.
Anyone know what the problem is with my code, and how I can force the inputs in both tabs to keep the same values as chosen in the other tabs?
Thanks!

A: I significantly restructured how I approached this problem and came up with a solution.  Basically, I used shinydashboard and decided that I would define the species and island selectInput controls outside of my modules.
The values to those controls were then passed to the modules as reactive objects that were then used to filter the data before the data got plotted.  This works so much better now!  Have a look at my two files:
#app.R

library(data.table)
library(shiny)
library(ggplot2)
library(ggthemes)
library(shinythemes)
library(shinydashboard)
source("Modules.R")

penguins <<- as.data.table(palmerpenguins::penguins)

ui = dashboardPage(header = dashboardHeader(title = "Penguin Dashboard"),
                    sidebar = dashboardSidebar(
                     sidebarMenu(id = "tabs",
                                 selectInput("species", "Choose 1+ species:", choices = penguins[, sort(unique(species))], multiple = TRUE),
                                 selectInput("island", "Choose 1+ islands:", choices = penguins[, sort(unique(island))], multiple = TRUE),
                                 menuItem("Bill Length by Species", expandedName = "tab1", tabName = "tab1", startExpanded = TRUE,
                                          sliderInput("mass", "Select a range of body masses:",
                                                      min = penguins[, min(body_mass_g, na.rm=TRUE)],
                                                      max = penguins[, max(body_mass_g, na.rm=TRUE)],
                                                      value = penguins[, range(body_mass_g, na.rm=TRUE)])
                                          ),
                                 menuItem("Flipper Length by Body Mass", expandedName = "tab2", tabName = "tab2",
                                          checkboxGroupInput("sex", "Choose sex of penguins:",
                                                             choices = c("male","female")))
                     )),
                     body = dashboardBody(
                       uiOutput("plots")
                       )
)

#inputs <<- reactiveValues(species = NULL, island = NULL)

server <- function(input, output, session) {
  #inputs <- reactiveValues(species=input$species, island=input$island)

  in_species = reactive({input$species})
  in_island = reactive({input$island})
  in_mass = reactive({input$mass})
  in_sex = reactive({input$sex})

  bill_species_server("tab1", in_species, in_island, in_mass)
  flipper_mass_scatter_server("tab2", in_species, in_island, in_sex)

  output$plots = renderUI({
    validate(need(!is.null(input$sidebarItemExpanded), ""))

    if (input$sidebarItemExpanded == "tab1") {
      ui_code("tab1")
    } else {
      ui_code("tab2")
    }

  })
}

# Run the application
shinyApp(ui = ui, server = server)

#Modules.R

ui_code = function (id) {
  ns = NS(id)

      plotOutput(ns("plot"))
}

bill_species_server = function(id, in_species, in_island, in_mass) {

  moduleServer(id, function(input, output, session) {

    ns <- session$ns

    output$plot = renderPlot({

      if (length(in_species()) > 0) {
        penguins = penguins[species %in% in_species()]
      }

      if (length(in_island()) > 0) {
        penguins = penguins[island %in% in_island()]
      }

      penguins = penguins[body_mass_g %between% c(in_mass()[1], in_mass()[2])]

      ggplot(penguins) + geom_histogram(aes(x = `bill_length_mm`, fill = species)) + scale_fill_canva(palette = "Striking and energetic")
    })
  })

}

flipper_mass_scatter_server = function (id, in_species, in_island, in_sex) {

  moduleServer(id, function(input, output, session) {

    output$plot = renderPlot({

      if (length(in_species()) > 0) {
        penguins = penguins[species %in% in_species()]
      }

      if (length(in_island()) > 0) {
        penguins = penguins[island %in% in_island()]
      }

      if (length(in_sex()) > 0) {
        penguins = penguins[sex %in% in_sex()]
      }

      ggplot(penguins) + geom_point(aes(x = `flipper_length_mm`, y = body_mass_g, colour = species)) + scale_colour_canva(palette = "Striking and energetic")
    })

  })

}


text:
Q: Is there way to insert selected code into template twice? I've created a template in Delphi XE to use it often
<?xml version="1.0" encoding="utf-8" ?>

<codetemplate   xmlns="http://schemas.borland.com/Delphi/2005/codetemplates"
                version="1.0.0">
    <template name="noado" surround="true" invoke="manual">
        <description>
            no ado
        </description>
        <author>
            BVA
        </author>
        <![CDATA[{$ifndef no_ado}
|selected||*||end|
{$endif}]]>

    </template>
</codetemplate>

Now it looks like this
{$ifndef no_ado}
|selected|
{$endif}
I want to simplify my work by making something like this
{$ifndef no_ado}
|selected| overload; deprecated 'Use AppData';
{$endif}
|selected| overload;
//------------------------------------------

A: I solved my problem.
//--------------------------------------1 Template

<codetemplate   xmlns="http://schemas.borland.com/Delphi/2005/codetemplates"
                version="1.0.0">
    <template name="noado" surround="true" invoke="manual">
        <description>
            no ado
        </description>
        <author>
            BVA
        </author>
        <![CDATA[{$ifndef no_ado}
|selected| overload; deprecated {$IF CompilerVersion > 21}'Use AppData'{$IFEND};
{$endif}
|end| overload;
//------------------------------------------------------------------------------]]>

    </template>
</codetemplate>

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

<codetemplate   xmlns="http://schemas.borland.com/Delphi/2005/codetemplates"
                version="1.0.0">
    <template name="noado_func" surround="true" invoke="manual">
        <description>
            no ado
        </description>
        <author>
            BVA
        </author>
        <![CDATA[{$ifndef no_ado}
|selected|
{$endif}
|end|
//------------------------------------------------------------------------------]]>

    </template>
</codetemplate>

This is how to use the templates.
First template is used to define function in Interface
1) Select and copy function definition: function NameFunc(params);
2) Use template
3) The cursor now is at the beginning of the line, so just paste copied code
Second template is used for body of the function:
1) Select and copy body of the function
2) Use template
3) Press up key, then press down key (or vice versa), so the cursor will be set behind the block
4) Paste copied code
This let me do all of the changes 3 times faster...


text:
Q: Warmup Request Error of Django app on GAE My Django app on GAE is throwing an error warming request, which I cannot understand.
When I manually type www.mydomainname.com/_ah/warmup I get 404 error, but that's normal.
Where should I start debugging for this? Below is the error message.
E 2013-10-15 18:26:19.551
Internal Server Error: /_ah/warmup
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/core/handlers/base.py", line 92, in get_response
    response = middleware_method(request)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/middleware/common.py", line 57, in process_request
    host = request.get_host()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/http/request.py", line 72, in get_host
    "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host)
SuspiciousOperation: Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): 1.myappname.appspot.com

2013-10-15 18:26:22.030
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 266, in Handle
    result = handler(dict(self._environ), self._StartResponse)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/core/handlers/wsgi.py", line 255, in __call__
    response = self.get_response(request)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/core/handlers/base.py", line 178, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/core/handlers/base.py", line 224, in handle_uncaught_exception
    return callback(request, **param_dict)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/utils/decorators.py", line 91, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/views/defaults.py", line 41, in server_error
    return http.HttpResponseServerError(template.render(Context({})))
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 140, in render
    return self._render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 134, in _render
    return self.nodelist.render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 844, in render_node
    return node.render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/loader_tags.py", line 124, in render
    return compiled_parent._render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 134, in _render
    return self.nodelist.render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 844, in render_node
    return node.render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/defaulttags.py", line 285, in render
    return nodelist.render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 844, in render_node
    return node.render(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/templatetags/cache.py", line 29, in render
    key = ':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 659, in resolve_variable
    return Variable(path).resolve(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 728, in resolve
    value = self._resolve_lookup(context)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/django-1.5/django/template/base.py", line 771, in _resolve_lookup
    (bit, current))  # missing attribute
VariableDoesNotExist: Failed lookup for key [user] in u"[{'False': False, 'None': None, 'True': True}, {}]"

A: In your settings.conf file, you need to add:
ALLOWED_HOSTS = ('.myappname.appspot.com',)
More info here:
https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts


text:
Q: pySide: ExtensionLoader_Pyside_QtGUI.py specified module could not be found I'm using CXFreeze with PySide (QT). I get an error:
cx_Freeze: Python error in main script.
myscript.py line 33, in
File ExtensionLoader_Pyside_QtGUI.py, line 11, in
Import Error: DLL load failed: The specified module could not be found
When running a fresh install of Windows server 2008.
I'm running the frozen EXE package (with the folder). It seems to work on my own system and other systems. What might be the issue?
After reading, online, I tried to replace the Qt4Gui file, but this didn't solve the issue.
Python version is 2.7

A: Based on your Import Error: DLL load failed it is most likely an installation issue causing the missing DLL. To figure our exactly which DLL you are missing, use http://www.dependencywalker.com/ Run the .exe and open the .pyd file for File ExtensionLoader_Pyside_QtGUI.py and it will show you exactly which DLL's are missing and more importantly the locations where they should be. You can probably then track down the missing DLL online.

A: there are known issues with pyside 1.2.0 and cxFreeze. All should be fixed in development version (available on git repo). Please build the PySide from latest sources yourself or wait for PySide version 1.2.1. Build instructions are here [1].
[1] https://github.com/PySide/pyside-setup#building-pyside-on-a-windows-system

A: I used Py2exe instead of CXFreeze and it worked perfectly.
Also, apparently Python requires the MS Visual C++ Dependency Files:
http://www.microsoft.com/en-us/download/details.aspx?id=29
So any bundling needs that as well, if it's a fresh install. (Although I think they are now bundled with newer Windows versions.)
Other Notes:
In my experience, sometimes you should try CXFreeze, Py2EXE and PyInstaller quickly and see if one works best. As ideal as CXFreeze is re: cross platform, it just isn't going to happen perfectly.
Also, while I don't know if this was a factor, I set up a Windows 2000 Pro virtual machine and ran Py2exe on that. That was to ensure compatibility for all older Windows versions, and seemed to work well. (NOTE: Many things won't even run on Win2000 anymore so be careful that your other tools and libraries will run on it.)
Finally, be extra careful to match the bit level (32 vs 64) of all your libraries, and your Python install itself. If you have 32-bit python, ensure that your PySide, CXFreeze and any other libraries you use are 32-bit. (Or 64-bit if you're using 64-bit python.)


text:
Q: How to fix DataGridView Error: Is it possible that my null field result in MySQL query is the cause? I was trying to show my query result using a datagridview when i bumped into these errors...
The following exception occurred in the DataGridView:
System.ArgumentException: Parameter is not valid.
at System.Drawing.IMage.FromStream(Stream stream, BooleanuseEmbeddedColorManagement,     Boolean validateImageData)
at System.Drawing.ImageConverter.ConvertFrom(ITypeDescriptorContext context,     CultureInfo culture, Object value)
at System.Windows.Forms.Formatter.FormatObjectInternal(Objectvalue, Type targetTyep,     TypeConverter sourceConverter, TypeConverter targetConverter, String formatString,     IFormatProvider formatInfo, Object formattedNullValue)
at System.Windows.Forms.Formatter.FormatObject(Object value, Type targetType,     TypeConverter sourceConverter, TypeConverter targetConverter, String formatString,     IFormatProvider formatInfo, Object formattedNullValue, Object dataSourceNullValue)
at System.Window.Forms.DataGridViewCell.GetFormattedValue(Object value, Int32 rowIndex,     DataGridViewCellStyle& cellStyle, TypeConverter valueTypeConverter,     TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)

To replace this default dialog please handle the DataError event.

Well, I do get something like 8 dialogs like this when I use the datagridview, however, when I run a line-by-line checking using a breakpoint, I don't get prompted for a single error! I think it's this datagridview. I already tried to delete the datagridview and just put a new one but the same problem exists.
for your reference, here is the code I use in putting data into my datagridview:
  Public Sub fillDGVBulk()
    Try

        Dim bulkCmd As New MySqlCommand("select * from " _
                                    + "( " _
                                    + "  select controlno, bulk.catid, bulk.bcode, " _
                                    + "  ( " _
                                    + "    bulk.itemqty " _
                                    + "  ) as stock, " _
                                    + "  case when resv.qty is null then " _
                                    + "  '0' else resv.qty end as booked, " _
                                    + "  case when " _
                                    + "  ( " _
                                    + "    bulk.itemqty-sumqty " _
                                    + "  ) is null then " _
                                    + "  bulk.itemqty else (bulk.itemqty-sumqty) end as available, bulk.itemname, bulk.deptcode, bulk.loccode, resv.resdate, resv.timestart, resv.timeend " _
                                    + "  from tbl_items_bulk bulk " _
                                    + "  left join " _
                                    + "  ( " _
                                    + "    select rs.controlno, rs.bcode, rs.qty, sum(rs.qty) as sumqty, rs.resdate, rs.timestart, rs.timeend " _
                                    + "    from tbl_reservations rs " _
                                    + "    where retdate is null " _
                                    + "    and restype='1' " _
                                    + "    and resdate = @date " _
                                    + "    and not " _
                                    + "    ( " _
                                    + "      (timestart between @tStart and @tEnd) or " _
                                    + "      (timeend between @tStart and @tEnd) or " _
                                    + "      (timestart <= @tStart and timeend >= @tEnd) " _
                                    + "    ) " _
                                    + "    or rs.bcode is null " _
                                    + "    and (claimdate is null and retdate is null) " _
                                    + "    group by bcode " _
                                    + "  ) resv " _
                                    + "  on bulk.bcode=resv.bcode " _
                                    + "  where ((bulk.itemqty-sumqty) >= 1) or (bulk.itemqty-sumqty) is null " _
                                    + "  order by resdate, timestart " _
                                    + ") rvs " _
                                    + "where rvs.catid=@catid " _
                                    + "order by controlno", conn)

        With bulkCmd
            .Parameters.AddWithValue("@catid", cbo_catbulk.SelectedValue.ToString)
            .Parameters.AddWithValue("@date", dtp_datebulk.Value.ToString)
            .Parameters.AddWithValue("@tStart", cbo_startbulk.SelectedValue.ToString)
            .Parameters.AddWithValue("@tEnd", cbo_endbulk.SelectedValue.ToString)
        End With

        Dim DAdapter2 As New MySqlDataAdapter()

        DAdapter2.SelectCommand = bulkCmd

        If conn.State = ConnectionState.Open Then
            conn.Close()
            conn.Open()
        Else
            conn.Open()
        End If

        Dim table2 As New DataTable
        DAdapter2.Fill(table2)

        DataGridView2.DataSource = table2

        conn.Close()

        'controlno, catid, bcode, stock, booked, available, resdate, timestart, timeend

        With DataGridView2
            .Columns(0).Visible = False
            .Columns(1).HeaderText = "Category ID"
            .Columns(2).HeaderText = "Barcode"
            .Columns(3).HeaderText = "Stock"
            .Columns(4).HeaderText = "Booked"
            .Columns(5).HeaderText = "Available"
            ' .Columns(5).DefaultCellStyle.BackColor = Color.LightGreen
            .Columns(6).HeaderText = "Item"
            .Columns(7).HeaderText = "Department"
            .Columns(8).HeaderText = "Storage Area"
            .Columns(9).Visible = False
            .Columns(10).Visible = False
            .Columns(11).Visible = False
        End With
    Catch ex As Exception
        MsgBox(ex.Message.ToString + " Error No: " + Err.Number.ToString)
    End Try
End Sub

Can anybody help me out? Thanks in advance! :)

A: I'm trying a wild guess here..
During runtime, while this code sets table2 as the dataSource of the DataGridView,
DataGridView2.DataSource = table2

these codes immediately runs...
With DataGridView2
            .Columns(0).Visible = False
            .Columns(1).HeaderText = "Category ID"
            .Columns(2).HeaderText = "Barcode"
            .Columns(3).HeaderText = "Stock"
            .Columns(4).HeaderText = "Booked"
            .Columns(5).HeaderText = "Available"
            ' .Columns(5).DefaultCellStyle.BackColor = Color.LightGreen
            .Columns(6).HeaderText = "Item"
            .Columns(7).HeaderText = "Department"
            .Columns(8).HeaderText = "Storage Area"
            .Columns(9).Visible = False
            .Columns(10).Visible = False
            .Columns(11).Visible = False
        End With

Which will rename/hides the columns.
Rather renaming the DataGridView2's column header texts,
which I think causes the runtime error, because it doesn't yet have the columns of the result set.
Why not use the AS keyword on the SELECT statement, so that you can rename the column names
of the result set of your query.
Try this on your initial select statement..
 Dim bulkCmd As New MySqlCommand("select catid AS `Category ID`, bcode AS `Barcode`, stock AS Stock, booked AS `Booked`, available AS `Available`, resdate AS `Item`, timestart AS `Department`, timeend AS `Storage Area` from " _


text:
Q: how to run local web application in android webview can anybody tell how to run the local webapplication using android webview
I want to run my own webpages in android using web view
Thanks

A: I'm guessing you want something like this:
private WebView mWebView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.yourLayoutWithAWebView);

    mWebView = (WebView)findViewById(R.id.yourWebViewIdFromTheLayout);
    mWebView.getSettings().setJavaScriptEnabled(true); // Enable JavaScript

    mWebView.loadData(yourHtmlData, "text/html", "utf-8");
}

Hopefully, that at least points you in the right direction.
Also, I'd recommend reading the documentation on the WebView, it's pretty thorough.

A: Just run your application on the emulator, as you normally do (and be sure to have your computer connected to internet).


text:
Q: xml parsing in firefox not working I have a xml file whose content is
<?xml version="1.0" encoding="UTF-8"?>

<ReturnMessage>
<root>ReturnMessage</root>
<cancelMessage>Request cancelled.  /cancelMessage>
<confirmMessage>Click 'Create Document' to continue.</confirmMessage>
</ReturnMessage>

I load my xml like this
var result = responseText;
if (document.implementation && document.implementation.createDocument)
{
    alert("firefox");
    xml=document.implementation.createDocument("","",null);
    xml.load(result);
}

When execute the below code
var cnfmMsgCnt = xml.getElementsByTagName("confirmMessage");
alert(cnfmMsgCnt.lenght);

it alerts a 0 is firefox.
var displayMsg = xml.getElementsByTagName("confirmMessage").item(0).text

also does not provide any output in FF.
It works perfect in IE but it is not working in Firefox.

A: The method load() takes a file name as argument, not an XML string.  See https://developer.mozilla.org/en/DOM/document.load  (and more normative: W3C DOM Level 3 Load & Save module)
What you probably want is explained here https://developer.mozilla.org/en/Parsing_and_serializing_XML
var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>";
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");


text:
Q: Devise authentication gem: How to save the logged in user id? I'm using the Devise Ruby gem in my Ruby on Rails 3 application. When a logged in user creates one of my models, I want to save their user id as the person who created it. What should I do?

A: *

*Create a migration file with a column of type integer named user_id, this is where the association will be stored. (see the migration guide for details on how to do this).

*in your model, add: belongs_to :user (see the associations guide for more details)

*in the controller for your model, add @your_model.user = current_user in the create action. This will do the association you're looking for.  (current_user is a method provided by devise that returns the User ActiveRecord for the currently logged in user)
Note: there are more than one way of doing the actual association. I'm suggesting to do it in the controller but it could be done in the model or elsewhere.


text:
Q: "returned as a different man" or " returned a different man"?
If he had fought in the First World War, he might have returned _____.

Is it correct to insert " as a different man" or " a different man"?
I suppose both are correct.  "as a different man" function as an adverb phrase for return; for "a different man," I think it is an adjunct for "he," to give more description of him.

A: In the UK we say, "returned a different man". We might also say "a changed man."
If we were to say, "He returned as a different man" it would mean he was pretending to be a different man, one of the meanings of as being "in the rôle of " or "playing the part of." For example, if an actor plays two parts in a film we might we say he "returns as a different man."
As you say, without "as" it is an adjunct; with "as" it's an adverbial phrase.


text:
Q: yet another burned MOSFET issue in H-bridges I'm trying to get into how H-bridges could be utilised in a heating/cooling peltier module for a personal fun project;
I designed the circuitry (shown below), which BTW your feedback and suggestions regarding the whole design is much appreciated, the problem is as soon as I'm switching ON the DC source(12V@3A) I'm burning the high-side P-MOSFETs. the DMP3056L could theoretically be able to handle 3A with Id_max of (-4.3/-3.4A for Vgs of -10/-4.5V) according to the datasheet; on the other hand, with Rds of (50/70mOhm for Vgs of -10/-4.5V) and considering the 3A drain current the dissipated power should be: 3^2 * (0.05 or 0.07) = 0.45-0.63 Watts and again according to the datasheet the temp rise should be 91C/W which I doubt that could cause a significant rise in the temperature to be the reason for the burning of MOSFETs.
Am I missing something here?
Datasheets:
https://www.diodes.com/assets/Datasheets/DMP3056L.pdf
https://www.diodes.com/assets/Datasheets/ZXMN3F30FH.pdf

A: Notice the fine print on DMP3056 datasheet about how RthJA of 91°C/W is measured...

Note 5: Device mounted on FR-4 substrate PC board, 2oz copper, with thermal vias to bottom layer 1inch square copper plate.

The other FET specs 131°C/W but...

(a) For a device surface mounted on 25mm x 25mm FR4 PCB with high coverage of single sided 1oz copper, in still air conditions.

In other words these specs count on having enough copper on the board to act as a heat sink, with heat flowing through the component leads.
Some special packages can have a low Rth because the chip is mounted directly on the metal lead frame which conducts heat to the board through the pins and solder. This is not the case here, this standard SOT-23 can't dissipate half a watt.
Solution: use a FET package that will handle the required power, if this is a one-off prototype, TO220 is ideal because it's much easier to solder on protoboard than SMDs.
Or get a ready-made h-bridge, these are quite cheap.
Or keep SOT23s but pick ones with much lower RdsON.
Note if the power supply current limits at 3A, you need a more powerful supply for a 3A peltier.

A: Basically the reasons of that are:

*

*Use resistors the lower wattage than the mosfet needs.

*Short circuit in the circuit, making the mosfet die.

*Bad cooler or no disipation of temperature in the mosfet, it includes no disipator, no fan, no resistor.

*Overvoltage it can exceed the temperature, and make the mosfet burns like a FIRE!, very harmfull.

*Bad use of the mosfet, some mosfet are fragile to disconections and conections and it can stop working if you disconect some part, more if the amperage are high, 2.1A or more.

*Use a poor multimeter to test it, poor multimeter can make cut circuit when are used in a high amperage, don't care if are supported in the multimeter.

Solutions:

*

*Use a resistor to protect the mosfet, with a wattage capacity more higher than the potence that is required by the mosfet, in the in and out all in positive, not in gnd.

*Use a RELAY to disconect the circuit before the cut circuit go to the mosfet.

*I recommend a fan 12v 1a if is possibly, and a aluminium disipator, with cold special cream, for electronics.

*Use a Voltage regulator to protect it more higher than the mosfet needs.

*Do not disconnect any part of the circuit when are on.

*Use a professional multimeter, designed for transistors mosfet and amplifiers, a expencive multimeter.

My not expensive recommendation is Use a mosfet that supports the double capacity, than the current mosfet  burned, and use a better refrigeration(fan and dissipation of aluminium) for it...


text:
Q: When do you take input as T or &T in a Rust generic function? My class notes have code that implements the HasArea trait and prints the area, similar to the Rust Book example. The professor's note is as following:
trait HasArea<T> {
    fn area(& self) -> T,
}

fn print<T: Display, S: HasArea<T>>(s: &S) {
    println!("", s.area());  // println sth must impl Display trait
}

struct Circle {
    x: T,
    y: T,
    r: T,
}

impl <T: Copy + Mul <Output = T>>
    HasArea<T> for Circle<T>
{
    fn area(&self) -> T {
        self.r * self.r
    }
}

Comparing that to the Rust Book, which uses shape: T as input:
trait HasArea {
    fn area(&self) -> f64;
}

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

impl HasArea for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

fn print_area<T: HasArea>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}

fn main() {
    let c = Circle {
        x: 0.0f64,
        y: 0.0f64,
        radius: 1.0f64,
    };

    print_area(c);
}

I am not sure why the professor uses s: &S, while the Rust Book uses shape: T. Can anyone help compare when implementing a generic function, when do we pass a input as x: &T and when x: T?

A:
Can anyone help compare when implementing a generic function, when do we pass a input as x: &T and when x: T?

It's the same as when you would accept x: Foo and x: &Foo. Taking a x: Foo gives the function the ownership of of x, and (unless x is Copy) the caller will not be able to use it again.
In the Rust Book example, print_area takes the ownership of circle, so you cannot use circle after the print_area(circle); line. For example, the following:
fn main() {
    // ...
    print_area(c);
    print_area(c);
}

throws this error:
error[E0382]: use of moved value: `c`
  --> <anon>:29:16
   |
28 |     print_area(c);
   |                - value moved here
29 |     print_area(c);
   |                ^ value used here after move
   |
   = note: move occurs because `c` has type `Circle`, which does not implement the `Copy` trait

In my experience, most of the time you'll want to take : &T (like your Professor's note). Only when you need the ownership of the struct would you need to use : T. The Rust Book probably uses : T for simplicity.

A: This is not a question of generics but a question of borrowing and ownership. If you want your input to be moved into function then you use T, otherwise if you just want to borrow it you use &T or &mut T.
Relevant book section


text:
Q: Reordering columns with multiple variables in var.values after dcast I have used dcast to put a data.table into a wide format. Since I have many columns now (because I specified multiple variables in the var.values argument, I'd like to reorder the columns. This is an example for the data I have entered:
dt<-data.table(a_1=c(1,2,3), a_2=c(1,2,3), a_3=c(1,2,3), freq_1=c(1,2,3),freq_2=c(1,2,3), freq_3=c(1,2,3))

    a_1 a_2 a_3 freq_1 freq_2 freq_3
1:   1   1   1      1      1      1
2:   2   2   2      2      2      2
3:   3   3   3      3      3      3

This is how it should look like:
dt1<-data.table(a_1=c(1,2,3), freq_1=c(1,2,3), a_2=c(1,2,3), freq_2=c(1,2,3), a_3=c(1,2,3), freq_3=c(1,2,3))

   a_1 freq_1 a_2 freq_2 a_3 freq_3
1:   1      1   1      1   1      1
2:   2      2   2      2   2      2
3:   3      3   3      3   3      3

First hint was something like:
library("gtools")
cdat <- colsplit(names(dt),"\\_",c("name","num"))
dt<-dt[,order(mixedorder(cdat$name),cdat$num)]

But this did not work, unfortunately
Thank you very much for your help!

A: You can use setcolorder,
library(data.table)
setcolorder(dt, order(sub('.*_', '', names(dt))))

which gives,

   a_1 freq_1 a_2 freq_2 a_3 freq_3
1:   1      1   1      1   1      1
2:   2      2   2      2   2      2
3:   3      3   3      3   3      3


text:
Q: Translate excel inputs into json I am trying to extract a json file with the following inputs in Excel.

To do that, I have a code as follows (in VBA):
Public Sub ExceltoJson()

Dim rng As Range, items As New Collection, myitem As New Dictionary, i As Integer, cell
Set rng = Range("A1:A3")
i = 0
For Each cell In rng
    Debug.Print (cell.Value)
    myitem("CurrentPromo") = cell.Offset(1, 0).Value
    myitem("StartDateCP") = cell.Offset(2, 0).Value
    myitem("EndDateCP") = cell.Offset(3, 0).Value
    Set myitem = Nothing
    i = i + 1
    items.Add myitem
Next
'items.Add myitem
myfile = "C:\Users\gabriem\PycharmProjects\BigPromos" & "\json_vba.json"
Open myfile For Output As #1
Print #1, ConvertToJson(items, Whitespace:=2)
Close #1

End Sub

But, the result I get is:
[{"StartDateCP": "PastPromo","EndDateCP": "DPE16"},{"CurrentPromo":"PastPromo","StartDateCP": "DPE16"},{}]

This is not what I am looking for. I need each label together with its unique value.
Can anyone guide me?
Thanks a lot!

A: I think what you want to do is iterate over the headers and add the next row's value into a dictionary to generate the JSON string.
It looks like you are using the VBA-JSON project, but if you aren't the solution below requires this project to function, so make sure add this to your project. You can get a copy of the project here. Additionally, you must add a reference to the Microsoft Scripting Runtime for this to work.
Assuming you have headers in A1:C1 and data in A2:C2 in Sheet1 the below should work. The headers are the Keys and the next row is the Value.
Option Explicit

Private Sub createJSON()
    Dim ws      As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim rng     As Range: Set rng = ws.Range("A1:C1")
    Dim cll     As Range
    Dim dict    As Dictionary: Set dict = New Dictionary
    Dim JSON    As String

    'Add the items to a dictionary
    For Each cll In rng
        If Not dict.exists(cll.Value) Then dict.Add cll.Value, cll.Offset(1, 0).Value
    Next

    JSON = JsonConverter.ConvertToJson(dict, Whitespace:=2)
    Debug.Print JSON
End Sub


text:
Q: How do you get a persons phone number from the address book? All I want to do is let the user select a number from the address book. I found the code in this question:
How to get a Phone Number from an Address Book Contact (iphone sdk)
ABMultiValueRef container = ABRecordCopyValue(person, property);
CFStringRef contactData = ABMultiValueCopyValueAtIndex(container, identifier);
CFRelease(container);
NSString *contactString = [NSString stringWithString:(NSString *)contactData];
CFRelease(contactData);

The problem is that on the second line (when running on a 3.0 device) I get the following error:
Account Manager could not find account with identifier MobileMe:rustyshelf
followed by:
Program received signal:  "EXC_BAD_ACCESS".
This is all inside the picker delegate method:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

This is just one of the contacts in my address book, which is synched with Mobile Me
Edit: I think this might be a bug with the SDK, it happens for some of my contacts but not for others...

A: - (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
   if (property == kABPersonPhoneProperty)
   {
       ABMultiValueRef numbers = ABRecordCopyValue(person, property);
       NSString* targetNumber = (__bridge NSString *) ABMultiValueCopyValueAtIndex(numbers, ABMultiValueGetIndexForIdentifier(numbers, identifierForValue));

       NSLog(@"%@", targetNumber);
   }
   return NO;
}

I used this question to construct my own solution. The code I'm posting is not intended as answer, merely for someone to maybe find useful. These are the simple steps for get a property. Memory management excluded.

A: I use this to pull the mobile number from an ABRecordRef/  The "record" variable is the ABRecordRef you want the phone number for.  Where I have "" you can use another phone tag string to find other types of phone numbers.
//Get mobile phone number
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(record, kABPersonPhoneProperty);
NSString* mobile=@"";
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
    mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
    if([mobileLabel isEqualToString:@"_$!<Mobile>!$_"]) {
          mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
    }
}

A: You should be able to just do the following:
ABMultiValueRef phoneNumbers = (ABMultiValueRef)ABRecordCopyValue(person, kABPersonPhoneProperty);
CFRelease(phoneNumbers);
NSString* phoneNumber = (NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, 0);

Of course, that's only going to get you the first number of (potentially) many associated with the person who's been selected.

A: The "identifier" argument does not hold the CFIndex of the record touched.  The method I use to tell which phone number a user selected is this:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    if (property == kABPersonPhoneProperty) {
        ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
            if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
                CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
                CFRelease(multiPhones);
                NSString *phoneNumber = (NSString *) phoneNumberRef;
                CFRelease(phoneNumberRef);
                txtPhoneNumber.text = [NSString stringWithFormat:@"%@", phoneNumber];
                [phoneNumber release];
            }
        }
    }

    [self dismissModalViewControllerAnimated:YES];
    return NO;
}

A: Going off of JWDs answer, here is a safer version that uses the builtin constants and chooses the iphone number over another mobile number...
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobile=@"";
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
    mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
    if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
    {
        [mobile release] ;
        mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
    }
    else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
    {
        [mobile release] ;
        mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
        break ;
    }
}

A: you can also use this "ABMultiValueGetIndexForIdentifier" like in this code :
ABPropertyType pt = ABPersonGetTypeOfProperty(property);
NSString *phoneNumber;
if ((pt & kABMultiValueMask) == kABMultiValueMask) {
        ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
        CFIndex idx = ABMultiValueGetIndexForIdentifier(phoneProperty, identifier);
        phoneNumber = (NSString *)ABMultiValueCopyValueAtIndex(phoneProperty,idx);
        CFRelease(phoneProperty);
    }

A: Going off from Dan's answer :
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier
{
    if (property == kABPersonPhoneProperty) { // if tapped is equal to a phone property
        CFStringRef cfnumber;
        ABMultiValueRef numbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for(CFIndex i = 0; i < ABMultiValueGetCount(numbers); i++) {
            if(identifier == ABMultiValueGetIdentifierAtIndex (numbers, i)) { //if tapped number identifier is the same as identifier number tapped
                cfnumber = ABMultiValueCopyValueAtIndex(numbers, i); // copy the number to CFSTRING number
            }
        }
        NSString *number = [NSString stringWithFormat:@"%@",cfnumber];
        CFRelease(cfnumber);
        //do anything you want with the number
    }
    return NO;
}

Can't tell you if it's the best/correct way. But i ran into some errors using Dan's code.. hence i've decided to share it after figuring it out.
Still learning objective c.. haha..
Hope it helps..
Regards,
Steve0hh


text:
Q: Ubuntu Cross-compile for ARM - PATH variable - bash error I have downloaded CodeSourcery Toolchain tools located to the following path:
root@ab-pc:~/arm-2009q1/bin#
arm-none-linux-gnueabi-ar
arm-none-linux-gnueabi-ld
arm-none-linux-gnueabi-as
arm-none-linux-gnueabi-c++
arm-none-linux-gnueabi-c++filt
arm-none-linux-gnueabi-cpp
arm-none-linux-gnueabi-g++
arm-none-linux-gnueabi-gcc
arm-none-linux-gnueabi-gcc-4.3.3
arm-none-linux-gnueabi-gcov
arm-none-linux-gnueabi-gdb
and I have exported this path to my PATH variable:
root@ab-pc:~# echo $PATH
/root/arm-2009q1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
but when I execute the command:
root@ab-pc:~# arm-none-linux-gnueabi-gcc -v
-bash: /root/arm-2009q1/bin/arm-none-linux-gnueabi-gcc: No such file or directory
However Which command shows:
root@ab-pc:~# which arm-none-linux-gnueabi-gcc
/root/arm-2009q1/bin/arm-none-linux-gnueabi-gcc
Can someone explain to me what I am doing wrong and why I take this error?
Many thanks!


text:
Q: Redirect user to homepage on successful login Dojo I'm struggling to redirect a user after their login request to the server is successful. The response from the server is successful and I am able to display the values in alert boxes but I don't get redirected to a different page.
Here is the code I am using

A: True & false are not strings. Try this:
if(jsonObject.successful == true)
    window.location = "http://www.mysite.com";
else
    resultDiv.innerHTML = "

 The Email or Password you entered was incorrect.

 Register to get an account.

";

Failing that, do alert(jsonObject.successful + ' = ' + typeof(jsonObject.successful))


text:
Q: R: Find and remove all one to two letter words I am attempting to clean away any one or two letter words from a text passage. This was my first thought
gsub(" [a-zA-Z]{1,2} ", " ", "a ab abc B BB BBB")
[1] "a aaa BB BBBB"

I can see how the "a" is not replaced as it does not lead with a space and I can see how the "BB" is not replaced as the space it leads with has already been grabbed by the " B ".

A: You can make use of \b word boundary and [[:alpha:]] bracket expression with {1,2} limiting quantifier, and then trim the leading/trailing spaces and shrink multiple spaces into 1:
tr <- "a ab abc B BB BBB f"
tr <- gsub(" *\\b[[:alpha:]]{1,2}\\b *", " ", tr) # Remove 1-2 letter words
gsub("^ +| +$|( ) +", "\\1", tr) # Remove excessive spacing

Result:
[1] "abc BBB"

See IDEONE demo

A: Use the below Perl regex .
x <- gsub("\\s*(?<!\\S)[a-zA-Z]{1,2}(?!\\S)", "", "a ab abc B BB BBB", perl=T)
gsub("^\\s+", "", x)


text:
Q: Multiple, custom URLs for Rails 3 resources without ID In my app I've got various resources that I want to access via multiple URLs. For example, an invoice can be accessed via:
/invoices/:id

By the issuer of the invoice, and also via:
/pay/:payment_key

By the payer.
The latter URL does not require authentication (hence the secrefied payment_key).
The issue is how to get automatic URL helper methods for the custom URL. Usually you could use to_param to customize the resource URL (as described here), but that's not adequate in this case because I still want to retain the default resource URL.
If I create the helper methods by declaring a named route:
/pay/:payment_key, :as => :invoice_payment

Then I would expect invoice_payment_url(invoice) to include invoice.payment_key but it doesn't. Rails uses the invoice ID instead (similar to the behaviour reported here)
This seems like it's broken.
So I've been defining the url helpers for this resource manually.
def invoice_payment_path (invoice)
  url_for :controller => "invoices",
  :only_path => true,
  :action => "pay",
  :payment_key => invoice.payment_key
end

def invoice_payment_url (invoice)
  url_for :controller => "invoices",
  :only_path => false,
  :action => "pay",
  :payment_key => invoice.payment_key
end

Wondering if there is a DRYer way to do this?

A: RESTful is about resources. So are you sure the "payment" and "invoice" resources the same thing in your system? To me, it is more like a system design issue than a routing issue.
Another thought is using nested resources. You can view either "/payments/:id/invoices" or "/invoices/:id/payments", both make sense to me.
Yan


text:
Q: VBA how to remove string line in pragraph? For example , i want to remove all string in line 10 below .
What the VBA code can be use?

*

*Limitation: Quality metrics are not available

*Limitation Cause: HTTPS connection

*Service Bearer: Lte

*Data Radio Bearer: LTE

*Impairment free: Yes

*Is Multi RAB: No

*LTE Serving Cell Count Average: 1

*Number Of Video Session Interruptions: 0

*Maximum Duration Of Video Session Interruptions: 0.0 s

*Total Duration Of Video Session Interruptions: 0.0 s

*Clip Length: 100.704 s

A: The simplest approach is to go to menu Developer, click "Record macro" and do the action you want to do (that is remove string in row 10). Then you click "stop recording", click "Macros", select Macro1 and click the button Edit. A new window opens with VBA code that does what you just recorded. In your case the code is
Sub Macro1()
  Range("A10").Select
  Selection.ClearContents
End Sub

This is where you start. Then you can play with the code and further adjust it to your needs.


text:
Q: Conditional with number1 == number2 (of type Long) is never true? this code is supposed to list recent calls with recent same nos skipped but they are being displayed, please help
             //code
              Long number0=(long) 0;
          // loop through cursor
          while(mCallCursor.moveToNext()){
              Long number1 = mCallCursor.getLong(0);
              if(number1==number0)
                  continue;
              else
                  number0=number1;
              if(mCallCursor.getString(2)!=null){
                  String name = mCallCursor.getString(2);
                  System.out.println(name);
              }
              else
                  System.out.println(number1);

          }

A: Instead of
if(number1==number0)

use
if(number1.equals(number0))

Two Long values can satisfy equals without being ==.

A: The main reason why it is not working is that Long 's are objects and == operator works as it is testing equalities of two objects not the long values stored in these objects. On the other hand a long is not an object but a primitive.
if((long)number2 == (long)number1)

shall work as well.


text:
Q: SET value SELECT FROM variable table I need to get the value from SELECT with variable table.
My code looks like this:
SET @count = @count + 1;
SET @count = CAST (@count AS varchar)

IF @pocet> 0 AND @pocet <= 9

BEGIN
    SET @tab_val_ = 'tabVal_00' + @count;
    SET @tabSta _ = 'tabSta_00' + @count;
    SET @var1 = (SELECT DESC_POINT FROM @tabSta_ WHERE id_w = @ id_w);
    print @ var1;

Error
Msg 1087, Level 16, State 1, Line 54
Must declare the table variable "@tabSta_".

I'm sorry, I guess I spoke.
@tabSta_xxx is an actual table such as tabSta_001 and in the query SET @var1 = (SELECT DESC_POINT FROM @tabSta_ WHERE id_w = @ id_w); I need @var to be equal to DESC_POINT. For example, DESC_POINT is "abcdefg"

A: Thank you, here is the code, I need to get the value DESC_POINT from @table, which I will then need to add to the column name, which will no longer be a problem
SET @id_w = 50000269; --Comment
DECLARE @tbl_name varchar (100)
SET @tbl_name = 'tbl _' + @ id_w
DECLARE @tabSta_ varchar (20)

DECLARE @DropTable varchar (200)
SET @DropTable = 'DROP TABLE' + @ tbl_name

--DROP TABLE TempTableExport
IF OBJECT_ID ('' + @ tbl_name + '') IS NOT NULL EXEC (@DropTable)

DECLARE @CREATE VARCHAR (6144)
SET @CREATE = 'CREATE TABLE' + @ tbl_name + '(ID_R BIGINT, DATE date, TIME time (7), STT int, SV_P1 decimal (6,3))';
EXEC (@CREATE)

--DECLARE @id_w varchar (10) --id_w--
DECLARE @num_point int --number of points--
DECLARE @duplex int --number of points--
DECLARE @pocet int
DECLARE @pocet_d int
DECLARE @poceta_da varchar (3)
DECLARE @poceta varchar (3)
DECLARE @tab_val_ varchar (20)
DECLARE @Bod_ varchar (20)
DECLARE @ItemSQL VARCHAR (6144)
DECLARE @Alter VARCHAR (6144)
DECLARE @Alter_d VARCHAR (6144)
DECLARE @Insert VARCHAR (6144)
DECLARE @Update VARCHAR (6144)
DECLARE @Update_d VARCHAR (6144)
DECLARE @Cycle int
DECLARE @ var1 varchar (max)
Declare @sqla nvarchar (max)
--SET @id_w = 50000157; --Comment

SET @num_point = (SELECT NUM_POINT FROM tabSta_unit WHERE id_w = @ id_w);
SET @duplex = (SELECT MODE_WORK FROM tabSta_unit WHERE id_w = @ id_w);

SET @count = 0

WHILE @pocet <@num_point
BEGIN
SET @ count = @ count + 1;
SET @ count = CAST (@ count AS varchar)
IF @pocet> 0 AND @pocet <= 9
BEGIN
SET @ tab_val_ = 'tabVal_00' + @ count;
SET @tabSta _ = 'tabSta_00' + @ count;
SET @ var1 = (SELECT DESC_POINT FROM @tabSta_ WHERE id_w = @ id_w);
print @ var1;
PRINT @tabSta_;
SET @ Bod_ = 'Bod_00' + @ count;
END
IF @pocet> = 10 AND @pocet <= 99
BEGIN
SET @ tab_val_ = 'tabVal_0' + @ count;
SET @ Bod_ = 'Bod_0' + @ count;
END
IF @count * = 100
BEGIN
SET @ tab_val_ = 'tabVal _' + @ count;
SET @ Point_ = 'Point _' + @ count;
END
SET @Alter = 'ALTER TABLE' + @ tbl_name + 'ADD' + @ Bod_ + 'decimal (6,3) NULL';
EXEC (@Alter)
END
SET @insert = 'INSERT INTO' + @ tbl_name + '(ID_R, DATE, TIME, SV_P1, STT) SELECT tabVal_unit.ID_R, tabVal_unit.DATE, tabVal_unit.TIME, tabVal_unit.SV_P1, tabVal_unit.STT FROM tabVal_unit WH = '+ @ id_w;
EXEC (@insert)

SET @count = 0
WHILE @pocet <@num_point
BEGIN
SET @ count = @ count + 1;
SET @ count = CAST (@ count AS varchar)

IF @pocet> 0 AND @pocet <= 9
BEGIN
SET @ tab_val_ = 'tabVal_00' + @ count;
SET @ Bod_ = 'Bod_00' + @ count;
END
IF @pocet> = 10 AND @pocet <= 99
BEGIN
SET @ tab_val_ = 'tabVal_0' + @ count;
SET @ Bod_ = 'Bod_0' + @ count;
END
IF @count * = 100
BEGIN
SET @ tab_val_ = 'tabVal _' + @ count;
SET @ Point_ = 'Point _' + @ count;
END
SET @Update = 'UPDATE' + @ tbl_name + 'SET' + @ tbl_name + '.' + @ Bod_ + '='+@tab_val_+'.VAL FROM' + @ tbl_name + 'INNER JOIN' + @ tab_val_ + 'ON' + @tbl_name + '. ID_R ='+@tab_val_+'.ID_R';
EXEC (@Update)
END

if @duplex = 11
BEGIN
SET @count = 200
--SET @num_point = @pocet + @num_point
SET @Cycle = @pocet + @num_point
--PRINT @Cycle
WHILE @pocet <@Cycle
BEGIN
SET @ count = @ count + 1;
SET @ count = CAST (@ count AS varchar)
IF @pocet> 200 AND @pocet <= @ Cycle
BEGIN
SET @ tab_val_ = 'tabVal _' + @ count;
SET @ Point_ = 'Point _' + @ count;
END
SET @Alter_d = 'ALTER TABLE' + @ tbl_name + 'ADD' + @ Bod_ + 'decimal (6,3) NULL';
EXEC (@Alter_d)
END

SET @count = 200
SET @Cycle = @pocet + @num_point
WHILE @pocet <@Cycle
BEGIN
SET @ count = @ count + 1;
SET @ count = CAST (@ count AS varchar)

IF @pocet> 200 AND @pocet <= @ Cycle
BEGIN
--PRINT @pocet
--PRINT @Cycle
--PRINT @num_point
SET @ tab_val_ = 'tabVal _' + @ count;
SET @ Point_ = 'Point _' + @ count;
END
SET @Update_d = 'UPDATE' + @ tbl_name + 'SET' + @ tbl_name + '.' + @ Bod_ + '='+@tab_val_+'.VAL FROM' + @ tbl_name + 'INNER JOIN' + @ tab_val_ + 'ON' + @tbl_name + '. ID_R ='+@tab_val_+'.ID_R';
EXEC (@Update_d)```

A: I'm not sure exactly what you're looking to accomplish.  However you have your variable @tabSta_ declared as a VARCHAR variable but you appear to be using it as a TABLE variable since you're attempting to select from it in the query SELECT DESC_POINT FROM @tabSta_ WHERE id_w = @ id_w.  If you're planning on using that variable as a table, you need to declare it as a table variable as below with the appropriate columns, just as you would with a CREATE TABLE statement.
DECLARE @tabSta_ TABLE (col1 VARCHAR(10), col2 VARCHAR(10), ...)

A: try using this code pattern. The select statement must return only one value
declare @my_variable as varchar(20)

select @my_variable=value from table where id=1


text:
Q: What is the official way to add a new texmf tree to a texlive system on debian/ubuntu? I have texlive installed on a debian-like host (linux mint) via apt. Now I would like to add a new texmf tree. What is the correct or recommended way to do it? I would like to keep this new texmf tree separate from existing texmf trees on the system. I did some searching on the topic, and the closest answer to my question is to run this command:
$ tlmgr conf texmf TEXMFHOME "~/texmf:~/another-texmf"

Indeed this works fine on macOS, however on Linux Mint 19.2 it doesn't. After running the command, the new value of TEXMFHOME is set in /usr/share/texlive/texmf.cnf:
$ tlmgr conf texmf TEXMFHOME "~/texmf:~/another-texmf"
(running on Debian, switching to user mode!)
setting texmf TEXMFHOME to ~/texmf:~/another-texmf (in /usr/share/texlive/texmf.cnf)

but that file seems not being used:
$ kpsewhich -var-value TEXMFHOME
/home/tony/texmf
$ kpsewhich -var-value TEXMFCNF
/etc/texmf/web2c:/usr/local/share/texmf/web2c:/usr/share/texlive/texmf-dist/web2c

There are several texmf.cnf files on my system:
/etc/texmf/web2c/texmf.cnf
/usr/share/texmf/web2c/texmf.cnf
/usr/share/texlive/texmf-dist/web2c/texmf.cnf
/usr/share/texlive/texmf.cnf

So it seems that /usr/share/texlive/texmf.cnf is not read, although it was created by tlmgr conf texmf
What am I missing here? Thanks in advance for any hint.

A: Solution for vanilla TeX Live
Looking at tlmgr help and searching for auxtrees there shows the possibility of doing (at least on vanilla TeXlive 2019, please check before using this command on your system):
sudo tlmgr conf auxtrees add /path/to/folder

The folder doesn't need a ls-R file (so doesn't need to be indexed), and in fact you shouldn't, so that changes to that folder become available immediately and you don't forget to update the index.
You can remove a folder added this way doing:
sudo tlmgr conf auxtrees remove /path/to/folder


text:
Q: Windows 10 - Computer will not enter reduced power mode This has been asked before in the form of "Windows X won't sleep", and I've unsuccessfully followed all of the prescribed diagnostic steps everywhere I can find.
Some time, about 2 weeks ago, my desktop computer stopped being able to start the screensaver, sleep, or turn off the monitors. This manifests as an always-on 100% bright pair of screens, and it's driving me nuts. I've rebooted the machine several times and run powercfg -energy more than I can count looking for possible culprits. Likewise, powercfg /requests is generally empty. There's nothing readily identifiable as the problem. If I manually put the computer to sleep, it will generally (but not always) stay that way.
Can anyone suggest additional steps?
C:\>powercfg /requests
DISPLAY:
None.

SYSTEM:
None.

AWAYMODE:
None.

EXECUTION:
None.

PERFBOOST:
None.

Report from powercfg -energy:
https://jsfiddle.net/fajk78zm/embedded/result/

A: The cause of this issue turned out to be the PS4 controller I had connected via USB. Evidently, when the PS4 controller is connected, or InputMapper is running (software to enhance PS4 usability), Windows 10 will not sleep.


text:
Q: Unable to retrieve Application State in Model class Im facing a problem in one of MVC projects, that problem is about retrieving values from Application State object.
I am storing some value into the Application state in Application_Start() method of Global.axas.cs in this manner:
//var str = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
//Application["connString"] = str;

Application["connString"] = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());

I have made sure the value from web.config has been successfully retrieve at this point through debugging.
After this step I'm trying to retrieve this value in one of my Model Class in this manner:
var conn = new SqlConnection(Application["connString"].ToString());

But here I'm getting a NullReferenceException Object reference not set to an instance of an object.
Now this is very confusing for me here that if the value has been successfully retrieved and stored in AapplicationState at the point of Application_Start() than why isn't it available in my model class, aren't the ApplciatiopnSate available throughout the application?

A: My suggestion is not to keep the connection string in the Application variable. Rather you can declare a static method which can return the connection string.Store the connection string in a static variable as shown below
public class Utility
{
    static string connectionString;
    public static string GetConnectionString()
    {
        if(string.IsNullOrEmpty(connectionString))
            connectionString = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
        return connectionString;
    }
}

Configuration files are cached, henceforth you need not worry about performance of reading the files every time the method is called


text:
Q: Why i get different result in vim between `"+p` and `paste`? I want to paste something from web into vim .
1.select the content which i want to paste.
please attachment

2.the sentence2 which i paste with method clipboard

3.compare the sentence2 which i paste with method :+p

why sentence1 lost the letter C ?this is the only different place.

A: When you use "+p, vim pastes the contents of the + buffer. But when you paste from the clipboard, the terminal emulator passes vim each of the letters as input, as if from the keyboard. It so happens that the first letter of your pasted content is C, which causes vim to cut from the cursor to the end of the line and enter insert mode, so you only lose that one character. When pasting from the clipboard (either by the menu as you did or ctrl-v) you need to go to insert mode first. And depending on what you're pasting, you may want to :set paste, to prevent bindings and formatting from taking effect (use :set nopaste to turn it off).

A: Normally you don't want Vim to interpret whatever you're pasting from your system clipboard, only typed text. However Vim can't know the difference between pasted and type text in all scenarios, especially in a terminal. Using the paste mode will disable any interpreting, i.e. formatting, autocomplete by plugins or even commands, of the text pasted.
From :h paste:
        Put Vim in Paste mode.  This is useful if you want to cut or copy
        some text from one window and paste it in Vim.  This will avoid
        unexpected effects.
        Setting this option is useful when using Vim in a terminal, where Vim
        cannot distinguish between typed text and pasted text.  In the GUI, Vim
        knows about pasting and will mostly do the right thing without 'paste'
        being set.  The same is true for a terminal where Vim handles the
        mouse clicks itself.

Toggle paste mode using pastetoggle:
set pastetoggle=<F3>


text:
Q: Can a subordinate clause split subject and verb in the main clause? E.g. are these correct?

*

*Following the rules, even if it's difficult, is essential.

*Following the rules, although it's difficult, is essential.

A: Yes, there's nothing wrong with either sentence. They're both grammatical and idiomatic. The subordinate clauses you inserted in both sentences can come at the beginning, in the middle, or at the end of each sentence.


text:
Q: NFC intent on TabActivity starts a new activity instead of refreshing existing one After my old question was closed I'm trying it now again considering the advices you gave me...
I've got an Android-Test-App in which I want to change the text a TextView as soon as something (f.e. RFID chip) is read with NFC.
The problem is that my activity with the TextView lies in the Tab of a TabHost. When NFC is reading something the Activity is started in the foreground and the TextView is not changed.
What I want is that only the TextView changes and everything else stays as it is....
Here's my code:
My TabActivity:
public class NfcTabsActivity extends TabActivity {

    private NfcAdapter nfc;
    private PendingIntent nfcintent;
    private String[][] nfctechfilter = new String[][] { new String[] { NfcA.class.getName() } };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TabHost tabHost = getTabHost();

        Intent intent = new Intent().setClass(this, NfcTest.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        TabSpec spec = tabHost.newTabSpec("nfctab").setIndicator("NFC").setContent(intent);
        tabHost.addTab(spec);

        nfc = NfcAdapter.getDefaultAdapter(this);

            // PendingIntent using the NfcTest-Activity to receive the Intent. (Am I doing this correctly??)
        nfcintent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
    }

    // Start looking for NFC when activity is started/resumed.
    @Override
    protected void onResume() {
        super.onResume();
        nfc.enableForegroundDispatch(this, nfcintent, null, nfctechfilter);
    }

    // Disable NFC when leaving activity
    @Override
    protected void onPause() {
        super.onPause();
        nfc.disableForegroundDispatch(this);
    }
}

and here's my NfcTest Activity that should receive the intent when NFC is used:
public class NfcTest extends Activity {

    private TextView status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.nfctest);

        status = (TextView) findViewById(R.id.textView2);

    }

    @Override
    public void onNewIntent(Intent intent) {

        status.setText("RFID detected...");

    }
}

Thanks NFC guy for the advice to put the PendingIntent in the TabActivity!
Unfortunately - as I said in the other thread - that doesn't work neither for me... :( Maybe I did something wrong in my code?
Here's the activity definition in my AndroidManifest.xml:
        [...]
        <activity android:name=".NfcTest" android:clearTaskOnLaunch="true" android:alwaysRetainTaskState="true" android:finishOnTaskLaunch="true"></activity>
        [...]

Can anyone help me with this problem?
Maybe you NFC guy? Maybe I only understand something wrong on your idea or mixed something up in my code...? :/

A: try this
        Intent intent = new Intent().setClass(this, NfcTest.class);

    TabSpec spec = tabHost.newTabSpec("nfctab").setIndicator("NFC").setContent(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    tabHost.addTab(spec);


text:
Q: regarding amortized analysis? I have read amortized analysis in coreman but unable to understand what it realy is.
i went through internet but unable to understand.please someone make me understand.thanks

A: The idea behind amortized analysis is based on the idea of amortization in economics: you spend more money now, in order to save money over time. For example: you spend an extra $500 to buy the car with a more modern, more fuel-efficient engine, and over time, you amortize those $500 by saving gas.
The way that amortized analysis differs from most other kinds, is that it looks at a whole sequence of operations, not a single operation.
For example, worst-case analysis would look at insertion into a dynamic array and say "if the array is full, you need to copy the entire array into a bigger array, therefore the worst-case step complexity of inserting into a dynamic array is Ο(n)".
Amortized worst-case analysis would say that resizing only happens very seldomly, and it actually buys you the possibility of doing insertions in Ο(1) for the foreseeable future. So, while the worst-case for one individual insertion is Ο(n), this worst-case will only appear Ο(1) times every Ω(n) operations, which means the cost of resizing the array is amortized over the lifetime of the array, so the overall amortized worst-case step complexity of inserting into a dynamic array is Ο(1).


text:
Q: Create a grid with set constraints I'm building a little grid which needs to be generative to 6x6, but it needs to conform to 4 key constraints. Currently it conforms to 3. I can't work out how to manage the fourth.
001001
101101
010110
110010
001101

So what has to happen here is that:

*

*For each row there can't be more than 2 numbers of the same type consecutively

*the numbers are picked randomly

*for each column there can't be more than 2 numbers of the same type consecutively

*there can be a maximum of 3 of each type of number going by column or row

Here is the current code:
// JavaScript Document
$(document).ready(function () {
    var grid = new anyGrid(6, 6);
    for (var i = 0; i < grid.length; i++) {
        var printIt = "";
        for (var j = 0; j < grid[0].length; j++) {
            printIt += grid[i][j] + "  ";

        }
        console.log(printIt);
    }

});

function anyGrid(rows, cols) {
    var grid = [];
    for (var i = 0; i < rows; i++) {
        grid.push(new Array(cols));
    }
    var row = 0;
    for (var col = 0; col - row < cols; col++) {
        for (var r = row; r >= 0 && col - r < cols;) {
            setBit(grid, r, col - r--);
        }
        if (row < rows - 1) row++;
    }
    return grid;
}

function setBit(grid, row, col) {
    var vInd = calcVerticalIndicator(grid, row, col);
    var hInd = calcHorizontalIndicator(grid, row, col);
    if (isPartiallyRestricted(vInd, hInd)) {
        grid[row][col] = flip(vInd);
    } else if (isFullyRestricted(vInd, hInd)) {
        grid[row][col] = vInd;
        grid[row - 1][col] = flip(vInd);
    } else {
        grid[row][col] = Math.abs(vInd) <= 1
            ? flip(vInd)
            : Math.abs(hInd) <= 1 ? flip(hInd) : anyBit();
    }
}

function isPartiallyRestricted(vInd, hInd) {
    return vInd == hInd;
}

function isFullyRestricted(vInd, hInd) {
    return vInd + hInd == 1;
}

function calcVerticalIndicator(grid, row, col) {
    return calcIndicator(grid, row - 1, col, row - 2, col, 2);
}

function calcHorizontalIndicator(grid, row, col) {
    return calcIndicator(grid, row, col - 1, row, col - 2, 4);
}

function calcIndicator(grid, row1, col1, row2, col2, unrestricted) {
    try {
        return grid[row1][col1] * grid[row2][col2] + (grid[row1][col1] - grid[row2][col2]) * unrestricted;
    } catch (e) {
        return unrestricted;
    }
}

function anyBit() {
    return getRandomInt(0,1);
}

function flip(bit) {
    return bit == 0 ? 1 : 0;
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

The problem:
Currently it satisfies 3 of the 4 conditions, but what is required is that there are not more than 3 of each number in any row or column. How do I amend my code to make this possible?
example outputs:
0  1  1  0  1  0
1  1  0  0  1  0
1  0  1  1  0  1  (violation of 4 1s)
0  0  1  0  0  1  (violation of 4 0s)
1  1  0  0  1  0
1  1  0  1  1  0  (violation of 4 1s)
^  ^     ^  ^  ^
Violations

0  0  1  0  1  1
0  1  1  0  1  1   (violation of 4 1s)
1  0  0  1  0  0   (violation of 4 0s)
0  0  1  0  0  1
1  1  0  0  1  1   (violation of 4 1s)
1  1  0  1  1  0   (violation of 4 1s)
         ^  ^  ^
      Violations

A: This seems to work. Not sure if it is exactly what you are looking for since I removed the horizontal and vertical indicators, but seems to be able to generate a random grid with your constraints. I kept track of the number of times a character/bit appeared in row/col through the usedNumbers object.
I tried to keep a simplistic approach (i.e. an if statement for each of your listed constraints)... I tried to make it configurable for rows/cols in the grid along with "available characters" for the grid values (in case you want to expand). Of course, some solutions won't be possible since you might repeat more than 3 characters if the alphabet is too small and the grid too large (e.g. 0,1 bits for a 7x7). Here is the jsfiddle.
(function () {
    //Polyfill for Array.indexOf... Needed for older browsers.
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement, fromIndex) {
          if ( this === undefined || this === null ) {
            throw new TypeError( '"this" is null or not defined' );
          }

          var length = this.length >>> 0; // Hack to convert object.length to a UInt32

          fromIndex = +fromIndex || 0;

          if (Math.abs(fromIndex) === Infinity) {
            fromIndex = 0;
          }

          if (fromIndex < 0) {
            fromIndex += length;
            if (fromIndex < 0) {
              fromIndex = 0;
            }
          }

          for (;fromIndex < length; fromIndex++) {
            if (this[fromIndex] === searchElement) {
              return fromIndex;
            }
          }

          return -1;
        };
    }

    //availableBits to be used to determine the "alphabet" of characters to generate.
    var availableBits = [0, 1];
    var availLen = availableBits.length;
    //usedNumbers to keep track of how many were used in rows/cols.
    var usedNumbers;

    //How many times to try to generate a grid before failing.
    var numTries = 30;
    var currentTries = 1;
    var success = false;

    //Grid config
    var grid;
    var rows = 6;
    var cols = 6;
      var vThresh = rows/2;
      var hThresh = cols/2;

    //Impossible to generate a solution due to constraint 4. Pigeon-hole principle.
    if (rows / availLen > vThresh || cols / availLen > hTresh) {
        throw new Error("Need to shrink the grid size or add availableBits. There will be more than 3 characters in a row or column.");
    }

    //Try to generate the grid.
    while (!success && currentTries <= numTries) {
        try {
            grid = new anyGrid(rows, cols);
            success = true;
        }
        catch(e) {
            currentTries++;
            if (currentTries > numTries) {
                console.error(e.message);
                console.log("Could not generate anygrid after " + numTries + " attempts.");
            }
        }
    }

    if (success) {
        console.log("Generated anygrid after " + currentTries + " attempts.");
        printGrid(grid);
    }

    function printGrid (grid) {
        for (var i = 0; i < grid.length; i++) {
            var printIt = "";
            for (var j= 0; j < grid[0].length; j++) {
                printIt += grid[i][j] + "   ";
            }
            console.log(printIt);
        }
    }

    function anyGrid (rows, cols) {
        var grid = [];

        //set used numbers
         usedNumbers = {vNumbers: new Array(rows), hNumbers: new Array(cols)};

        for (var i = 0; i < rows; i++) {
            grid.push(new Array(cols));
        }

        var row = 0;
        for (var col = 0; col - row < cols; col++) {
            for (var r = row; r >= 0 && col - r < cols;) {
                setBit(grid, r, col - r--);
            }
            if (row < rows - 1) row++;
        }

        return grid;
    };

    //Complies to the 4 constraints:
    //No 2 numbers consecutively in a row
    //No 2 numbers consecutively in a column
    //Use random when able
    //No more than 3 of a number in a column or row
    function setBit (grid, row, col) {
        var needRandom = true;
        var bit;
        //"Clone" the availableBits to be able to remove characters when calling flip.
        var availClone = availableBits.slice();

        //Constraint 1: First check previous 2 rows
        if ((row - 2) >= 0 && grid[row - 2][col] === grid[row - 1][col]) {
            //Needs to flip
            bit = flip(grid[row - 1][col], availClone);

            needRandom = false;
        }
        //-------------------------------

        //Constraint 2: Check previous 2 cols
        else if ((col - 2) >= 0 && grid[row][col - 2] === grid[row][col - 1]) {
            //Needs to flip
            bit = flip(grid[row][col - 1], availClone);

            needRandom = false;
        }
        //---------------------------------

        //Constraint 3: Attempt a random
        if (needRandom) {
            bit = anyBit(availClone);
        }
        //-------------------------------

        //Constraint 4: Flip if constraint 4 is now violated.
        var vNumber = usedNumbers.vNumbers[row] || {};
        var hNumber = usedNumbers.hNumbers[col] || {};

        while (availClone.length && (vNumber[bit] >= vThresh || hNumber[bit] >= hThresh)) {
            bit = flip(bit, availClone);
        }
        //-------------------------------------

        //Set grid value and update vNumber and hNumber to be used in further iterations.
        grid[row][col] = bit;
        vNumber[bit] = vNumber[bit] + 1 || 1;
        hNumber[bit] = hNumber[bit] + 1 || 1;
        usedNumbers.vNumbers[row] = vNumber;
        usedNumbers.hNumbers[col] = hNumber;
        //----------------------------------
    };

    //Removes a bit from availableBits array and looks to return another random bit.
    function flip (bit, availableBits) {
        var index = availableBits.indexOf(bit);
        //Remove bit from the available bits.
        availableBits.splice(index, 1);

        var length = availableBits.length;

        if (length > 0) {
            //Try another random character
            return anyBit(availableBits);
        }
        //We cannot construct the grid, no more availble characters/bits
        else {
            throw new Error("Could not generate any grid for current configurations. Try again or expand the available characters.");
        }
    };

    //Returns a random bit from the availableBits array.
    function anyBit (availableBits) {
        var length = availableBits.length;
        var randomIndex = getRandomInt(0, length - 1);
        return availableBits[randomIndex];
    };

    //Returns a random integer between min and max.
    function getRandomInt (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };
}());

Edit: Use vThresh and hThresh and set them to rows/2 and cols/2 respectively. Code and fiddle updated.