text:
Q: Is there a fast (vectorized) way to count a list of string contained within another list of strings? I want to count the number of two character vowel permutations that are contained within a list of 5-letter words.  Vowel permutations are like 'aa','ae','ai,...,'ui','uo','uu'.
I successfully get this done using apply() but it is slow.  I want to see if there is a fast vectorized way to get this done.  I can't think of one.
Here's what I did:
import pandas as pd
import itertools

vowels = list('aeiou')
vowel_perm = [x[0]+x[1] for x in itertools.product(vowels,vowels)]

def wide_contains(x):
    return pd.Series(data=[c in x for c in vowel_perm], index=vowel_perm)

dfwd['word'].apply(wide_contains).sum()

aa     1
ae     2
ai    12
ao     2
au     8
ea    15
ee    15
ei     1
eo     5
eu     2
ia     7
ie    10
ii     0
io     3
iu     0
oa     2
oe     2
oi     3
oo    11
ou     7
ua     2
ue     9
ui     2
uo     0
uu     0

The above is the expected output using the following data
word_lst = ['gaize', 'musie', 'dauts', 'orgue', 'tough', 'medio', 'roars', 'leath', 'quire', 'kaons', 'iatry', 'tuath', 'tarea', 'hairs', 'sloid',
'beode', 'fours', 'belie', 'qaids', 'cobia', 'cokie', 'wreat', 'spoom', 'soaps', 'usque', 'frees', 'rials', 'youve', 'dreed', 'feute',
'saugh', 'esque', 'revue', 'noels', 'seism', 'sneer', 'geode', 'vicua', 'maids', 'fiord', 'bread', 'squet', 'goers', 'sneap', 'teuch',
'arcae', 'roosa', 'spues', 'could', 'tweeg', 'coiny', 'cread', 'airns', 'gauds', 'aview', 'mudee', 'vario', 'spaid', 'pooka', 'bauge',
'beano', 'snies', 'boose', 'holia', 'doums', 'goopy', 'feaze', 'kneel', 'gains', 'acoin', 'crood', 'juise', 'gluey', 'zowie', 'biali',
'leads', 'twaes', 'fogie', 'wreak', 'keech', 'bairn', 'spies', 'ghoom', 'foody', 'jails', 'waird', 'iambs', 'woold', 'belue', 'bisie',
'hauls', 'deans', 'eaten', 'aurar', 'anour', 'utees', 'sayee', 'droob', 'gagee', 'roleo', 'burao', 'tains', 'daubs', 'geeky', 'civie',
'scoop', 'sidia', 'tuque', 'fairy', 'taata', 'eater', 'beele', 'obeah', 'feeds', 'feods', 'absee', 'meous', 'cream', 'beefy', 'nauch']

dfwd = pd.DataFrame(word_lst, columns=['word'])

A: Well, if not using Pandas to do this computation at all is alright, it looks like plain old Counter() is 220x faster on my machine for the data given.
from collections import Counter
import timeit

def timetest(func, name=None):
    name = name or getattr(func, "__name__", None)
    iters, time = timeit.Timer(func).autorange()
    iters_per_sec = iters / time
    print(f"{name=} {iters=} {time=:.3f} {iters_per_sec=:.2f}")

def counter():
    ctr = Counter()
    for word in dfwd['word']:
        for perm in vowel_perm:
            if perm in word:
                ctr[perm] += 1
    return ctr

timetest(original)
timetest(counter)
print(counter())

outputs
name='original' iters=10 time=0.229 iters_per_sec=43.59
name='counter' iters=2000 time=0.212 iters_per_sec=9434.29
Counter({'ea': 15, 'ee': 15, 'ai': 12, 'oo': 11, 'ie': 10, 'ue': 9, 'au': 8, 'ou': 7, 'ia': 7, 'eo': 5, 'io': 3, 'oi': 3, 'oa': 2, 'ui': 2, 'ao': 2, 'ua': 2, 'eu': 2, 'oe': 2, 'ae': 2, 'ei': 1, 'aa': 1})

A: How about some dictionary comprehension? It should be faster than using apply
{v: dfwd['word'].str.count(v).sum() for v in vowel_perm}
# 6.9 ms ± 180 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

{'aa': 1,
 'ae': 2,
 'ai': 12,
 'ao': 2,
 'au': 8,
 'ea': 15,
 'ee': 15,
 'ei': 1,
 'eo': 5,
 'eu': 2,
 'ia': 7,
 'ie': 10,
 'ii': 0,
 'io': 3,
 'iu': 0,
 'oa': 2,
 'oe': 2,
 'oi': 3,
 'oo': 11,
 'ou': 7,
 'ua': 2,
 'ue': 9,
 'ui': 2,
 'uo': 0,
 'uu': 0}

A: Another option is to simply iterate over the the vowel pairs and count the number of occurrences in word_lst of each pair. Note that for the current task, you don't need to create an explicit list: vowel_perm either, simply iterate over the map object:
out = pd.Series({pair: sum(True for w in word_lst if pair in w)
                 for pair in map(''.join, itertools.product(vowels,vowels))})

On my machine, a benchmark says:
>>> %timeit out = pd.Series({pair: sum(True for w in word_lst if pair in w) for pair in map(''.join, itertools.product(vowels,vowels))})
492 µs ± 28.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit vowel_perm = [x[0]+x[1] for x in itertools.product(vowels,vowels)]; out = dfwd['word'].apply(wide_contains).sum()
40.6 ms ± 2.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: You can use numpy.char.find to search an array of string for a substring:
from itertools import product

word_lst = np.array([
    'gaize', 'musie', 'dauts', 'orgue', 'tough', 'medio', 'roars', 'leath', 'quire', 'kaons', 'iatry', 'tuath', 'tarea', 'hairs', 'sloid',
    'beode', 'fours', 'belie', 'qaids', 'cobia', 'cokie', 'wreat', 'spoom', 'soaps', 'usque', 'frees', 'rials', 'youve', 'dreed', 'feute',
    'saugh', 'esque', 'revue', 'noels', 'seism', 'sneer', 'geode', 'vicua', 'maids', 'fiord', 'bread', 'squet', 'goers', 'sneap', 'teuch',
    'arcae', 'roosa', 'spues', 'could', 'tweeg', 'coiny', 'cread', 'airns', 'gauds', 'aview', 'mudee', 'vario', 'spaid', 'pooka', 'bauge',
    'beano', 'snies', 'boose', 'holia', 'doums', 'goopy', 'feaze', 'kneel', 'gains', 'acoin', 'crood', 'juise', 'gluey', 'zowie', 'biali',
    'leads', 'twaes', 'fogie', 'wreak', 'keech', 'bairn', 'spies', 'ghoom', 'foody', 'jails', 'waird', 'iambs', 'woold', 'belue', 'bisie',
    'hauls', 'deans', 'eaten', 'aurar', 'anour', 'utees', 'sayee', 'droob', 'gagee', 'roleo', 'burao', 'tains', 'daubs', 'geeky', 'civie',
    'scoop', 'sidia', 'tuque', 'fairy', 'taata', 'eater', 'beele', 'obeah', 'feeds', 'feods', 'absee', 'meous', 'cream', 'beefy', 'nauch'
], dtype="U")

dfwd = pd.Series({
    perm: (np.char.find(word_lst, perm) != -1).sum()
    for perm in ["".join(p) for p in product(list("aoeui"), repeat=2)]
})

A: Here is another way:
df['word'].str.extractall('([aeiou]{2})').groupby([0]).size()

Output:
0
aa     1
ae     2
ai    12
ao     2
au     8
ea    15
ee    15
ei     1
eo     5
eu     2
ia     7
ie    10
io     3
oa     2
oe     2
oi     3
oo    11
ou     6
ua     2
ue     9
ui     2


text:
Q: Center child element within it's parent container border Basically I'm trying to center an amount of items vertically on it's parent border using HTML and CSS, I want it to look this way:
This is the test that i've done to explain it:

Basically, I want to center them the way the green elements are aligned, and so far what I'm getting is the way the blue element is positioned.
What could be the easiest way to make it?

A: You should give child elements negative margin-right value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать переключение между персонажами в unity? Нужно, чтобы при нажатии на кнопку персонажи переключались между собой. Но у меня возник баг, персонаж 2 не появляется на месте персонажа 1, а на своём изначальном месте.
Вот код переключателя, который прикреплён к Players, а char1 и char2 являются дочерними:
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Switcer : MonoBehaviour
{

public GameObject char1, char2;

int charOn = 1;

void Start()
{

char1.gameObject.SetActive(true);
char2.gameObject.SetActive(false);

}

public void SwitchCharecter()
{

   switch (charOn)
   {

        case 1:
        charOn = 2;

        char1.gameObject.SetActive(false);
        char2.gameObject.SetActive(true);
        break;
        case 2:
        charOn = 1;
        char1.gameObject.SetActive(true);
        char2.gameObject.SetActive(false);
        break;
       }
   }
}

A: switch (charOn)
   {

        case 1:
        charOn = 2;

        char1.gameObject.SetActive(false);
        char2.gameObject.SetActive(true);
        char2.transform.position = char1.transform.position;
        break;
        case 2:
        charOn = 1;
        char1.gameObject.SetActive(true);
        char2.gameObject.SetActive(false);
        char1.transform.position = char2.transform.position;
        break;
       }
   }


text:
Q: Hypergeometric function discontinuity The hypergeometric function$\ _2F_1(a,b;c;z)$ has a branch point at $z=1$. How do I compute the discontinuity around the point? In particular, how do I compute the following?
$$\lim_{\epsilon\rightarrow 0^+} \ _2F_1(1,b;b+1;1+\epsilon)-\ _2F_1(1,b;b+1;1-\epsilon)$$
Mathematica says that it is $-ib\pi$.

A: Here is Luke's "The Special Functions and Their Approximations: Volume 1"
https://www.amazon.com/Special-Functions-Their-Approximations/dp/0124110371
Section 3.4, Eq:15
answer with her variables
$A\left(z\right)=\,_{2}F_{1}\left(\begin{array}{c}
\nu+1,\nu+\mu+1\\
\nu+\mu+\lambda+2
\end{array};z\right)=\frac{\left(-1\right)^{\mu+1}\left(\nu+\mu+\lambda+1\right)!}{\lambda!\cdot\nu!\cdot\left(\nu+\mu\right)!\cdot\left(\mu+\lambda\right)!}\cdot\frac{d^{\nu+\mu}}{dz^{\nu+\mu}}\left[\left(1-z\right)^{\mu+\lambda}\cdot\frac{d^{\lambda}}{dz^{\lambda}}\left\{ z^{-1}\cdot ln\left(1-z\right)\right\} \right]$
Here is your example with $1\leq a\leq b < c;a,b,c:integer$
$\nu=0,a=1,b=\mu+1,\lambda=0,c=b+1,\lambda=0$
$A\left(1-z\right)=\,_{2}F_{1}\left(\begin{array}{c}
1,b\\
b+1
\end{array};1-z\right)=\frac{\left(-1\right)^{b}\left(b\right)!}{0!\cdot 0!\cdot\left(b-1\right)!\cdot\left(b-1\right)!}\cdot\frac{d^{b-1}}{dz^{b-1}}\left[\left(z\right)^{b-1}\cdot\frac{d^{0}}{dz^{0}}\left\{ \left(1-z\right)^{-1}\cdot ln\left(z\right)\right\} \right]$
For instance, for $b=3$:
Sagemath returns
$\frac{3\,\left(x^{2}-4\,x+2\,\log\left(x\right)+3\right)}{2\,\left(x-1\right)^{3}}$
Which matches Sagemath straight up result. The answer to the difference/shape around 1 is:
$-\frac{3\,\left(x^{2}+4\,x+2\,\log\left(-x\right)+3\right)}{2\,\left(x+1\right)^{3}}-\frac{3\,\left(x^{2}-4\,x+2\,\log\left(x\right)+3\right)}{2\,\left(x-1\right)^{3}}$

A: For the particular problem we can refer to Lerch's Function at:
Bateman Higher Transcendental Functions sections 1.11
and 6.11.1 and
DLMF  25.14
How do we get there?
We look at a term of the question;
say $x^{n}$ and set $x=1-\epsilon$
$\left[x^{n}\right]\,_{2}F_{1}\left(1,b;b+1;1-\epsilon\right)=\frac{\left(1\right)_{n}\left(b\right)_{n}}{\left(b+1\right)_{n}}\cdot\frac{x^{n}}{n!} =\frac{\Gamma\left(b+1\right)}{\Gamma\left(b\right)}\cdot\frac{\Gamma\left(b+n\right)}{\Gamma\left(b+1+n\right)}\cdot x^{n}=b\cdot\frac{1}{b+n}\cdot x^{n}$
And examining the terms involving n we get Lerch's Function
$=b\cdot\Phi\left(x,1,b\right)$
$\Phi\left(x,s,b\right)={\displaystyle \sum_{n=0}^{\infty}}\frac{x^{n}}{\left(b+n\right)^{s}}$
To me the most relevant part of section 1.11 starts at Eq-14 and winds up in the comments after Eq-18; but there are a lot of other goodies.


text:
Q: When using automatic proxy configuration in IE, does the settings get stored locally? If I'm on a corporate computer which has automatically configured proxy settings, can I still find out the proxy settings locally? Like for instance checking the following registry key?
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
With automatic settings I mean either by script or "autodetect":

A: Only a sort-of-answer, I'm afraid, but in the case where you've specified a script it should be possible to just fetch the script from the same location (in the general case, if I recall correctly, it's served over http) and extract the settings from that.
Obviously that doesn't help with the "autodetect" option.


text:
Q: Fetch API cannot load localhost:3000/send. URL scheme "localhost" is not supported I am using Node Js as backend and basic html css js for frontend. I am sending request through node js that
app.get("/send", async (req, res) => {
  let products = await Product.find();
  products = await products;
  res.send(products);
});

and getting fetch on an html page:
const getData = async () => {
    const response = await fetch("localhost:3000/send", {
      method: "GET",
    });
    const data = await response.json();
    console.log(data);
  };
  getData();

But i am not getting the data, I have tested the api on Postman it works fine there. But throwing error on browser:
Error is :
Fetch API cannot load localhost:3000/send. URL scheme "localhost" is not supported.
Please help me out. Bundles of thanks!

A: You should specify localhost as being http://localhost or https://localhost - otherwise fetch can't be sure which protocol you are mentioning:
const response = await fetch("http://localhost:3000/send", { ... });


text:
Q: Bootstrap Navbar works for some, but not everyone I've been having problems with Bootstrap Nav Bar drop downs.  I take the code directly from w3schools, but the drop downs don't work for everyone.  They work just fine for me and some of my friends but for others it doesn't work at all.  I've been looking around and people all seem to have there own JavaScript or some side code.  Is this just a unfixable problem with bootstrap?  And if so, is there some way to detect if a user is having the problem?  Here is my code:
<!DOCTYPE html>

<title>Dropdown test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

      Dropdown Test

Home

Members

          Mail

Send Mail

Read New Mail

Read Old Mail

          Profile

Invite Codes

Logout

Settings

Test

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum commodo augue iaculis, dictum ante eget, consequat purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum malesuada risus at condimentum condimentum. Sed tempor, elit non sodales commodo, dui elit auctor odio, id sollicitudin nisi nulla et urna. Nullam id rhoncus magna, nec posuere tortor. Duis scelerisque, nunc vel commodo fermentum, urna nunc lobortis diam, nec aliquam sem mi id dui. Morbi vitae leo ac felis congue maximus a in risus. Curabitur vehicula ornare porta. Ut pretium posuere dolor, vel ullamcorper metus gravida vel. Sed commodo justo id tincidunt posuere. Praesent quis aliquam felis. Sed quam ante, vestibulum vitae turpis eleifend, bibendum pretium arcu. Quisque vitae congue tellus, id molestie mi.


text:
Q: I've built and app using javascript /firebase and would like to have it return the last 5 searches and make each of them clickable I've built an app that is working fine. The only problem is that I'm trying to have it display the last 5 searches in my HTML div with the id of recentSearches. I would like each of them to be clickable and return the result they previously returned. I refered to my HTML div toward the bottom as: let recentSearchesDiv = $('#recentSearches')

var config = {
  apiKey: "AIzaSyCzaNmYb94HQPR70d6Omy5kP1d0kw5NLkc",
  authDomain: "eventtraveler-69f59.firebaseapp.com",
  databaseURL: "https://eventtraveler-69f59.firebaseio.com",
  projectId: "eventtraveler-69f59",
  storageBucket: "eventtraveler-69f59.appspot.com",
  messagingSenderId: "73086206077"
};

firebase.initializeApp(config);

var database = firebase.database();
// slider functionality
$(document).ready(function () {
    $('.slider').slider({ full_width: true });
});

var $hotelsContainer = $("#hotel-results");
var $eventsContainer = $("#events-results");

// input fields
var $city = $("#location-input");
var $checkInDate = $("#start-date-input");
var $checkOutDate = $("#end-date-input");
var $submit = $("#add-event");

// make global variable so functions can access
var city = "";
var checkin = "";
var checkout = "";
var pleaseWait = "";

// CORS un-blocker for eventful API
jQuery.ajaxPrefilter(function(options) {
  if (options.crossDomain && jQuery.support.cors) {
      options.url = "https://cors-anywhere.herokuapp.com/" + options.url;
  }
});

function getHotels(city) {
  // find location code
  $.ajax({
    url:
      "https://apidojo-kayak-v1.p.rapidapi.com/locations/search?where=" + city,
    method: "GET",
    headers: {
      "X-RapidAPI-Host": "apidojo-kayak-v1.p.rapidapi.com",
      "X-RapidAPI-Key": "811b0b509bmshf44ab7ab1214e55p19e182jsnc61a98a0c578"
    }
  }).then(function(response) {
    console.log(response);
    console.log(response[0].ctid); // MAKE SURE IT'S A CITY

    // make sure it's a city (response returns city and airport codes)
    $.each(response, function(i, value) {
      if (response[i].loctype === "city") {
        console.log("this is a city");
        console.log(i + ", " + value);
        citycode = response[i].ctid;
        console.log(citycode);
        return false;
      }
    });

    // now that we have the location code, we can use it to find hotels
    $.ajax({
      url:
        "https://apidojo-kayak-v1.p.rapidapi.com/hotels/create-session?rooms=1&citycode=" +
        citycode +
        "&checkin=" +
        checkin +
        "&checkout=" +
        checkout +
        "&adults=1",
      method: "GET",
      headers: {
        "X-RapidAPI-Host": "apidojo-kayak-v1.p.rapidapi.com",
        "X-RapidAPI-Key": "811b0b509bmshf44ab7ab1214e55p19e182jsnc61a98a0c578"
      }
    }).then(function(response) {
      console.log("kajak success");
      console.log(response);
      console.log(response.hotelset);

      // reference for hotel list
      var hotelListMain = response.hotelset;
      var hotelList = response.hotelset;
      // only keep 10 results
      if (hotelList.length > 10) {
        hotelList.length = 10;
      }

      console.log(hotelList);

      // if no results
      if (hotelList.length === 0) {
        console.log("no results");
        var newP = $("
").text("No results.");
        $hotelsContainer.append(newP);
      }

      // go through each hotel and show on page
      $.each(hotelList, function(i, value) {
        console.log("hotel " + i);

        // get relevent info
        if (response.hotelset[i].brand !== undefined) {
            var hotelName = response.hotelset[i].brand;
        } else {
            var hotelName = response.hotelset[i].name;
        }
        var hotelAddress = response.hotelset[i].displayaddress;
        var hotelRating = response.hotelset[i].ratinglabel;
        var hotelStarCount = response.hotelset[i].stars;
        var hotelThumbnail =
          "https://kayak.com" + response.hotelset[i].thumburl;

        // if cheapest provider object is included
        console.log("t/f: " + response.hotelset[i].cheapestProvider !== undefined);

        if (response.hotelset[i].cheapestProvider !== undefined) {
          var cheapestProviderName = response.hotelset[i].cheapestProvider.name;
          var bestPrice =
            response.hotelset[i].cheapestProvider.displaybaseprice;
          var linkToHotel =
            "https://kayak.com" + response.hotelset[i].cheapestProvider.url;
        } else {
          var cheapestProviderName = response.hotelset[i].brand;
          var bestPrice = response.hotelset[i].price;
          var linkToHotel = "https://kayak.com" + response.hotelset[i].shareURL;
        }

        //create elements for html
        var newTitle = $("
").text(
          hotelName + " (via " + cheapestProviderName + ")"
        );
        var newAddress = $("
").text(hotelAddress);
        var newPrice = $("
").text(bestPrice);
        var newRating = $("
").text(
          hotelRating + ", " + hotelStarCount + " stars"
        );
        var newImage = $("").attr("src", hotelThumbnail);
        var newLink = $("")
          .attr("href", linkToHotel)
          .text("see hotel");

        // img container
        var imgContainer = $("
")
          .addClass("card-image")
          .append(newImage);

        var content = $("
")
          .addClass("card-content")
          .append(newTitle, newAddress, newPrice, newRating);
        var action = $("
")
          .addClass("card-action")
          .append(newLink);

        // content container
        var allContentContainer = $("
")
          .addClass("card-stacked")
          .append(content, action);

        // make parent div for this hotel
        var newHotelDiv = $("
")
          .append(imgContainer, allContentContainer)
          .addClass("card horizontal");

        // add this hotel's div to the hotel container
        $hotelsContainer.append(newHotelDiv);

        // remove wait message
        pleaseWait.remove();

      });
    });
  });
}

function displayEvent() {
    $("#events-results").empty();

    var where = $("#location-input")
        .val()
        .trim();

    var start = moment($("#start-date-input").val()).format("YYYYMMDD00");
    var end = moment($("#end-date-input").val()).format("YYYYMMDD00");

    // search for button name in omdb and show info underneath
    var queryURL =
        "https://api.eventful.com/json/events/search?" +
        "app_key=n69CWBNZRrGZqdMs" +
        "&l=" +
        where +
        "&t=" +
        start +
        "-" +
        end;

    console.log(queryURL);

    $.ajax({
        url: queryURL,
        method: "GET"
    }).then(function(response) {
        var schema = JSON.parse(response);
        console.log(schema.events);
        console.log(schema.events.event);
        // if no results
        if (schema.events.event.length === 0) {
            console.log("no event results");
            var newP = $("
").text("No results.");
            $eventsContainer.append(newP);
        }

        for (var i = 0; i < schema.events.event.length; i++) {
            total = parseFloat(i) + 1;

            //create elements for html
            var eventTitle = $("
").text(schema.events.event[i].title);
            var eventAddress = $("
").text(
                schema.events.event[i].venue_address +
                ", " +
                schema.events.event[i].city_name +
                ", " +
                schema.events.event[i].postal_code
            );
            var eventLink = $("")
                .attr("href", schema.events.event[i].url)
                .text("see event");

            // img container
            if (schema.events.event[i].image !== null) {
                var eventimage = schema.events.event[i].image.medium.url;
                if (eventimage.includes("http")) {
                    var neweventImage = $("
")
                        .addClass("card-image")
                        .append("");
                } else {
                    var neweventImage = $("
")
                        .addClass("card-image")
                        .append("");
                }
            }

            // start time
            var begins = schema.events.event[i].start_time;
            var days = schema.events.event[i].all_day;
            if (begins.includes("00:00:00")) {
                var date = begins.slice(0, 10);
                var startTime = $("
").text("Starts on " + date + ". Happening for " + days + " days");
            } else {
                var date = begins.slice(0, 16);
                var startTime = $("
").text(begins);
            }

            //build container
            var eventContent = $("
")
                .addClass("card-content")
                .append(eventTitle, eventAddress, startTime);
            var eventAction = $("
")
                .addClass("card-action")
                .append(eventLink);

            // content container
            var eventContentContainer = $("
")
                .addClass("card-stacked")
                .append(eventContent, eventAction);

            // make parent div for this event
            var newEventDiv = $("
")
                .append(neweventImage, eventContentContainer)
                .addClass("card horizontal");

            // add this event's div to the event container
            $("#events-results").append(newEventDiv);

        }

    })
}

$submit.on("click", function (event) {
    event.preventDefault();

    // clear out current results
    $hotelsContainer.empty();
    $eventsContainer.empty();

    // save their inputted data
    city = $city.val().trim();
    checkin = $checkInDate.val();
    checkout = $checkOutDate.val();
    var citycode = "";

    // if user filled out all fields
    if (city !== "" && checkin !== "" && checkout !== "") {
        // show message that results are being generated - so user knows button did submit
        if ($(".please-wait").length === 0) {
            console.log("results are generating....please wait");
            pleaseWait = $("
").text("Searching for results...").addClass("please-wait");
            $(document.body).append(pleaseWait);
            pleaseWait.insertAfter($submit);
        }

        // get hotel results and display them
        //getHotels();

        // get event results and display them
        //displayEvent();

        // construct object literal for firebase
        let travelEvent = {
          city,
          checkin,
          checkout
        };

        // add event to firebase
        database.ref().push(travelEvent)

        database.ref().limitToLast(5).on("value", snapshot => {
          let keys = Object.keys(snapshot.val())

          let recentSearchesDiv = $('#recentSearches');
          recentSearchesDiv.empty();

          for(let i = 0; i < keys.length; i++) {
            let val = snapshot.val()[keys[i]]
            let city = val.city
            let checkin = val.checkin
            let checkout = val.checkout

            let search = $(`<div><span>City: ${city} </span><span>Check-in: ${checkin} </span><span>Check-out: ${checkout}</span></div>`);
            search.addClass('recentSearch')
            search.on('click', function(){

            })

            recentSearchesDiv.append(search)
          }
        });

        // clear inputs
        $city.val("");
        $checkInDate.val("");
        $checkOutDate.val("");
    } else {
        // show error message
        if ($(".required-error").length === 0) {
            var required = $("
").text("* All fields are required").addClass("required-error");
            $("#event-form").prepend(required);
        }
    }

});
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>EventTraveler</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link rel="stylesheet" type="text/css "href="assets/css/style.css">

Search for hotels and events

        <form id="event-form">
          Enter city and state
          <input type="text" id="location-input" />

          Check In
          <input type="date" id="start-date-input" />

          Check Out
          <input type="date" id="end-date-input" />

          <input id="add-event" class="btn btn-info" type="submit" value="Search" />
        </form>

Recent Searches

Hotels

Use the search form above to see results

Events

Use the search form above to see results

          © 2019 Los Cinco

A: If I understand it correctly, your only problem is that there are more then 5 Elements displayed? You can set a limit on the results returned.
https://dinosaur-facts.firebaseio.com/yourJson.json?
orderBy="price"&limitToLast=5;

As you can see, you can also sort it by a Property, e.g. Price and then query only a set number of items. It is also possible to specify if it should be ordered ASC oder DESC.


text:
Q: Complexity between if-else, switch and regex I'm going to optimize javascript code in which I seen old code is like below,
var emcont = $('#emcont').val();
numericMatch = emcont.match(/\d/g);
if (numericMatch == null) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (emcont.length != 14) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (numericMatch.length && numericMatch.length != 10) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else {
    $('#msg_emcont').html('').hide();
}

I going to convert if-else conditions into switch conditions, but the problem in the above code is 2nd condition validation used emcont variable so I can't directly use numericMatch in switch statement. So I decided used emcont variable directly in the switch statement like the below code,
switch(emcont)
    {
        case emcont.match(/\d/g) == null:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
        case emcont.length != 14:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
         case emcont.match(/\d/g).length && emcont.match(/\d/g).length != 10:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
        default:
            $('#msg_emcont').html('').hide();
            break;
    }

In used regex in switch case validation, so i need to know which code better in performance wise.

A: Please do not abuse side effects of switch(true) which is what you meant
This is DRY and easier to read
var emcont = $('#emcont').val();
const numericMatch = emcont.match(/\d/g);
$('#msg_emcont')
  .html(getMessage('msg_emcont'))
  .toggle(
    numericMatch == null ||
    emcont.length != 14  ||
    (numericMatch.length && numericMatch.length != 10)
  )

You might even consider to move
$('#msg_emcont').html(getMessage('msg_emcont'))

to the page load so it is only done once


text:
Q: Write AWS Lambda Logs to CloudWatch Log Group with Terraform I am trying write the logs of a lambda function into a CloudWatch Log Group created by terraform.
This is the lambda policy json -
{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "Stmt1580216411252",
        "Action": [
          "logs:CreateLogStream",
          "logs:CreateLogDelivery",
          "logs:PutLogEvents"
        ],
        "Effect": "Allow",
        "Resource": "arn:aws:logs:*:*:*"
      }
    ]
  }

This is the lambda assume policy json -
{
    "Version": "2012-10-17",
    "Statement": [{
        "Action": "sts:AssumeRole",
        "Principal": {
            "Service": "lambda.amazonaws.com"
        },
        "Effect": "Allow",
        "Sid": ""
    }]
}

I have added this to the lambda.tf file -
resource "aws_cloudwatch_log_group" "example" {
  name              = "/test/logs/${var.lambda_function_name}"
}

Although the CloudWatch Log Group '/test/logs/${var.lambda_function_name}' is getting created through terraform, I am unable to write the log of the lambda function to this group.
If I change the lambda policy json to this -
{
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "Stmt1580204738067",
        "Action": "logs:*",
        "Effect": "Allow",
        "Resource": "*"
    }]
}

Then It automatically stores the log in /aws/lambda/ directory.
How can I make sure that the lambda logs get written into a CloudWatch Log Group that I create and not in the /aws/lambda/ group created by lambda itself?

A: If you want Terraform to manage the CloudWatch log group, you have to create the log group ahead of time with the exact name the Lambda function is going to use for its log group. You can't change the name at all. Then in your Terraform you need to make the log group a dependency of the Lambda function, to make sure Terraform has a chance to create the log group before Lambda creates it automatically.

A: Just adding the log group as a dependency to the lambda is not enough. You also have to attach the IAM policy to the lambda role.
The steps are following:

*

*Define the IAM role for lambda:

resource "aws_iam_role" "iam_for_lambda" {
  name               = "iam_for_lambda"
  assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Principal": {
            "Service": "lambda.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
    }]
}
EOF
}

*Define the IAM policy that allows lambda to create log streams and put log events

resource "aws_iam_policy" "function_logging_policy" {
  name   = "function-logging-policy"
  policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        Action : [
          "logs:CreateLogStream",
          "logs:PutLogEvents"
        ],
        Effect : "Allow",
        Resource : "arn:aws:logs:*:*:*"
      }
    ]
  })
}

*Attach the policy to the IAM role created in step 1, by creating new resource 'aws_iam_role_policy_attachment'

resource "aws_iam_role_policy_attachment" "function_logging_policy_attachment" {
  role       = aws_iam_role.iam_for_lambda.id
  policy_arn = aws_iam_policy.function_logging_policy.arn
}

*Define the log group

resource "aws_cloudwatch_log_group" "lambda_log_group" {
  name              = "/aws/lambda/${var.lambda.function_name}"
  retention_in_days = 7
  lifecycle {
    prevent_destroy = false
  }
}

*Define your lambda function with the depends_on parameter:

resource "aws_lambda_function" "lambda_function" {
  filename      = "../${var.lambda.function_filename}"
  function_name = "${var.lambda.function_name}"
  role          = aws_iam_role.iam_for_lambda.arn
  handler       = "${var.lambda.handler}"
  layers        = [aws_lambda_layer_version.lambda_layer.arn]
  depends_on    = [aws_cloudwatch_log_group.lambda_log_group]
  source_code_hash = filebase64sha256("../${var.lambda.function_filename}")
  runtime = "python3.9"
}

The IAM policy creation & attachment comes from this article, the rest is from my personal project that worked for me.


text:
Q: Cannot replace fragment inside tab with another fragment I am working on Android app which has 4 tabs in action bar (main_activity.xml).
In one tab, i would call it MapListFragment (map_list_fragment.xml), i have to show two different fragments (list and map view representation of some data). All other tabs are fragments and are put in the same container as MapListFragment (id/main_fragments_container).
So, map Fragment is shown first, and buttons map and list are shown in the bottom. Only one Fragment (map or list) is shown at the time, and on button click (map or list) you can show other Fragment, and go back to first Fragment again clicking on the button. Container for these map and list Fragment is (id/fragments_container). I change this Fragment by calling replace() method on FragmentTransaction and i forward same container (id/main_fragments_container) that ActionBar TabListener uses to change tabs. I also tried to create new container for particularly this tab and use him for all operations inside this tab, but I ran into same problems. Changing this Fragment works well, but...
Then I added button at the ActionBar which calls new Fragment that should represent view for adding some data. Container for this Fragment is (id/main_fragments_container) Problem is that, when i go back to MapListFragment, I cannot get same behavior as initial. First question would be is this best work practice or should i call Activity instead Fragment?
When I call new Fragment from ActionBar button, I always remove map fragment (I got same result and when i don't remove), and when I go back to MainFragment blank view is shown, although I call addToBackStack() method.
So I have multiple problems in here, and I hope that I explained some of them, can anybody know what can i try to get this working?
XML layout of MainActivity that contains 4 tabs.
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:layout_gravity="center"
     android:orientation="vertical"
     android:background="@android:color/white">

     <LinearLayout
         android:id="@+id/main_fragments_container"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical" >
     </LinearLayout>

 </LinearLayout>

MapListFragment layout which contains fragments and two buttons, fragments are added dynamically.
map_list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/events_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/white" >

<LinearLayout
    android:id="@+id/fragments_container"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:orientation="horizontal" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center|bottom"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/button_map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="@android:color/white"
        style="?android:attr/buttonBarButtonStyle"/>

    <Button
        android:id="@+id/button_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="@android:color/white"
        style="?android:attr/buttonBarButtonStyle" />

    </LinearLayout>


text:
Q: how can i create a load balancer in AWS using the AWS java sdk as part of a project i need to create a new load balancer on amazon AWS.
i need to do it using the java sdk
how can i set the load balancer up using code?
here is what i tried so far without success.
//create load balancer
        CreateLoadBalancerRequest lbRequest = new CreateLoadBalancerRequest();
        lbRequest.setLoadBalancerName("loader");
        List<Listener> listeners = new ArrayList<Listener>(1);
        listeners.add(new Listener("HTTP", 80, 80));
        lbRequest.withAvailabilityZones(availabilityZone1,availabilityZone2);
        lbRequest.setListeners(listeners);

        CreateLoadBalancerResult lbResult=new CreateLoadBalancerResult();
        System.out.println("created load balancer loader");

A: well finelly i got it:
first create an elb client
AmazonElasticLoadBalancingClient elb = new AmazonElasticLoadBalancingClient(credentials);

then
use it to initiate the request
  //create load balancer
        CreateLoadBalancerRequest lbRequest = new CreateLoadBalancerRequest();
        lbRequest.setLoadBalancerName("loader");
        List<Listener> listeners = new ArrayList<Listener>(1);
        listeners.add(new Listener("HTTP", 80, 80));
        lbRequest.withAvailabilityZones(availabilityZone1,availabilityZone2);
        lbRequest.setListeners(listeners);

        CreateLoadBalancerResult lbResult=elb.createLoadBalancer(lbRequest);
        System.out.println("created load balancer loader");

then register your instances to the Load balancer
//get the running instances
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        List<Instance> instances = new ArrayList<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        //get instance id's
        String id;
        List instanceId=new ArrayList();
        List instanceIdString=new ArrayList();
        Iterator<Instance> iterator=instances.iterator();
        while (iterator.hasNext())
        {
            id=iterator.next().getInstanceId();
            instanceId.add(new com.amazonaws.services.elasticloadbalancing.model.Instance(id));
            instanceIdString.add(id);
        }

        //register the instances to the balancer
        RegisterInstancesWithLoadBalancerRequest register =new RegisterInstancesWithLoadBalancerRequest();
        register.setLoadBalancerName("loader");
        register.setInstances((Collection)instanceId);
        RegisterInstancesWithLoadBalancerResult registerWithLoadBalancerResult= elb.registerInstancesWithLoadBalancer(register);

and you are done...

A: V2 code --
package com.example.loadbalance;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticloadbalancing.ElasticLoadBalancingClient;
import software.amazon.awssdk.services.elasticloadbalancing.model.CreateLoadBalancerRequest;
import software.amazon.awssdk.services.elasticloadbalancing.model.ElasticLoadBalancingException;
import software.amazon.awssdk.services.elasticloadbalancing.model.CreateLoadBalancerResponse;
import software.amazon.awssdk.services.elasticloadbalancing.model.Listener;

import java.util.ArrayList;
import java.util.List;

public class CreateLoadBalancer {

    public static void main(String[] args) {

        Region region = Region.US_WEST_2;
        ElasticLoadBalancingClient loadClient = ElasticLoadBalancingClient.builder()
                .region(region)
                .build();

        try {

            Listener listener = Listener.builder()
                .protocol("HTTP")
                .instancePort(80)
                .loadBalancerPort(80)
                .build();

            List<Listener> listeners = new ArrayList<>();
            listeners.add(listener);

            List<String> avZone = new ArrayList<String>();
            avZone.add("us-west-2a");
            avZone.add("us-west-2b");

            //Define security groups
            List<String> secGroups = new ArrayList<String>();
            secGroups.add("sg-7aba5827");

        CreateLoadBalancerRequest loadBalancerRequest = CreateLoadBalancerRequest.builder()
                .availabilityZones(avZone)
                .securityGroups(secGroups)
                .loadBalancerName("LoadB44")
                 .listeners(listeners)
                .scheme("internet-facing")
                .build();

            CreateLoadBalancerResponse response = loadClient.createLoadBalancer(loadBalancerRequest);
            System.out.println("The DNS Name is "+response.dnsName());

    } catch (ElasticLoadBalancingException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }

    }
}


text:
Q: how to convert List items = new List(); to List? can you help me? how to convert List items = new List(); to List? can you help me?

A: List<Doctor> items = new List();

--- add data to items list ---
then,
List<String> strings = new ArrayList<>(items.size());
for (Doctor doctor: items) {
    strings.add(Objects.toString(doctor, null));
}

if you are using java 8,
List<String> strings = items.stream()
   .map(doctor -> Objects.toString(doctor , null))
   .collect(Collectors.toList());

A: https://api.dartlang.org/stable/2.4.0/dart-core/List-class.html
^ Use .map method of List<Doctor> instance.
For example
var itemStrings = items.map((doc) {
    // Title property as example
    return doc.title;
}).toList();

I recommend that you take dart language tour


text:
Q: I want to create Revit Plugin and in that the command class will be generic [Transaction(TransactionMode.Manual)]
    public class InteropCommand<T, V> : IExternalCommand
    {
        public Result Execute( ExternalCommandData commandData, ref string message,
                               ElementSet elements )
        {
             InterfaceDialog<T, V> interfaceDlgBox = new InterfaceDialog<T, V>( (IDocumentationModel<T>)Revit2014Model );

        }
}

The command.cs file looks like shown above. If I write class as
class InteropCommand then I need to change the .Addin file accordingly otherwise the command will not work. Now I have question that how can I write a command class in such a way that it will load the Revit addin command. In current scenario I am not able to load the Revit command.
My .Addin file look like below. Do you have any idea how to tackle with this kind of problem ?
<RevitAddIns>
  <AddIn Type="Command">
    <Text>Test</Text>
    <Description>Test Command</Description>
    <Assembly>test.dll</Assembly>
    <FullClassName>InteropCommand</FullClassName>
    <ClientId>0072bf73-c900-449b-bce2-e50a899a72ae</ClientId>
    <VendorId>XYZ</VendorId>
    <VendorDescription>XYZ</VendorDescription>
  </AddIn>
</RevitAddIns>

A: You need to implement a separate class for each command.
You can derive all your external command implementation classes from a single base class to share part of the implementation, or call a generic class from each individual external command implementation class' Execute method.

A: Adding to Jeremy's reply, you can have a class that implements IExternalApplication, then on the OnStartup method, create as many IExternalCommands as you want, on the fly, without changing the .addin file.
This still requires one class for each command, as already mentioned.


text:
Q: I am trying to write a program that will keep track of a players wins everything works except can anyone tell me why my if statement wont work? I am trying to write a program that will keep track of a players wins.
Everything works except can anyone tell me why my if statement wont work?
Option Strict On
Option Explicit On

Public Class Form1
Private Player1 As String
Private Player2 As String
Private Player1Wins As Integer
Private Player2Wins As Integer
Private Tie As Integer

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Me.Close()
End Sub

Private Sub frmMainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Player1 = InputBox("Enter Player 1's Name: ")
    lblPlayer1.Text = (Player1 + "'s Score:")

    Player2 = InputBox("Enter Player 2's Name:")
    lblPlayer2.Text = (Player2 + "'s Score:")

End Sub

Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
    ' game of rolling dice

    Dim randGen As New Random
    Dim intNum1 As Integer
    Dim intNum2 As Integer
    Dim intNum3 As Integer
    Dim intNum4 As Integer
    Dim intTotal As Integer
    Dim intTotal2 As Integer

    ' make random integer from 1 through 6
    intNum1 = randGen.Next(1, 7)
    intNum2 = randGen.Next(1, 7)
    intNum3 = randGen.Next(1, 7)
    intNum4 = randGen.Next(1, 7)

    ' display the right image in picDie1
    Select Case intNum1
        Case 1
            picDie1.Image = picOneDot.Image
        Case 2
            picDie1.Image = picTwoDots.Image
        Case 3
            picDie1.Image = picThreeDots.Image
        Case 4
            picDie1.Image = picFourDots.Image
        Case 5
            picDie1.Image = picFiveDots.Image
        Case 6
            picDie1.Image = picSixDots.Image
    End Select

    ' display the right image in picDie2
    Select Case intNum2
        Case 1
            picDie2.Image = picOneDot.Image
        Case 2
            picDie2.Image = picTwoDots.Image
        Case 3
            picDie2.Image = picThreeDots.Image
        Case 4
            picDie2.Image = picFourDots.Image
        Case 5
            picDie2.Image = picFiveDots.Image
        Case 6
            picDie2.Image = picSixDots.Image
    End Select

    ' display the right image in picDie3
    Select Case intNum3
        Case 1
            picDie3.Image = picOneDot.Image
        Case 2
            picDie3.Image = picTwoDots.Image
        Case 3
            picDie3.Image = picThreeDots.Image
        Case 4
            picDie3.Image = picFourDots.Image
        Case 5
            picDie3.Image = picFiveDots.Image
        Case 6
            picDie3.Image = picSixDots.Image
    End Select

    ' display the right image in picDie4
    Select Case intNum4
        Case 1
            picDie4.Image = picOneDot.Image
        Case 2
            picDie4.Image = picTwoDots.Image
        Case 3
            picDie4.Image = picThreeDots.Image
        Case 4
            picDie4.Image = picFourDots.Image
        Case 5
            picDie4.Image = picFiveDots.Image
        Case 6
            picDie4.Image = picSixDots.Image
    End Select
    ' calculate and display total number of dots
    intTotal = intNum1 + intNum2
    lblTotal.Text = intTotal.ToString()

    intTotal2 = intNum3 + intNum4
    lblTotal2.Text = intTotal2.ToString()

    If Player1 > Player2 Then
        MessageBox.Show("Player1 Wins")
        lblWins.Text = CStr(Player1Wins)
        Player1Wins = Player1Wins + 1

        If Player2 > Player1 Then
            MessageBox.Show("Player2Wins")
            lblWins2.Text = CStr(Player2Wins)
            Player2Wins = Player2Wins + 1

        Else : MessageBox.Show("Tie")
            lblTies.Text = CStr(Tie)
            Tie = Tie + 1
        End If

End Sub

A: You are comparing the NAMES of the two players instead of the values and the comparison for the second player should be an else if for the first if
' calculate and display total number of dots
intTotal = intNum1 + intNum2
lblTotal.Text = intTotal.ToString()

intTotal2 = intNum3 + intNum4
lblTotal2.Text = intTotal2.ToString()

If intTotal > intTotal2 Then
    MessageBox.Show("Player1 Wins")
    Player1Wins = Player1Wins + 1
    lblWins.Text = CStr(Player1Wins)
Else If intTotal2 > intTotal1 Then
    MessageBox.Show("Player2Wins")
    Player2Wins = Player2Wins + 1
    lblWins2.Text = CStr(Player2Wins)
Else
    MessageBox.Show("Tie")
    Tie = Tie + 1
    lblTies.Text = CStr(Tie)
End If

And the label update should be after the increment of the counter for wins and ties


text:
Q: pandas series row-wise comparison (preserve cardinality/indices of larger series) I have two pandas series, both string dtypes.

*

*reports['corpus'] has 1287 rows
0    point seem peaking effects drug unique compari...
1    mother god seen much difficult withstand spent...
2    getting weird half breakthrough feels like sec...
3    vomited three times bucket suddenly felt much ...
4    reached peak mild walk around without difficul...

*labels['uniq_labels'] has 52 rows
0           amplification
1             enhancement
2             psychedelic
3                 sensory
4                  visual
I want to create a new series object equal to the size of reports['corpus']. In it, each row needs to contain a list of string matches (i.e. searching reports['corpus'] for exact string matches to strings in labels['uniq_labels']).
I have tried looping over the two series to check if a string from labels['uniq_labels'] is in a report from reports['corpus']. I split at the report iter and am able to return a list of the strings that match. Though I can't seem to preserve conditions such as: allocating string matches for a given report to the reports' index position (very important).
Edit (Adding example of the series objects):
reports_series = pd.Series(['This is a test first sentence. \
                            This is the first row of a pandas series.',
                            'Here is the second row. The row that means the most. The row that never goes away.',
                            'The third sentence. The third row to the example pandas series.',
                            'This is the fourth and only fourth row of the pandas series.',
                            'Here is the fifth row. The fifth row that means the most.'])

labels_series = pd.Series(['first', 'sentence', 'second row'])

A: Convert uniq_labels column from the labels dataframe to a list, and split the corpus column from reports dataframe on white space, and take the values that are in both the lists.
(reports['corpus']
.str.split(' ')
.apply(lambda x:[i for i in labels['uniq_labels'].tolist() if i in x]))
0    []
1    []
2    []
3    []
4    []
Name: corpus, dtype: object

In the sample you have mentioned above, no values actually match, so the output has empty list only.


text:
Q: Generating correlated positive random numbers (given means, variances and degree of correlation)? I have a vector of means and a covariance matrix and I'm trying to create a data set that would like to
generate strictly positive numbers that would fit the parameters.
I have seen quite a few options but all of them resulted in creating some negative observations.
I have implemented the following code using the MASS package, but I have also tried the mvtnorm as well as several other options which have not produced the needed results.
means <- c(0.1505, 0.1596, 0.1552)

cov_matrix <- matrix(c(0.23915, -0.04556, -0.04729,
                     -0.04556, 0.21460, -0.05269,
                     -0.04729, -0.05269, 0.20674), ncol = 3)

t <- MASS::mvrnorm(n = 50, mu = means, Sigma = cov_matrix, empirical = TRUE)

head(t)
        [,1]     [,2]     [,3]
[1,]  0.1432  0.51024  0.29832
[2,]  1.0483  0.29353 -1.02127
[3,]  0.3252  0.45140 -0.41820
[4,] -0.3459  0.08166  0.04431
[5,] -0.3144  0.29057  0.55096
[6,]  1.1736 -0.63583 -0.56427

I feel as if it should be quite simple and I'm just missing something.

A: Here is one suggested path.
Start by assuming that your data follows, for example, a Lognormal distribution, which provides a positive continuous probability function supported on the positive real numbers.
Required are the associated relationships in the Lognormal population between your target mean for, say variable Y, namely $Y_m$, and also its variance, $Var(Y)$, together with their relationship to the parameters of the generated lognormal deviate. The latter expressions for the mean is given by $\exp( \mu + \sigma^2/2)$ and the $Var(Y)$ is equal to $\exp(\sigma^2 -1)\exp(2\mu + \sigma^2)$. Also, per these two references, Wikipedia and this forum, we note:
$\text{Cov}(X,Y)=E(X)E(Y)[\exp(\rho\sigma_x\sigma_y)-1]$
So, upon dividing both sides of the expression by the product, $\sigma_X\sigma_Y$ (that is, the product of the respective standard deviations of X and Y in Lognormal population), we have a relationship connecting the parent bivariate Lognormal population target correlation with the $\rho$ associated with the correlation associated between the logs of X and Y, which I call simply ρ.
As the log of a Lognormal deviate is Normally distributed, one can now use relationships associated with the conditional distribution of $X$ given a value for $Y$, namely:
$E(X|Y=y) = \mu_X+ σ_X ρ(y−Y_m )/σ_Y $
$Var(X|Y=y) = σ_X^2 (1−ρ^2)$
Source, see, for example, Page 267 here.
So, the simulation procedure is to derive the corresponding parameter values of means, variances and correlation for the log of the lognonormal deviates. As these are Normally distributed, proceed to generate an appropriate random normal deviate for Y, and use the conditional Normal distribution expression to obtain the corresponding X. Repeat.
You now have a simulated population of bivariate Normal random deviates. Upon applying the exponential transform, you should now have a Lognormal population with the targetted parameter values.

A: Originally I preferred not to transform my distribution to log-normal, yet I have ended up doing so and I used the dmutate package for generating my numbers:
t <- rlmassnorm(n = 1000, mu = means, Sigma = cov_matrix, empirical = TRUE)


text:
Q: Error in installing unity-tweak-tool I cannot install unity-tweak-tool. When ever i try to install through software center is shows installing and suddenly changes to install.

A: Your issue is you didn't use apt correctly.
First, remove unity-tweak-tool:
sudo apt-get remove unity-tweak-tool

Then, install it again:
sudo apt-get install unity-tweak-tool


text:
Q: How to validate controls in each column of a gridview I would like to validate columns in an asp:Gridview but am unsure how to do so as all the tutorials I have found show a previous version on Microsoft Visual Studio (I am using 2010).
How do I validate each column of the Gridview?
Thanks
This is the code of my Gridview generated by visual studio.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
    DataKeyNames="registrationNo" DataSourceID="SqlDataSource3"
    onselectedindexchanged="GridView2_SelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="fullName" HeaderText="fullName"
            SortExpression="fullName" />
        <asp:BoundField DataField="address" HeaderText="address"
            SortExpression="address" />
        <asp:BoundField DataField="work" HeaderText="work"
            SortExpression="work" />
        <asp:BoundField DataField="home" HeaderText="home" SortExpression="home" />
        <asp:BoundField DataField="mobile" HeaderText="mobile"
            SortExpression="mobile" />
        <asp:BoundField DataField="registrationNo" HeaderText="registrationNo"
            InsertVisible="False" ReadOnly="True" SortExpression="registrationNo" />
        <asp:ButtonField ButtonType="Button" CommandName="Edit" HeaderText="Edit"
            ShowHeader="True" Text="Edit" />
        <asp:ButtonField ButtonType="Button" CommandName="Update" HeaderText="Update"
            ShowHeader="True" Text="Update" />
        <asp:ButtonField ButtonType="Button" CommandName="Delete" HeaderText="Delete"
            ShowHeader="True" Text="Delete" />
    </Columns>
    <HeaderStyle BorderColor="#33CC33" />
    <RowStyle BorderStyle="Double" Font-Names="Monotype Corsiva" />
</asp:GridView>

A: //native asp.net clientside validation (ATLAS Ajax)
Instead of using BoundFields you should use TemplateField. This will allow you to add Validation controls in the field i.e.
Tutorial from 2007 which is still pertinent to this question
//serverside validation
In order to validate the values on the server side you have a couple of options:
a) add a CustomValidator pointing to codebehind server validation method i.e. msdn doc
b) on the gridviews RowUpdating method you could validate manually (this would also be for batch updates)


text:
Q: Adding shiny navbar element which triggers JS when clicked This navigation bar is what I want:

However, clicking Test, should not open a panel, but just run some JS code, in this case create an alert. Test should look like a standard navbar element. This is what I tried ...
library(shiny)

ui <- navbarPage(title = "test", inverse = T,
              tabPanel("Simulate", "simulate panel"),
              tabPanel("Test", "test panel"),

             #------ Add onclick action ------#
             tags$script("var a = $('.navbar-nav  li:nth-child(2) a');
               a.attr('data-toggle', 'noclass');
               a.click(function() {
                  alert('link clicked');
               });")
  )

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)

and it basically works, but when looking at the ui output, an additional
element is appended, which does not need to be there.

        Simulate

        Test

My questions:

*

*How can I create a link in the navbar avoiding the extra li element.

*Is there a better way to achieve this, i.e. without messing so much with the li attributes?

A: You can place the script in the header of the navbarPage and the extra li will not be created. You can add an id to the navbarPage and use that to reference the element in your script:
library(shiny)

ui <- navbarPage(title = "test", id = "nbpID", inverse = T,
                 header = tags$script("var a = $('#nbpID a[data-value=\"Test\"]');
                             a.attr('data-toggle', 'noclass');
                             a.click(function() {
                             alert('link clicked');
                             });"),
                 tabPanel("Simulate", "simulate panel"),
                 tabPanel("Test", "test panel")
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)


text:
Q: How to set Angular UI Bootstrap Datepicker to set empty field by default? I'm  working  a date picker using Angular UI Bootstrap Datepicker. My  challenge is to  set the input field of the date picker to  empty field by  default.
Let me show u the input  field i have used .

    <input class="form-control" type="text" datepicker-popup="dd/MM/yyyy" id='txtDate' ng-model="personalDetail.date" is-open="personalDetail.isOpen" close-text="Close" ng-click="open($event, personalDetail)" name="datefilter" value="" />

And my  script
  $scope.personalDetails.forEach(function(personalDetail){
    personalDetail.date = new Date(personalDetail.date);
  });

  $scope.open = function($event, personalDetail) {
    $event.preventDefault();
    $event.stopPropagation();

    personalDetail.isOpen = true;
  };

I'm using it  in the html  table with  ng-repeat . But  what  i need is to  show the date field empty untill i set the respective date. Please help  me from this.

A:

    <input class="form-control" type="text" datepicker-popup="dd/MM/yyyy" id='txtDate' ng-model="personalDetail.date" is-open="personalDetail.isOpen" close-text="Close" ng-click="open($event, personalDetail)" name="datefilter" value="" />

Your controller should be
$scope.personalDetails.forEach(function(personalDetail){
    //personalDetail.date = new Date(personalDetail.date);//sets the value to the control
    personalDetail.date = !personalDetail.date || new Date(personalDetail.date).toISOString() == new Date('1/1/1900').toISOString()
        ? '' // Date is null, undeclared, or default value
        : new Date(personalDetail.date);
  });

  $scope.open = function($event, personalDetail) {
    $event.preventDefault();
    $event.stopPropagation();

    personalDetail.isOpen = true;
  };

A: Change from
personalDetail.date = new Date(personalDetail.date);
to
personalDetail.date = "";

like $scope.personalDetail={
            date: ""
            }


text:
Q: how to insert user-defined button icons in intel XDK? I am using intel-XDK and I want to assign my own icons in the project.
How do I specify custom icons with the Intel XDK project?

A: On the "Projects" under "Launch icons and Splash Screens" you can supply images that will be used for those icons.  Each OS has different requirements for size and shape, but there are probably tools online that help generate them, given a starting point, e.g. https://romannurik.github.io/AndroidAssetStudio/


text:
Q: Facebook iOS SDK 3.6 startWithGraphPath completion block not executed I've integrated with Facebook so that I can, among other things, post statuses to my feed. I  based some of my code off of the publish to feed developer tutorial. When running the following Graph API request from my iOS application the completion block of the request is never called and no error appears in the XCode debug log.
[FBRequestConnection
startWithGraphPath:@"me/feed"
parameters:params
HTTPMethod:@"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    if (error) {
        DLog(@"error: domain = %@, code = %d", error.domain, error.code);
    } else {
        DLog(@"Posted action, id: %@", result[@"id"]);
    }
}];

I have two convenience functions that perform checks against the current activeSession before executing this request. They look like this:
+ (BOOL)facebookSessionIsOpen {
    return (FBSession.activeSession.isOpen);
}

+ (BOOL)facebookSessionHasPublishPermissions {
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound ||
        [FBSession.activeSession.permissions indexOfObject:@"publish_stream"] == NSNotFound ||
        [FBSession.activeSession.permissions indexOfObject:@"manage_friendlists"] == NSNotFound) {
        return NO;
    } else {
        return YES;
    }
}

Both of these functions return YES indicating an active session with the necessary publishing permission. What's more confusing is that I can pull the user's profile without issue after performing the same checks successfully (granted publishing permissions are not required to pull the profile) using the following code:
[FBRequestConnection
startWithGraphPath:@"me"
parameters:[NSDictionary dictionaryWithObject:@"picture,id,birthday,email,location,hometown" forKey:@"fields"]
HTTPMethod:@"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    NSDictionary* resultDict = (NSDictionary*)result;

    NSString* emailAddress = resultDict[@"email"];
    NSString* location = resultDict[@"location"][@"name"];
    NSString* birthday = resultDict[@"birthday"];
    NSString* homeTown = resultDict[@"hometown"][@"name"];
    ...
}];

Any suggestions on how to debug this issue?

A: Turns out the issue was a threading one. The Facebook iOS SDK doesn't seem to like to execute a FBRequest on a different thread from the one that you called openActiveSessionWithReadPermissions on and promptly deadlocks. It turns out I was running the postStatus request in a separate thread like so:
dispatch_queue_t some_queue = dispatch_queue_create("some.queue.name", NULL);
dispatch_async(some_queue, ^{
    [FacebookHelper postStatusToFacebookUserWall:newStatus withImage:imageData];
}];

Make sure your openActiveSessionWithReadPermissions and any FBRequest permutations all happen on the same thread, or you'll likely run into these silent failures.


text:
Q: How to insert Header Rows into Gridview with custom method I have a method that I call on page load that iterates through the rows in a gridview. What I would like to happen is for a header row to be inserted when the 'SectionID' of the row changes (it is a data key.)
There will be 6 additional header rows inserted and my code is doing just that except it is inserting all of the additional rows at the top (under the original header and before the first data row.) I want it to insert when the 'SectionID' changes.
Here is my method:
protected void addHeaders() {
    foreach (GridViewRow row in GridView1.Rows) {
        if (row.RowType == DataControlRowType.DataRow) {
            tmpSectionID = GridView1.DataKeys[row.RowIndex].Values["SectionID"].ToString();
            System.Diagnostics.Debug.WriteLine(tmpSectionID);

            if (sectionID != tmpSectionID) {
                sectionID = tmpSectionID;
                GridView gvw = (GridView)GridView1;
                DataRowView drv = (DataRowView)row.DataItem;

                GridViewRow HeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
                Table tbl = row.Parent as Table;
                Table myTable = (Table)GridView1.Controls[0];
                TableCell HeaderCell = new TableCell();

                HeaderCell.ColumnSpan = this.GridView1.Columns.Count;
                HeaderCell.Style.Add("font-weight", "bold");
                HeaderCell.Style.Add("background-color", "#22539B");
                HeaderCell.Style.Add("color", "white");
                HtmlGenericControl HeaderSpan = new HtmlGenericControl("span");
                HeaderCell.ToolTip = "Tooltip Here";
                HeaderSpan.InnerHtml = "Inserted Row";
                HeaderCell.Controls.Add(HeaderSpan);
                HeaderRow.Cells.Add(HeaderCell);
                myTable.Rows.AddAt(1, HeaderRow);
            }
        }
    }
}


text:
Q: What is the effect of (typeof arr1)[number]? Is there any other usage? Such as [string] or [union type]? What is the effect of [number]? Is there any other usage? Such as [string] or [union type]?
I want to find the relevant handbook
const paths = ['index', 'demo'] as const;
export type RoutePath = (typeof paths)[number];

A: [number] refers to an Indexed Type, from the Advanced Types page of the handbook.

An index signature parameter type must be 'string' or 'number'. If you have a type with a string index signature, keyof T will be string | number (and not just string, since in JavaScript you can access an object property either by using strings (object['42']) or numbers (object[42])).

paths is an array of strings, which could also be described this way:
interface ArrayOfStrings {
  [index: number]: string;
}

Therefore, (typeof paths) is a string[], so (typeof paths)[number] is a string. This syntax also works if your object is an array-like object, or has string properties in addition to numeric indexes.
See also: Typescript: Retrieve element type information from array type


text:
Q: How to achieve this style in HTML and CSS I have been try but this functionality I haven't been able to solve.
These 4 divs are child div of the parent div
We need to create so that the 3 child divs are in a column but the last div that is an image will be in a separate column and right aligned inside the parent div.
Could you please help me find answer to this question.

A: You could easily use a CSS Grid Layout to achieve this. I guess you want something like this, right:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  gap: 0px 0px;
  grid-template-areas:
    "Div-1 Div-4"
    "Div-2 Div-4"
    "Div-3 Div-4";
}
.grid-container div {padding: 10px;}
.Div-4 { grid-area: Div-4; background: #f90;}
.Div-1 { grid-area: Div-1; background: #ccf;}
.Div-2 { grid-area: Div-2; background: #cfc;}
.Div-3 { grid-area: Div-3; background: #fcc;}

Div 4

Div 1

Div 2

Div 3

Here your parent container is .grid-container. I used Interactive CSS Grid Generator | Layoutit Grid to generate this code.
Preview


text:
Q: Listview for SQL lite I was following a school tutorial for sql lite, and the output was a list of buttons. Is it possible to output this to a ListView instead?
I've tried googling and youtube but somehow  the tutorial I was following seems to have more files?
Confused newbie here!
Thanks in advance!
This code appears in the onCreate(Bundle savedInstanceState)
private void ShowExistingIdeas() {
        Idea[] ideas = new Ideas(this).getAllIdeas();
        if(ideas != null && ideas.length > 0)
        {
            for(int index = 0; index < ideas.length; index++)
            {
                Button ideaButton = new Button(this);
                ideaButton.setText(ideas[index].getTitle());
                final int id = ideas[index].getId();
                ideaButton.setTag(id);
                ideaButton.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(OverviewActivity.this,
                                EditIdeaActivity.class);
                        i.putExtra("id", id);
                        startActivityForResult(i, 0);
                    }
                });

//!!! The bit I'm trying to change. the xml with LinearLayout1 is completely empty****
                ((LinearLayout) findViewById(R.id.LinearLayout1)).
                addView(ideaButton);
            }
        }
    }

For your reference - the Ideas file
public class Ideas {
    private Idea[] ideas;
    private Context context;

    public Ideas(Context context) {
        this.context = context;
    }

    public Idea[] getAllIdeas() {
        return getIdeasWithKeyword(null);
    }

    public Idea[] getIdeasWithKeyword(String keyword) {
        ideas = null;

        SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
        String where = null;
        String[] whereArgs = null;
        if (keyword != null) {
            where = DbHelper.COL_TITLE + " LIKE '%?%' OR " + DbHelper.COL_DESC
                    + " LIKE '%?%'";
            whereArgs = new String[] { keyword };
        }
        Cursor c = db.query(DbHelper.TABLE_IDEAS, DbHelper.COLUMNS, where,
                whereArgs, null, null, null);
        if (c != null && c.moveToFirst()) {
            ideas = new Idea[c.getCount()];
            boolean hasMore = true;
            for (int index = 0; hasMore; hasMore = c.moveToNext(), index++) {
                int id = c.getInt(c.getColumnIndex(DbHelper.COL_ID));
                String title = c
                        .getString(c.getColumnIndex(DbHelper.COL_TITLE));
                String description = c.getString(c
                        .getColumnIndex(DbHelper.COL_DESC));
                int priority = c
                        .getInt(c.getColumnIndex(DbHelper.COL_PRIORITY));

                ideas[index] = new Idea(id, title, description, priority);
            }
        }

        if (db != null && db.isOpen())
            db.close();

        return ideas;
    }
    public Idea getIdea(int id) {
        SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
        Cursor c = db.query(DbHelper.TABLE_IDEAS, DbHelper.COLUMNS, "_id = "
                + id, null, null, null, null);
        Idea idea = null;
        if (c != null && c.moveToFirst()) {
            String title = c.getString(c.getColumnIndex(DbHelper.COL_TITLE));
            String description = c.getString(c
                    .getColumnIndex(DbHelper.COL_DESC));
            int priority = c.getInt(c.getColumnIndex(DbHelper.COL_PRIORITY));

            idea = new Idea(id, title, description, priority);
        }

        if (db != null && db.isOpen())
            db.close();

        return idea;
    }

    public void addIdea(Idea idea) {
        SQLiteDatabase db = new DbHelper(context).getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(DbHelper.COL_TITLE, idea.getTitle());
        values.put(DbHelper.COL_DESC, idea.getDescription());
        values.put(DbHelper.COL_PRIORITY, idea.getPriority());
        db.insert(DbHelper.TABLE_IDEAS, null, values);

        if (db != null && db.isOpen())
            db.close();
    }

    public void deleteIdea(int ideaId) {
        SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
        db.delete(DbHelper.TABLE_IDEAS, DbHelper.COL_ID + "=" + ideaId, null);

        if (db != null && db.isOpen())
            db.close();
    }
}


text:
Q: Discord - I'm trying to split a message using discord.js v13.1 I'm trying to split a message when it exceeds 2000 characters, but after i update discord.js to 13.1 i can't do it anymore
message.channel.send(code, { split: true, code: "js" })

what i tried
message.channel.send({
            content: Util.splitMessage(code)
            })
// let {Util} = require("discord.js")

A: You'll have to pass a char as splitter in the SplitOptions.

Splits a string into multiple chunks at a designated character that do
not exceed a specific length.
(Util.splitMessage())

Honestly I find it a little weird how the method is designed. Although the char where the string should be splitted is necessary in order to make it work, the char parameter itself is optional. And it's even weirder that you don't get the error when sending a message > 2000 chars but actually when using the Util-method.
const {
  Util: { splitMessage },
} = require("discord.js");
const split = splitMessage("test".repeat(255) + "x" + "test".repeat(250), {
  char: "x",
}); // => ["test"*255, the other 255 "test"]

I suppose you're seeking for a way to automatically shorten a message when it exceeds the limit of 2000 characters.
I'm afraid you'll have to start building your own helper functions in the future for that kind of stuff.

This functionality will now have to be handled manually, such as via the Formatters.codeBlock and Util.splitMessage helpers.

Sending messages, embeds, files, etc.
Luckily it's pretty straight forward:
const customSplitMessage = (text) => [
  text.substring(0, 2000),
  text.substring(2000, text.length),
];

And then use it like so:
message.channel.send({
  content: customSplitMessage("test".repeat(501))[0],
}); // => sends the first exactly 2000 chars


text:
Q: JOIN table if condition is satisfied, else perform no join I have one table transaction and another table transaction_item.
One transaction has multiple transaction_items.
I want to left join transaction_item if transaction_item.amount >= 2, else perform no join.
select ti.*
from transaction t
LEFT JOIN transaction_item ti on ti.unique_id = t.unique_id
    AND ti.location_id =  t.location_id
    AND ti.transaction_date = t.transaction_date
    AND ti.amount >= 2
where t.pos_transaction_id = 4220
and t.location_id = 1674
and t.transaction_date = '2020-05-08';

If I do it this way it is results in 15 rows in place of total 20 rows, because 20 rows are in transaction_item table corresponding to transaction_id 4220. But I want no join in this case because 5 rows in transaction_item have amount < 2.

A: Your description a bit confusing, but the title says:
"else perform no join"
So I think you want something this:
SELECT ti.*
FROM   transaction t
LEFT   JOIN transaction_item ti ON ti.unique_id        = t.unique_id
                               AND ti.location_id      = t.location_id
                               AND ti.transaction_date = t.transaction_date
                               AND NOT EXISTS (
                                    SELECT FROM transaction_item tx
                                    WHERE  tx.unique_id        = t.unique_id
                                    AND    tx.location_id      = t.location_id
                                    AND    tx.transaction_date = t.transaction_date
                                    AND    tx.amount < 2)  -- !
WHERE  t.pos_transaction_id = 4220
AND    t.location_id = 1674
AND    t.transaction_date = '2020-05-08';

However, the LEFT JOIN in combination with only columns from the right table in the SELECT list is dubious at best. This way you get one row with all NULL values for every row in transaction that qualifies and has no matching rows in transaction_item or one or more matching rows with amount < 2. I doubt you want that.
Typically, you'll want to include columns from transaction in the SELECT list, or use an [INNER] JOIN instead.
So it could be:
SELECT ti.*
FROM   transaction t
JOIN   transaction_item ti USING (unique_id, location_id, transaction_date)
WHERE  t.pos_transaction_id = 4220
AND    t.location_id = 1674
AND    t.transaction_date = '2020-05-08';
AND    NOT EXISTS (
   SELECT FROM transaction_item tx
   WHERE  tx.unique_id        = t.unique_id
   AND    tx.location_id      = t.location_id
   AND    tx.transaction_date = t.transaction_date
   AND    tx.amount < 2);

Then again, a table transaction_item would typically have a FK column transaction_id referencing transaction - in which case we can simplify
SELECT ti.*
FROM   transaction t
JOIN   transaction_item ti ON ti.transaction_id = t.transaction_id -- ?
WHERE  t.pos_transaction_id = 4220
AND    t.location_id = 1674
AND    t.transaction_date = '2020-05-08';
AND    NOT EXISTS (
   SELECT FROM transaction_item tx
   WHERE  tx.transaction_id = t.transaction_id
   AND    tx.amount < 2);

You mentioned both pos_transaction_id and transaction_id, so I am guessing here ...
The major insight to take away from this: always show exact table definitions with any such question.


text:
Q: Rails: NoMethodError on creating has_one association with devise model I am a complete beginner in Rails as such and I am trying to build a page to add extra profile data once the user logs in.
I am using Devise for authentication purposes and that works fine.  I get this error and I have been stuck here.

undefined method `profiles'

Can you please help?
Codes
profiles_controller.rb
class ProfilesController < ApplicationController

  before_action :authenticate_user!, only: [:new, :create, :show]

  def new
    @profile = current_user.profiles.build
  end

  def create
    @profile = current_user.profiles.build(profile_params)
    if @profile.save
      format.html {redirect_to @profile, notice: 'Post was successfully created.'}
    else
      format.html {render 'new'}
    end

  end

  def show
    @profile = current_user.profiles
  end

  private

  def profile_params
    params.require(:profile).permit(:content)
  end
end

The error seems to be coming from these lines in particular
  def new
    @profile = current_user.profiles.build
  end

Other codes for reference:
/views/profiles/new.html.erb

Profiles#new

Find me in app/views/profiles/new.html.erb

Welcome <%= current_user.email %>

<%= form_for(@profile) do |f| %>

    <%= f.label :content %>

    <%= f.text_field :text, autofocus: true %>

    <%= f.submit "Sign up" %>

<%end%>

routes.rb
Rails.application.routes.draw do
  get 'profiles/new'

  get 'profiles/create'

  get 'profiles/show'

  get 'profiles/update'

  get 'pages/home'

  get 'pages/dashboard'

  devise_for :users,  controllers: { registrations: "registrations" }
  resources :profiles

  root 'pages#home'

  devise_scope :user do
    get "user_root", to: "page#dashboard"
  end
end

models/user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :profile, dependent: :destroy
end

models/profile.rb
class Profile < ActiveRecord::Base

  belongs_to :user
end

A: I just figured it out!
As the relationship is has_one, we should be using
def new
   @profile = current_user.build_profile
end

instead of
def new
   @profile = current_user.profiles.build
end

according to the documentation -
http://guides.rubyonrails.org/association_basics.html#has-one-association-reference

A: You are trying to call an undefined relationship:
  def new
    @profile = current_user.profiles.build
  end

  has_one :profile

You should be calling:
  def new
    @profile = current_user.build_profile
  end

A: 1) If your user must have many profiles. Set in your app/models/user.rb has_many :profiles
2)  In your ProfilesController in new method instead of @profile = current_user.profiles use @profile = Profile.new
3) In your routes.rb delete
  get 'profiles/new'

  get 'profiles/create'

  get 'profiles/show'

  get 'profiles/update'

because you have already used resources :profiles
4) To stay with rules of DRY you can render form from a partial. Just add in views/profiles/_form.html.erb with the same content in your new.html.erb and after this you can delete everything im new.htm.erb and paste <%= render "form" %>. In future it will help you to render edit form if you want.
5) In your ProfilesController you can add method index with all profiles
def index
  @profiles = Profile.all
end


text:
Q: Primefaces selectManyMenu - Loading list from Object So the scenario I have is such:
I have a person that I load up that has a list of integer values that represent all of the videos that person has watched.
For example, if person 12345 has viewed three videos, it would be represented in a list as such [4012, 2001292, 50201]
That list can be 0..x and is represented by a selectManyMenu in Primefaces.
When I load the people from the database and attempt to edit the person, instead of seeing every video that person has viewed checked in the selectManyMenu, it shows the first one and that is it. It either shows 0 or 1. Not many.
Code:
<p:selectManyMenu id="editPersonVideoList" value="#{backingBean.viewedPerson.allViewedVideos}">
    <f:selectItems value="#{backingBean.allVideos}" var="v" itemLabel="#{v.name}" itemValue="#{v.id}"/>
</p:selectManyMenu>

Any ideas...?

A: If allViewedVideos is only integer type list , then it won't display any data.
Type of the allViewedVideos should selectedItem and need to put data item label and item id format.
create a class(Ex : SelectedList) with having two fields 1. Label 2. Id. Set allViewedVideos value data to this list. Return List newList of value.
use


text:
Q: Type Erasure in Scala I'm rather confused about what's happening here:
import scala.collection.immutable._

object Main extends App {
  sealed trait Node

  sealed trait Group

  case class Sheet(
    val splat: String,
    val charname: String,
    val children: ListMap[String, Node],
    val params0: ListMap[String, Param], //params0 to separate sheet-general parameters

    val note: Option[Note]
    ) extends Node with Group

  case class Attributes(val name: String) extends Node with Group

  case class Param(val name: String, val value: String) extends Node
  case class Note(val note: String) extends Node

I've got three versions of a replace function - the last one is the one I'm actually trying to write, the others are just debugging.
  class SheetUpdater(s: Sheet) {
    def replace1[T <: Group](g: T): Unit = {
      s.children.head match {
        case (_, _:Sheet) =>
        case (_, _:Attributes) =>
      }
    }
  }

This version throws no warnings, so apparently I have access to the type of s.children at runtime.
  class SheetUpdater(s: Sheet) {
    def replace2[T <: Group](g: T): Unit = {
      g match {
        case _:Sheet =>
        case _:Attributes =>
      }
    }
  }

Neither does this version, so apparently the details of g's type are also available at runtime...
  class SheetUpdater(s: Sheet) {
    def replace3[T <: Group](g: T): Unit = {
      s.children.head match {
        case (_, _:T) => //!
        case (_, _:Attributes) =>
      }
    }
  }

... but even so, this ends up throwing me the dreaded Abstract type pattern T is unchecked since it is eliminated by erasure warning. What's going on here?

A: In Scala, generics are erased at runtime, which means that the runtime type of List[Int] and List[Boolean] is actually the same. This is because the JVM as a whole erases generic types. All this is due because the JVM wanted to remain backwards compatible way back when generics were first introduced...
There is a way around this in Scala using a ClassTag, which is an implicit parameter that then can be threaded around with whatever generic you are using.
You can think of : ClassTag as passing the type of the generic as an argument. (It is syntactic sugar for passing an implicit parameter of type ClassTag[T].)
import scala.reflect.ClassTag

class SheetUpdater(s: Sheet) {
  def replace3[T <: Group : ClassTag](g: T): Unit = {
    s.children.head match {
      case (_, _:T) => //!
      case (_, _:Attributes) =>
    }
  }
}

Newer answers of this question have more details.


text:
Q: Passing PHP id to a jQuery function I have this jQuery in my header:
$(document).ready(function(){
    $("h5").click(function(){
        $("p").slideToggle();
    });
});

and I am  fetching data from database. When I clicks on h5 it shows and hides all the paragraphs. I want to show and hide a particular paragraph when I click on h5. This is my PHP:
while($results = mysqli_fetch_array($raw_results))
{
    echo "
";echo"
".$results['question']."
";echo "
option A:" .$results['option_a']."
option B:".$results['option_b']."
option C:".$results['option_c'].
    "
option D:".$results['option_d']."
option E:".$results['option_e']."
Correct Ans:".$results['correct_ans'].
    "
FMGE Year:".$results['fmge_year']."
FMGE Month :".$results['fmge_month']."
Contributor:".$results['contributor']."
";
    echo "
";
}

A: Use jQuery .siblings() to select the matching paragraph:
$(this).siblings('p').slideToggle(); //<- slideToggle is just for example

A: Like  @jeroen said, but different- just require  in
css: !writing style in php can be headache
div.content {
    background-color: #F1F0FF;
    pading:35px
}

Html format

...

...

Jquery
$(".content").on("click", "h5", function() {
     $(this).parent()
          .children('p')
          .slideToggle();
});

And there is still other way.


text:
Q: maven shows up some modules marked as "unnamed" I'm working with maven in a multi module project and it works fine. But when it starts it refers to some projects as unnamed. Why does this happen, and how can I solve it?

A: You need to give a name entry in every module you use. That should help. May be you can post your pom...if it isn't the problem.
<name>Entry</name>

A: In every sub module, simply specify a <name>:
<project>
    ...
    <name>My project</name>
    ...

This name will then be used by the Reactor to display the build order of the modules.


text:
Q: How to resolve time-exceeded error(codechef) for stable-marraige? I am trying to implement the stable marriage using lists and arrays. When i try to submit it on codechef it gives runtime exceeded errors.If someone could help but i want to use the very same data-structure i am using.
import java.util.*;
public class Main {

private int size;
private static LinkedList<Integer>[] menlist;
private static int[][] womatrix;
private static int[][] invwomatrix;
private static int[] womatch;
private static int[] menmatch;
public static void main(String[] args){
    Scanner Input = new Scanner(System.in);
    int TestCases = Input.nextInt();
    while(TestCases-- > 0) {
        int size = Input.nextInt();
        womatrix=new int[size][size];
        invwomatrix=new int[size][size];
        menlist=new LinkedList[size];
        womatch=new int[size];
        menmatch=new int[size];
        for(int i = 0; i < size; i++){
             int temp=Input.nextInt();
             for(int j = 0; j < size; j++)
             {
                        womatrix[i][j] = Input.nextInt();
                        invwomatrix[i][womatrix[i][j]-1]=j+1;
             }
             }
        for(int i = 0; i < size; i++){
             int temp=Input.nextInt();
             LinkedList<Integer> menpref = new LinkedList<Integer>();
             for(int j = 0; j < size; j++)
                {
                        int a=Input.nextInt();

                        menpref.add(a);

             }
             menlist[i]=menpref;
             }

        LinkedList<Integer> ll = new LinkedList<Integer>();
        for(int i=0;i<size;i++){
            womatch[i]=0;
            menmatch[i]=0;
            ll.add(i+1);
        }

        while((ll.isEmpty()!=true) || menlist[ll.getFirst()-1].isEmpty()!=true ){

            int newman=ll.removeFirst();
            //System.out.print("freeman "+newman+" "+menlist[newman-1].isEmpty()+"\n");
            int women=(menlist[newman-1].removeFirst());
            //System.out.print("highrank "+women+"intial_pair "+womatch[women-1]+"\n");
            if(womatch[women-1]==0){
                womatch[women-1]=newman;
                menmatch[newman-1]=women;
                //int a=ll.removeFirst();

            }
            else{
                int oldman=womatch[women-1];

                if(invwomatrix[women-1][newman-1]<invwomatrix[women-1][oldman-1]){
                    womatch[women-1]=newman;
                    menmatch[newman-1]=women;
                    ll.addFirst(oldman);

                }
                else{
                    ll.addFirst(newman);
                }
            }
            /*for(int i=0; i<this.size; i++) {
                System.out.print((i+1)+" "+ menmatch[i] +"\n");
                }*/

            if(ll.isEmpty()==true){break;}

        }

        for(int k=0;k<size;k++){
             System.out.print((k+1)+" "+menmatch[k] +"\n");
         }

    }
}

}


text:
Q: Page A to page B - Connect the pages to be recognized as logged in I have created some access controlled pages which can be viewed only after logged in. I had to create another page which holds a form where the user is going to fill the details and submit it. But am not able to connect page A to page B so that the user is still logged in.
I try to add the codes that I used in the access controlled pages to the Page B which has a form. But then the page shows internal error 500.
The code that I am using on the access controlled pages is
<?PHP
require_once("./include/membersite_config.php");

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
?>

When I try to use the same for the Page B which has a form for submission, it doesn't work.
Something is conflicting.
Here is the code on the Page B
<?PHP

require_once("./separate/include/fgcontactformuser.php");
require_once("./separate/include/captcha-creator.php");

$formproc = new FGContactForm();
$captcha = new FGCaptchaCreator('scaptcha');

$formproc->EnableCaptcha($captcha);

$formproc->AddRecipient('mail.com'); //<<---Put your email address here

$formproc->SetFormRandomKey('H04uLRJh4CY5sR4');

if(isset($_POST['submitted']))
{
   if($formproc->ProcessForm())
   {
        $formproc->RedirectToURL("PageB.php");
   }
}

?>

Why is there a conflict and why it doesn't work?


text:
Q: Polymorphic Associations or something easier This is my first post and I can't seem to find the answer anywhere....
I have a database that has multiple companies,each company has multiple locations.
I'm running into problems trying to define the contacts. Some contacts need to be global and available
at any location....some contacts only need to exist for one location. In the contact_info table below
we specify the visibility of the contact (company or location). However the location needs to choose its primary contact.
That leaves a FK from contact -> location and from location -> contact.
I know there is another table involved but I can't seem to conceptualize it.
CREATE TABLE `company_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '',
PRIMARY KEY  (`id`),
UNIQUE KEY `name` (`name`));

CREATE TABLE `location_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_info` INT NOT NULL DEFAULT -1,
`name` VARCHAR(100) NOT NULL DEFAULT '',
`primary_contact_id` INT NOT NULL DEFAULT -1,
PRIMARY KEY(`id`),
UNIQUE KEY(`company_id`,`name`),
FOREIGN KEY (company_id) REFERENCES company_info(id)
FOREIGN KEY (primary_contact_id) REFERENCES contact_info(id));

CREATE TABLE `contact_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_id` INT
`location_id` INT,
`type` ENUM('Company','Location') NOT NULL DEFAULT 'Company',
`first_name` VARCHAR(50) NOT NULL DEFAULT '',
`last_name` VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY(`id`),
UNIQUE KEY(`id`,`company_id`,`location_id`),
FOREIGN KEY (location_id) REFERENCES location_info(id),
FOREIGN KEY (company_id) REFERENCES company_info(id)

A: The most effective way would be splitting it up so that there's a table for your companies, a table with your users, and a table solely for the purpose of storing all connections (i.e. EntryID, UserID, CompanyID). This way you'll be able to easily load them afterwards.


text:
Q: C# Convert a 2-dimensional array into a dataset / datatable does anyone know how to turn a 2-dimensional array into a dataset or datatable in c#?
Source: a range of values from excel (interop) in an object[,] array.
Thanks.

A: Please take a look at the following article
Converting an Excel Spreadsheet to a DataSet, DataTable and Multi-Dimensional Array

A: You can create a dataset / datatable in code:
http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx
From there you would loop through your array and populate the rows and their columns with the array information.

A: Option given by mr.phoenix should work. If you are stuck with dealing with arrays...here is some pseudocode.
var sample = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};
var table = new DataTable("SampleTable");

// iteration logic/loops for the array
{
   var newRow = table.NewRow();
   newRow["Col1"] = sample[i,j0]; // like sample [0,0]
   newRow["Col2"] = sample[i,j1]; // like sample [0,1]
   table.Add(newRow);
}


text:
Q: Navigation in SwiftUI - App Setup Navigation View flow into a Tab View Navigation flow Picking up swift again for the first time in a while and this seems way more difficult than it should be to find a clear answer on the correct way to go about this as it seems like a common scenario for an app.
I need to present the user with a few set up screens (user registration, login, other details) that will only be presented once when first setting up the app.
When finished with this setup process the app should navigate to a Tab View based Home Screen which will be the main navigation throughout the app (with each tab item having its own NavigationView navigation)
Navigating from the setup to the home view with a Navigation Link stays within that initial navigation view hierarchy and I end up with double navigation bars on the Home Screen. I've also tried presenting the setup view as a FullScreenCover, but that didn't seem to fully work correctly either.
I'm avoiding posting code as I want to find the best way this will work for multiple projects, not specifically for what I'm currently working on.


text:
Q: android-How to return to same activity after search is done in a single activity I have implemented my search widget in the Main Activity.. And my MainActivity is handling all the searching feature..
When the query is executed the results are come up as per desired..
But the real problem is while the search query result are visible if i want to go back to the basic MainActivity contents then i try pressing the Home/Up button or device Back button...
On pressing Home/Up button nothing happens.. simply the open search widget collapse...
but on pressing the Back button the app exits..
What i want is.. I would like to return to the basic on start results in MainActivity without exiting the app after search contents are shown..
Here is my Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pockettutsforcosm"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="20" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:parentActivityName=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>

    <meta-data
        android:name="android.app.default_searchable"
        android:value=".MainActivity" />
</application>

</manifest>

UPDATE
MainActivity Source-
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);

        // Associate searchable configuration with the SearchView
SearchManager searchManager =(SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        // Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        // Do not iconify the widget; expand it by default
        searchView.setIconifiedByDefault(false);
        searchView.setSubmitButtonEnabled(true);
        restoreActionBar();
        return true;
    }
return super.onCreateOptionsMenu(menu);}

I am handling it using the following code-
@Override
protected void onNewIntent(Intent intent)
{
    setIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String searchText = intent.getStringExtra(SearchManager.QUERY);
        doMySearch(searchText);

        // Do work using string

    }
}

private void doMySearch(String searchText)
{
    c = dbOpen.getMySearchFromDB(searchText);
    showListContent(c);
}

i am calling-
    handleIntent(getIntent);
in onCreate() of MainActivity