text:
Q: Convert.ToDateTime DD:HH:mm:ss C#/ASP.net GridView RowDataBound The basis of my question is to color a cell in a ASP.net Grid View control.
I have a bound field that is produced from this in SQL
 RIGHT('0' + CONVERT(varchar(6), SUM([Coaching]) / 86400), 2) + ':' + RIGHT('0' + CONVERT(varchar(6), SUM([Coaching]) % 86400 / 3600), 2) + ':' + RIGHT('0' + CONVERT(varchar(2), SUM([Coaching]) % 3600 / 60), 2) + ':' + RIGHT('0' + CONVERT(varchar(2), SUM([Coaching]) % 60), 2)

It is not great for working with I know but the Project rules that I have says I have to have in a format of DD:HH:MM:SS for the display.
All that being said I'm trying to do a row data bound event in C# to color the cell if it is over a certain Minute
    protected void TheGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //this is where we will color the columns

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int CoachingIndex = GetColumnIndexByName(e.Row, "Coaching");
        DateTime CoachingValue = Convert.ToDateTime(e.Row.Cells[CoachingIndex].Text);
        string columnValue = ((Label)e.Row.FindControl("Coaching")).Text;
        if (Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, columnValue)) > Convert.ToDateTime("00:00:40:00"))
        {
            e.Row.Cells[CoachingIndex].BackColor = System.Drawing.Color.Red;
        }
    }
}
int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
                break;
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return columnIndex;
}

This conversion if (Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, columnValue)) > Convert.ToDateTime("00:00:40:00")) is where the problem lies just trying to figure out how to get this to work in C# so I can do the comparison.
Any help will be appreciated.

A: Thank you for all the help I was able to work on it today after all the info provided was able to get it to work.
 if (e.Row.RowType == DataControlRowType.DataRow)
    {

        int CoachingIndex = GetColumnIndexByName(e.Row, "Coaching");
        TimeSpan timeStamp;
        string timeStampString = e.Row.Cells[CoachingIndex].Text; // just change the index of cells to get the correct timestamp field
        if (TimeSpan.TryParse(timeStampString, out timeStamp))
        {
            TimeSpan TS = timeStamp;
            int mins = TS.Minutes;
            int hours = TS.Hours;
            int days = TS.Days;
            if (mins > 40 || hours >= 1 || days >= 1)
            {
                e.Row.Cells[CoachingIndex].BackColor = System.Drawing.Color.Red;
            }
        }
    }
}
int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
                break;
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return columnIndex;
}

A: Try using a common safe function like that while parsing the date:
public DateTime? GetSafeDateTimeValue(object datetimeValue)
        {
            if (datetimeValue == null || datetimeValue == DBNull.Value)
                return null;
            else
            {
                try
                {
                    if (!DateTime.TryParse(datetimeValue.ToString(), out tempDateTimeValue))
                        return null;
                    else
                        return tempDateTimeValue;
                }
                catch
                {
                    return null;
                }
            }
        }

And replace your line with
DateTime? dt = GetSafeDateTimeValue((DataBinder.Eval(e.Row.DataItem, columnValue)));
if(dt.HasValue)
 if (dt.Value > Convert.ToDateTime("00:00:40:00"))

Second problem you will face that the date time parser must expect the year, instead of parsing the datetime string take datetime instance like below:
DateTime comparedDt = new DateTime(2014, 03, 10, 00, 40, 00);


text:
Q: Metadata API not working on sandboxs I am trying to connect to the metadata Api via a python script. Essentially, I am authenticating into the SOAP Api, getting a session Id, then setting the session if in my Metadata client class. This works well for production orgs but when trying to connect to the metadata api for a sandbox, I keep getting an "invalid session id" error. Perhaps the URL is wrong? If so I cannot figure out how to set it.
Thanks in advanced!

A: To set uRL you can use below sample code
final LoginResult loginResult = loginToSalesforce(USERNAME, PASSWORD,
private static LoginResult loginToSalesforce(
        final String username,
        final String password,
        final String loginUrl) throws ConnectionException {
    final ConnectorConfig config = new ConnectorConfig();
    config.setAuthEndpoint(loginUrl);
    config.setServiceEndpoint(loginUrl);
    config.setManualLogin(true);
    return (new EnterpriseConnection(config)).login(username, password);
}
from the loginResult you can get the session id.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Draw on any website (without extensions)? Injecting HTML/CSS/JS into any website I'm following a tutorial to draw shapes on a local webpage using Canvas Html5 canvas paint.
Thats all well and good, but I'm wanting to replicate the relevant drawing functions/CSS/HTML and "inject" that into any sites source code, for the purposes of being able to draw rectangles/lines on any website. But I'm stuck. Code below:
from json import dumps
import time

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

URL = "https://www.google.com/"

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.headless = False
options.add_argument("--start-maximized")

driver = webdriver.Chrome(
    options=options, executable_path=ChromeDriverManager(log_level=0).install()
    )
driver.get(URL)

# HTML from `<head>` inject style code to existing head style tag
html_head = driver.find_element_by_tag_name("head") # Find the head
html_head_style= html_head.find_element_by_tag_name("style") # Within the head, find the style
inner_html_style = html_head_style.get_property("innerHTML") # Get the styles innerHTML
# Add properties for eventual canvas
new_style = inner_html_style + "#imageView {position:absolute;top:0;left:0;border: 10px solid #000;}"

# Add canvas style to existing style string as a string
driver.execute_script("document.getElementsByTagName('style')[0].innerHTML =" +  dumps(new_style)) #  Inject new_style into the script tag!

# HTML from `<body>`
html_body = driver.find_element_by_tag_name("body") # find the body
location = html_body.location # Get body lcoation
height = driver.execute_script("return document.body.scrollHeight") # Get body height
width = driver.execute_script("return document.body.scrollWidth") # Get body width

# add canvas to body
new_body = html_body.get_attribute('innerHTML') + f'<canvas id="imageView" width="{width}" height="{height}"></canvas>'
driver.execute_script("document.body.innerHTML =" + dumps(new_body))

# Not working from here on out

js = """
`
<script>/* © 2009 ROBO Design
            * http://www.robodesign.ro
            */

           // Keep everything in anonymous function, called on window load.
           if(window.addEventListener) {
           window.addEventListener('load', function () {
             var canvas, context;

             // Initialization sequence.
             function init () {
               // Find the canvas element.
               canvas = document.getElementById('imageView');
               if (!canvas) {
                 alert('Error: I cannot find the canvas element!');
                 return;
               }

               if (!canvas.getContext) {
                 alert('Error: no canvas.getConmtext!');
                 return;
               }

               // Get the 2D canvas context.
               context = canvas.getContext('2d');
               if (!context) {
                 alert('Error: failed to getContext!');
                 return;
               }

               // Attach the mousemove event handler.
               canvas.addEventListener('mousemove', ev_mousemove, false);
             }

             // The mousemove event handler.
             var started = false;
             function ev_mousemove (ev) {
               var x, y;

               // Get the mouse position relative to the canvas element.
               if (ev.layerX || ev.layerX == 0) { // Firefox
                 x = ev.layerX;
                 y = ev.layerY;
               } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                 x = ev.offsetX;
                 y = ev.offsetY;
               }

               // The event handler works like a drawing pencil which tracks the mouse
               // movements. We start drawing a path made up of lines.
               if (!started) {
                 context.beginPath();
                 context.moveTo(x, y);
                 started = true;
               } else {
                 context.lineTo(x, y);
                 context.stroke();
               }
             }

             init();
           }, false); }

           // vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
           </script>
`
"""

# Tried the below code via debugger no luck
'''
driver.execute_script("document.body.innerHTML += " + dumps(js))
driver.execute_script("debugger;")
driver.refresh()
'''

I've been using google as my test site. Now I have managed to "inject" a canvas that I can see via the new black borders around google successfully!
but I fall apart at the javascript. I realized I can't inject my own premade JS files, so I tried injecting js functions directly between script tags (as in the code 'js' variable). Then I realized JS won't run if its injected, it needs to be there at page load aka refresh, but injected files are lost on refresh. Then I tried using breakpoints and debugging to "save and refresh" my JS on the page - still no luck.I've also tried bookmarklets. This is day 3 of trial and error!
Please help I feel like this can be accomplished, just need smarter folks insight

A: @opticMan generally "good guys" in browsers world do everything possible to prohibit from executing 3rd party scripts on their sites. It is something known as XSS, you can read more here
If you want to manipulate any website you want, you would need to to it with a browser extension. If just want to learn and experiment try injecting code to your own website you control (maybe simple development server using nodejs and express).


text:
Q: Safari web inspector: view css grid Is there a way to see the position of the grid with Safari Web Inspector like Firefox do it with grid inspector ?

A: Stretching the Metrics tab in Inspect Element's Right side pane of Elements tab will display the css box model with padding, border, margin and position.
If you are using Safari version 9.1, you can see it by selecting "Styles - Computed" in the Styles dropown in the Styles drawer on the right of the dev tools. (The Styles section otherwise defaults to "Styles - Visual", so you need to make the selection to make the box visible). Hope this helps.
The question was about grid inspector. There is no grid inspectors in Safari. Although Safari is noted for Safari Responsive Design mode there is no grid inspector in Safari yet.

A: As of Safari Technology Preview 123 and Safari 15, there is now a CSS Grid inspector.
In the Elements tab you'll find a grid button, if a grid is present.
In the Layout subtab, all grids on the page will be listed at the bottom.

A: Just to help clarify, the image below shows where the grid overlay can be turned on in Safari's Inspector.


text:
Q: How to execute multiple rails commands when creating a new rails app? I want to execute the following rails commands when creating a new rails app.
rails new xx -d mysql
rails g model Post name:string
rails g model User name:string
bundle exec rake db:create
bundle exec rake db:migrate

I don't know how to make it due to lack of ruby knowledge.
let me know quick tips on how to make it if you know.
Thanks for reading my question.

A: For the commands you listed, I would recommend reading up on the Rails Application Template API. You will be able to put your generators, migrations, and more in there.
An example template with your requirements could be like this:
# template.rb
generate(:model, "Post name:string")
generate(:model, "User name:string")
rails_command("db:create")
rails_command("db:migrate")

Then you would call the following to build your new app with your template
rails new xx -m ./template.rb

A: Not with a gem—but with a rakefile, perhaps.


text:
Q: Is "webkit" a CSS standard? Such as when used with "@-webkit-keyframes flash{0%,50%,100%{opacity:1} ... ;animation-name:flash}" I am trying to understand where this type of "webkit" content is coming from. I have seen in in multiple CSS files.
Is this an open standard in CSS?

A: This is not a standard.

WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome.

Other browser's use other rendering engines.
Try to use a clean css, without -webkit or -moz attributes. Use them only if you very need them, or better even use sass (compass tool) that will add all of them if you will put some css that will need special support for special engine.


text:
Q: I am unable to render a flatlist in react native and solutions aren't working I tried rendering a flatlist in react native with data from a json file but it is not working.
JSON File:
[
  {
    "user_id": "1",
    "user_name": "user1",
    "user_display_name": "User 1"
  },
  {
    "user_id": "2",
    "user_name": "user2",
    "user_display_name": "User 2"
  },
]

This is my index.js file code. A contact list with search functionality:
I implemented the search functionality using useEffect hook to check when the search bar changes and filter the JSON file I am importing (dummyContacts)
import React, { useState, useEffect } from "react";

import { View, Text, FlatList, StyleSheet, TextInput, Pressable } from "react-native";
import dummyContacts from "../../../assets/data/contacts.js";

export default function ContactsScreen() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filteredContacts, setFilteredContacts] = useState(dummyContacts);

  useEffect(() => {
    const newContacts = dummyContacts.filter(contact =>
      contact.user_display_name.toLocaleLowerCase().includes(searchTerm.toLocaleLowerCase())
    );
    setFilteredContacts(newContacts);
  },[searchTerm]);

  return (
    <View style={styles.page}>
      <TextInput
        value={searchTerm}
        onChangeText={setSearchTerm}
        style={styles.searchInput}
        placeholder="Search  ksboeli swin Contact name"
      />

      <FlatList
        data={filteredContacts}
        renderItem={({ item }) => (<Text style={styles.contactPage} > {item.user_display_name}</Text>)}
        ItemSeparatorComponent={() => <View style={styles.seperatorLine} />}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  page: {
    padding: 15,
    backgroundColor:'white',
    flex:1,
  },
  contactPage: {
    fontSize: 17,
    marginVertical: 12,
  },
  seperatorLine: {
    width: "100%",
    height: 1,
    backgroundColor: "#f0f0f0",
  },
  searchInput: {
    padding: 10,
    borderRadius: 5,
    backgroundColor: "#f0f0f0",
  },
});

This is my app.js file:
Not sure what to do. Im stuck
import React from 'react';
import {SafeAreaView, StatusBar, StyleSheet} from 'react-native';
import ContactsScreen from './src/screens/ContactScreen';

const App = () => {
  return (
    <SafeAreaView>
      <StatusBar barStyle={'dark-content'} />

      <ContactsScreen />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({});

export default App;

What am I doing wrong please?

A: <FlatList
    data={filteredContacts}
    renderItem={({ item }) => (<Text style={styles.contactPage} > {item.user_display_name}</Text>)}
    ItemSeparatorComponent={() => <View style={styles.seperatorLine} />}
    kexExtractor={item => item.user_id}
/>


text:
Q: Detect when Discord bot was authorized on server Just started to implement a simple bot for Discord.
All goes well but I just cannot find an info on how to detect when bot was authorized on some server.
I mean when somebody use OAuth2 link provided in Discord developer portal to add my bot to a server.
How can I get ID of this server? Is there some event for that?
Thanks.

A: You can detect the event when your bot joins a guild using the on_guild_join() event: (ref: https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.guilds)
@client.event
def on_guild_join(guild):
    # Do something

You can always get the list of guilds your bot is in by using client.guilds (ref: https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.guilds) Note that you require permissions to access this event.


text:
Q: Spring MVC + Springfox 2.9.2 downloads damaged PDF I have a Spring MVC project (no SpringBoot) with a GET endpoint which returns a PDF file. The PDF file is either generated manually or read from resources. I also have a SpringFox dependency to generate swagger-ui.html.
Dependency versions:

*

*Spring: 4.3.25.RELEASE

*SpringFox: 2.9.2

The problem is that when I try to download the PDF directly using the "Download file" button then the file is downloaded but somehow corrupted and impossible to open. But when I use the "Request URL"  I'm able to download the PDF without any problem.

My REST request:
    @RequestMapping(value = "/v1/generatePdfSync", method = RequestMethod.GET)
    public ResponseEntity<Resource> generatePdfSync(@RequestParam String templateName) {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Hello world!");
        model.put("pages", new ArrayList<>(Arrays.asList(1, 2, 3)));

        byte[] bytes = pdfGenerator.generatePdf(templateName, model);

        // Create response
        ByteArrayResource resource = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(resource.contentLength())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"test.pdf\"")
                .body(resource);
    }

My question is whether I don't have some mistake in the request itself.

A: The error was mine, this code worked for me:
@RequestMapping(value = "/v2/generatePdfSync", method = RequestMethod.POST, produces = {MediaType.APPLICATION_PDF_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Resource> generatePdfSync(@RequestBody GeneratePdfRequest generatePdfRequest) {
//        Map<String, Object> model = new HashMap<>();
//        model.put("title", "Hello world!");
//        model.put("pages", new ArrayList<>(Arrays.asList(1, 2, 3)));

        LOGGER.info("GeneratePdfSync: {}", generatePdfRequest);

        byte[] bytes = pdfGenerator.generatePdf(generatePdfRequest.getTemplateName(), generatePdfRequest.getTemplateModel());

        // Create response
        ByteArrayResource resource = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(resource.contentLength())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + generatePdfRequest.getResultPdfName() + "\"")
                .body(resource);
    }


text:
Q: How to make nvd3 work in Internet Explorer 8? I am creating a dashboard project for which i am using nvd3 but as we know svg is not supported in IE8 so it does not render graphs/charts in IE8..please suggest how i can make nvd3 work in IE8

A: I'm in the same situation and I think I may just ditch nvd3 (besides no ie8 support, I'm finding other bugs). I'm wondering, has anyone successfully used r2d3 with nvd3?
My concern is that r2d3 uses d3v3 now, which nvd3 is not presently supporting (currently d3v2... d3v3 support in the works as of writing this).
For an alternative to nvd3, I'm considering:
MorrisJS!
 - Works on ie8 (Raphael-based), but a newer project and less flexibility/options with the charts comparatively.
Google Chart Engine!
 - I think this may be the way to go (for my project), I don't like that its not open source, but I'm already working extensively with the Google Maps API and this solution is very stable and easy to use from my experiences thus far. In limited testing in ie8 it works very well.
Also, here's another stackoverflow question on this topic, [question]: nvd3.js rendering solution for Internet Explorer
 ...seems r2d3 was the accepted answer there, but no one really verified it.

A: The library r2d3 is "a customized build of D3 powered by RaphaelJS. The combination of D3 and Raphael enable developers to easily build data visualizations that work in IE7+ and all modern browsers." - it has its limitations (see the link for details), but it would be a good place to start


text:
Q: Similar to PIE but works quite exact in this case, why? Take a number. $n=100,000$ suppose.
To get the count of numbers less than $n$ which are coprime to $2,3,5,7,11,13$, we can use Principle of Exclusion-Inclusion.
In that case, we will consider terms like $\bigg\lfloor\frac{100,000}{p_1p_2\cdots}\bigg\rfloor$ where $p_i$ are the primes.
But there's a very li'l amount of difference when the product of primes in the denominator divide $n$ and when they don't divide it. It's differs by something $<1$.
Had it been the case when they divided $n$, the answer would've been $\Bigg(100,000-100,000\big(1-\frac{1}{2}\big)\big(1-\frac{1}{3}\big)\big(1-\frac{1}{5}\big)\big(1-\frac{1}{7}\big)\big(1-\frac{1}{11}\big)\big(1-\frac{1}{13}\big)\Bigg)$
But here it's not the case where all the primes divide $n$, but still the round figure of the above result holds exact.
Why so? Can anyone explain me that? As I said, there's a very li'l amount of difference when the product of primes in the denominator divide $n$ and when they don't divide it. It's differs by something $<1$. Even then, small differences together can make a huge difference but here it doesn't happen?
Can I get a rigorous proof instead of intuitive proofs? I think rigorousness is possible here as I have mentioned the value of $n=100,000$ and also the primes $(2,3,5,7,11,13)$.
Now, tell me if this holds for any $n$ and a set of $x$ number of primes or not. If so, explain that. If not, still explain. What my intuition says is that it will hold when $n$ goes bigger and $x$ is as small as possible. The bigger the $x$, the less will be the precision. This is what I believe. Can't justify with rigour.
Thanks a lot StackExchangers!!

A: If the statements $n$ is coprime to $2$ and $n$ is coprime to $3$ were independent, we wouldn't have to worry about inclusion-exclusion.  There would be some fraction coprime to $2$ and the fraction of those coprime to $3$ would be the same fraction as the fraction of $n$.  That would make the multiplication exact.  As you say, that works any time $n$ is a multiple of $6=2 \cdot 3$  With your larger set of primes, the computation assuming independence will be exact when $n$ is a multiple of $2 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 13=30030$
We can look at how close it is for the primes $2,3,5$.  Multiplication predicts that $\frac {1 \cdot 2 \cdot 4}{2 \cdot 3 \cdot 5}=\frac 4{15}$ of the numbers will be coprime to all of these.  We can see how close it is
$$\begin {array} {r r r r}n&coprime up to n&prediction&error\\1&1&0.266667&0.733333\\2&1&0.533333&0.466667\\3&1&0.8&0.2\\4&1&1.066667&-0.06667\\5&1&1.333333&-0.33333\\6&1&1.6&-0.6\\7&2&1.866667&0.133333\\8&2&2.133333&-0.13333\\9&2&2.4&-0.4\\10&2&2.666667&-0.66667\\11&3&2.933333&0.066667\\12&3&3.2&-0.2\\13&4&3.466667&0.533333\\14&4&3.733333&0.266667\\15&4&4&0\\16&4&4.266667&-0.26667\\17&5&4.533333&0.466667\\18&5&4.8&0.2\\19&6&5.066667&0.933333\\20&6&5.333333&0.666667\\21&6&5.6&0.4\\22&6&5.866667&0.133333\\23&7&6.133333&0.866667\\24&7&6.4&0.6\\25&7&6.666667&0.333333\\26&7&6.933333&0.066667\\27&7&7.2&-0.2\\28&7&7.466667&-0.46667\\29&8&7.733333&0.266667\\30&8&8&0 \end {array}$$
If we had started at $0$ all the predictions would have been $\frac 4{15}$ higher.


text:
Q: Solving different kinds of prob questions I have started to learn Probability. I have difficulties with solving some problems. I need help how to solve these kind of questions. I have wrote $3$ of them below:

*

*Moment generating function of rv $X$ is $$m_X(t)=\frac16^{−} + \frac12^{−2} + \frac13^{−3}$$
Find mean and variance of $X$.

*Let $X$ be a geometric rv with parameter $p$. Show that $$P(  =  +  \mid   >  ) = P( = )$$

*The probability $p$ of being able to log on to a computer from a remote terminal at any given time is $0.7$.

*

*a) What is the probability that at least $5$ attempts will be made to gain access to the computer?

*b) What is the expected number of attempts that must be made to gain access to the computer? (Define random variable for the question, determine its type and solve.)

A: *

*The $n$-th moment $EX^n$of a rv $X$ with moment generating function $m_X(t)$ can be calculated as $$EX^n=\frac{d^nm_X(t)}{dt^n}\Bigg|_{t=0}$$ In your case, e.g. $$EX=\frac{dm_X(t)}{dt}\Bigg |_{t=0}=\left(-\frac16e^{-t}-\frac22e^{-2t}-\frac33e^{-3t}\right)\Bigg|_{t=0}=-\frac{13}6$$ To calculate the variance, recall that $$Var(X)=EX^2-\left(EX\right)^2$$so you just need to calculate the second moment $EX^2$ as above, by differentiating one more time.

*Since $X\sim$geometric$(p)$, you know that $P(X=k)=p(1-p)^{k-1}$ for $k\ge1$. Hence \begin{align}P(X=n+k \mid X> n)&=\frac{P(X>n\mid X=n+k)P(X=n+k)}{P(X>n)}\\[0.4cm]&=\frac{1\cdot p(1-p)^{n+k-1}}{\sum_{m=n+1}^{+\infty}p(1-p)^{m-1}}=\frac{p(1-p)^{n}(1-p)^{k-1}}{p(1-p)^n\sum_{m=0}^{+\infty}(1-p)^m}\\[0.4cm]&=\frac{(1-p)^{k-1}}{\frac1{1-(1-p)}}=p(1-p)^{k-1}=P(X=k)\end{align} By the way, this is called the memoryless property of the geometric distribution.

*Hint: The number $X$ of times until the first success (first time to gain access) is a geometric random variable with parameter $p=0.7$. You want to find

*

*a) $P(X\ge 5)$. Use 2. or that $P(X\ge 5)=1-P(X\le 4)$.

*b) $E[X]$.


text:
Q: How would I change the content overflow of an element What I am trying to do?
I have created a custom footer for my textarea. And want to alter the content overflow of my textarea. So that the text would never go beyond the footer of my textarea.
https://imgur.com/hOfqRQ7
As you can see in the picture the text goes beyond the footer (that horizontal line is where the footer starts) of my textarea. How would I prevent it ? so that the text starts to overflow before it reaches the footer.
My code:

#message textarea {
  resize: none;
  min-height: 250px;
  padding-bottom: 45px;
  overflow: hidden;
}

#sendMsg #separator hr {
  margin-top: -35px;
}

#sendMsg #contactFormBtn,
#showContactErrMsg {
  position: absolute;
  margin-top: -30px;
}

#sendMsg #showContactErrMsg {
  padding-left: 40px;
  font-size: 12px;
}

#showContactErrMsg {
  font-size: 14px;
  color: maroon;
  font-family: "Century Gothic";
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

       Message
      <textarea class="form-control" class="formInput" id='inputContactMsg'></textarea>

          <button type="submit" id='contactFormBtn'>Send</button>

A: Change below code in #message textarea
max-height: 250px; /*max instead of min*/
overflow: auto;/*scroll or auto instead of hidden*/

This will force your textarea to take scroll once height reaches your set value.
Hope this helps :)

#message textarea {
  resize: none;
  max-height: 250px; /*change this to max*/
  padding-bottom: 45px;
  overflow: auto;/*change this to scroll*/
    height: 90px;
    width: 100%;
    border: none;
}

#message textarea:focus{
  border: none;
  outline: none;
}

#sendMsg #separator hr {
  margin-top: -35px;
}

#sendMsg #contactFormBtn, #showContactErrMsg {
  position: absolute;
  margin-top: -30px;
}

#sendMsg #showContactErrMsg {
  padding-left: 40px;
  font-size: 12px;
}

#showContactErrMsg {
  font-size: 14px;
  color: maroon;
  font-family: "Century Gothic";
}

div .extra {
  height: 130px;
  display: block;
  overflow: auto;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

       Message

        <textarea class="" class="formInput" id='inputContactMsg'></textarea>

      <button type="submit" id='contactFormBtn'>Send</button>

Edit: Added textarea into one div and gave class="extra" to it.


text:
Q: Pandas how to convert a timestamp column (EST) to local TimeZone info available in other column From
colA (EST)                 colB (local tz)
2016-09-19 01:29:13        US/Central
2016-09-19 02:16:04        Etc/GMT+2
2016-09-19 01:57:54        Europe/London

To
colA (EST)                 colB (local tz)      colC (timestamp in local tz)
2016-09-19 01:29:13        US/Central           2016-09-19 02:29:13
2016-09-19 02:16:04        Etc/GMT+2            2016-09-19 08:16:04
2016-09-19 01:57:54        Europe/London        2016-09-19 05:57:54

A: Read the datetime column as timestamp and localize to US/Eastern time and then apply tz_convert
df['colA (EST)'] = pd.to_datetime(df['colA (EST)']).dt.tz_localize('US/Eastern')
df['colC (timestamp in local tz) '] = df.apply(lambda x: x['colA (EST)']\
.tz_convert(x['colB (local tz)']), axis = 1)

    colA (EST)                 colB (local tz)  colC (timestamp in local tz)
0   2016-09-19 01:29:13-04:00   US/Central      2016-09-19 00:29:13-05:00
1   2016-09-19 02:16:04-04:00   Etc/GMT+2       2016-09-19 04:16:04-02:00
2   2016-09-19 01:57:54-04:00   Europe/London   2016-09-19 06:57:54+01:00


text:
Q: Find the index of the last true occurrence in a column by row I have the following table format:

id
bool

1
true

2
true

3
false

4
false

5
false

6
true

I'd like it so that I could get another column with the index of the last true occurrence in the bool column by row. If it's true in it's own row then return it's own id. It doesn't sound too hard using a for loop but I want it in a clean pandas format. I.e in this example I would get:
column = [1,2,2,2,2,6]

A: IIUC, you can mask and ffill:
df['new'] = df['id'].where(df['bool']).ffill(downcast='infer')

output:
   id    bool  new
0    1   True    1
1    2   True    2
2    3  False    2
3    4  False    2
4    5  False    2
5    6   True    6

A: In your case do
df['new'] = df['id'].mul(df['bool']).cummax()
Out[344]:
0    1
1    2
2    2
3    2
4    2
5    6
dtype: int64

A: df1.assign(col1=np.where(df1.bool2,df1.id,pd.NA)).fillna(method='pad')

  id  bool2  col1
0   1   True     1
1   2   True     2
2   3  False     2
3   4  False     2
4   5  False     2
5   6   True     6


text:
Q: Работа с окном формы Всем доброго времени суток.
Имеется приложени е(игра), запущенное в полнооконноом режиме (курсор не используется в явном виде, т.е. скрыт). Имеется приложение, написанное на делфи и программно расположенное поверх всех окон (также спрятанное из таскбара). Требуется.

*

*
Чтобы курсор не появлялся в игре при выходе его за пределы формы приложении (в идеале отключить/спрятать его совсем при запуске приложения). Пробовал ShowCursor(False) и Screen.Cursor := crNone; в обработчике TForm1.FormPaint, загрузку пустого курсора из файла при создании формы, но при движении мышкой курсор все равно появляется в игре на некоторое время и затем только исчезает.

*
Чтобы при попадании мыши в пределы формы и клике игра не сворачивалась. Пробовал form1.Enabled:=false но не помогло.
Пробовал изучить ловушки, но не понял как ими пользоваться.
A: procedure TForm1.FormCreate(Sender: TObject);

   var
    rtemp,rtemp2,rtemp3,rtemp4,rtemp5,rtemp6:thandle;
    wx,wy,ww,wh:integer;
    begin

    windows.SetParent(form1.Handle,getdesktopwindow);
    SetWindowPos(form1.handle,HWND_TOPMOST,0,0,form1.Width,form1.Height,SWP_SHOWWINDOW or SWP_NOOWNERZORDER or SWP_NOZORDER);
    SetWindowLong(form1.handle, GWL_EXSTYLE, GetWindowLong(form1.handle, GWL_EXSTYLE) or WS_EX_LAYERED {or WS_EX_TRANSPARENT} or WS_EX_TOPMOST);
    form1.show;
    SetWindowPos(form10.handle,HWND_TOPMOST,0,0,form10.Width,form10.Height,SWP_SHOWWINDOW {or SWP_NOOWNERZORDER or SWP_NOZORDER});

 wx:=200; wy:=40; //левый верхний край  окна на десктоп
  ww:=800; wh:=600; //размеры окна на десктоп

  with form1 do begin
   rTemp := CreaterectRgn(0, 0, screen.Width, screen.Height);
   rTemp2 := CreaterectRgn(wx,wy+5+13,wx+ww,wy+wh-17);

   rTemp3 := CreaterectRgn(33,wy+25,33+72,wy+25+93);
   rTemp4 := CreaterectRgn(33,wy+118+46,33+72,wy+118+46+93);
   rTemp5 := CreaterectRgn(33,wy+257+46,33+72,wy+257+46+93);
   rTemp6 := CreaterectRgn(33,wy+396+46,33+72,wy+396+46+93);

   CombineRgn(rTemp, rTemp, rTemp2, RGN_DIFF);
   CombineRgn(rTemp, rTemp, rTemp3, RGN_DIFF);
   CombineRgn(rTemp, rTemp, rTemp4, RGN_DIFF);
   CombineRgn(rTemp, rTemp, rTemp5, RGN_DIFF);
   CombineRgn(rTemp, rTemp, rTemp6, RGN_DIFF);
   SetWindowRgn(form1.Handle, rTemp, True);
   DeleteObject(rTemp);
   DeleteObject(rTemp2);
   DeleteObject(rTemp3);
   DeleteObject(rTemp4);
   DeleteObject(rTemp5);
   DeleteObject(rTemp6);
  end;

  Application.OnIdle := OnIdle;

 end;


text:
Q: Classification of 20 million records to 200 categories I have a data set of 20 million records, which I need to assign to 200 categories.
(Business language - based on the text description, I need to assign it to one of the 200 departments).
Suppose I have to use (multinomial) logistic regression, how can I handle such huge number of target categories?
To generalise, for any ML classification algorithm, what should be the approach to handle such target variables with a large number of options.
Note : I am using Python + NLP (with an option for deep learning)


text:
Q: How to use a randomly generated string as primary key in MySQL? I want to store data about passengers/guests, who book together, with a common reference number consisting of 6 alphanumeric characters. The primary key in the table would have to be (ref_number, number_of_guest) together (e.g. (ASDFJK; 1) refers to guest #1 within the reservation, (ASDFJK; 2) refers to guest #2 within the reservation).
What I want is to create this reference number with a BEFORE INSERT ON trigger like SET NEW.ref = randomlyGeneratedString, but was sad to see that MySQL has only row level statements, therefore I can only add n different reference numbers to all people within the same reservation, but that just makes no sense.

A: I don't think you need a primary key, as usual primary key as auto increase,so you can add a field save,then you can do everything.


text:
Q: Not able to update document in mongodb from node.js I am developing an online course application and I am trying to add new video lectures for a particular course, once the course is created. Once a course is created, after that, if we try to add new course then it sends update request, even if I am adding new video lectures, which is not present so far in the MongoDB. Here is my mongoose schema. File Name:- course.server.model.js.
    'use strict';
 /**
  * Module dependencies
  */
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;

 /**
  * Course Schema
  */
 var CourseSchema = new Schema({
     created: {
         type: Date,
         default: Date.now
     },
     title: {
         type: String,
         default: '',
         trim: true,
         required: 'Title cannot be blank'
     },
     content: {
         type: String,
         default: '',
         trim: true
     },
     // courseLecture: [String],
     courseLecture: [{
         lecture_title: {
             type: String
         },
         //  week_number: { type: Number },
         lecture_video: [String],
         pdf_files: [String]
         // lecture_video: [{ videoUrl: String }]
     }],
     /*
     courseLecture: {
     type: String,
     default: '',
     trim: true
     },*/
     user: {
         type: Schema.ObjectId,
         ref: 'User'
     }
 });

 mongoose.model('Course', CourseSchema);

Here is my node.js controller which updates the course. File Name:- courses.server.controller.js
   'use strict';

 /**
  * Module dependencies
  */
 var path = require('path'),
     mongoose = require('mongoose'),
     Course = mongoose.model('Course'),
     errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

 /**
  * Create an course
  */
 exports.create = function(req, res) {
     var course = new Course(req.body);
     course.user = req.user;

     course.save(function(err) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(course);
         }
     });
 };

 /**
  * Show the current course
  */
 exports.read = function(req, res) {
     // convert mongoose document to JSON
     var course = req.course ? req.course.toJSON() : {};

     // Add a custom field to the Course, for determining if the current User is the "owner".
     // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Course model.
     course.isCurrentUserOwner = !!(req.user && course.user && course.user._id.toString() === req.user._id.toString());

     console.log('course value is: ' + course);
     console.log('video lecture embed value is: ' + course.courseLecture.lecture_video);

     res.json(course);
 };

 /**
  * Update an course
  */
 exports.update = function(req, res) {
     var course = req.course;

     course.title = req.body.title;
     course.content = req.body.content;
     course.courseLecture.lecture_video = req.body.courseLecture.lecture_video;
     course.courseLecture.lecture_title = req.body.courseLecture.lecture_title;
     course.courseLecture.pdf_files = req.body.courseLecture.pdf_files;
     console.log('course lecture video url is: ' + req.body.courseLecture.lecture_video);
     course.save(function(err) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(course);
         }
     });
 };

 /**
  * Delete an course
  */
 exports.delete = function(req, res) {
     var course = req.course;

     course.remove(function(err) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(course);
         }
     });
 };

 /**
  * List of Courses
  */
 exports.list = function(req, res) {
     Course.find().sort('-created').populate('user', 'displayName').exec(function(err, courses) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(courses);
         }
     });
 };

 /**
  * Course middleware
  */
 exports.courseByID = function(req, res, next, id) {

     if (!mongoose.Types.ObjectId.isValid(id)) {
         return res.status(400).send({
             message: 'Course is invalid'
         });
     }

     Course.findById(id).populate('user', 'displayName').exec(function(err, course) {
         if (err) {
             return next(err);
         } else if (!course) {
             return res.status(404).send({
                 message: 'No course with that identifier has been found'
             });
         }
         req.course = course;
         next();
     });
 };

Interestingly I am able to update two fields i.e. title and content, however, whatever is there inside the courseLecture array, that I'm not able to update or make new save.
Please let me know, where I am going wrong here.
TO add more clarity about my frontend work, I'm adding my angular controller and HTML file code.
Angular controller. File name :- course.client.controller.js
(function () {
'use strict';

angular
.module('courses.admin')
.controller('CoursesAdminController', CoursesAdminController);

CoursesAdminController.$inject = ['$scope', '$state', '$window', 'courseResolve', 'Authentication', 'Notification'];

function CoursesAdminController($scope, $state, $window, course, Authentication, Notification) {
var vm = this;

vm.course = course;
vm.authentication = Authentication;
vm.form = {};
vm.remove = remove;
vm.save = save;
vm.ShowHide = ShowHide;
vm.addNewChoice = addNewChoice;

$scope.IsVisible = false;
function ShowHide() {
  // If DIV is visible it will be hidden and vice versa.
  $scope.IsVisible = $scope.IsVisible ? false : true;
}

function addNewChoice() {
  $scope.vm.course.courseLecture.push('');
}

// Remove existing Course
function remove() {
  if ($window.confirm('Are you sure you want to delete?')) {
    vm.course.$remove(function() {
      $state.go('admin.courses.list');
      Notification.success({ message: ' Course deleted successfully!' });
    });
  }
}

// Save Course
function save(isValid) {
  if (!isValid) {
    $scope.$broadcast('show-errors-check-validity', 'vm.form.courseForm');
    return false;
  }

  // Create a new course, or update the current instance
  vm.course.createOrUpdate()
    .then(successCallback)
    .catch(errorCallback);

  function successCallback(res) {
    $state.go('admin.courses.list'); // should we send the User to the list or the updated Course's view?
    Notification.success({ message: ' Course saved successfully!' });
  }

  function errorCallback(res) {
    Notification.error({ message: res.data.message, title: ' Course save error!' });
  }
}
}
}());

My HTML file. File Name:- form-course.client.view.html

{{vm.course._id ? 'Edit Course' : 'New Course'}}

  <form name="vm.form.courseForm" class="form-horizontal" ng-submit="vm.save(vm.form.courseForm.$valid)" novalidate>
     <fieldset>

           Title
           <input name="title" type="text" ng-model="vm.course.title" id="title" class="form-control" placeholder="Title" required autofocus>

Course title is required.

           Content
           <textarea name="content" data-ng-model="vm.course.content" id="content" class="form-control" cols="30" rows="10" placeholder="Content"></textarea>

{{vm.course._id ? 'Edit Lecture' : 'New Lecture'}}

  <form name="vm.form.courseForm" class="form-horizontal" ng-submit="vm.save(vm.form.courseForm.$valid)" novalidate>
  <fieldset data-ng-repeat="field in vm.course.courseLecture track by $index">

  Lecture Title
  <input name="courseLecture" type="text" ng-model="vm.course.courseLecture.lecture_title[$index]" id="LectureTitle" class="form-control" placeholder="Lecture Title" required autofocus>

Lecture name is required.

  Add Lecture video url here
  <input name="courseLecture" type="text" ng-model="vm.course.courseLecture.lecture_video[$index]" id="courseLecture" class="form-control" placeholder="course Lecture">

  </fieldset>
  <input type="button" class="btn btn-default" ng-click="vm.addNewChoice()" value="Add another URL">
  </form>

  <button type="submit" class="btn btn-default">{{vm.course._id ? 'Update' : 'Create'}}</button>

  </fieldset>
  </form>

A:  exports.update = function(req, res) {
 var course = req.course;

Your req.course is not a mongodb object. you can use findOneAndUpdate method of mongoose
http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

A: If your data currently looks like:
{
   courseLecture: {
     lecture_title: 'Test',
     lecture_video: ['vid1', 'vid2'],
     pdf_files: ['pdf1', 'pdf2']
   }
}

I think what you need to do is change this bit:
 courseLecture: [{
     lecture_title: {
         type: String
     },
     //  week_number: { type: Number },
     lecture_video: [String],
     pdf_files: [String]
     // lecture_video: [{ videoUrl: String }]
 }]

to this:
 courseLecture: {
     lecture_title: {
         type: String
     },
     lecture_video: {type: [String] },
     pdf_files: {type: [String] }
 }

You've initially defined the Schema as having an array of objects in the 'courseLecture' field, so either the validation doesn't pass during save, or the Schema doesn't even perform the set operation.


text:
Q: Using the "Add Another" button with inline formsets? I have figured out how to use the admin style "Add Another" button (which adds a new record of the foreign key and pops it into your current form's select box). Here's that question/answer. I am wondering if this is possible with an inline formset where the user can dynamically add additional formsets.
For example, I have an estimate app where the user can select items from a drop down menu. They can add a new inline formset instance and select another item. If they cannot find the item, I want them to be able to add a new item record by clicking the same little + symbol I used (and therefore all the same JS code) for all my other forms.
Any thoughts?

A: I don't think this is something that is natively supported, maybe do a google search on django admin tree structure or so.
What you are looking at achieving is essentially a chained menu, might need to build an interface for it


text:
Q: How to duplicate a tab in Firefox? Is it possible to clone/duplicate tab in Firefox?
Basicaly, the other new tab should contain the same history of the tab I'm trying to clone.

A: There are two possible ways that I've found out:
Using the History

*

*Right clicking on the back/forward buttons of the browser which will open the history of the page. (You can also do the next step directly on the arrows, but if you opened the history you get to choose which page to open from the history, instead of opening directly the previous or next one)

*

*

*Press (and keep pressing) the Ctrl button and click on one of pages in the history.

*Click on one of the pages with the mouse's middle click button.

*Now, after doing any of the steps in the second point, it will open a new tab with the same history of the old tab, and the starting page will be the page you've chosen from the history.

Wihout using the History
If you try to drag and drop the tab as if you were re-arranging it, keep holding Ctrl button before releasing the mouse button while dragging the tab.
This will do the same as above except that you can get to choose where to clone the tab in the tab-bar, and the starting page of the cloned tab is the same as the original one.
Thought I'd share my simple but interesting findings

A: I didn't know Dan's methods. Here are some additional ways:

*

*simply middleclick the refresh button

*drag the icon on the left of the address (the "i" in circle or the lock) to the tab bar

*doubleclick the address to select it whole, then move the mouse a little (to not register a triple click) and click again and hold to drag it to the tab bar


text:
Q: Easier way to change environment variables in Windows 8?
Possible Duplicate:
What are PATH and other environment variables, and how can I set or use them?

I know that I can edit my environment variables in windows 8 by going to
Start -> All Apps -> Control panel -> System ->
    Advanced System Settings -> Advanced -> Environment variables.

But honestly, this is ridiculously complex.
Is there an easier way to change environment variables in Windows 8?
For instance if I just want to append new folder to PATH, it is really annoying to go through all these steps. The UI also sucks, because it is really painful to edit long variable values with the small text input.
Requirement 1: I need the changes to persist (e.g. when I use set in console the changes are lost when I close the console)
Requirement 2: I'd prefer a solution that doesn't involve installing extra pieces of software, since this is the kind of problem that I stumble across every time I configure a new Windows box.

A: It's pretty easy on the command line:
set MyVar=HelloWorld

(to get to the command line, type cmd from the start screen>.)
To view a variable:
echo %MyVar%

Use setx to permanently set a variable. The syntax is slightly different. Try looking here, or there's lots of other sites out there that will tell you how to use it.

A: I change them in Powershell. For instance to add a folder to the PATH variable, open powershell then:
$newPath = $env:Path + ';C:\Temp'
[Environment]::SetEnvironmentVariable('Path', $newpath, 'Machine')

That would change it for all users. To change it just for the user running the command, change that last parameter to 'User'. Or to just change it temporarily in this session:
$env:Path += ';C:\temp'

A: Have you explored the set and setx command? With them you can set a persistent variable. Moreover, the value will be applied immediately, not after the next logon.
Example of windows SET command:
Print the PATH environment variable:
C:\Users\Charity>echo %PATH%
C:\windows\system32;C:\windows and space;C:\foobar

Use set command to set the PATH variable
C:\Users\Charity>set PATH=%PATH%;C:\epicpath
C:\Users\Charity>

The above command only applies to the current window and the change is lost when the cmd window is closed.
C:\Users\Charity>echo %PATH%
C:\windows\system32;C:\windows and space;C:\foobar;C:\epicpath

Example of windows SETX command:
Print the PATH environment variable:
C:\Users\Charity>echo %PATH%
C:\windows\system32;C:\windows and space;C:\foobar

Use setx to set the environment variable:
C:\Users\Charity>setx PATH "%PATH%;C:\zombiepoke"
SUCCESS: Specified value was saved.

Close and re-open cmd terminal, then run:
C:\Users\Charity>echo %PATH%
C:\windows\system32;C:\windows and space;C:\foobar;C:\zombiepoke

You have to be careful with double quotes.  If you let quotes get into your path variable it might break something.  However they are necessary for specifying addendums to the original %PATH%.

A: Set Environment variable in Windows 8.
You can access the advanced system setting by right clicking Computer in a file-explorer and going to properties.
This is same as older versions of windows.  You can also set environment variables from command line as given here :
What are PATH and other environment variables, and how can I set or use them?


text:
Q: Scala class cant override compare method from Java Interface which extends java.util.comparator I'm currently working on a port of a jEdit plugin to write all code in Scala. However Im forced at a certain point to implement my own Comparator.
My simplified code is as follows:
class compare extends MiscUtilities.Compare {
  def compare(obj1: AnyRef, obj2: AnyRef): Int = 1
}

The MiscUtilities.Compare has the following signature when looking from IntelliJ
public static interface Compare extends java.util.Comparator {
    int compare(java.lang.Object o, java.lang.Object o1);
}

However when im trying to compile my class I get a error saying:
error: class compare needs to be abstract, since method compare in trait Comparator of type (x$1: T,x$2: T)Int is not defined
class compare extends MiscUtilities.Compare {
I have also tried with Any and java.lang.Object as types, but no luck so far.
Help is very much appreciated:)
Regards Stefan

A: It may be impossible. If this is wrong, I would like to know.
EDIT: But you can do this instead:
// CompareImpl.java
abstract class CompareImpl implements MiscUtilities.Compare {
  public int compare(Object o, Object o1) {
    return doCompare(o, o1);
  }

  public abstract int doCompare(Object o, Object o1);
}

// MyCompare.scala
object MyCompare extends CompareImpl {
  def doCompare(a: AnyRef, b: AnyRef) = 0
}

So you still have to write some Java, but only one trivial class for each interface like MiscUtilities.Compare.

A: Producing a standalone example is the first step to solving these sort of problems.
 ~/code/scratch/raw: cat Compare.java
interface Compare extends java.util.Comparator {
}
 ~/code/scratch/raw: cat MyCompare.scala
object MyCompare extends Compare  {
  def compare(a: AnyRef, b: AnyRef) = 0
}
 ~/code/scratch/raw: scalac MyCompare.scala Compare.java
MyCompare.scala:1: error: object creation impossible, since method compare in trait Comparator of type (x$1: T,x$2: T)Int is not defined
object MyCompare extends Compare  {
       ^

The temptation is to extend Comparator[AnyRef] directly from MyCompare, along with Compare:
object MyCompare extends java.util.Comparator[AnyRef] with Compare  {
  def compare(a: AnyRef, b: AnyRef) = 0
}

But this leads to:
error: illegal inheritance;
 self-type MyCompare.type does not conform to java.util.Comparator[AnyRef]'s selftype java.util.Comparator[AnyRef]

So I'm inclined to agree that this isn't possible, at least directly. Write the class in Java, delegating to Scala if need be.

A: Does it work if you put [AnyRef] after MiscUtilities.Compare? I.e.,
class Compare extends MiscUtilities.Compare[AnyRef] {
  def compare(a1:AnyRef, a2:AnyRef) = 0
}

I tried that with java.util.Comparator directly and the compiler seemed happy.


text:
Q: scroll bar for 100% height div I've managed to create this, it's the height of the page but I'm trying to get it to scroll rather than stretch forever downwards

css for .leftnavdiv
.leftnavdiv {
    padding-top: 40px;
    overflow: hidden;
    z-index: 99;
    position: fixed;
    _position:absolute;
    top: 0px;
    _top:expression(eval(document.body.scrollTop));
    left: 0px;
    width: 10px;
    height: 100%;
    background-color: white;
    a:link color:#FF0000;
    a:visited color:#00FF00;
}

html:

                                <?php
                                //code removed
                                ?>

A: Forget height: 100%, you can use:
.leftnavdiv {
   bottom: 0;
   left: 0;
   overflow-x: hidden;
   overflow-y: auto;
   padding: 0;
   position: fixed;
   top: 0;
   width: 300px;
}


text:
Q: AS3 Client Socket can't connect to a local network server I have a c# server socket on a PC, and a client AS3 socket on another PC on the same local network as the first PC.
the problem is when the c# and AS3 are on the same PC the connection is OK, but when i move the c# on another PC on the local network the AS3 can't reach it !!

A: *

*Socket Programming Using AS 3.0

*Socket Programming AS 3.0 API
Please refer given below Code :
package {
        import flash.display.Sprite;

        public class SocketExample extends Sprite {
            private var socket:CustomSocket;

            public function SocketExample() {
                socket = new CustomSocket("localhost", 80);
            }
        }
    }

    import flash.errors.*;
    import flash.events.*;
    import flash.net.Socket;

    class CustomSocket extends Socket {
        private var response:String;

        public function CustomSocket(host:String = null, port:uint = 0) {
            super();
            configureListeners();
            if (host && port)  {
                super.connect(host, port);
            }
        }

        private function configureListeners():void {
            addEventListener(Event.CLOSE, closeHandler);
            addEventListener(Event.CONNECT, connectHandler);
            addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
        }

        private function writeln(str:String):void {
            str += "\n";
            try {
                writeUTFBytes(str);
            }
            catch(e:IOError) {
                trace(e);
            }
        }

        private function sendRequest():void {
            trace("sendRequest");
            response = "";
            writeln("GET /");
            flush();
        }

        private function readResponse():void {
            var str:String = readUTFBytes(bytesAvailable);
            response += str;
        }

        private function closeHandler(event:Event):void {
            trace("closeHandler: " + event);
            trace(response.toString());
        }

        private function connectHandler(event:Event):void {
            trace("connectHandler: " + event);
            sendRequest();
        }

        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("ioErrorHandler: " + event);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + event);
        }

        private function socketDataHandler(event:ProgressEvent):void {
            trace("socketDataHandler: " + event);
            readResponse();
        }
    }


text:
Q: Angular Universal html lang tag In Angular Universal I have an index.html file. At the top it has
<html lang="en">

I would like to change this based on the page I am on. maldonadoattorney.com/es/jailreleases would be
<html lang="es">

maldonadoattorney.com/jailreleases would be
<html lang="en">

Is there an accepted way of doing this? Have read other questions and DOCUMENT is deprecated, so am wary of using it.
I have my site map set up with hreflang tags, but would like the html lang tag to be correct. Currently, I'm taking the lang="en" tag out of my index.html.

A: You're right but DOCUMENT from @angular/platform-browser is deprecated in favor of DOCUMENT from @angular/common.
So you can use the following code:
import { DOCUMENT } from '@angular/common';

...

export class AppComponent implements OnInit {

  constructor(@Inject(DOCUMENT) private document: Document) {}

  ngOnInit() {
    this.document.documentElement.lang = 'es';
  }
  ...
}


text:
Q: How to make react native apps look like other android apps? I've done a single page app in react native using native base UI kit. The page consists of a grid view with 3 rows and 3  columns. When I take the build in the emulator the grid view fit within the screen width. But after taking build on Moto-G3 and Redmi Note5-pro. I got the following screens. The problem is the last row takes the scroll. So the grid does not fit in Moto-G3. Following are the screenshots, please have a look.
1. Moto-G3

2. Redmi Note5-pro

I tried to avoid Content and used View and got this in emulator https://i.stack.imgur.com/MPkce.png
Following is my code for a single row please have a look.
<Container>
 <Content style={{padding:20,paddingLeft:8,flex:1,marginBottom:30}}>
 <Grid>
<Row style={{marginTop:10,flex:1,marginLeft:8}}>
 <Col style={styl.col}>
<TouchableOpacity onPress ={() => console.log("hii")}>
 <Col style={styl.col2}>
<Image source={require('../../imgs/inquiry.png')} style={styl.image} />
 </Col>
 </TouchableOpacity>
<Text style={styl.text}>Inquiry</Text>
 </Col>
 <Col style={styl.col}>
<TouchableOpacity onPress ={() => console.log("hii")}>
<Col style={styl.col2}>
<Image source={require('../../imgs/passport.png')} style={styl.image} />
 </Col>
</TouchableOpacity>
 <Text style={styl.text}>Visa Status Inquiry</Text>
</Col>
<Col style={styl.col}>
<TouchableOpacity onPress ={() => console.log("hii")}>
 <Col style={styl.col2}>
<Image source={require('../../imgs/document.png')} style={styl.image} />
 </Col>
</TouchableOpacity>
 <Text style={styl.text}>Service Procedures</Text>
</Col>
 </Row>
</Grid>
</Content>

const styl = StyleSheet.create({
  col:{
    flex:1,
     margin:10,
     marginBottom:30
   },
   col2:{
     padding:20,
     backgroundColor:"#000080",
      borderRadius:20,
      flex:1,
      elevation:10
    }, text:{
     fontSize:15,
     marginTop:10,
     textAlign:'center'
   },
   image:{
     width:40,
     height:40,
      alignSelf:'center'
    })}

What should I do to make it responsive? It is responsive for sure, but the problem is with the scroll.

A: The problem is that you are defining a constant size for all of your images, margins, etc...
You should use some kind of multiplier to modify this number depending on the image size or use percentages (but the percentage way could go horribly wrong, depending on the devices screen, so I use the multiplier way)
You can achieve this using react-native-size-matters package. For example:
import { scale, verticalScale, moderateScale } from 'react-native-size-matters';

const Component = props =>
    <View style={{
        width: scale(30),
        height: verticalScale(50),
        padding: moderateScale(5)
    }}/>;

Just read the docs that I provided in the link. There is everything.
I think that you will just need to wrap the number 40 in the scale method and tweak the sizes.


text:
Q: Vue watcher and Vuex do not work properly I have a component that updates state in the Vuex  and I can see via vue dev tools that vuex state is changed, however when I try to execute some logic when state changes via watchers bound to the mapGetters or mapState on Vuex it does not work at all.
the code from vuex:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    companyDetails: {},
    //date: "",
    showSearchForm: false,
    consumptionData: {
      dateTo: new Date(),
      dateFrom: new Date(new Date().setDate(new Date().getDate() - 7))
    }
  },
  getters: {
    getConsumptionData(state) {
      return state.consumptionData;
    }
  },.....

The code on watcher and computed property that gets data from Vuex either by MapState or MapGetters commented code means that I tried all those options
  computed: {
    // need to ask about reactiveness
    // ...mapGetters({
    //   consumptionDataVuex: "getConsumptionData"
    // })
    //  ...mapState({
    //  consumptionDataVuex: "ConsumptionData"
    //  })
    consumptionDataVuex () {
      return this.$store.getters.getConsumptionData;
    }
  },
    watch: {
    consumptionDataVuex() {
      console.log("changed");
      this.getConsumption();
    }
  },.....

The only code that does synchroniously gets data from vuex is this
  created() {
    //console.log(this.parentData);
this.$store.watch(
  (state)=>{
    return this.$store.state.consumptionData // could also put a Getter here
  },
  (newValue, oldValue)=>{
    //something changed do something
    console.log(oldValue)
    console.log(newValue)
    this.getConsumption();
  },
//Optional Deep if you need it
    {
      deep:true
    }
  )
  },

So, I do not understand why the code above cannot get updates from state while the code in the created Hook does? A lot of examples in internet do prove it should work

A: Try to change your watch
    watch: {
        consumptionDataVuex: {
            handler () {
              console.log("changed");
              this.getConsumption();
            },
            deep: true
        }
    }


text:
Q: How to get list of mongodb databases and collections list from a ruby on rails app I am using Rails 3 and Mongoid gem. But I need to fill a combobox with the list of mongodb databases. In mongodb shell we can list databases with "show dbs" command. Also there is getDBNameList()  and db.getCollectionNames() commands in mongodb drivers. But I could not figure out how to use these commands from a ruby on rails app.
Also I wonder; if I can get databases and collections list with using mongoid gem. Because I am sure that I had read that mongoid supports using more than one database, but I think it was model dependent.
So what do you think; is there any solution or I have to use mongo-ruby-driver gem, not mongoid.

A: It would be easier to get the Mongo::DB out of the Mongoid config:
db = Mongoid::Config.master
db.collection_names

A: A short version.
db = Mongoid.master
db.collection_names

A: In mongoid 3
Mongoid.default_session.collections # returns the collections

I usually extract the names as follows:
Mongoid.default_session.collections.map(&:name).sort

A: You can do the following using the mongo ruby driver:
require 'rubygems'
require 'mongo'

connection = Mongo::Connection.new("localhost")
connection.database_names.each do |name|
  db = connection.db(name)
  db.collections.each do |collection|
    puts "#{name} - #{collection.name}"
  end
end


text:
Q: mongoose prehook fails for updateOne call My database schema is this on high level:
{"host_id" : Object ID,
"hostname":<string>,
"userNames":[] //Array of userNames
"usersCount: <Number> }

usersCount field should hold the Total Count of users present at that instant.
While adding/deleting userNames as part of updateOne calls , i have added pre-hook to the updateOne calls.
async function addUsers(user){
...
...

await host.updateOne({ $addToSet: { 'userNames': user.name } });

}

Prehook for updateOne calls
  host.pre('updateOne', updateUsersCount);

  const updateUsersCount = function () {
    this.set([{ usersCount: { $size: "$userNames" }}])

  }

The pre-hook query runs in mongo shell but fails from script.I can see the query getting invoked and it doesn't throw any error/exceptions, but nothing gets written to the db. What am i missing here ? or is there a better way to do this ?
I need to have the count field updated  depending on the array increase/decrease


text:
Q: Merge data inside foreach in Laravel I create function inside Model.
Variable $category=1,2,3; is string
I want that function to look in table categories and to return me name of this ids in one variable to be like $categoryName=first,second,third
public function getCategory($category){
    $names = explode(",",$category);

    foreach ($names as $name){
        $categories = DB::table('categories')->where('id',$name)->first();
        $categoryName = implode(',',(array)$categories->name);
    }
    return $this->$categoryName;
}

A: Simply, what you want to do can be done as following.
public function getCategory($categoryIds) // ex) 1,2,3
{

    $categoryIdArray = explode(",", $categoryIds); // [1,2,3]
    $categoryName = '';
    foreach ($categoryIdArray as $categoryId){
      $category = DB::table('categories')->where('id',$categoryId)->first();
      $categoryName .= $category->name . ',';
    }
    $categoryName = substr($categoryName, 0, -1);
    return $categoryName;
}

However, the example above don't make use of the advantage of Model.
Does the Model which have getCategory method have category_ids attribute?
If it is, you can write as follows.
public function getCategory()
{

    $categoryIdArray = explode(",", $this->category_ids);
    $categoryName = '';
    foreach ($categoryIdArray as $categoryId){
      $category = DB::table('categories')->where('id',$categoryId)->first();
      $categoryName .= $category->name . ',';
    }
    $categoryName = substr($categoryName, 0, -1);
    return $categoryName;
}

You can access category_ids which have 1,2,3 value for instance via $this so it doesn't need argument.
To do moreover effectively, you can have category_id attribute in another model.
In that case, you can do above more simply.
Reference:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

A: No need to loop over your ids and do multiple DB queries - you can get them all with just one query using whereIn
public function getCategory($category) {
    $ids = explode(",",$category);
    $categories = DB::table('categories')->whereIn('id',$ids)->get();
    return $categories->implode('name', ',');
}

More info about whereIn in the docs.
However it would be neater to do this using Eloquent, the Laravel way, for example (this assumes you have a Category model to match your categories table):
public function getCategory($category) {
    $ids = explode(",",$category);
    $categories = App\Category::find($ids);
    return $categories->implode('name', ',');
}

More info about retrieving models in the docs.


text:
Q: Issue with calling a procedure from within Workbook_SheetChange I created a workbook with multiple sheets requiring numerous two-way linked cells in different worksheets within the same workbook. So, if I edit cell B5 in worksheetA, it will automatically update cell J2 in worksheetB with the same value. Conversely, if I update cell J2 in worksheetB, it will automatically update cell B5 in worksheetA.  To accomplish the two-way link, I included the following code in ThisWorkbook:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Sh.Name = "Smith,Joe" Then
        If Not Application.Intersect(Target, Range("B4")) Is Nothing Then
            Application.EnableEvents = False
            If Target.Parent.Name = "SomeProject" Then
                Sheets("Smith,Joe").Range("B4") = Target
            Else
                Sheets("SomeProject").Range("B10") = Target
            End If
            Application.EnableEvents = True
        End If
    End If
    If Sh.Name = "SomeProject" Then
        If Not Application.Intersect(Target, Range("B10")) Is Nothing Then
            Application.EnableEvents = False
            If Target.Parent.Name = "Smith,Joe" Then
                Sheets("SomeProject").Range("B10") = Target
            Else
                Sheets("Smith,Joe").Range("B4") = Target
            End If
            Application.EnableEvents = True
        End If
    End If
    If Sh.Name = "Smith,Joe" Then
        If Not Application.Intersect(Target, Range("C4")) Is Nothing Then
            Application.EnableEvents = False
            If Target.Parent.Name = "SomeProject" Then
                Sheets("Smith,Joe").Range("C4") = Target
            Else
                Sheets("SomeProject").Range("D10") = Target
            End If
            Application.EnableEvents = True
        End If
    End If
    If Sh.Name = "SomeProject" Then
        If Not Application.Intersect(Target, Range("D10")) Is Nothing Then
            Application.EnableEvents = False
            If Target.Parent.Name = "Smith,Joe" Then
                Sheets("SomeProject").Range("D10") = Target
            Else
                Sheets("Smith,Joe").Range("C4") = Target
            End If
            Application.EnableEvents = True
        End If
    End IF
    'This continues with for many different people/projects
End Sub

This worked without issue until the procedure bumped up against the 64k limit (Found out about that on the forum).  To get around the limitation, I created multiple separate procedures called from a main proc, but the cells no longer update automatically.  After countless errors and visits to a myriad of forums I've ended up with WorkSheet_Change in ThisWorkbook calling a controlling proc in a module and all of the worksheet and cell references being passed in as variables. It's still no longer updating cells on either worksheet. As it stands right now, I'm getting a Run-time error 91 (Object variable or With block variable not set) when I step through the module code at the ChangeLogic sub.
ThisWorkbook code:
Option Explicit

Public Sh As Object
Public Target As Range
Public ResourceSheet As Object
Public ProjectSheet As Object
Public ResourceCell As String
Public ProjectCell As String

Private Sub Worksheet_Change(ByVal Sh As Object, ByVal Target As Range)

   Run "Main"

End Sub

Code in "Main" module:
Sub Main()

    Call JoeMain

End Sub

Sub JoeMain()

    Set ResourceSheet = Sheets("Smith,Joe")
    Set ProjectSheet = Sheets("SomeProject")

    Call Joe1
    Call ChangeLogic(Sh, Target, ResourceSheet, ProjectSheet, ResourceCell, ProjectCell)

    Call Joe2
    Call ChangeLogic(Sh, Target, ResourceSheet, ProjectSheet, ResourceCell, ProjectCell)

    'Continues on for all cases involing Joe Smith.  I haven't gotten to iterating through project names as of yet

End Sub

Sub Joe1()

    ResourceCell = "B4"
    ProjectCell = "B10"

End Sub

Sub Joe2()

    ResourceCell = "C4"
    ProjectCell = "D10"

End Sub

Sub ChangeLogic(Sh, Target, ResourceSheet, ProjectSheet, ResourceCell, ProjectCell)
    If Sh.Name = ResourceSheet.Name Then
        If Not Application.Intersect(Target, Range(ResourceCell)) Is Nothing Then
            Application.EnableEvents = False
            If Target.Parent.Name = ProjectSheet.Name Then
                Sheets(ResourceSheet.Name).Range(ResourceCell) = Target
            Else
                Sheets(ProjectSheet.Name).Range(ProjectCell) = Target
            End If
            Application.EnableEvents = True
        End If
    End If
    If Sh.Name = ProjectSheet.Name Then
        If Not Application.Intersect(Target, Range(ProjectCell)) Is Nothing Then
            Application.EnableEvents = False
            If Target.Parent.Name = ResourceSheet.Name Then
            Sheets(ProjectSheet.Name).Range(ProjectCell) = Target
            Else
                Sheets(ResourceSheet.Name).Range(ResourceCell) = Target
            End If
            Application.EnableEvents = True
        End If
    End If
End Sub

At this point my newbie colors are showing and I'm in over my head. Any suggestions for what I'm doing wrong and how I can get this to work?
Thanks.

A: I was tired of typing in comments so I might as well type here and make it more clear as to what I am saying.
I am not sure how did you reach the 64k limit. As mentioned in the comments above, you can write your code in a more stuctured/compact manner. Currently you code is of 44 lines excluding the Sub/End Sub/Comments The same code can be written in 24 lines
So that is a straight saving of 20 lines!!!.
Imagine how much your final code will reduce to when you remove all the unnecessary Application.EnableEvents/IF-ENDIF
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    Select Case Sh.Name
    Case "Smith,Joe"
        If Not Application.Intersect(Target, Range("B4")) Is Nothing Then _
        If Target.Parent.Name = "SomeProject" Then Sheets("Smith,Joe").Range("B4") = Target Else _
        Sheets("SomeProject").Range("B10") = Target

        If Not Application.Intersect(Target, Range("C4")) Is Nothing Then _
        If Target.Parent.Name = "SomeProject" Then Sheets("Smith,Joe").Range("C4") = Target Else _
        Sheets("SomeProject").Range("D10") = Target
    Case "SomeProject"
        If Not Application.Intersect(Target, Range("B10")) Is Nothing Then _
        If Target.Parent.Name = "Smith,Joe" Then Sheets("SomeProject").Range("B10") = Target Else _
        Sheets("Smith,Joe").Range("B4") = Target

        If Not Application.Intersect(Target, Range("D10")) Is Nothing Then _
        If Target.Parent.Name = "Smith,Joe" Then Sheets("SomeProject").Range("D10") = Target Else _
        Sheets("Smith,Joe").Range("C4") = Target

        'This continues with for many different people/projects
    End Select
LetsContinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub


text:
Q: Image deload itself in a filtered list I have a filtered image list with buttons to change the filter in which changes the rendered list.
The problem is that after back and forth switching sometimes images get deloaded and needs to be downloaded again.
I tried using v-once and still doesn't fix the issue
Codepen
<button v-on:click="filter('all')">All</button>
  <button v-on:click="filter('tag1')">Tag 1</button>
  <button v-on:click="filter('tag2')">Tag 2</button>

methods: {
  filter(tag) {
    this.currentTag= tag;
  }
},
computed: {
  filteredItems: function() {
    var filter = this.currentTag;
    return this.items.filter(function(item) {
        return item.tags.indexOf(filter) !== -1;
    });
  }
}

For some reason this issue is very hard to trigger in the codepen example(it deloads only sometime), but on my local dev environment the images deload every time I toggle the filters.
The Vue computed filters would remove the images directly from the Dom, I'm thinking would it be possible to let it just be display none like v-show?

A: The issue here is that you re-render the img elements on filtering, thus the images are fetched again.
I've removed the computed property and instead rendered the full list. To filter, I've used v-show on .list-complete-item to toggle visibility.

new Vue({
  el: '#list-complete-demo',
  data: {
    items: [{
        id: 1,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x600'
      },
      {
        id: 2,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x601'
      },
      {
        id: 3,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x602'
      },
      {
        id: 4,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x603'
      },
      {
        id: 5,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x604'
      },
      {
        id: 6,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x605'
      },
      {
        id: 7,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x606'
      },
      {
        id: 8,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x607'
      },
      {
        id: 9,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x608'
      },
      {
        id: 10,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x608'
      },
      {
        id: 11,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x609'
      },
      {
        id: 12,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x610'
      },
      {
        id: 13,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x611'
      },
      {
        id: 14,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x612'
      },
      {
        id: 15,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x613'
      },
      {
        id: 16,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x614'
      },
      {
        id: 17,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x615'
      },
      {
        id: 18,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x616'
      },
      {
        id: 19,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x617'
      },
      {
        id: 20,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x618'
      },
      {
        id: 21,
        tags: ['all', 'tag1'],
        img: 'https://source.unsplash.com/random/800x619'
      },
      {
        id: 22,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x620'
      },
      {
        id: 23,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x621'
      },
      {
        id: 24,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x622'
      },
      {
        id: 25,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x623'
      },
      {
        id: 26,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x624'
      },
      {
        id: 27,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x625'
      },
      {
        id: 28,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x626'
      },
      {
        id: 29,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x627'
      },
      {
        id: 30,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x628'
      },
      {
        id: 31,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x629'
      },
      {
        id: 32,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x630'
      },
      {
        id: 33,
        tags: ['all', 'tag2'],
        img: 'https://sour3ce.unsplash.com/random/800x631'
      },
      {
        id: 34,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x632'
      },
      {
        id: 35,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x633'
      },
      {
        id: 36,
        tags: ['all', 'tag2'],
        img: 'https://sour46e.unsplash.com/random/800x634'
      },
      {
        id: 37,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x635'
      },
      {
        id: 38,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x636'
      },
      {
        id: 39,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x637'
      },
      {
        id: 40,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x638'
      },
      {
        id: 41,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x639'
      },
      {
        id: 42,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x640'
      },
      {
        id: 43,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x641'
      },
      {
        id: 44,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x642'
      },
      {
        id: 45,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x643'
      },
      {
        id: 46,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x644'
      },
      {
        id: 47,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x645'
      },
      {
        id: 48,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x646'
      },
      {
        id: 49,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x647'
      },
      {
        id: 50,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x648'
      },
      {
        id: 51,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x649'
      },
      {
        id: 52,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x650'
      },
      {
        id: 53,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x651'
      },
      {
        id: 54,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x652'
      },
      {
        id: 55,
        tags: ['all', 'tag2'],
        img: 'https://source.unsplash.com/random/800x653'
      }

    ],
    currentTag: 'all'
  },
  methods: {
    shuffle: function() {
      this.items = _.shuffle(this.items)
    },
    filter: function(tag) {
      this.currentTag = tag;
    }
  }
})
.list-complete {
  display: flex;
  width: 100%;
  flex-direction: row;
  flex-wrap: wrap;
}

.list-complete-item {
  transition: transform 1s;
  flex: 1 1 25%;
  height: 200px;
  padding: 10px;
  /*   display: inline-block;
  margin-right: 10px; */
}

.list-complete-img {
  object-fit: cover;
  height: 100%;
  width: 100%;
}

.list-complete-enter,
.list-complete-leave-to
/* .list-complete-leave-active for <2.1.8 */

{
  opacity: 0;
  transform: translateY(30px);
}

.list-complete-leave-active {
  position: absolute;
}

  <button v-on:click="shuffle">Shuffle</button> Filter:
  <button v-on:click="filter('all')">All</button>
  <button v-on:click="filter('tag1')">Tag 1</button>
  <button v-on:click="filter('tag2')">Tag 2</button>

    <template v-for="item in items">

  </template>


text:
Q: What does the .NET CLR do with the memory overhead in empty types? All .NET classes have sync block and type pointers stored as part of their instances. These take up a total of 8 bytes in 32-bit processes and 16 bytes in 64-bit processes. However, the object size of an instance of an empty type is 12 and 24 bytes, respectively.
I've seen some articles saying it is an alignment issue, but since the sync block and type handle are pointer-sized, I don't understand why any padding needs to be added.
Other articles say that the garbage collector needs it, but what does it do with the overhead? It can't store anything there because that extra space is actually used if a type has instance fields. Does the garbage collector do something with that memory some time after object finalization and before it is freed that it needs a place to put something (maybe a pointer)?
Here are some of the articles I have read regarding empty type sizes:
Performance Considerations of Class Design and General Coding in .NET:

If you made an object with no fields and looked at it in the debugger, you would notice that its size is actually 12 bytes, not 8. For 64-bit processes, the object would be 24 bytes. This is because the minimum size is based on alignment. Thankfully, this "extra" 4 bytes of space will be used by a field.

Of memory and strings:

There's a "minimum" size of 12 bytes and 24 bytes respectively. In other words, you can't have a type which is just the overhead. Note how the "Empty" class takes up the same size as creating instances of Object… there's effectively some spare room, because the CLR doesn't like operating on an object with no data.

Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects:

As discussed previously, the current GC implementation needs an object instance of at least 12 bytes. If a class does not have any instance fields defined, it will carry an overhead of 4 bytes. The rest of the 8 bytes will be taken up by the Object Header (which may contain a syncblk number) and TypeHandle.

A: Ah, I see what is going on.
Arrays store their length as the first 4 or 8 bytes (in 32 and 64-bit systems, respectively) of their instance field data (after the type pointer). In order to get the size of memory usage, the CLR gets the base size from the method table (pointed to by the type pointer) and adds the length multiplied by the per-item size (which it also gets from the method table).
In other words, the formula is:

memory size = base size + length * item size

Rather than have one formula for arrays and a different one for other types, the implementors of the CLR wanted to have a single formula for both, thus eliminating the need for any conditional logic when getting the memory size.
But how could that work? Other object types don't store a length in the first 4 or 8 bytes of their instance field data.
The key is the item size, which is stored in the method table. For non-array types, the item size is 0. This means that length * item size will always be 0 regardless of the value stored in the first 4 or 8 bytes of the instance field data, and the formula will work.
But even though the value of the first 4 or 8 bytes of instance field data doesn't matter, it still needs to be allocated to prevent access violations.
Thanks to Hans for pointing me to the SetFree method. Once I saw that the CLR was essentially converting an arbitrary object to a 1-dimensional byte array, I realized that it was assuming that everything could be converted in that manner, and the investigation into why led me to this answer.

A: Yes, even an empty class requires 4/8 bytes for the section of the object that normally stores the fields of the object.  So a completely empty class still takes 4 + 4 + 4 = 12 bytes in 32-bit mode, 8 + 8 + 8 = 24 bytes in 64-bit mode.  Those 4/8 extra bytes are simply not used when the object exists.
This storage is required when the object is released.  It can then become part of the free block list of a heap segment.  This happens if the heap segment contains pinned objects and could not be compacted perfectly.  In that case, the sync block is set to -1 in the debug build, the type handle is set to the internal fake FreeObject type.  And the object size takes 4 bytes.
Visible from the SSCLI20 source code, clr/src/vm/gcsmp.cpp file, SetFree() function.


text:
Q: Visualizing dependency tree depth in autofac I may have been searching for the wrong stuff, looking in the wrong boxes. But I can't seem to find a good way to visualize how deep my dependecy tree is in C#.
I've initially tried just hooking up on the preparing-event & the activating-event from Autofac. But I can't figure out if this is good enough. The results looks kinda funky. It seems that the preparing-event is initiated too often. And it seems that the activating event is only activated when a new object is actually created.
Our code is .NET 4.7.2
We're using Autofac as our container to handle the dependency injection.
Does anyone have a good idé for how we can visualize the depth? Maybe there exists some good code or a product out there that can help us?

A: Some time ago, I had a similar quest with Autofac. What I ended up with was the following:
public class DebugResolveModule : Module
{
    private readonly ThreadLocal<ResolveInfo> _current = new ThreadLocal<ResolveInfo>();

    protected override void AttachToComponentRegistration(
        IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        registration.Preparing += Registration_Preparing;
        registration.Activating += Registration_Activating;

        base.AttachToComponentRegistration(componentRegistry, registration);
    }

    private void Registration_Preparing(object sender, PreparingEventArgs e)
    {
        _current.Value = new ResolveInfo(e.Component.Activator.LimitType, _current.Value);
    }

    private void Registration_Activating(object sender, ActivatingEventArgs<object> e)
    {
        var current = _current.Value;
        current.MarkComponentAsResolved();
        _current.Value = current.Parent;

        if (current.Parent == null)
        {
            VisualizeGraph(current);
            Debug.WriteLine(
                $"total resolve time: {current.ResolveTime.TotalMilliseconds} ms.");
        }
    }

    private static void VisualizeGraph(ResolveInfo node, int depth = 0)
    {
        for (int i = 0; i < depth; i++)
        {
            Debug.Write("   ");
        }

        Debug.Write(node.ComponentType);
        Debug.Write(" (");
        Debug.Write(node.ResolveTime.TotalMilliseconds.ToString("F1"));
        Debug.Write(" ms. / ");
        Debug.Write(node.CreationTime.TotalMilliseconds.ToString("F1"));
        Debug.Write(" ms.)");

        Debug.WriteLine("");

        foreach (var dependency in node.Dependencies)
        {
            VisualizeGraph(dependency, depth + 1);
        }
    }

    private sealed class ResolveInfo
    {
        private Stopwatch _watch = Stopwatch.StartNew();

        public ResolveInfo(Type componentType, ResolveInfo parent)
        {
            ComponentType = componentType;
            Parent = parent;
            Dependencies = new List<ResolveInfo>(4);

            if (parent != null)
            {
                parent.Dependencies.Add(this);
            }
        }

        public Type ComponentType { get; }

        // Time it took to create the type including its dependencies
        public TimeSpan ResolveTime { get; private set; }

        // Time it took to create the type excluding its dependencies
        public TimeSpan CreationTime { get; private set; }
        public ResolveInfo Parent { get; }

        public List<ResolveInfo> Dependencies { get; }

        public void MarkComponentAsResolved()
        {
            ResolveTime = _watch.Elapsed;
            CreationTime = ResolveTime;

            foreach (var dependency in this.Dependencies)
            {
                CreationTime -= dependency.ResolveTime;
            }

            _watch = null;
        }
    }
}

Do note that this does not exactly what you want, because it is a resolve trigger. This means that a SingleInstance is only resolved once, which means the next time you request the graph, you'll be missing the singletons. This wasn't a problem for me, because I used this code to detect slow-resolving parts of the object graphs.
This code might, however, still give you some ideas of how to do this.


text:
Q: Triple Integral on the xy-plane For the solid bounded by $x=0 , x=2, z=y, z=y-1, z=0, z=4$ I am looking at the $xy-plane$ and setting up a triple integral. I'm not sure where to start on this problem, as some of the plans are "$z=$" but I know $z=0$ is the xy-plane. I think I may need two integrals here. I get $\int_{0}^{2} \int_{z}^{z+1} \int_{y-1}^{y} dzdydx$ and $\int_{0}^{2} \int_{0}^{4} \int_{y-1}^{y} dzdydx$. Not sure if this is correct however since the volume together would be 10 and for the yz plane I got 8 and they are supposed to be the same. Any help appreciated

A: $\displaystyle \int_0^2\int_0^4\int_z^{z+1}dydzdx=8=\displaystyle \int_0^4\int_0^2\int_z^{z+1}dydxdz$. $\:$Since $x$ and $z$ have limits which are constants we take them outside in whatever order. The innermost integral must be the one with variable limits. The limits are $\:0\leq x\leq 2,\:\:0\leq z\leq 4,\:\:z\leq y\leq z+1.$


text:
Q: How to play audio file in php? I want to play an MP3 file in using a PHP script. Where to store the audio file and how to give the path in PHP?

A: I'm afraid you can't do this directly in PHP. You'll have to use HTML5 audio or Flash.

A: PHP is a server-side programming language. You can use it to move the file's information and contents, such as via a form upload, to your server, but playing the audio is a client-side concern.

A: You need to play the mp3 clientside, either with javascript or to embed it with <embed src="file.mp3">
You can store the filepath as a variable in PHP with
$soundfile = "file.mp3";

and then spit out some markup
echo "<embed src =\"$soundfile\" hidden=\"true\" autostart=\"true\"></embed>";

Tho, im not sure you can play the .mp3 fileformat using embed. Wav should be fine.

A: use this:
jplayer
or
soundmanager2
this are both javascript and html5 based. though, you can control its playlist using php, depending on how you implement it.


text:
Q: String literals in lazy vars in Swift 2 / XCode 7 [Cannot convert value of type String ...] Whenever a String literal appears in the declaration of a lazy var I get a compilation error in Swift 2 / XCode 7: Cannot convert value of type String to expected argument type '(_builtinStringLiteral: RawPointer, byteSize: Word, isASCII: Int1)' ...
(I had no problems in Swift 1.2 / XCode 6)
The simplest line that produces this error looks something like this:
lazy var foo = "bar"

But more relevantly (annoyingly), it also happens with initializers that take string arguments:
lazy var viewsLabel = HWLabel(color: COLOR_WHITE, font: ProximaNova("Semibold", 13))
lazy var durationIconView = HWIconView(imageName: "TimeIcon", color: COLOR_WHITE)

These are obviously my own initializers, and I'm noticing Apple SDKs don't seem to have Strings as args in initializers very often. Are Strings in inits bad practice?
What does work is wrapping the declaration in a block.
I might do that for now, or just make them not lazy.
I'm still curious though. Is this an XCode 7 bug?
UPDATE:
Just noticed that what does work is not wrapping the declaration in a closure, but rather specifying the type of the var so that it's not inferred.
So, what does work:
lazy var viewsLabel: HWLabel = HWLabel(color: COLOR_WHITE, font: ProximaNova("Semibold", 13))
lazy var durationIconView: HWIconView = HWIconView(imageName: "TimeIcon", color: COLOR_WHITE)

Why the appearance of a String in a lazy var declaration messes with type inference is beyond me. Still have a hunch it might be an XCode 7 bug.

A: It's a bug, if you add the type of the var it could compile :
I found the answer here : Swift 2.0 'unexpected trailing closure' error with lazy var assignment


text:
Q: Rails console: backtrace brakes text formatting Every time I see an exception in Rails console, it breaks console output.

Cursor is placed on the last line of exception, and after I press Alt+Backspace it deletes part of output. After pressing Enter formatting is back to normal. As far as I understand it, there are some escape characters in these lines which aren't handled properly by the terminal.
There is no issue with pure irb console.
How do I fix that?