text:
Q: How to create a new "time difference" column from start and finish time columns in an R table I have been given a table of data to analyse.
I have a column with start times and a column with finish times given in 3 or 4 digits, example: 3:40pm is 1540, 7:25am is 725.
How can I obtain a new column in my table with the difference of these times, given in minutes?
There are over 2000 entries.
Thanks for any help.
structure(list(schedtime = c(1455L, 1640L, 1245L, 1715L, 1039L,
840L), deptime = c(1455L, 1640L, 1245L, 1709L, 1035L, 839L),
distance = c(184L, 213L, 229L, 229L, 229L, 228L), flightnumber =
c(5935L,
6155L, 7208L, 7215L, 7792L, 7800L), weather = c(0L, 0L, 0L,
0L, 0L, 0L), dayweek = c(4L, 4L, 4L, 4L, 4L, 4L), daymonth = c(1L,
1L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")

This is an example of the dataset (Im unsure are to why there are L's after each number, these are not shown in the table). I want, in minutes, deptime (finish) - schedtime (start).
Given the new column, there are 2 values with a schedtime before midnight and a deptime after midnight, for example schedtime 2120 and deptime 0010. The answer to this is given as -1270, considering it to be an extremely early departure. How could I change this to be calculated as +170, a late departure?

A: dat <- data.frame(c(1540,1820,1330,545,100),c(1850,2150,2325,1330,101))
60*(floor(dat[,2]/100) - floor(dat[,1]/100)) - dat[,1] %% 100 + dat[,2] %% 100

Taking the floor of the the hundreds gives the hours. Taking the difference and multiplying by 60 gives the minutes from the difference of the hours. Then you can subtract the original minutes and add the final minutes to get total minutes passed.

A: You can use library lubridate to find the difference in minutes . Hope this helps. lubridate provides very good functionality for time related data.
library(lubridate)
df$deptime_new <- minutes(df$deptime-df$schedtime)

Data
df <- structure(list(schedtime = c(1455L, 1640L, 1245L, 1715L, 1039L,
                                   840L), deptime = c(1455L, 1640L, 1245L, 1709L, 1035L, 839L),
                     distance = c(184L, 213L, 229L, 229L, 229L, 228L), flightnumber =
                       c(5935L,
                         6155L, 7208L, 7215L, 7792L, 7800L), weather = c(0L, 0L, 0L,
                                                                         0L, 0L, 0L), dayweek = c(4L, 4L, 4L, 4L, 4L, 4L), daymonth = c(1L,
                                                                                1L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")

A: Efficient way for larger dataset-
data.table::setDT(dt)[,time_diff:=minutes(deptime-schedtime)]

> dt
   schedtime deptime distance flightnumber weather dayweek daymonth time_diff
1:      1455    1455      184         5935       0       4        1        0S
2:      1640    1640      213         6155       0       4        1        0S
3:      1245    1245      229         7208       0       4        1        0S
4:      1715    1709      229         7215       0       4        1    -6M 0S
5:      1039    1035      229         7792       0       4        1    -4M 0S
6:       840     839      228         7800       0       4        1    -1M 0S

EDIT- (To handle cases like 1730 - 1600 = 130 mins ( Actually, it is 90 mins).
library(data.table)
library(stringr)
setDT(dt)
dt[,schedtime:=str_pad(schedtime, 4, pad = "0")]
dt[,deptime:=str_pad(deptime, 4, pad = "0")]

dt[,time_diff:=difftime(as.ITime(strptime(x = schedtime, format = "%H%M")),as.ITime(strptime(x = deptime, format = "%H%M")),units = "mins")]

> dt
   schedtime deptime distance flightnumber weather dayweek daymonth time_diff
1:      1455    1455      184         5935       0       4        1    0 mins
2:      1640    1640      213         6155       0       4        1    0 mins
3:      1245    1245      229         7208       0       4        1    0 mins
4:      1715    1709      229         7215       0       4        1    6 mins
5:      1039    1035      229         7792       0       4        1    4 mins
6:      1730    1600      228         7800       0       4        1   90 mins

A: I have the same query, Is there a way to calculate the time difference of times in a column and display the answers in a new column in minutes


text:
Q: Python Selenium webscraping of Tableau Public: how to assign favourites to workbook? I have  written my first Selenium script to practise webscraping in Python. The idea is to scrape all workbooks, views and favourites from a Tableau Public profile. I managed to extract those three key variables, but I don't know how to assign favourites to their respective workbooks since not all workbooks have at least one favourite.
For example "Skyler on Broadway" has no favourites, but if I were to match workbooks and favourites in a dictionary, it would pull in the next best value, namely 4.
f.text != "" only removes empty values at the end of the list.
What's the best way to approach this problem?
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome(executable_path=r',mypath')

driver.get("https://public.tableau.com/profile/skybjohnson#!/")

#load entire website:

while True:

   try:
       show_more = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.ID, "load-more-vizzes")))
       driver.find_element_by_id("load-more-vizzes")
       driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
       WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.ID, "load-more-vizzes")))

   except Exception as e:
       print(e)
       break

#get workbook titles
titles = driver.find_elements_by_class_name("workbook-title")

workbook_titles = [i.text for i in titles if i.text != ""]
print(workbook_titles)

#get number of views per workbook
views = driver.find_elements_by_class_name('workbook-view-count')

workbook_views = [int(v.text.split()[0]) for v in views if v.text != ""]
print(workbook_views)

#get number of favourites per workbook
favs = driver.find_elements_by_xpath('//SPAN[@ng-bind="controller.workbook.numberOfFavorites"]')

workbook_favs = [f.text for f in favs if f.text != ""]
print(workbook_favs)

A: First you can get all Vizzes and then get children title, views and favorites. Also you have to check if views count and favorites are exist. You can find improved scroll and correct way to get views count (0 if no views) and favorites (0 if no favorites):
wait = WebDriverWait(driver, 10)
with driver:
    driver.get("https://public.tableau.com/profile/skybjohnson#!/")

    wait.until(EC.presence_of_element_located((By.ID, "load-more-vizzes")))
    while driver.find_element_by_id("load-more-vizzes").is_displayed():
        driver.execute_script("arguments[0].scrollIntoView()", driver.find_element_by_id("load-more-vizzes"))

    vizzes = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".viz-container li.media-viz")))
    for viz in vizzes:
        if not viz.is_displayed():
            continue

        title = viz.find_element_by_css_selector('[ng-bind="controller.workbook.title"]').text

        views_count_list = viz.find_elements_by_css_selector('[ng-bind="controller.workbook.viewCount"]')
        views_count = views_count_list[0].text if len(views_count_list) > 0 else 0

        number_of_favorites_list = viz.find_elements_by_css_selector('[ng-bind="controller.workbook.numberOfFavorites"]')
        number_of_favorites = number_of_favorites_list[0].text if len(number_of_favorites_list) > 0 else 0

        print(title, views_count, number_of_favorites)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this not a stopping time? I am going through Shreve's Stochastic Calculus book and he has a random time $\rho$ defined as follows:
$$\rho(HH) = 0, \quad \rho (HT) = 0, \quad \rho(TH) = 1, \quad \rho(TT) = 2$$
which he claims is not a stopping time. I was under the impression that this is, as $\rho(HX) = 0$, regardless of time outcome of $X$. Would anyone be able to clear up where I have misunderstood? Thanks.

A: It is not a stopping time because $\{\omega : \rho(\omega) \le 1 \} = \{HH,HT,TH\}$ is not in $\mathcal F_1 = \{\emptyset,\Omega,\{HH,HT\},\{TH,TT\}\}.$


text:
Q: Create pdf with tooltips in R Simple question: Is there a way to plot a graph from R in a pdf file and include tooltips?

A:
Simple question: Is there a way to plot a graph from R in a pdf file and include tooltips?

There's always a way.  But the devil is in the details, so the real question is: are you willing to get your hands dirty?
PDF does support tooltips for certain kinds of objects such as hyperlinks.  So, if there is a way to insert raw PDF statements indicating there should be a hyperlink-like object at some position in your plot, then there is a way to pop up a tooltip.
Now, the only way I know of to generate and compile raw PDF statements is to create the document using TeX.  There are definitely other ways to do it, but this is the one I am familiar with.  The following examples use a graphics device that Cameron Bracken and I wrote, the tikzDevice, to render R graphics to LaTeX code.  The tikzDevice has preliminary support for injecting arbitrary LaTeX code into the graphics output stream through the tikzAnnotate function---we will be using this to drop PDF callouts into the plot.
The steps involved are:

*

*Set up a LaTeX macro to generate the PDF commands required to produce a callout.

*Set up an R function that uses tikzAnnotate to invoke the LaTeX macro at specific points in the plot.

*???

*Profit!

In the examples that follow, one major caveat is attached to step 2.  The coordinate calculations used will only work with base graphics, not grid graphics such as ggplot2.

Simple Tooltips
Step 1
The tikzDevice allows you to create R graphics that include the execution of arbitrary LaTeX commands.  Usually this is done to insert things like $\alpha$ into plot titles to generate greek letters, α, or complex equations.  Here we are going to use this feature to invoke some raw PDF voodoo.
Any LaTeX macros that you wish to be available during the generation of a tikzDevice graphic need to be defined up-front by setting the tikzLatexPackages option.  Here we are going to append some stuff to that declaration:
require(tikzDevice)  # So that default options are set
options(tikzLatexPackages = c(
  getOption('tikzLatexPackages'),  # The original contents: required stuff
    # Avert your eyes for a sec, all will be explained below
    "\\def\\tooltiptarget{\\phantom{\\rule{1mm}{1mm}}}",
    "\\newbox\\tempboxa\\setbox\\tempboxa=\\hbox{}\\immediate\\pdfxform\\tempboxa \\edef\\emptyicon{\\the\\pdflastxform}",
    "\\newcommand\\tooltip[1]{\\pdfstartlink user{/Subtype /Text/Contents  (#1)/AP <</N \\emptyicon\\space 0 R >>}\\tooltiptarget\\pdfendlink}"
))

If all that quoted nonsense were to be written out as LaTeX code by someone who cared about readability, it would look like this:
\def\tooltiptarget{\phantom{\rule{1mm}{1mm}}}

\newbox\tempboxa
\setbox\tempboxa=\hbox{}
\immediate\pdfxform\tempboxa
\edef\emptyicon{\the\pdflastxform}

\newcommand\tooltip[1]{%
  \pdfstartlink user{%
    /Subtype /Text
    /Contents  (#1)
    /AP <<
      /N \emptyicon\space 0 R
    >>
  }%
  \tooltiptarget%
  \pdfendlink%
}

For those programmers who have never taken a walk on the wild side and done some "programming" in TeX, here's a blow-by-blow for the above code (as I understand it anyway, TeX can get very weird---especially when you get down in the trenches with it):

*

*Line 1: Define an object, tooltiptarget, which is non-visible (a phantom) and is a 1mm x 1mm rectangle (a rule).  This will be the onscreen area which we will use to detect mouseovers.

*Line 2: Create a new box, which is like a "page fragment" of typset material. Can contain pretty much anything, including other boxes (sort of like an R list).  Call it tempboxa.

*Line 3: Assign the contents of tempboxa to contain an empty box that arranges its contents using a horizontal layout (which is unimportant, could have used a vbox or other box).

*Line 4: Create a PDF Form XObject using the contents of tempboxa.  A Form XObject can be used by PDF files to store graphics, like logos, that may be used over and over.  Here we are creating a "blank icon" that we can use later to cut down on visual clutter.  TeX defers output operations, like writing objects to a PDF file, until certain conditions have been met---such as a page has filled up.  Immediate makes sure this operation is not deferred.

*Line 5: This line captures an integer value that serves as a reference to the PDF XObject we just created and assigns it the name emptyicon.

*Line 6: Starts the definition of a new macro called tooltip that takes 1 argument which is referred to in the body of the macro as #1.  Each line in the macro ends with a comment character, %, to keep TeX from noticing the newlines that have been added for readability (newlines can have strange effects inside macros).

*Line 7: Output raw PDF commands (pdfstartlink). This begins the creation of a new PDF annotation object (\Type \Annot) of which there are about 20 different subtypes---among them are hyperlinks.  Every line following this contains raw PDF markup with a couple of TeX macros.

*Line 8: Declare the annotation subtype we are going to use.  Here I am going with a plain Text annotation such as a comment or sticky note.

*Line 9: Declare the contents of the annotation.  This will be the contents of our tooltip and is set to #1, the argument to the tooltip macro.

*Lines 10-12:  Normally text annotations are marked by an icon, such as a sticky note, to highlight their location in the text.  This behavior will cause a visual mess if we allow it to splatter little sticky notes all over our graphs.  Here we use an appearance array (\AP << >>) set the "normal" annotation icon (\N) to be the blank icon we created earlier.  The integer we stored in emptyicon along with 0 R forms a reference to the Form XObject we made on Line 4 using an empty box.

*Line 14: If we were making a normal hyperlink, here is where the text/image/whatever would go that would serve as the link body.  Instead we insert tooltiptarget, our invisible phantom object which does not show up on the screen but does react to mouseovers.
Step 2
Allright, now that we have told LaTeX how to create tooltips, it is time to make them usable from R.  This involves writing a function that will take coordinates on our graph, such as (1,1), and convert them into canvas or "device" coordinates.  In the case of the tikzDevice the required measurement is "TeX points" (1/72.27 of an inch) from the absolute bottom left of the plotting area.  Fortunately for base graphics, there are handy functions to calculate this for us.  Grid graphics work differently, so the approach taken in the examples here won't work for them.
The final task for our R function is to call tikzAnnotate to insert a TikZ "node" into the output stream that is located at the coordinates we computed.  Nodes can contain arbitrary TeX commands, in this case we will be calling upon tooltip.
Here is an R function that contains the above functionality:
place_PDF_tooltip <- function(x, y, text){

  # Calculate coordinates
  tikzX <- round(grconvertX(x, to = "device"), 2)
  tikzY <- round(grconvertY(y, to = "device"), 2)

  # Insert node
  tikzAnnotate(paste(
    "\\node at (", tikzX, ",", tikzY, ") ",
    "{\\tooltip{", text, "}};",
    sep = ''
  ))

  invisible()

}

Step 3
Try it out on a plot:
# standAlone creates a complete LaTeX document. Default output makes
# stripped-down graphs ment for inclusion in other LaTeX documents
tikz('tooltips_ahoy.tex', standAlone = TRUE)
plot(1,1)
place_PDF_tooltip(1,1, 'Hello, World!')
dev.off()

require(tools)
texi2dvi('tooltips_ahoy.tex', pdf = TRUE)

Step 4
Behold the result (download a pdf):

Advanced Tooltips
Step 1
So, now that we have simple tooltips out of the way, why not crank it to 11?  In the previous example, we used an empty hbox to get rid of the tooltip icon.  But what if we had put something in that box, like text or a drawing? And what if there was a way to make it so that the icon only appeared during mouseover events?
The following TeX macro is a little rough around the edges, but it shows that this is possible:
\usetikzlibrary{shapes.callouts}
\tikzset{tooltip/.style = {
  rectangle callout,
  draw,
  callout absolute pointer = {(-2em, 1em)}
}}

\def\tooltiptarget{\phantom{\rule{1mm}{1mm}}}
\newbox\tempboxa

\newcommand\tooltip[1]{%
  \def\tooltipcallout{\tikz{\node[tooltip]{#1};}}%

  \setbox\tempboxa=\hbox{\phantom{\tooltipcallout}}%
  \immediate\pdfxform\tempboxa%
  \edef\emptyicon{\the\pdflastxform}%

  \setbox\tempboxa=\hbox{\tooltipcallout}%
  \immediate\pdfxform\tempboxa%
  \edef\tooltipicon{\the\pdflastxform}%

  \pdfstartlink user{%
    /Subtype /Text
    /Contents  (#1)
    /AP <<
      /N \emptyicon\space 0 R
      /R \tooltipicon\space 0 R
    >>
  }%
  \tooltiptarget%
  \pdfendlink%
}

The following modifications have been made compared to the simple callout.

*

*The shapes.callouts library is loaded which contains templates for TikZ to use when drawing callout boxes.

*A tooltip style is defined which contains some TikZ graphics boilerplate. It specifies a rectangular callout box that is to be visible (draw). The callout absolute pointer business is a hack because I've had too many beers by this point to figure out how to place annotation icons using dynamically generated PDF primitives.  This relies on the default anchoring of icons at their upper left corner and so pulls the pointer of the callout box toward that location.  The result is that the boxes will always appear to the lower right of the pointer and if the callout text is long enough, they won't look right.

*Inside the macro, the tooltip is generated using a one-shot tikz command that is stuffed into the tooltipcallout macro. A form XObject is generated from tooltipcallout and assigned to tooltipicon.

*emptyicon is also dynamically generated by evaluating tooltipcallout inside of phantom.  This is required because the size of the default icon apparently sets the viewport available for the rollover icon.

*When generating PDF commands, a new row is added to the /AP array, /R for rollover, that uses the XObject referenced by tooltipicon.
The ready to consume R version is:
require(tikzDevice)
options(tikzLatexPackages = c(
  getOption('tikzLatexPackages'),
  "\\usetikzlibrary{shapes.callouts}",
  "\\tikzset{tooltip/.style = {rectangle callout,draw,callout absolute pointer = {(-2em, 1em)}}}",
  "\\def\\tooltiptarget{\\phantom{\\rule{1mm}{1mm}}}",
  "\\newbox\\tempboxa",
  "\\newcommand\\tooltip[1]{\\def\\tooltipcallout{\\tikz{\\node[tooltip]{#1};}}\\setbox\\tempboxa=\\hbox{\\phantom{\\tooltipcallout}}\\immediate\\pdfxform\\tempboxa\\edef\\emptyicon{\\the\\pdflastxform}\\setbox\\tempboxa=\\hbox{\\tooltipcallout}\\immediate\\pdfxform\\tempboxa\\edef\\tooltipicon{\\the\\pdflastxform}\\pdfstartlink user{/Subtype /Text/Contents  (#1)/AP <</N \\emptyicon\\space 0 R/R \\tooltipicon\\space 0 R>>}\\tooltiptarget\\pdfendlink}"
))

Step 2
The R-level code is unchanged.
Step 3
Let's try a slightly more complicated graph:
tikz('tooltips_with_callouts.tex', standAlone = TRUE)

x <- 1:10
y <- runif(10, 0, 10)
plot(x,y)
place_PDF_tooltip(x,y,x)

dev.off()

require(tools)
texi2dvi('tooltips_with_callouts.tex', pdf = TRUE)

Step 4
The result (download a PDF):

As you can see, there is an issue with both the tooltip and the callout being displayed.  Setting \Contents () so that the tooltip has an empty string won't help anything.  This can probably be solved by using a different annotation type, but I'm not going to spend any more time on it at the moment.

Caveats

*

*Lots of TeX commands contain backslashes, you will need to double the backslashes when expressing things in R code.

*Certain characters are special to TeX, such as _, ^, %, complete list here, you will need to ensure these are properly escaped when using the tikzDevice.

*Even though PDF is supposed to be superior to HTML in that it has a consistant rendering across platforms, your mileage will vary significantly depending on which viewer is being used.  The screenshots were taken in Acrobat 8 on OS X, Preview also did a passable job but did not render the rollover callout.  On Linux, xpdf didn't render anything and okular showed a tooltip, but did not suppress the tooltip icon and displayed a stock icon that looked a little garish in the middle of a plot.
Alternative Implementations
cooltooltips and fancytooltips are LaTeX packages that provide tooltip functionality that could probably be used from the tikzDevice.  Some ideas used in the above examples were taken from cooltooltips.
Concluding Thoughts
Was this worth it? Well, by the end of the day I did learn two things:

*

*I am not a PDF expert and I had to search a couple mailing lists and digest some parts of a 700+ page specification to even answer the question "is this possible?" let alone come up with an implementation.

*I am not a SVG expert and yet I know that tooltips in SVG is not a question of "is this possible?" but rather "how sexy do you want it to look?".
Given that observation, I say that it is getting to be time for PDF to ride off into the sunset and take it's 700 page spec with it.  We need a new page description markup language and personally I'm hoping SVG Print will be complete enough to do the job.  I would even accept Adobe Mars if the specification is accesible enough.  Just give us an XML-based format that can exploit the full power of today's JavaScript libraries and then some real innovation can begin.  A LuaTeX backend would be a nice bonus.

References

*

*tikzDevice: A device for outputting R graphics as LaTeX code.

*comp.text.tex: Source of much insight into esoteric TeX details.  Posts by Herbert Voß and Mycroft provided implementation ideas.

*The pdfTeX manual: Source of information concerning TeX commands that can generate raw PDF code, such as \pdfstartlink

*TeX by Topic: Go-to manual for low-level TeX details such as how \immediate actually works.

*The Adobe PDF Specification: The lair of details concerning PDF primitives.

*The TikZ Manual: Quite possibly the finest example of open source documentation ever written.

A: Well, not pdf, but you could include tooltips (among ohers) in svg format with SVGAnnotation  or RSVGTipsDevice package.

A: The pdf2 package works fine for me. (https://r-forge.r-project.org/R/?group_id=193). You can just include a 'popup' in the regular text command. It's not current as of 2.14, but I imagine he'll get round to it before too long.
text(x,y,'hard copy text',popup='tooltip text')


text:
Q: How do I test if all the variables are present inside the settings? I am working with Fastapi and I would like to include a test to check if all settings variables exist in the env file (which currently goes to read directly into the pipeline), I would like it not to create the container (last step) if it doesn't pass the tests, but it happens that the tests pass and I end up with an environment variable not set or forgotten.
I use the .env file to retrieve the variables
My setting file (I removed some variables so as not to paste in too much stuff, fields could not match, some I made up):

class Settings(BaseSettings):
    app_name: str
    kafka_broker: str
    healthcheck_topic: str = "_healthcheck"

    # Apicurio
    apicurio_uri: str
    apicurio_journal_topic: str = "kafkasql-journal"

    business_rules_topic: str = "_message"

    jwt_secret: str
    jwt_expiration_sec: int = 24 * 60 * 60  # A day
    _jwt_algorithm: str = PrivateAttr(default_factory=lambda: "HS256")

    admin_username: str
    admin_password: str

    azure_auth_url: str

    class Config:
        try:
            env_file = '.env'
            env_file_encoding = 'utf-8'
            case_sensitive = False
        except:
            env_file = '.env_local'
            env_file_encoding = 'utf-8'
            case_sensitive = False

    def __init__(self, **data):
        super().__init__(**data)

        self._postgresql_conn = make_url(self.postgresql_conn_url)

    @property
    def postgresql_conn(self) -> URL:
        return self._postgresql_conn

    @property
    def jwt_algorithm(self) -> str:
        return self._jwt_algorithm

    @validator('redis_user', 'redis_password')
    def field_is_not_empty_if_not_null(cls, v):
        if v is not None and len(v) == 0:
            raise ValueError("Field cannot be empty string")

        return v

    _fields_not_empty = validator(
        'kafka_broker',
        'app_name',
        'apicurio_journal_topic',
        'business_rules_topic',
        'jwt_secret',
        allow_reuse=True
    )(field_not_empty)

    _fields_are_positive = validator(
        'cache_short_expiration_hours',
        'cache_medium_expiration_hours',
        'cache_long_expiration_hours',
        'jwt_expiration_sec',
        allow_reuse=True
    )(field_non_zero_positive)

    _fields_are_uri = validator(
        'apicurio_uri',
        'ticket_uri',
        allow_reuse=True
    )(field_is_uri)

    def build_api_definition(self) -> TicketApiDefinition:
        return TicketApiDefinition(

            webservice_endpoint=self.ticket_webservice_path,
            webservice_path=self.ticket_webservice_path,

            create_session=self.ticket_webservice_create_session_endpoint,

        )

@lru_cache
def get_settings():
    return Settings()

At the moment I wrote this simple test, but maybe it is not enough:
from gateway_api.settings import get_settings
from gateway_api.settings import Settings

def test_00_check_env_variables():
    sett = get_settings()
    assert isinstance(sett, Settings)

Do you have any advice for me? Or is this test sufficient?
Thank you


text:
Q: How to change a QLineEdit bullet's color in password mode I would like to have a "Confirm password" line edit whose bullet points turn to red when the passwords don't match. Is there a way to change the bullet color?
My current attempt is:
class CreateUserDialog(QDialog):

    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        layout.addSpacing(30)
        layout.addWidget(QLabel("Create a new account", self))

        self.username_edit = QLineEdit(parent=self)
        self.username_edit.setPlaceholderText("Username")
        layout.addWidget(self.username_edit)

        self.pwd_edit = QLineEdit(parent=self)
        self.pwd_edit.setPlaceholderText("Password")
        self.pwd_edit.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.pwd_edit)

        self.confirm_pwd_edit = QLineEdit(parent=self)
        self.confirm_pwd_edit.setPlaceholderText("Confirm password")
        self.confirm_pwd_edit.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.confirm_pwd_edit)

        self.pwd_edit.textChanged.connect(self.checkPasswordMatches)
        self.confirm_pwd_edit.textChanged.connect(
            self.checkPasswordMatches)

    def checkPasswordMatches(self, text):
        if not self.pwd_edit.text() == self.confirm_pwd_edit.text():
            palette = qt.QPalette()
            palette.setColor(qt.QPalette.Text, qt.Qt.red)
            self.confirm_pwd_edit.setPalette(palette)
        else:
            # restore normal style
            self.confirm_pwd_edit.setPalette(
                self.username_edit.palette())

This actually works on the placeholder text, but not on the bullets when the user starts typing.

A: You can create a pyqtProperty that indicates that the password is valid or not.
from PyQt5 import QtCore, QtGui, QtWidgets

qss = '''
ValidationLineEdit[echoMode="2"][isValid="true"] {
    color: green;
}
ValidationLineEdit[echoMode="2"][isValid="false"] {
    color: red;
}
'''

class ValidationLineEdit(QtWidgets.QLineEdit):
    valid_length_changed = QtCore.pyqtSignal(int)

    def __init__(self, *args, **kwargs):
        valid_length = 0
        if kwargs.get("valid_length"):
            valid_length = kwargs.pop("valid_length")
        super(ValidationLineEdit, self).__init__(*args, **kwargs)
        self._valid_length_ = valid_length
        self.textChanged.connect(self.update_stylesheet)

    @QtCore.pyqtProperty(bool)
    def isValid(self):
        if self.valid_length == 0: return False
        return len(self.text()) == self.valid_length

    def update_stylesheet(self):
        self.style().unpolish(self)
        self.style().polish(self)

    def valid_length(self):
        return self._valid_length_

    def set_valid_length(self, lenght):
        if self._valid_length_ == lenght: return
        self._valid_length_ = lenght
        self.valid_length_changed.emit(lenght)

    valid_length = QtCore.pyqtProperty(int, fget=valid_length, fset=set_valid_length, notify=valid_length_changed)

class CreateUserDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(CreateUserDialog, self).__init__(parent)

        self.username_edit = QtWidgets.QLineEdit(placeholderText="Username")
        self.pwd_edit = QtWidgets.QLineEdit(placeholderText="Password", echoMode=QtWidgets.QLineEdit.Password)
        self.confirm_pwd_edit = ValidationLineEdit(placeholderText="Confirm password", echoMode=QtWidgets.QLineEdit.Password)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addSpacing(30)
        lay.addWidget(QtWidgets.QLabel("Create a new account"))
        lay.addWidget(self.username_edit)
        lay.addWidget(self.pwd_edit)
        lay.addWidget(self.confirm_pwd_edit)

        self.pwd_edit.editingFinished.connect(self.on_editingFinished)

    @QtCore.pyqtSlot()
    def on_editingFinished(self):
        self.confirm_pwd_edit.valid_length = len(self.pwd_edit.text())

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet(qss)
    w =  CreateUserDialog()
    w.show()
    sys.exit(app.exec_())


text:
Q: Getting unpredictable issue in QTP I'm trying to automate some web application using QTP and I have automated most of the modules. But in one module I'm facing an unpredictable issue that when we click the record hyperlink manually it fetches 3 rows of data, but it doesn't fetch any record when we do the same through QTP scripts.
Can some one help me on this, please?

A: It could be that the application is listening to an event that QTP doesn't replay.
See this answer on how to use Device Replay to solve this problem.


text:
Q: Get callback when ADMOB reward ad is closed without seeing whole ad in ios swift I am using reward admob ad in my project with latest sdk. How can i get proper callback that the user has closed the ad in between. I know there is a delegate method of fullscreencontentdelegate which has a function adDidDismiss but in that function i am doing some code block which i perform when i complete watching the ad and it just works fine but what if i closed the ad in between, because what happens is that whether i see the whole ad or not this delegate function gets called and there is no way to differentiate how would i proceed with complete and incomplete ad. Please help me with this.
video link
as in the video first time i am not watching the whole ad and i just close it then also the scratch card popup comes because of the delegate method being called, which i dont want to open and then i just watch the whole ad and get my reward which is working fine
My code snippet:
enum RewardAdType {
    case avatar, freeChips, scratchCard, chips250
}

typealias AD_COMPLETION_BLOCK = (_ success: Bool) -> ()

class RewardAdManager : NSObject
{
    //MARK: - PROPERTIES
    var rewardBasedVideoAd : GADRewardedAd? = nil
    var rewardValue = ""
    var type: RewardAdType? = nil
}

//MARK: - HELPERS
extension RewardAdManager
{
    func loadRewardedAd(vc: UIViewController, userId: String, type: RewardAdType, imageName: String? = nil, chipsCoin: String? = nil, completion: @escaping AD_COMPLETION_BLOCK)
    {
        self.type = type
        let adUnit = self.type == .avatar ? Constants.REWARD_AD_AVATAR_LIVE_ID : Constants.REWARD_AD_WINCHIPS_LIVE_ID

        let request = GADRequest()
        GADRewardedAd.load(withAdUnitID: adUnit, request: request) { [weak self] ad, error in

            guard let self = self, error == nil else {
                Helpers.hidehud()
                self?.type = nil
                self?.rewardBasedVideoAd = nil
                return
            }

            let serverSideVerificationOptions = GADServerSideVerificationOptions()
            serverSideVerificationOptions.userIdentifier = userId

            if type == .scratchCard {
                self.rewardValue = self.generateRandomRewardValue()
                serverSideVerificationOptions.customRewardString = self.rewardValue
            } else if type == .avatar {
                serverSideVerificationOptions.customRewardString = imageName
            } else if type == .freeChips {
                serverSideVerificationOptions.customRewardString = chipsCoin
            } else if type == .chips250 {
                serverSideVerificationOptions.customRewardString = "250"
            }

            self.rewardBasedVideoAd = ad
            self.rewardBasedVideoAd?.serverSideVerificationOptions = serverSideVerificationOptions
            self.rewardBasedVideoAd?.fullScreenContentDelegate = self

            self.showRewardedAd(viewController: vc, type: type, completion: completion)
        }
    }

    func showRewardedAd(viewController: UIViewController, type: RewardAdType? = nil, completion: @escaping AD_COMPLETION_BLOCK)
    {
        Helpers.hidehud()

        if let ad = self.rewardBasedVideoAd {
            self.type = type
            DispatchQueueHelper.delay {
                ad.present(fromRootViewController: viewController) {}
            }
            completion(true)
        } else {
            self.type = nil
            self.checkForSavedLanguage(viewController: viewController)
        }
    }

    func checkForSavedLanguage(viewController: UIViewController)
    {
        let lang = LanguageCode(rawValue: Defaults[.LangCode]) ?? .english
        viewController.showToast(msg: Constants.NO_ADS_MESSAGE.localizeString(string: lang))
    }

    func generateRandomRewardValue() -> String
    {
        var val = 0

        let random = Double.random(in: 0.1...1.0)

        if random < 0.20 {
            val = 150
        } else if random < 0.50 {
            val = 200
        } else if random < 0.70 {
            val = 250
        } else {
            val = 350
        }

        return val.toString()
    }
}

//MARK: - GADFullScreenContentDelegate
extension RewardAdManager : GADFullScreenContentDelegate {

    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error)
    {
        self.type = nil
        Helpers.hidehud()
        let lang = LanguageCode(rawValue: Defaults[.LangCode]) ?? .english
        let userInfo = ["msg":Constants.NO_ADS_MESSAGE.localizeString(string: lang)]
        NotificationCaller.shared.showLeaveMsg(userInfo: userInfo)
    }

    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd)
    {
        guard let type = self.type else { return }
        self.rewardBasedVideoAd = nil
        let userInfo: [String:RewardAdType] = ["type":type]
        NotificationCaller.shared.showRewardTypePopup(userInfo: userInfo)
    }
}


text:
Q: Can I use multiple same route guards one after another? For example,
router.beforeEach((to, from, next) => {
    ...
    ...
})
router.beforeEach((to, from, next) => {
    ...
    ...
})

The official documentation says:

Global before guards are called in creation order, whenever a
navigation is triggered.

Before guards are in plural here. But when I use multiple before guards only the first one is called but other are skipped.
The question is not only about the beforeEach but all the navigation guards.
The code with 2 beforeEach that doesn't work:
router.beforeEach((to, from, next) => {
  if (to.name !== 'Logon' && !localStorage.getItem('authToken')) {
    next({ name: 'Logon' })
  } else next()
})

router.beforeEach((to, from, next) => {
  if (to.name !== 'Logon' && localStorage.getItem('authToken')) {
    next({ name: 'Homepage' }) //тут будет логика проверки токена на сервере
  } else next()
})

A: This is not currently supported and does not seem like it will be. There are some workarounds mentioned in the thread though such as calling multiple guards within a single guard
https://github.com/vuejs/vue-router/issues/721


text:
Q: What does "$\operatorname{rot}[\vec{a} \times \vec{b}]$" mean? (from an article written in the $60$s) I saw in old article written in $60$'s a mathematical expression
$$\operatorname{rot}[\vec{a} \times \vec{b}]$$
What is the function of $\operatorname{rot}$ and what it means?

A: Maybe slipped through from a german text where "rot" stands for "rotation" or "rotor".  The english term is "curl":
$$\operatorname{rot}[a\times b] = \nabla\times(a\times b)$$

A: From looking at your equation it appears to be a Lorentz equation with the force on a charged particle of charge $Q$ in some kind of radial magnetic field $H_\mu$ with a magnetic vector potential of $\vec{\mu}\times\vec{r}/r^3$, and the mysterious "rot" would just be the usual curl of the magnetic field, $H=\nabla \times A$, where $A$ is the magnetic vector potential.


text:
Q: Offline Arcmap digitize map display on android Im quite new in arcmap map and i have been spending more than 2 week stuck in how to show map online offline.
I have tried the code is attached but when i run the application.It crashes nothing to show.
You can see my code and i also attached geodatabase file.
i follow this tutorial:
http://www.activeg.com/agBlog/android-running-an-arcgis-map-offline
And my geodatabase file is here
https://files.fm/u/q5xuznvy
I just want to thank you in advance to those who are willing to share.
MapView mMapView;
Geodatabase geodatabase;
private GeodatabaseFeatureTable geodatabaseFeatureTable;
private FeatureLayer featureLayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMapView = (MapView) findViewById(R.id.map); //Instantiates the MapView object
    LoadMap mLoadMap = new LoadMap(); //Runs the LoadMap class on another thread
    mLoadMap.execute(); //Calls the background thread
}

private class LoadMap extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        try { //Opens up the basemap.geodatabase file from it's location on the physical device
            Log.d("_EXC", "Loading File");
            geodatabase = new Geodatabase("/mnt/shared/Database/mygeodata.gdb");
            Log.d("_EXC", "File Loaded");
        } catch (FileNotFoundException e) {
            Log.d("_EXC", e.getMessage());
        } finally { //Takes each layer one by one from the Geodatabase and adds it to the MapView
            if (geodatabase == null){
                Log.d("_EXC", "File not Loaded");
            }
            for (int i = (geodatabase.getGeodatabaseTables().size()) - 1; i >= 0; i--) {
                geodatabaseFeatureTable = geodatabase.getGeodatabaseFeatureTableByLayerId(i);
                featureLayer = new FeatureLayer(geodatabaseFeatureTable);
                mMapView.addLayer(featureLayer);
            }
        }
        return null;
    }
}

}`


text:
Q: What is the easing jQuery effect slower at the end? I'm trying to generate the effect of a slot machine ring spinning who starts to slow down until it stops. I have three animations:

*

*The icon goes from current position to start position.

*The icon goes from start position to start position (complete circle).

*The icon goes from start position to new position.

The first and second animations have linear easing, but I don't know what should be the third one. I tried with (almost all) animations availables on jQuery UI library, but I don't get what I want.
Look:

PS: I didn't know how to ask this answer properly, please feel free to edit it and delete this message.

A: These graphs show you everything.
https://jqueryui.com/easing/


text:
Q: Trying to import csv to postgres through sequelize : TypeError: _sequelize2.default.import is not a function So I've got a barebones node backend API that I am making. As part of the seeding for the db it is connected to (postgres), I want to populate it from a csv.
I'm trying to import a csv file with the following columns into my postgres db called 'cities'.
I have defined the model and migrate file for the city.
When I am trying to make my "seed" file to populate the database with the csv rows, I get the error:
                                     ^

TypeError: _sequelize2.default.import is not a function
    at Object.<anonymous> (/Users/shawnelbaz/backend-coding-challenge/src/server/controllers/city.js:2:14)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at loader (/Users/shawnelbaz/backend-coding-challenge/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.<computed> [as .js] (/Users/shawnelbaz/backend-coding-challenge/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Module.require (internal/modules/cjs/loader.js:666:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/Users/shawnelbaz/backend-coding-challenge/src/server/seeders/seed.js:4:22)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at loader (/Users/shawnelbaz/backend-coding-challenge/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.<computed> [as .js] (/Users/shawnelbaz/backend-coding-challenge/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:824:10)
    at Object.<anonymous> (/Users/shawnelbaz/backend-coding-challenge/node_modules/babel-cli/lib/_babel-node.js:154:22)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:824:10)
    at internal/main/run_main_module.js:17:11

Ive tried this suggestion, but it didn't help: Sequelize create not a function?
seed.js
import fs from 'fs';
import csv from 'csv';
import sequelize from 'sequelize'
var adminCodeToZip = require('../controllers/city.js').adminCodeToZip;
const Cities = sequelize.import('../models/cities');

var input = fs.createReadStream('/Users/shawnelbaz/backend-coding-challenge/src/data/cities_canada-usa.tsv');
var parser = csv.parse({
    delimiter: '\t',
    columns: true
})

var transform = csv.transform(function(row) {
    var resultObj = {
        name: row['name'],
        country: row['country'],
        admin1: adminCodeToZip(row['admin1']),
        longitude: row['long'],
        latitude: row['lat'],
        population: row['population'],
    }
    console.log(resultObj);
    Cities.create(resultObj)
        .then(function() {
            console.log('Record created')
        })
        .catch(function(err) {
            console.log('Error encountered: ' + err)
        })
})

input.pipe(parser).pipe(transform)

city.js (service)
import sequelize from 'sequelize';
const City = sequelize.import('../models/cities');

class Cities {
  static async Create(req, res) {
    const { name, country, admin1, longitude, latitude, population } = req.body
    console.log(req.body);
    return await City
      .create({
        name,
        country,
        admin1,
        longitude,
        latitude,
        population
      })
      .then(city => res.status(201).send({
        message: `Your city ${name} has been created successfully `,
        book
      }))
    }
}

function adminCodeToZip(adminCode){
    switch(adminCode){
        case '01': return 'AB';
        case '02': return 'BC';
        case '03': return 'MB';
        case '04': return 'NB';
        case '05': return 'NL';
        case '07': return 'NS';
        case '08': return 'ON';
        case '09': return 'PE';
        case '10': return 'QC';
        case '11': return 'SK';
        case '12': return 'YT';
        case '13': return 'NT';
        case '14': return 'NU';
    }
}

export {Cities, adminCodeToZip}

cities.js (model)
export default (sequelize, DataTypes) => {
  const City = sequelize.define('cities', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    country: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    admin1: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    latitude: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    longitude: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    population: {
      type: DataTypes.INTEGER,
      allowNull: false,
    }
  });
  return City;
};

index.js (sequelize)
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;


text:
Q: ASP.NET Web API Help Page can't process Generic Type Controller I have a question about ASP.NET Web API HelpPages.
Usually HelpPages can generate the WebAPI by XMLDocumentation
Sample Code:
public class ValueControllerBase : ApiController
{
    /// <summary>
    /// Base Do
    /// </summary>
    public IEnumerable<string> Do()
    {
       return new string[] { "value1", "value2" };
    }
}

public class ValuesController : ValueControllerBase
{
    /// <summary>
    /// Testing API
    /// </summary>
    public string Get(int id)
    {
        return "value";
    }
}

this can generate successfully, like this:
API
GET api/Values/Get/{id}

Description
Testing API

API
POST api/Values/Do

Description
Base Do

but if I use a generic base controller, it will not generate the API Document.
Sample:
public class ValueControllerBase<T> : ApiController
{
    /// <summary>
    /// Base Do
    /// </summary>
    public IEnumerable<string> Do()
    {
        return new string[] { "value1", "value2" };
    }
}

public class ValuesController<String> : ValueControllerBase
{
    /// <summary>
    /// Testing API
    /// </summary>
    public string Get(int id)
    {
        return "value";
    }
}

If I use the code at the second section, HelpPages can generate the API document, but doesn't generate the API annotation. The difference between my two examples is just second section code use a generic type.
API
GET api/Values/Get/{id}

Description
Testing API

API
POST api/Values/Do

Description
null

In the method Do(), the annotation doesn't display compared with the first
Is there any solution to fix these problems?

A: I was able to solve this by adjusting some code in the XmlDocumentationProvider.
The original implemention of XmlDocumentationProvider.GetTypeName(Type) is the following:
private static string GetTypeName(Type type)
{
    string name = type.FullName;
    if (type.IsGenericType)
    {
        // Format the generic type name to something like: Generic{System.Int32,System.String}
        Type genericType = type.GetGenericTypeDefinition();
        Type[] genericArguments = type.GetGenericArguments();
        string genericTypeName = genericType.FullName;

        // Trim the generic parameter counts from the name
        genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
        string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
        name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames));
    }
    if (type.IsNested)
    {
        // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.
        name = name.Replace("+", ".");
    }

    return name;
}

I don't know why, but they attempt to create the type name for the xml lookup to include the actual generic attributes, rather than the generic type name itself (for example, they create Nullable{bool} rather than Nullable`1).  Only the generic name itself is defined in the xml file.
A simple change to the code gets it to name/reference the documentation for the generic class correctly:
....
if (type.IsGenericType)
{
    Type genericType = type.GetGenericTypeDefinition();
    name = genericType.FullName;
}
....

After making that change, the annotations began to display correctly for generics types, and for me, this didn't break anything else either.


text:
Q: Triangles generator program I'm trying to write a program in C++ that read from standard input some lines in the format "name;x;y". Each one represents a point in the Cartesian place and I want to print all the triangles that can be generated from them.
This is my code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

struct Point {
    string name;
    double x = 0, y = 0;
};

typedef Point Triangle[3];

vector<Point> ReadPoints();
vector<Triangle> GetTriangles(vector<Point> points);

int main() {
    auto points = ReadPoints();
    auto triangles = GetTriangles(points);

    for (auto beg = triangles.begin(); beg != triangles.end(); ++beg) {
        for (auto bg = begin(*beg); bg != end(*beg); ++bg) {
            cout << bg->name << " ";
        }
        cout << endl;
    }

}

vector<Point> ReadPoints() {
    vector<Point> points;

    string line;
    while (getline(cin, line)) {
        istringstream record(line);
        Point pn;

        getline(record, pn.name, ';');

        string xy;
        getline(record, xy, ';');
        pn.x = stod(xy);

        getline(record, xy, ';');
        pn.y = stod(xy);

        points.push_back(pn);
    }

    return points;
}

vector<Triangle> GetTriangles(vector<Point> points) {
    vector<Triangle> triangles;

    for (int i = 0; i < points.size()-2; ++i)
        for (int j = i+1; j < points.size()-1; ++j)
            for (int k = j+1; k < points.size(); ++k)
                triangles.emplace_back(points[i], points[j], points[k]);

    return triangles;
}

I get these errors from the compiler, but I can't understand why:
Error image
Someone can help me?


text:
Q: Why can't I strcpy? For an assignment, I have to make a grade book in C consisting of several interlocking functions. I've gotten through the first few without (too many) headaches, but then there's this thing. Basically, I'm trying to take a character string and copy it into a two-dimensional array inside of a structure. I think I'm on the cusp of success, but the strcpy keeps throwing these two charming fellow in my face:

passing argument 1 of strcpy makes pointer from integer without a cast
expected 'char *restrict' but argument is of type 'char'.

Here's my code. gb is a pointer pointing to the structure. If I haven't clarified anything enough, please ask.
int add_assignment(Gradebook *gb, const char assgn[MAX_NUMBER_OF_ASSIGNMENTS]) {
  int i, j;

  for(i=0; i < MAX_NUMBER_OF_ASSIGNMENTS; i++) {
    for(j=0; j < (MAX_NAME_LEN+1); j++) {
      strcpy(gb->assignment_names[i][j], assgn);
    }
  }

  return 1;
}

Here is the Gradebook structure:
typedef struct gradebook {
  int number_of_students;
  Students students[MAX_NUMBER_OF_STUDENTS];
  int number_of_assignments;
  char assignment_names[MAX_NUMBER_OF_ASSIGNMENTS][MAX_NAME_LEN + 1];
  int scores[MAX_NUMBER_OF_STUDENTS][MAX_NUMBER_OF_ASSIGNMENTS];
} Gradebook;

A: The problem is in the use of two loops:
for(i=0; i < MAX_NUMBER_OF_ASSIGNMENTS; i++) {
  for(j=0; j < (MAX_NAME_LEN+1); j++) {
   strcpy(gb->assignment_names[i][j], assgn);
  }
}

The inner loop is trying to copy a string (assgn) into a single char. You probably meant
for(i=0; i < MAX_NUMBER_OF_ASSIGNMENTS; i++) {
  strcpy(gb->assignment_names[i], assgn);
}

instead, but this may not be what you want either, where one assignment overwrites the entire list of assignments. It's hard to tell what logic you are looking for.

A: assignment_names[i][j] is a single character, not a string. assignment_names[i] is a character array, so you should copy to that. You don't need the inner loop.
int add_assignment(Gradebook *gb, const char assgn[]) {
    int i;

    for(i=0; i < MAX_NUMBER_OF_ASSIGNMENTS; i++) {
       strcpy(gb->assignment_names[i], assgn);
    }

    return 1;
}


text:
Q: How to make matlab only read dates in one year when the files consist of several year? So, I have four excel files with dates, that I read out and convert.
num = xlsread('1.xlsx', 1, 'A:B')
num2 = xlsread('2.xlsx', 1, 'A:B');
num3 = xlsread('3.xlsx', 1, 'A:B');
num4 = xlsread('4.xlsx', 1, 'A:B');

dnum = datetime(num(:,1),1,1) + caldays(num(:,2));
dnum2= datetime(num2(:,1),1,1) + caldays(num2(:,2));
dnum3= datetime(num3(:,1),1,1) + caldays(num3(:,2));
dnum4=datetime(num4(:,1),1,1) + caldays(num4(:,2));

plot(dnum, 1*ones(size(dnum)), 'x-','linewidth', 1)
plot(dnum2, 2*ones(size(dnum2)), 'x-','linewidth', 1 )
plot(dnum3, 3*ones(size(dnum3)), 'x-', 'linewidth', 1)
plot(dnum4, 4*ones(size(dnum4)), 'x-', 'linewidth', 1)

This are the files that contain dates from many years, but if I want to just collect dates from 2016, what can I do?

A: Create a filter array with year.
FilterYears=year(dnum)==2016
 FilteredData=data[FilterYears]
Hope this helps.


text:
Q: Default CSS colours being shown on JQuery Mobile website I have built a mobile app
and on the following page the default CSS for links is being shown when a transition between pages takes place.
Link to mobile app webpage.

A: Open your browsers inspector, find the a element and then write your own css for the document in a new files, preferably.


text:
Q: How can I create parallel stages in Jenkins scripted pipeline? I am trying to implement parallelization in my Jenkins pipeline code where I can run two stages in parallel. I know this is possible in declarative pipeline, but I am using scripted pipeline.
I've attempted to implement this by doing something like this:
parallel(
    stage('StageA') {
        echo "This is branch a"
    },
    stage('StageB') {
        echo "This is branch b"
    }
  )

When I run this and look at this in Blue ocean, the stages do not run in parallel, but instead, StageB is executed after StageA.
Is it possible to have parallel stages in scripted jenkins pipeline? If so, how?

A: Try this syntax for scripted pipeline:
            parallel(
                    "StageA": {
                        echo "This is branch a"
                    },
                    "StageB": {
                        echo "This is branch b"
                    }
            )

It should look like this in Blue Ocean, this is what you expect right?

If you want to see the stages (and console output) in the classic view, you can use stage like this:
 parallel(
                        "StageA": {
                            stage("stage A") {
                                echo "This is branch a"
                            }
                        },
                        "StageB": {
                            stage("stage B") {
                                echo "This is branch b"
                            }
                        }
                )

A: This worked for me
    stage('Check code quality') {
      parallel {
        stage('Run prospector') {
          when {
            expression { params.SKIP_PROSPECTOR == false }
          }

          steps {
            checkout scm
            sh 'echo "Running prospector..."'
            sh 'make dockerized-run-prospector'
          }
        }

        stage('Run Tests') {
          when {
            expression { params.SKIP_TESTS == false }
          }

          steps {
            checkout scm
            sh 'echo "Running tests..."'
            sh 'make dockerized-test'
          }
        }
      }
    }

This runs stages inder the parent stage parallely.
Jenkins blue shows it like this


text:
Q: Which platforms does Apache Cordova support? which platforms are officaly supported by cordova? I got two different information on this form the cordova website.
The about section says: iOS, Android, Blackberry, Windows Phone, Palm WebOS, Bada, and Symbian (http://cordova.apache.org/#about)
The doc says: Amazon Fire OS, Android, BlackBerry, Firefox OS, iOS, Ubuntu, Windows Phone 8, Windows, Tizen (http://cordova.apache.org/docs/en/4.0.0/guide_support_index.md.html#Platform%20Support)

A: Platform Supports :

*

*Android

*BlackBerry 10

*iOS

*Ubuntu

*Windows Phone 8

*Windows

*OSx

Platform support at a glance is shown here
Also Platform guide is available here


text:
Q: Reset the rem or font-size only for all the elements inside a particular div I've a typical HTML structure as shown in the code below.

Child 1

      Some text here...

New Child

        Some text here...

Now, I need to change the font-size or the rem size of all the elements inside the div.parent including itself.
Since the default rem size is equal to 16px, I need to reduce it to 12px that is 75%. I can't change it on 'html' tag as it will affect all the other elements as well.
How do I change it only for 'div.parent' and all the elements inside that using SCSS or CSS?

A: The CSS length unit 'rem' means 'Root EM' and it always depends on the root element . So if you want a font size depending on a particular parent element's font-size settings, you may use other units like em or percentage.

A: If you can live with a solution that works on all browsers except Firefox, use this:
.parent {
    zoom: 0.75;
}

For Firefox, use quirks like:
.parent {
    transform: scale(0.75);
    transform-origin: top left;
    width: 133.33%;
}

A: Just use a pixel measurement to "reset" the base font-size:
.common-parent div.parent{
    font-size: 12px;
}

Then, each element contained in .common-parent div.parent will read 1em as 12px.
Note: Normally you shouldn't mix pixel units with ems, but for resetting base font-sizes, it's a justified solution.


text:
Q: Spark convert timestamps from CSV into Parquet "local time" semantics Consider this minimal Spark job that reads a CSV to a DataFrame and and writes it out as Parquet:
val df = spark.read.format("csv").option("inferSchema", true).load(filename)
df.write.parquet("parquet_folder/")

For any timestamp columns in the input file, the Parquet output will contain a timestamp, with instant semantics, interpreting the time string in the source data in the current Spark session/JVM timezone.  So "2020-01-01 00:00" becomes "2020-01-01 00:00-0500" if my Spark job is running in EST/EDT.
This means, I could have discrepancies unless all Spark jobs run in a single consistent timezone.
There is also a theoretical problem which is that the Parquet doesn't actually represent my data.  I don't know whether the midnight in the file is really midnight EST, PST, UTC, etc., and I don't really care.
The Parquet format does support the concept of timestamps with local time semantics analogous to java.util.LocalDateTime -- an abstract concept of date/time, not a specific moment in time, which would be interpreted consistently regardless of the Spark session's or JVM's time zone.
What I would like is for Spark to read timestamps from CSV into local times, that get written to Parquet accordingly.  Ideally I would like to apply the same to Spark JDBC extraction as well, from date and "timestamp without time zone" columns.
Is this even possible?
(Note: The Parquet format documentation explains the distinction between instant semantics and local time semantics.)

A: I'm having the same issue. Spark timestamp conversion can be confusing.
To make spark jobs robust against the default local timezone settings of any hosting machine, add an extra layer to temporarily and explicitly set the spark time zone:
from contextlib import contextmanager
from pyspark.sql import SparkSession

@contextmanager
def spark_timezone(timezone: str):
    """Context manager to temporarily set spark timezone during context manager
    life time while preserving original timezone. This is especially
    meaningful in conjunction with casting timestamps when automatic timezone
    conversions are applied by spark.

    Please be aware that the timezone property should be adjusted during DAG
    creation and execution (including both spark transformations and actions).
    Changing the timezone while adding filter/map tasks might not be
    sufficient. Be sure to change the timezone when actually executing a spark
    action like collect/save etc.

    Parameters
    ----------
    timezone: str
        Name of the timezone (e.g. 'UTC' or 'Europe/Berlin').

    Examples
    --------
    >>> with spark_timezone("Europe/Berlin"):
    >>>     df.select(df["ts_col"].cast("timestamp")).show()

    """

    spark = get_active_spark_context()
    current = spark.conf.get("spark.sql.session.timeZone")
    spark.conf.set("spark.sql.session.timeZone", timezone)

    try:
        yield None
    finally:
        spark.conf.set("spark.sql.session.timeZone", current)

def get_active_spark_context() -> SparkSession:
    """Helper function to return the currently active spark context.

    """

    return SparkSession.builder.getOrCreate()

Now, you can wrap your spark.read.csv via the context manager with explicit UTC timezone to prevent any conversion:
with spark_timezone("UTC"):
    df = spark.read.csv("path_to_file")

Update 2022-01-31
Just came across this issue once again while reading a CSV file containing timestamp columns. The timestamp columns will be interpreted in local timezone regardless of whether you set spark's timezone explicitly or not.
Spark's timezone does not take affect for converting string to timestamp within the JVM. Instead, you need to modify JVMs timezone settings, as described in this SO article.


text:
Q: Switching Endian of encrypted char array I am working on a project at school, where we set up a simple key distribution center on our network, encrypted with blowfish. I have successfully coded it and have it working on same-endian machines. The issue arises when I have to send it to a machine of a different endian. The key is encrypted as a character array, and sent and received across the network as such. When the encrypted key is printed on either end, it displays the same encrypted string, but decrypting fails. I have tried reversing the order of the array and decrypting, but the results are the same.
My questions:

*

*Is my reversing of the char array the proper way to deal with endian issues in this situation?

*Could the issue be that it has been encrypted on a machine of one endian style and there for can not be decrypted with the same algorithm on a little endian machine? (here is the version of blowfish I used: http://www.codeproject.com/KB/security/blowfish.aspx)

A: It depends on the algorithm implementation. Looking at the implementation your are using (look at the BytesToBlock and BlockToBytes functions), it is casting the blocks of bytes to unsigned ints.
This transformation is endian dependant and so the the algorithm will have to be adjusted based on the endianness of the machine it is being run on.

A: Endianness applies to smaller elements in your data. If a different endian machine can't read your char array then it possibly means it is expecting bytes in the same order but with their bits reversed.
So you need to reverse the order of bits in your char elements. Your array order should remain intact.

A: It is possible that the bytes are reversed in some capacity, but that usually only happens with numbers (see https://beej.us/guide/bgnet/html/multi/htonsman.html). More likely it is the bits with in each char. You just need a simple algorithm to switch them around before decrypting. Of course, if the bits AND bytes are reversed, that's even more fun.
Now, the fact that it displays the same string leads me to believe that the issue is not actually in the character array - it's something in the decryption algorithm itself that is depending on byte order. In that case you definitely need to look at the above link and think about operations you perform on multi-byte types. (64-bit endian switchers generally have to be manually written, but byte-swapping isn't a hard algorithm to write.)


text:
Q: Symbols and html tags conversion through PHP For example this is the string I have taken from the user in html form
Welcome to the
    world!
I want to store this value in database through PHP but encoding it i.e by converting the bold tag for example convert < to "& lt;"
If also the input consists of any special symbols like @ or ! It should also convert that to appropriate
Then after it is stored in database while receiving the values I want that values to be decoded i.e "& lt;" converted to < back again and respective the special symbols
Please do suggest any process through PHP
I have searched many sites but not got any satisfactory answers.

A: You can use htmlentities() on the way in to encode the HTML, and html_entity_decode() on the way out. More info on the manual:
http://php.net/manual/en/function.htmlentities.php
http://php.net/manual/en/function.html-entity-decode.php
htmlentities('test'); //would output: "test"

html_entity_decode('test'); //would output: "test" but bolded


text:
Q: React Native / Redux - create helper function connected to Redux store in separate file I'm building an app using React Native & Redux and for a <ListView> component I'd like to factorise the way in which dataBlob, sectionIDs & rowIDs are created and contain the function within a separate file.
Within the separate file I'd like to create a function called formatDataForListView which is passed an array of IDs, with which the correct parts of the Redux store can be retrieved and the ListView arrays are constructed accordingly.
I've tried to contain the function within a React element however because I just want to return (dataBlob, sectionIDs, rowIDs), which aren't React elements, I'm getting the error: A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
What I've done thus far:
import { Component } from 'react';
import { connect } from 'react-redux';

class BookingsListViewObjectsCreator extends Component {
  render() {
    const { bookings } = this.props;

    // function that retrieves bookings from Store and structures data
    // into something suitable for ListViewWithSections
    const formatDataForListView = bookingIDs => {
      const dataBlob = {};
      const sectionIDs = [];
      const rowIDs = [];

      // create array of all the different products for grouping into sections
      console.log('bookingIDs: ', bookingIDs);

      bookingIDs.map((id) => {
        // is product already in sectionIDs array? If not, add to sectionIDs & dataBlob
        if (sectionIDs.indexOf(bookings[id].product_id) < 0) {
          sectionIDs.push(bookings[id].product_id);
          dataBlob[bookings[id].product_id] = bookings[id].title;
        }
        // add booking to rowIDs & dataBlob
        rowIDs.push(bookings[id].id);
        dataBlob[bookings[id].product_id + ':' + bookings[id].id] = bookings[id];
        return id;
      });

      console.log('dataBlob: ', dataBlob);
      console.log('sectionIDs: ', sectionIDs);
      console.log('rowIDs: ', rowIDs);
      return { dataBlob, sectionIDs, rowIDs };
    };

    // create objects required to render ListView and return them
    const { dataBlob, sectionIDs, rowIDs } = formatDataForListView(this.props.bookingIDs);
    return (dataBlob, sectionIDs, rowIDs);
  }
}

const mapStateToProps = state => {
  return { bookings: state.bookings };
};

export default connect(mapStateToProps)(BookingsListViewObjectsCreator);

So how do I store this straight JS function in a separate file and call it from a React element to retrieve (dataBlob, sectionIDs, rowIDs)?

A: I think @oldo.nicho means a structure to looks like this.
Just export that function from a file and import it into the components that need the functionality
// somefile.js
// function that retrieves bookings from Store and structures data
// into something suitable for ListViewWithSections
export default function formatDataForListView = bookingIDs => {
  const dataBlob = {};
  const sectionIDs = [];
  const rowIDs = [];

  // create array of all the different products for grouping into sections
  bookingIDs.forEach((id) => {
    // is product already in sectionIDs array? If not, add to sectionIDs & dataBlob
    if (sectionIDs.indexOf(bookings[id].product_id) < 0) {
      sectionIDs.push(bookings[id].product_id);
      dataBlob[bookings[id].product_id] = bookings[id].title;
    }
    // add booking to rowIDs & dataBlob
    rowIDs.push(bookings[id].id);
    dataBlob[bookings[id].product_id + ':' + bookings[id].id] = bookings[id];
  });
  return { dataBlob, sectionIDs, rowIDs };
};

// otherfile.js
import { Component } from 'react';
import { connect } from 'react-redux';
import formatDataForListView from './somefile';

class BookingsListViewObjectsCreator extends Component {
  render() {
    const { bookings } = this.props;

    // create objects required to render ListView and return them
    const { dataBlob, sectionIDs, rowIDs } = formatDataForListView(this.props.bookingIDs);
    return (dataBlob, sectionIDs, rowIDs);
  }
}

const mapStateToProps = state => {
  return { bookings: state.bookings };
};

export default connect(mapStateToProps)(BookingsListViewObjectsCreator);


text:
Q: In IE8, why am I getting a javascript error on my DocType line I am getting this error when running a webpage in internet explorer 8 (not sure if it matters but it happens when I load up a jquery ui dialog)

When I click yes, it brings up the IE8 javascript debugging tools but what is weird is that it shows the error being on the doctype line  . .

Can anyone explain what IE is trying to tell me and how I can debug this??
Update:
in response to folks saying i need to remove the blank line at the top, here is my code.  There is no extra blank line on anything in my site.master file so i don't understand what it would take to remove this blank line that i see when i view source in IE8.
<%@ Import Namespace="DomainModel" %>
<%@ Import Namespace="Mvc.Views.OrganisationalUnit" %>
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<Mvc.ViewModels.BaseViewModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

A: Try removing the whitespace at the top of the file (i.e. line 1).  If that doesn't help, try retyping the string manually to make sure no odd characters are hidden in there.  Otherwise, the code looks valid to me.
Update:
Try removing the line breaks between your import statements like this:
<%@ Import Namespace="DomainModel" %><%@ Import Namespace="Mvc.Views.OrganisationalUnit" %><%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<Mvc.ViewModels.BaseViewModel>" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">


text:
Q: Spring Data MongoDB Aggregation involve Unwind,Match,Sort &Group I have a collection named User which contains embedded document called Message. The embedded document Message contains array of message object as below :
{
  "_id" : ObjectId("58e09daa192216e39fd85433"),
  "userId" : "user123",
  "message" : [
    {
        "messageId" : "5277941e-9d84-46c3-b927-ef33abbf35f2",
        "dateCreated" : 1491115000,
        "body" : "howdy?",
        "type" : "text"
    },
    {
        "messageId" : "c2ce0480-bc0d-4393-89d4-27174d323b98",
        "dateCreated" : 1491119000,
        "body" : "i've problem with my account. can you help?",
        "type" : "text"
    },
    {
        "messageId" : "45b2593c-a960-4066-8723-db2531dd8bab",
        "dateCreated" : 1491100000,
        "body" : "this is urgent",
        "type" : "text"
    }
  ]
}

My objective is to sort embedded document Message based on dateCreated key. I need to translate this mongo query into Spring Data MongoDB :
db.user.aggregate(
  {$unwind: "$message"},
  {$match: {userId: "user123"}},
  {$sort: {"message.dateCreated": 1}},
  {$group: {_id: "$_id", "message": {"$push": "$message"}}})

I've tried the following codes but still getting error :
AggregationOperation unwind = Aggregation.unwind("message");
AggregationOperation match = Aggregation.match(Criteria.where("userId").in("user123"));
AggregationOperation sort = Aggregation.sort(Direction.ASC, "message.dateCreated");
AggregationOperation group = Aggregation.group("userId", "message");

Aggregation aggregation = Aggregation.newAggregation(unwind, match, sort, group);

AggregationResults<User> groupResults = mongoTemplate.aggregate(aggregation, User.class, User.class);

Error :

Failed to instantiate [java.util.List]: Specified class is an interface

User class :
@Document(collection="user")
public class User {

  @Id
  private String id;
  private String userId;
  @Field("message")
  @DBRef
  private List<Message> message;
  //constructor, getter, setter
}

Message class :
@Document
public class Message {
  private String messageId;
  private long dateCreated;
  private String body;
  private String type;
  //constructor, getter, setter
}

Hint :
Based on my research, I'm pretty sure that I need to use GroupOperationBuilder group =
 Aggregation.group("userId").push("message") but I don't really know how to proceed with this as AggregationResults will not allow me to use it in the mongoTemplate.aggregate()

A: Optimize query will be:
db.user.aggregate(
 {$match: {userId: "user123"}},
 {$unwind: "$message"},
 {$sort: {"message.dateCreated": 1}},
 {$group: {_id: "$_id", "message": {"$push": "$message"}}});

If you use this given query first it will filter the documents that match your criteria, then it will unwind the filtered documents.

A: It seems like your entity classes are wrong. Why does Message have @DBRef as annotation?
In my opinion it should be like that:
@Document(collection="user")
public class User {

  @Id
  private String id;
  private String userId;
  @Field("message")
  private List<Message> message;
  //constructor, getter, setter
}

public class Message {
  private String messageId;
  private long dateCreated;
  private String body;
  private String type;
  //constructor, getter, setter
}


text:
Q: The Slot Game Concern I'm working on a slot game.. and I cannot figure out to get the spinner getting the numbers, and then after the spin it would display like: "You won 1,000,000 points!". I cannot figure out how to do this. Could someone help me? It's just a random number spinner (js) and rewards.

<button onclick="myFunction()">Spinner
<style>
.button {
  border-radius: 4px;
  background-color: white ;
  border: none;
  color: #FFFFFF;
  text-align: center;
  font-size: 28px;
  padding: 20px;
  width: 200px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
}
</style>
</button>

<script>

function myFunction() {

var y = Math.floor((Math.random() * 15) + 1);

var x = document.createElement("INPUT");            ///Need to break this out of function...Bug
    x.setAttribute("type", "text");
    x.setAttribute("value", y);//random number will be y
    document.body.appendChild(x);

returnRandom(y);
}

function returnRandom(r){
//window.alert(r);

var result;

switch (r)
            {
               case 1: var result = 'A whopping 15,000,000 points! Great job!';
               break;
               case 2: var result = 'Awh man.. -500,000 points.';
               break;
               case 3: var result = 'A win! 50,000 points.';
               break;
               case 4: var result = 'A good win! 1,500,000 points.';
               break;
               case 5: var result = 'A bad loss.. -355,555 points.';
               break;
               case 6: var result = 'Nothing! Not bad nor good.';
               break;
               case 7: var result = ' Lucky seven! 77,777,777 points!';
               break;
               case 8: var result = '444,444 points.';
               break;
               case 9: var result = 'Cry me a river! -3,333,333 points';
               break;
               case 10: var result = 'Oh, You won 5,000,000 points!';
               break;
               case 11: var result = 'Oh! Wow! 99,999,999 points!';
               break;
               case 12: var result = 'Meh. -150,000 points.';
               break;
               case 13: var result = 'You earned it, take 3,000,000 points.';
               break;
               case 14: var result = 'You lost. -100,000 points.';
               break;
               case 15: var result = 'You got Fifteen? A big win! 100,000,000 points!';
               break;

            }
   window.alert(result);

}

</script>

A: Your code looks a bit messy. You seem to have the css integrated as style within the body of the text and the script in the body of the text aswell. Are you acquainted with css stylesheets and external javascript files? easily made. But for now, the following code will work. Check out the snippet.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Slot Machine</title>

<style> /*style and script should go in the head section - didn't look like you had them there */
#spin { /*gave the button an id - you could have other buttons*/
  border-radius: 4px;
  border: none;
  color: #FFFFFF; /* took out the background color - white on white? how was that going to work? you could put it back in but change the color to #000000;  or something*/
  text-align: center;
  font-size: 28px;
  padding: 20px;
  width: 200px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
}
#spinresult{width:29px; color:#000000;}
</style>

<script>

function myFunction() {

var y = Math.floor((Math.random() * 15) + 1);
var x = document.getElementById("spinresult");           ///put an input element in the body so it didn't keep creating new ones.
    x.setAttribute("type", "number"); //changed text to number
    x.setAttribute("value", y);   //random number is y
    document.body.appendChild(x);

returnRandom(y);
};

function returnRandom(r){
//window.alert(r);

var result;

switch (r)
            {
               case 1: var result = 'A whopping 15,000,000 points! Great job!';
               break;
               case 2: var result = 'Awh man.. -500,000 points.';
               break;
               case 3: var result = 'A win! 50,000 points.';
               break;
               case 4: var result = 'A good win! 1,500,000 points.';
               break;
               case 5: var result = 'A bad loss.. -355,555 points.';
               break;
               case 6: var result = 'Nothing! Not bad nor good.';
               break;
               case 7: var result = ' Lucky seven! 77,777,777 points!';
               break;
               case 8: var result = '444,444 points.';
               break;
               case 9: var result = 'Cry me a river! -3,333,333 points';
               break;
               case 10: var result = 'Oh, You won 5,000,000 points!';
               break;
               case 11: var result = 'Oh! Wow! 99,999,999 points!';
               break;
               case 12: var result = 'Meh. -150,000 points.';
               break;
               case 13: var result = 'You earned it, take 3,000,000 points.';
               break;
               case 14: var result = 'You lost. -100,000 points.';
               break;
               case 15: var result = 'You got Fifteen? A big win! 100,000,000 points!';
               break;

            }
   window.alert(result);

};

</script>

</head>

<body>
<button id="spin" onclick="myFunction()">Spinner</button>
<!--<input type="number" id="spinresult">-->      <!---if you unhide this and hide the other input, you'll see the number-->
<input type="number" hidden="true" id="spinresult"> <!--hid the input so you don't see the number-->

</body>
</html>

This would be better separated like so:

function calcresult() {

var y = Math.floor((Math.random() * 15) + 1);
var x = document.getElementById("spinresult");           ///put an input element in the body so it didn't keep creating new ones.
    x.setAttribute("type", "number"); //changed text to number
    x.setAttribute("value", y);   //random number is y
    document.body.appendChild(x);

returnRandom(y);
};

function returnRandom(r){
//window.alert(r);

var result;

switch (r)
            {
               case 1: var result = 'A whopping 15,000,000 points! Great job!';
               break;
               case 2: var result = 'Awh man.. -500,000 points.';
               break;
               case 3: var result = 'A win! 50,000 points.';
               break;
               case 4: var result = 'A good win! 1,500,000 points.';
               break;
               case 5: var result = 'A bad loss.. -355,555 points.';
               break;
               case 6: var result = 'Nothing! Not bad nor good.';
               break;
               case 7: var result = ' Lucky seven! 77,777,777 points!';
               break;
               case 8: var result = '444,444 points.';
               break;
               case 9: var result = 'Cry me a river! -3,333,333 points';
               break;
               case 10: var result = 'Oh, You won 5,000,000 points!';
               break;
               case 11: var result = 'Oh! Wow! 99,999,999 points!';
               break;
               case 12: var result = 'Meh. -150,000 points.';
               break;
               case 13: var result = 'You earned it, take 3,000,000 points.';
               break;
               case 14: var result = 'You lost. -100,000 points.';
               break;
               case 15: var result = 'You got Fifteen? A big win! 100,000,000 points!';
               break;

            }
   window.alert(result);

};
#spin { /*gave the button an id - you could have other buttons*/
  border-radius: 4px;
  border: none;
  color: #FFFFFF; /* took out the background color - white on white? how was that going to work? you could put it back in but change the color to #000000;  or something*/
  text-align: center;
  font-size: 28px;
  padding: 20px;
  width: 200px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
}
#spinresult{width:29px; color:#000000;}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Slot Machine</title>
</head>
<body>

<button id="spin" onclick="calcresult()">Spinner</button>
<!--<input type="number" id="spinresult">-->      <!---if you unhide this and hide the other input, you'll see the number-->
<input type="number" hidden="true" id="spinresult"> <!--hid the input so you don't see the number-->

</body>
</html>

You can save the javascript (even by using notepad-> save as-> all files (with the extension js) and link it in using <script> </script> tags
Similar for the css.  (e.g. <link rel="stylesheet" type="text/css" href="file.css"/> ) Welcome to Stackoverflow!


text:
Q: The jumping and movement code for my player only works intermittently So I am developing an online multiplayer FPS game for my SDD major work, and I have run into a problem. Below is the movement code for my player. I am trying to implement strafing and bunnyhopping into my game, and so I setup a test environment within my project and I managed to get everything working. The only problem was that after I tried to put this back into my main project, it stopped working.
The main problem is that the jumping only works sometimes.  The player only jumps a very small amount, and sometimes stay there, meaning that there is no friction as the player is stuck off the ground. He also seems to phase beneath the ground a tiny bit, but the collider on him shouldn't let that happen. I have tried to remove the code that makes downward falls faster, but that only fixes it sometimes.
Code link: https://pastebin.com/cLkemQhX
    public class PlayerMovement: MonoBehaviourPun
{
    [Header("Movement Settings")]
    public float maxVelocityGround = 15f;
    public float maxVelocityAir = 10f;
    public float groundAccelerate = 90f;
    public float airAccelerate = 180f;
    public float fallMultiplier = 1.2f;
    public float lookSens = 8f;
    public float slowDrag = 0;
    public float thrusterForce = 7f;
    public float friction = 10f;
    private float _friction = 0f;

    [Header("Rotation")]
    float xRot = 0F;
    float yRot = 0F;
    float minY = -90f;
    float maxY = 90f;
    Quaternion originalRotation;

    //More Movement Variables
    private float distToGround;
    private Vector3 _velocity;
    private Vector2 xyVelocity;

    [Header("References")]
    //public Text grounded;
    //public Text velocity;
    public Camera cam;
    private Move motor;
    private Rigidbody rb;
    private CapsuleCollider collidr;
    private GameObject rayPoint;

    //private PlayerSetup playerSetup;

    //Booleans
    private bool jumpy = false;

    void Start()
    {
        _friction = friction;

        //Locks the cursor to the middle of the screen, and hides it from view
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;

        //These attatch the correct objectss to their references in the script, defined above
        motor = GetComponent<Move>();
        rb = GetComponent<Rigidbody>();
        collidr = GetComponent<CapsuleCollider>();
        rayPoint = GameObject.Find("point");
        //playerSetup = GetComponent<PlayerSetup>();

        //Sets the distance to the ground from the center of the collider, used in determining whe nthe player is on the ground
        distToGround = collidr.bounds.extents.y;

        if (GetComponent<Rigidbody>())
            GetComponent<Rigidbody>().freezeRotation = true;
        originalRotation = transform.localRotation;

    }

    void FixedUpdate()
    {
        //Debug function that shows a visual representation of when the player is on the ground
        //string a = isGrounded().ToString();
        //grounded.GetComponent<Text>().text = a;

        //Finds the Velocity in the x plane. Also used in debug, as it shows it on screen
        //xyVelocity = new Vector2(rb.velocity.x, rb.velocity.z);
        //velocity.GetComponent<Text>().text = xyVelocity.magnitude.ToString("0.000");

        //This statement checks if the player both is on the ground, and has requested to jump. If so it will jump
        //while also not allowing multiple jumps while in the air. If the player holds it down, he will jump as soon
        //as he touches the ground, avoiding friction and allowing the player to bunnyhop
        if (Input.GetKey("space") && isGrounded())
        {
            rb.AddForce(Vector3.up * thrusterForce, ForceMode.Impulse);
            jumpy = true;
        }
        //rb.AddForce(Jump(), ForceMode.Impulse);
        //This makes you fall faster than you rise, and make jumping feel nicer overall.
        if (rb.velocity.y < 0)
        {
            rb.velocity += Vector3.up * Physics.gravity.y * fallMultiplier * Time.deltaTime;
        }

        //Gets the input from the axis'
        float input_y = Input.GetAxis("Vertical");
        float input_x = Input.GetAxis("Horizontal");

        //Calculates the direction we want to move in, taking into account mouse movement to allow for strafing
        Vector3 accelDir = (transform.forward * input_y + transform.right * input_x).normalized;

        //Checks if we are not pressing any inputs, and makes us decelerate faster, to make moving feel more snappy
        decelerate(accelDir);

        //This code adjusts the vector to be projected onto the plane that we are currently moving on. Makes strafing better
        RaycastHit hit;
        Physics.Raycast(collidr.center, Vector3.down, out hit, 1000);
        accelDir = Vector3.ProjectOnPlane(accelDir, hit.normal).normalized;

        //Finds the current velocity of our RIgidBody
        Vector3 curVel = rb.velocity;
        //Determines whether or not we want to use the air movement(ignore friction) or not.
        //The boolean checks if we have just jumped, so while we are still on the ground, we don't want to calculate friciton
        if (isGrounded() && jumpy == false)
        {
            _velocity = MoveGround(accelDir, curVel);
        }
        else
        {
            _velocity = MoveAir(accelDir, curVel);
        }

        //Apply Movement
        rb.velocity = _velocity;

        //These call the rotation functions below, one rotates the camera in the y plane, the other the rigidbody in the x plane, which has the camera as a child
        cameraRotate();
        rbRotate();

        jumpy = false;

    }

    private Vector3 MoveGround(Vector3 accelDir, Vector3 prevVelocity)
    {
        // Apply Friction
        float speed = prevVelocity.magnitude;
        if (speed != 0) // To avoid divide by zero errors
        {
            float drop = speed * _friction * Time.fixedDeltaTime;
            prevVelocity *= Mathf.Max(speed - drop, 0) / speed; // Scale the velocity based on friction.
        }

        return Accelerate(accelDir, prevVelocity, groundAccelerate, maxVelocityGround);
    }

    private Vector3 MoveAir(Vector3 accelDir, Vector3 prevVelocity)
    {
        return Accelerate(accelDir, prevVelocity, airAccelerate, maxVelocityAir);
    }

    private Vector3 Accelerate(Vector3 accelDir, Vector3 prevVelocity, float accelerate, float max_velocity)
    {
        float projVel = Vector3.Dot(prevVelocity, accelDir); // Vector projection of Current velocity onto accelDir.
        float accelVel = accelerate * Time.fixedDeltaTime; // Accelerated velocity in direction of movment

        // If necessary, truncate the accelerated velocity so the vector projection does not exceed max_velocity
        if (projVel + accelVel > max_velocity)
        {
            accelVel = max_velocity - projVel;
        };

        return prevVelocity + accelDir * accelVel;
    }

    //Function to check if we are on the ground
    public bool isGrounded()
    {
        return Physics.Raycast(collidr.bounds.center, Vector3.down, distToGround);

        //Below is a capsule cast, it would be better to implement because it has a thickness
        //return Physics.CheckCapsule(collider.bounds.center, new Vector3(collider.bounds.center.x, collider.bounds.min.y, collider.bounds.center.z), collider.radius * 0.9f);
    }

    /// <summary>
    /// decelerates us faster when not moving
    /// </summary>
    /// <param name="input"></param>
    public void decelerate(Vector3 input)
    {
        if (input == Vector3.zero)
        {
            _friction = 10f * friction;
        }
        else
        {
            _friction = friction;
        }
    }
    /// <summary>
    /// This function is the camera rotation function
    /// </summary>
    public void cameraRotate()
    {
        //Get the input from the mouse and multiply it by sensitivity so it can be adjusted from ingame
        yRot += Input.GetAxis("Mouse Y") * lookSens;
        //Clamp it so that we cant just keep spinning in the Y direction
        yRot = clamp(yRot, minY, maxY);
        //Calculate the quaternion using the amount of rotation found before. We use the negative mouse input as the amount
        //of rotation, and then specify that we want this rotation to be around the x axis. It seems counter intuitive, but this is the way to do it
        Quaternion yRotAngle = Quaternion.AngleAxis(-yRot, Vector3.right);
        //Apply this rotation to the cameras transform
        cam.transform.localRotation = originalRotation * yRotAngle;
    }
    /// <summary>
    /// Basically the same as above, but we dont need to clamp it because we want to be able to forever spin to the left and right
    /// </summary>
    public void rbRotate()
    {
        xRot += Input.GetAxis("Mouse X") * lookSens;
        Quaternion xRotAngle = Quaternion.AngleAxis(xRot, Vector3.up);
        rb.transform.localRotation = originalRotation * xRotAngle;
    }
    /// <summary>
    /// just clamps the angle we input between the next 2 floats
    /// </summary>
    /// <param name="angle">the float representation of the angle</param>
    /// <param name="min">the min that the angle can be</param>
    /// <param name="max">you got it by now right?></param>
    /// <returns></returns>
    private float clamp(float angle, float min, float max)
    {
        return Mathf.Clamp(angle, min, max);
    }
}


text:
Q: Multiple wildcards not working in centos 7 In Ubuntu I could run truncate -s 0 /var/log/*/* &> /dev/null to clear all the log files in /var/log/ dir and directories under that in one command
But in centos, it doesn't work. Instead I have to run truncate -s 0 /var/log/* &> /dev/null ; truncate -s 0 /var/log/*/* &> /dev/null to clear the /var/log/ dir and then clear the dirs under /var/log/


text:
Q: Serilog Appsettings and setting filters Using the Serilog.Settings.AppSettings project I am having difficulty setting a filter to exclude certain namespaces from a configured sink.
In code I would do something like this:
[...].Filter.ByExcluding(Matching.FromSource<MyNameSpace>())

However I don't seem able to do it using the app settings.
Is this supported and if so how can I achieve this using configuration?
Thanks
Vincent

A: Make sure you have the package.
Install-Package Serilog.Filters.Expressions

Then follow the example here: https://github.com/serilog/serilog-filters-expressions and https://github.com/serilog/serilog-settings-configuration/blob/dev/sample/Sample/appsettings.json#L64
"Using": ["Serilog.Settings.Configuration"],
"Filter": [
      {
        "Name": "ByIncludingOnly",
        "Args": {
          "expression": "SourceContext = 'MyNameSpace'"
        }
      }
    ]


text:
Q: How to insert JS into HTML alert()? How to insert below swal() function to inside alert() onclick function?

  <button class="button" onclick="alert('');">Pokaz Opis</button>

EDIT:
How to display swal() functions when users click on button?
Swal() function is javascript function and i can't do that like this below,
because it doesn't work:
<button class="button" onclick="swal("<?php echo htmlentities($row['description'], ENT_QUOTES);?>");">Pokaz Opis</button>
This is wrong too:
<button class="button" onclick="">Pokaz Opis</button>
Do you understand? I don't know how to display JS function swal() inside HTML DOM button onclick=""

A: I would recommend you to stop putting event handlers into your HTML markup and learn to use addEventListener instead.
Then
a) your code will be easier to read and easier to maintain and debug, and
b) little problems like this can disappear at the same time.
With this approach your requirement becomes easy to implement. Demo:

document.getElementById("alertButton").addEventListener("click", function() {
  swal("test");
});

  <button class="button" id="alertButton">Pokaz Opis</button>


text:
Q: What methods do I need to implement for my matrix-like class in R? I'm designing a class in R that has a lot of the same behaviors as a 2-dimensional matrix: it can be subsetted by row or column, it has dimnames, etc. So I want it to support all the "standard" matrix operations such as rownames, [, and so on. But I'm not sure what all of these method names are, and I'm not sure which of them I need to implement. For instance, do I need to implement rownames and rownames<- explicitly, or is it sufficient to implement dimnames and dimanmes<-? Basically, is there a list somewhere of all the functions that one would have to implement for a class to act like a 2-dimensional matrix-like thing?

A: Can you just extend the matrix class? You can add a bunch of other stuff without getting in the way of existing methods. That would be a whole lot easier than rewriting all the basics.
For generics, you can do
> methods(class = "matrix")
 [1] anyDuplicated.matrix as.data.frame.matrix as.raster.matrix*
 [4] boxplot.matrix       determinant.matrix   duplicated.matrix
 [7] edit.matrix*         head.matrix          isSymmetric.matrix
[10] relist.matrix*       subset.matrix        summary.matrix
[13] tail.matrix          unique.matrix

For something like rownames, the help specifies that it works on "matrix-like objects", so depending on how different your class is, it may just work. You can look at the code to see how things work, in the case of rownames, it looks like if you define dimnames and maybe NROW you're good. The bad news is that, because it works on "matrix-like objects" rather than being a method for the matrix class, it that you'll be hard-pressed to find a list of other such functions.