text:
Q: Getting and printing random value as string from javascript array get a random string value from a JavaScript array.
var randomcity = ["Adana", "Adıyaman", "Afyonkarahisar", "Ağrı"," Aksaray", "Amasya", "Ankara", "Antalya", "Ardahan", "Artvin", "Aydın", "Balıkesir", "Bartın", "Batman", "Bayburt", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale", "Çankırı", "Çorum", "Denizli", "Diyarbakır", "Düzce", "Edirne", "Elazığ", "Erzincan", "Erzurum", "Eskişehir", "Gaziantep", "Giresun", "Gümüşhane", "Hakkâri", "Hatay", "Iğdır", "Isparta", "İstanbul", "İzmir", "Kahramanmaraş", "Karabük", "Karaman", "Kars", "Kastamonu", "Kayseri", "Kilis", "Kırıkkale", "Kırklareli", "Kırşehir", "Kocaeli", "Konya", "Kütahya", "Malatya", "Manisa", "Mardin", "Mersin", "Muğla", "Muş", "Nevşehir", "Niğde", "Ordu", "Osmaniye", "Rize", "Sakarya", "Samsun", "Şanlıurfa", "Siirt", "Sinop", "Sivas", "Şırnak", "Tekirdağ", "Tokat", "Trabzon", "Tunceli", "Uşak", "Van", "Yalova", "Yozgat", "Zonguldak"];

var random;

function generateRandom () {
    random=Math.floor(Math.random * randomcity.length);
    console.log(random.value);
    document.getElementById('newInputBox1').value=random;
}

a new InputBox generated with id: 'newInputBox1'.
I get value from the user via a prompt and cannot insert it into this generated box

A: A small change to your code should make everything work nicely.
We'll get a randomIndex using Math.random() then use it as an index to the input array.
We'd wrap this up in a getRandomElement() function and pass the randomcity array to it:

const randomcity = ["Adana", "Adıyaman", "Afyonkarahisar", "Ağrı"," Aksaray", "Amasya", "Ankara", "Antalya", "Ardahan", "Artvin", "Aydın", "Balıkesir", "Bartın", "Batman", "Bayburt", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale", "Çankırı", "Çorum", "Denizli", "Diyarbakır", "Düzce", "Edirne", "Elazığ", "Erzincan", "Erzurum", "Eskişehir", "Gaziantep", "Giresun", "Gümüşhane", "Hakkâri", "Hatay", "Iğdır", "Isparta", "İstanbul", "İzmir", "Kahramanmaraş", "Karabük", "Karaman", "Kars", "Kastamonu", "Kayseri", "Kilis", "Kırıkkale", "Kırklareli", "Kırşehir", "Kocaeli", "Konya", "Kütahya", "Malatya", "Manisa", "Mardin", "Mersin", "Muğla", "Muş", "Nevşehir", "Niğde", "Ordu", "Osmaniye", "Rize", "Sakarya", "Samsun", "Şanlıurfa", "Siirt", "Sinop", "Sivas", "Şırnak", "Tekirdağ", "Tokat", "Trabzon", "Tunceli", "Uşak", "Van", "Yalova", "Yozgat", "Zonguldak"];

function getRandomElement(arr) {
    return arr[Math.floor(Math.random()*arr.length)];
}

function generateRandom () {
   document.getElementById('newInputBox1').value = getRandomElement(randomcity);
}

generateRandom();

Result: <input id='newInputBox1' value = ''/>
<button type='Button' onclick='generateRandom()'>Generate Random</button>

A: Check out the commented code below, as a candidate solution for your problem

 const randomcity = [
            "Adana", "Adıyaman", "Afyonkarahisar", "Ağrı", " Aksaray", "Amasya", "Ankara", "Antalya", "Ardahan", "Artvin", "Aydın", "Balıkesir", "Bartın", "Batman", "Bayburt", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale", "Çankırı", "Çorum", "Denizli", "Diyarbakır", "Düzce", "Edirne", "Elazığ", "Erzincan", "Erzurum", "Eskişehir", "Gaziantep", "Giresun", "Gümüşhane", "Hakkâri", "Hatay", "Iğdır", "Isparta", "İstanbul", "İzmir", "Kahramanmaraş", "Karabük", "Karaman", "Kars", "Kastamonu", "Kayseri", "Kilis", "Kırıkkale", "Kırklareli", "Kırşehir", "Kocaeli", "Konya", "Kütahya", "Malatya", "Manisa", "Mardin", "Mersin", "Muğla", "Muş", "Nevşehir", "Niğde", "Ordu", "Osmaniye", "Rize", "Sakarya", "Samsun", "Şanlıurfa", "Siirt", "Sinop", "Sivas", "Şırnak", "Tekirdağ", "Tokat", "Trabzon", "Tunceli", "Uşak", "Van", "Yalova", "Yozgat", "Zonguldak"
        ]
        var randomCityIndex;
        var element;
        var divElement;

        function generateRandom() {
            //Get the elements by ID
            element = document.getElementById('newInputBox1');
            divElement = document.getElementById('div');

            // Get the index of Random City
            const rand = Math.floor(Math.random() * randomcity.length);

            // Set the value for input tag as el.value = randomValue
            element.value = randomcity[rand];

            // For other type of tags like div and p, use el.innerHtml or el.innerText = randomValue
            divElement.innerHTML = randomcity[rand];

        }
 #div, p {
            font-size: 16px;
            width: 400px;
            margin: 5px auto;
            background-color: burlywood;
            text-align: center;
            padding: 10px;
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Random City</title>

Random City

<button onclick="generateRandom()">Random City</button>
In Input: <input id="newInputBox1"/>

Random City in div:

{Click the button to see RandomCity}

A: Something is missing in your code. Here down i can explain your mistake
1. You forget to add round bracket () after Math.random
2. You can not linked your array with random variable so, it's always take undefined as value
3. You forget to call generateRandom() method.
Here down is code:

var randomcity = ["Adana", "Adıyaman", "Afyonkarahisar", "Ağrı"," Aksaray", "Amasya", "Ankara", "Antalya", "Ardahan", "Artvin", "Aydın", "Balıkesir", "Bartın", "Batman", "Bayburt", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale", "Çankırı", "Çorum", "Denizli", "Diyarbakır", "Düzce", "Edirne", "Elazığ", "Erzincan", "Erzurum", "Eskişehir", "Gaziantep", "Giresun", "Gümüşhane", "Hakkâri", "Hatay", "Iğdır", "Isparta", "İstanbul", "İzmir", "Kahramanmaraş", "Karabük", "Karaman", "Kars", "Kastamonu", "Kayseri", "Kilis", "Kırıkkale", "Kırklareli", "Kırşehir", "Kocaeli", "Konya", "Kütahya", "Malatya", "Manisa", "Mardin", "Mersin", "Muğla", "Muş", "Nevşehir", "Niğde", "Ordu", "Osmaniye", "Rize", "Sakarya", "Samsun", "Şanlıurfa", "Siirt", "Sinop", "Sivas", "Şırnak", "Tekirdağ", "Tokat", "Trabzon", "Tunceli", "Uşak", "Van", "Yalova", "Yozgat", "Zonguldak"]
var random;
function generateRandom () {
    random = randomcity[Math.floor(Math.random() * randomcity.length)];
    document.getElementById('txtcity').value = random;
}

generateRandom();
City:
<input id='txtcity' value = ''/>


text:
Q: JUnit Test & Integration Test - Jenkins - Cucumber I have recently started applying Cucumber in my Project and creating the framework.
Now, what we are facing is, when we are running the test cases via Jenkins, then what we want to achieve is a method where we can call our Junit test cases separately like before the deployment and Integration Test cases separately(Cucumber Tests) like after the deployment.
How we can achieve this via Jenkins, if we use the same POM file for Cucumber tests as used for the Development?
Jenkins Pipeline
Before deployement - Trigger Junit - Deployment - after deployment - Trigger Integration Cucumber

A: There is not much information that you have shared here. But here's how you can achieve it. If you are using maven, then via maven's surefire plugin you can configure to run (J)unit tests. Then do deployment either via maven or custom scripts. Then using failsafe plugins trigger your integration tests. All of these can be controlled via different maven goals / phases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the part of the html code from html code in c#? In My program i have used string  variable content. I have assigned a small HTML program for this string. For Example,
String content = "  <TITLE>Your Title Here</TITLE>
This is a Medium Header Send me mail atsupport@yourcompany.com.This is a new sentence without a paragraph break.
";

From this i want to get "This is a Medium Header
Send me mail at  support@yourcompany.com.This is a new sentence without a paragraph break." alone.
This string available inside the  tag. how i get this string using c#.

A: Don't use string methods or regex to parse HTML. You can use HtmlAgilityPack.
string content = "  <TITLE>Your Title Here</TITLE>
This is a Medium Header Send me mail atsupport@yourcompany.com.This is a new sentence without a paragraph break.
";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);
string headerText = doc.DocumentNode.Descendants("H2").First().InnerText;

Result:
This is a Medium Header Send me mail atsupport@yourcompany.com.This is a new sentence without a paragraph break.

A: Complete sample
HtmlFormatHelper.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Tools
{
    ///
    /// набор утилит для форматирования HTML текста
    ///
    public static class HtmlFormatHelper
    {
        private static Regex _regexLineBreak;
        private static Regex _regexStripFormatting;
        private static Regex _regexTagWhiteSpace;
        private static Regex _regexHyperlink;

        ///
        /// статический конструктор
        ///
        static HtmlFormatHelper()
        {
            _regexLineBreak = new Regex(@"<(br|BR|p|P)\s{0,1}\/{0,1}>\s*|</[pP]>", RegexOptions.Singleline);
            _regexStripFormatting = new Regex(@"<[^>]*(>|$)", RegexOptions.Singleline);
            _regexTagWhiteSpace = new Regex(@"(>|$)(\W|\n|\r)+<", RegexOptions.Singleline);
            _regexHyperlink = new Regex(@"]*href\s*=\s*[""']?([^""'>]+)[""']?[^>]*>([^<]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }

        ///
        /// конвертировать HTML в текст
        ///
        /// <param name="html"> HTML </param>
        /// <returns></returns>
        public static string HtmlToPlainText(string html)
        {
            var text = html;

            text = System.Net.WebUtility.HtmlDecode(text);
            text = _regexTagWhiteSpace.Replace(text, "><");
            text = _regexLineBreak.Replace(text, Environment.NewLine);
            text = _regexStripFormatting.Replace(text, string.Empty);

            return text;
        }

        ///
        /// конвертировать HTML в текст с "умным" оформлением
        ///
        /// <param name="html"> HTML </param>
        /// <returns></returns>
        public static string HtmlToPlainTextSmart(string html)
        {
            // обрабатываем ссылки
            html = _regexHyperlink.Replace(html, e =>
            {
                string url = e.Groups[1].Value.Trim();
                string text = e.Groups[2].Value.Trim();

                if (url.Length == 0 || string.Equals(url, text, StringComparison.InvariantCultureIgnoreCase))
                {
                    // ссылки идентичны или ссылка отсутствует
                    return e.Value;
                }
                else
                {
                    // ссылки отличаются
                    return string.Format("{0} ({1})", text, url);
                }
            });

            return HtmlToPlainText(html);
        }

        ///
        /// кодировать HTML код с "мягком" режиме
        ///
        /// <param name="html"> HTML </param>
        /// <returns></returns>
        public static string SoftHtmlEncode(string html)
        {
            if (html == null)
            {
                return null;
            }
            else
            {
                StringBuilder sb = new StringBuilder(html.Length);

                foreach (char c in html)
                {
                    if (c == '<')
                    {
                        sb.Append("<");
                    }
                    else if (c == '>')
                    {
                        sb.Append(">");
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                return sb.ToString();
            }
        }
    }
}

How to use:
// input string
string content = "  <TITLE>Your Title Here</TITLE>
This is a Medium Header Send me mail atsupport@yourcompany.com.This is a new sentence without a paragraph break.
";

// extract html body
string htmlBody = Regex.Match(content, @"^.*?(.*).*?$", RegexOptions.IgnoreCase).Groups[1].Value;

// plain text
string plainText = Tools.HtmlFormatHelper.HtmlToPlainText(htmlBody);
//: This is a Medium Header Send me mail atsupport@yourcompany.com.This is a new sentence without a paragraph break.

// plain text (with url in brackets)
string plainTextSmart = Tools.HtmlFormatHelper.HtmlToPlainTextSmart(htmlBody);
//: This is a Medium Header Send me mail atsupport@yourcompany.com (mailto:support@yourcompany.com).This is a new sentence without a paragraph break.


text:
Q: Parse a JSON file with Javascript I am using the Coingecko API. But I just couldn't parse the data. Sample data is below. Parse each block I want to do.
https://api.coingecko.com/api/v3/exchanges
Sample code I use:

$.getJSON( "https://api.coingecko.com/api/v3/exchanges", function( data ) {
 var objArray = JSON.parse(data);
 console.log(objArray["0"]['id']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

A: Basically you don't need to do anything

$.getJSON( "https://api.coingecko.com/api/v3/exchanges", function( data ) {
 console.log(data[0].id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: Use only while and assignment to truncate a list of numbers? I've been asked (or challenged) by a friend (just taking some Python course) about this interesting question: given a list of numbers, you can only use - 1) while-loop, and 2) assignment to truncation this list and print each step of truncating (starting with first number each time).  In other words, no slicing, no extra intermediate data structure (eg. copy) allowed.  (He claimed no one in the class is able to answer it....)
An example will be easier to understand the strange requirements:

L = [1, 2, 3, 4, 5]
while ???:
    <assignment statement>
    <print ??? >

# expected:
2 3 4 5
3 4 5
4 5
5
[]

A: I kind of disappoint him - or surprise him by the end of a few minutes pause.
This is what I share with him, the syntax is called extend assignment.   Wonder if there is better/more elegant solution to this.  But this is what I can come up within 3-min...

>>> L = [1, 2, 3, 4, 5]
>>> while L:
    f,  *L = L
    #_, *L = L     # another way, since don't care the dropping num
    print(L)

# Output
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]

A: I was trying out and got this solution, before I read yours. I think yours is more elegant, haha!
L = [1, 2, 3, 4, 5]
while len(L) >0:
    L.pop(0)
    print(L)

[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]


text:
Q: Is there a way to shuffle two or more lists in the same order? I want something like this pseudocode:
a = [1, 2, 3, 4];
b = [3, 4, 5, 6];
iter = a.iter_mut().zip(b.iter_mut());
shuffle(iter);
// example shuffle:
// a = [2, 4, 3, 1];
// b = [4, 6, 5, 3];

More specifically, is there some function which performs like:
fn shuffle<T>(iterator: IterMut<T>) { /* ... */ }

My specific case is trying to shuffle an Array2 by rows and a vector (array2:Lndarray:Array2<f32>, vec:Vec<usize>).
Specifically array2.iter_axis(Axis(1)).zip(vec.iter()).

A: Shuffling a generic iterator in-place is not possible.
However, it's pretty easy to implement shuffling for a slice:
use rand::Rng;

pub fn shufflex<T: Copy>(slice: &mut [T]) {
    let mut rng = rand::thread_rng();

    let len = slice.len();
    for i in 0..len {
        let next = rng.gen_range(i, len);
        let tmp = slice[i];
        slice[i] = slice[next];
        slice[next] = tmp;
    }
}

But it's also possible to write a more general shuffle function that works on many types:
use std::ops::{Index, IndexMut};
use rand::Rng;

pub fn shuffle<T>(indexable: &mut T)
where
    T: IndexMut<usize> + Len + ?Sized,
    T::Output: Copy,
{
    let mut rng = rand::thread_rng();

    let len = indexable.len();
    for i in 0..len {
        let next = rng.gen_range(i, len);
        let tmp = indexable[i];
        indexable[i] = indexable[next];
        indexable[next] = tmp;
    }
}

I wrote a complete example that also allows shuffling across multiple slices in the playground.
EDIT: I think I misunderstood what you want to do. To shuffle several slices in the same way, I would do this:
use rand::Rng;

pub fn shuffle<T: Copy>(slices: &mut [&mut [T]]) {
    if slices.len() > 0 {
        let mut rng = rand::thread_rng();

        let len = slices[0].len();
        assert!(slices.iter().all(|s| s.len() == len));

        for i in 0..len {
            let next = rng.gen_range(i, len);

            for slice in slices.iter_mut() {
                let tmp: T = slice[i];
                slice[i] = slice[next];
                slice[next] = tmp;
            }
        }
    }
}

A: To shuffle in the same order, you can first remember the order and then reuse it for every shuffle. Starting with the Fisher-Yates shuffle from the rand crate:
fn shuffle<R>(&mut self, rng: &mut R)
where R: Rng + ?Sized {
    for i in (1..self.len()).rev() {
        self.swap(i, gen_index(rng, i + 1));
    }
}

It turns out that we need to store random numbers between 0 and i + 1 for each i between 1 and the length of the slice, in reverse order:
// create a vector of indices for shuffling slices of given length
let indices: Vec<usize> = {
    let mut rng = rand::thread_rng();
    (1..slice_len).rev()
    .map(|i| rng.gen_range(0, i + 1))
    .collect()
};

Then we can implement a variant of shuffle where, instead of generating new random numbers, we pick them up from the above list of random indices:
// shuffle SLICE taking indices from the provided vector
for (i, &rnd_ind) in (1..slice.len()).rev().zip(&indices) {
    slice.swap(i, rnd_ind);
}

Putting the two together, you can shuffle multiple slices in the same order using a method like this (playground):
pub fn shuffle<T>(slices: &mut [&mut [T]]) {
    if slices.len() == 0 {
        return;
    }
    let indices: Vec<usize> = {
        let mut rng = rand::thread_rng();
        (1..slices[0].len())
            .rev()
            .map(|i| rng.gen_range(0, i + 1))
            .collect()
    };
    for slice in slices {
        assert_eq!(slice.len(), indices.len() + 1);
        for (i, &rnd_ind) in (1..slice.len()).rev().zip(&indices) {
            slice.swap(i, rnd_ind);
        }
    }
}


text:
Q: Calculating distance of point along line using QGIS I have a polyline (movement path) and points recorded along the line. I would like to calculate for each point the distance along the line in QGIS. I hope for a result which will add a new column to the point attribute table indicating the distance along which it is on the line.

A: Other way to measure this, it is using Qchainage (QGis plugin) to produce  nodes equallly spaced from line. Then, you may use Distance to nearest hub (QGis plugin) to calculate distance among points.

A: If you'd like to go with the GRASS plugin, there's a module v.distance that does just that.
First you'll bring the polyline and point layers into GRASS using the v.in.ogr module in the GRASS Toolbox. Then locate the v.distance module. The From and To vectors are obviously the points and line. Then select "Distance to nearest point ... along linear feature". You'll also need an attribute column name to accept the distance values (Use v.db.addcol to add that attrib if you don't already have). That should do it.

A: You can use fieldcalculator with an expression such as:
line_locate_point(overlay_nearest('line',$geometry)[0],$geometry)

Replace 'line' with the name of your line layer. overlay_nearest() will get the geometry of the nearest line to your point. line_locate_point() the distance in crs units along that line to the specified point. Of course you can also use this expression on the line layer, therefore just modifiy it a little.

A: The KP Find plugin does this with a layer of points and another layer, containing a line feature. It projects a point on the line and gives the geodetic distance along the line and the distance to that line. It has an interactive mode or can iterate over an entire point layer, adding new attribute fields.

A: You can use a virtual layer and join each point to a line (I use within 5 m distance below) and measure the distance along the line. ST_Line_Locate_Point:

return a number (between 0.0 and 1.0) representing the location of the
closest point on LineString to the given Point, as a fraction of total
2d line length

so I multiply with the line length.
Replace "waypoint" with the name of your point layer and "path" with the name of your line layer. And add more fields from the point layer if you want to. Like select pnt.id, pnt.someotherfield, ...
select  pnt.id, pnt.geometry,
        round(ST_Line_Locate_Point(line.geometry, pnt.geometry)*st_length(line.geometry),1) as distalongline
from "waypoint" pnt
left join "path" line
on PtDistWithin(pnt.geometry, line.geometry, 5)
order by ST_Line_Locate_Point(line.geometry, pnt.geometry)


text:
Q: How to log JSON from a GCE Container VM to Stackdriver? I'm currently using GCE Container VMs (not GKE) to run Docker Containers which write their JSON formated log to the Console. The Log Information is automatically collected and stored in Stackdriver.
Problem: Stackdriver displays the data-field of the jsonPayload as text - not as JSON. It looks like the quotes of the fields within the payload are escaped and therefore not recognized as JSON structure.
I used both, logback-classic (like explained here) and slf4j/log4j (using JSONPattern) to generate JSON output (which looks fine), but the output is not parsed correctly.
I assume that, I have to configure somewhere that the output is JSON structured, not plain text. So far I haven't found an option where to do this when using a Container VM.

A: What does your logger output into stdout?
You shouldn't create a jsonPayload field yourself in your log output. That field gets automatically created when your logs get parsed and meet certain criteria.
Basically, write your log message into a message field of your JSON output and any additional data as additional fields. Stackdriver strips all special fields from your JSON payload and if there is nothing left then your message will end up as textPayload otherwise you'll get a jsonPayload with your message and other fields.
Full documentation is here:
https://cloud.google.com/logging/docs/structured-logging


text:
Q: Suite level capabilities with webdriver.io Let's say I have wdio tests organised into suites for ios, android etc. Is there a way for me to specify what capabilities apply to those suites so that when I run the tests in those suites, they are only run against specific browsers etc?
I'm trying to see if there's a way to only have a single config file with the important stuff, instead of a separate conf file for each plaatform I want to test against.
Thanks,
JB


text:
Q: Redshift Copy errors out when trying to load NUL I am loading data to Redshift using Copy.  The text file has NUL.
I have looked at several options and tried using options such as:
null as '\0'  EMPTYASNULL  ACCEPTINVCHARS TRIMBLANKS TRUNCATECOLUMNS escape

However, it still errors out.
Below sample records and the error message.
NUL is after Main St|
2278|2047|5|1|1|1|18 N Main St| |Bowman|1|39|16443|15811|58623|Y|544|2018-05-21 17:29:12.000||||
2491|2047|6|1|1|1|18 N Main| |Bowman|1|39|16443|15811|58623-9613|Y|920|2018-11-26 18:28:26.000||||
2491|2047|7|1|1|1|18 N Main| |Bowman|1|39|16443|15811|58623-9613|Y|920|2018-11-26 18:28:26.000||||
2408|2154|7|1|1|1|101 Main St| |Lakota|1|39|16469|15956|58344|Y|447|2018-08-17 08:10:54.000||||

copy table1 from 's3://....txt' iam_role xx delimiter '|' null as '\0'  EMPTYASNULL  ACCEPTINVCHARS TRIMBLANKS TRUNCATECOLUMNS escape;

Missing newline: Unexpected character 0x7d found at location nn


text:
Q: Assign number input to number variable? Typescript is telling me that type string is not assignable to type number.
How can I make Typescript happy?
Two voluntary related questions:
What is a good way to learn what TypeScript types I should use for various callback arguments? I had to google to find that React.FormEvent<HTMLInputElement>  is the type I am expected to use for html events
Why does typescript assume string for event.currentTarget.value?
interface SoftwareLicenseCodesState {
    duration: number,
}

<input
    type="number"
    value={this.state.duration}
    onChange={this.onDurationChange}
/>

onDurationChange(event: React.FormEvent<HTMLInputElement> ): void {
    this.setState({duration: event.currentTarget.value});
}


text:
Q: Create a new column as a count of the Pandas DataFrame I have a Pandas DataFrame. How do I create a new column that is like a count of the Pandas DataFrame because I already made my index a Datatime.
For example, the following code is reproducible on your local PC:
import datetime
import numpy

dates = [
    datetime.date(2019, 1, 13),
    datetime.date(2020, 5, 11),
    datetime.date(2018, 7, 24),
    datetime.date(2019, 3, 23),
    datetime.date(2020, 2, 16)
]

data = {
    "a": [13.3,12.3,np.nan,10.3,np.nan],
    "b": [1,0,0,1,1],
    "c": ["no","yes","no","","yes"]
}

pd.DataFrame(index=dates,data=data)

Right now, I would like to add a new column as a count. Something like 1,2,3,4,5 until the end of the data

A: df['count'] = range(1, len(df) + 1)

len(df) returns the number of rows in the DataFrame, so you can call the builtin range function to create a range from 1 to the number of rows in the DataFrame, and then assign it to a new column. When assigning a range to a column, it is automatically converted to a pandas Series.

A: You can build a Series using df.index and apply some processing to it before assigning it to a column of the dataframe.
Here, we could use:
df['count'] = pd.Series(1, index=df.index()).cumsum()

Here it would be far less efficient (more than 1 magnitude order) than df['count'] = np.arange(1, 1 + len(df)) that directly builds a numpy array with the expected values, but it can be useful in more complex uses cases.


text:
Q: How to insert an "Optimizer hint" to Hibernate criteria api query i have a hibernate query that is dynamically put together using the criteria api.
it generates queries that are unbearably slow, if executed as-is.
but i have noted they are about 1000% faster if I prepend /*+ FIRST_ROWS(10) */ to the query. how can i do this with the criteria api?
i tried criteria.setComment(..), but this seems to be ignored.
in the hibernate docs, 3.4.1.7. Query hints are mentioned, but it clearly states: "Note that these are not SQL query hints"
the result of the query will be paginated, so in 99% of the cases i will display the results 1-10.

A: I have another generic solution, that should work for every Criteria query :
use a standard comment and an Hibernate Interceptor changing the ultimate SQL to the database.
(I used it with Hibernate 3.3, but should be useable for every version, registering of the Interceptor may be different.)
In your query code use:
criteria.setComment("$HINT$ push_pred(viewAlias)");

Write an Interceptor to change to SQL text (this one uses commons.lang3.StringUtils):
public class HibernateEntityInterceptor extends EmptyInterceptor {

@Override
public String onPrepareStatement(String sql) {
    if (sql.startsWith("/* $HINT$")) {
        String hintText = StringUtils.substringBetween(sql, "/* $HINT$", "*/");
        sql = sql.replaceFirst("select ", "select /*+" + hintText + "*/ ");
    }
    return sql;
}

Above is for Oracle, but should be easily adjustable for every DBMS.
Maybe you can/should create a constant for the hint marker "$HINT$".
Logging should be done, too (so you can easily see the correct calling of the Interceptor), I left it out above for simplicity.
The Interceptor must be registered. In Spring this is done in applicationContext.xml:
<bean id="entityListener" class="your.package.HibernateEntityInterceptor"/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="entityInterceptor" ref="entityListener"/>
    [...]

Or (copy from the Hibernate 3.3 docs):

A Session-scoped interceptor is specified when a session is opened
  using one of the overloaded SessionFactory.openSession() methods
  accepting an Interceptor.
Session session = sf.openSession( new HibernateEntityInterceptor() );
A SessionFactory-scoped interceptor is registered with the
  Configuration object prior to building the SessionFactory. Unless a
  session is opened explicitly specifying the interceptor to use, the
  supplied interceptor will be applied to all sessions opened from that
  SessionFactory. SessionFactory-scoped interceptors must be thread
  safe. Ensure that you do not store session-specific states, since
  multiple sessions will use this interceptor potentially concurrently.
new Configuration().setInterceptor( new HibernateEntityInterceptor() );

A: I was able to put in a Oracle hint by a adding a ProjectionList to the criteria.
ProjectionList proList = Projections.projectionList();
proList.add(Projections.sqlProjection("/*+INDEX_DESC(this_ MY_INDEX_NAME)*/ 1 as MYHINT",
    new String[]{},
    new Type[]{}));
//add properties from your class
proList.add(Projections.property("field1"));
proList.add(Projections.property("field2"));
proList.add(Projections.property("field3"));
c.setProjection(proList);

c.list() returns List<Object[]> in order of ProjectionList

A: You could modify the optimizer mode at the session level:
ALTER SESSION SET optimizer_mode = FIRST_ROWS;

Either just before your query and then putting it back to its default value (ALL_ROWS) or in your case since 99% of the queries would benefit from it you could modify it at the schema level (with an ON LOGON trigger for exemple) or even at the instance level (modify the init parameter).

A: The problem is that the hint syntax is not a comment, it just looks a bit like one.  It really has to go between the SELECT and the selected columns, whereas setComment() prepends the comment before the SELECT.
Beyond that, there are no silver bullets.  FIRST_ROWS is not a performance enhancing tool.  It may end up taking longer to get all the rows back.  Of course, in a user-facing program retrieving the first ten rows may be all we need to do.
But, which ever way you bounce it, if you want to use Oracle's hint syntax you'll need to go down the Native SQL route.
What else can you do?  I don't (yet) have much experience tuning Hibernate.  The one time I have under such a task the query was grabbing rows from a whole bunch of tables to instantiate an object with lots of sub-types.  Each sub-type was a separate table.  The query generated by Hibernate had many OUTER JOINs, which confused the heck out the optimizer.  Breaking that monster into several focused queries (one per sub-type) which used only INNER JOINs produced a two hundredfold reduction in retrieval time.
This may not be of any immediate use to you.  But the principle is, look at the Hibernate query and see whether it can be implemented in a different, more efficient way.


text:
Q: File Read, printing on a single line Why does it print the file it reads on a single line? The txt file is not.
The file is like this:

Student N. 3
ID: 999
Surname: Spider
Name: Man
************
Subject N. 1 : d. Chart Reading
Homework 1: 89
Homework 2: 65
Homework 3: 32
Exam 1: 45
Exam 2: 56
Exam 3: 78
public static void main(String[] args) throws Exception {

    Scanner data = new Scanner(new FileReader("StudData1.txt"));

    while(data.hasNextLine())
    {
        System.out.print(data.nextLine());
    }

A: Change System.out.print() to System.out.println() if you want to print in different line.
You should know the difference between these two. Follow this link.


text:
Q: How to provide x-axis and y-axis values in WebGL? am trying to use WebGL to plot a 3D surface. My problem is that it is not letting me provide the x and the y values. It plots the z axis values against the values of x ranging from 0 to n and the values of y ranging from 0 to m (all integral values).
How can I make a surface where I can also provide the x and the y values for the 3D surface construction. Also if its not possible to do it in WebGL then what solution can I use?
PS Also, WebGL tooltip function doesnt function. any comments on that?

A: I'm guessing that you are saying that you can't specify the scale of x and y relative to the plotted (z) value?
What you need is to apply a non-uniform scale to the entire surface (the modelview matrix), so that the X and Y axes are stretched into the shape you want. Are you using three.js or a similar library, or... ? The answer will define the specific commands you should use.
As an example, let's say that you have a 100x50 plot, with the spacing forced by the library to 1.0 between x and y. Instead, you want the size to be 300x200 in x and y. You would scale the matrix by (3,4,1).
If you want to change the displayed range of your Z data, I would suggest adjusting its zero point (i.e., translating it up or down to be centered) and then scaling appropriately as-needed.


text:
Q: Use jQuery Sparkline for composite chart with ui-jq in Angularjs I use jQuery Sparkline for some chart like this:

but I don't know how to render Composite Sparkline chart because in documentation of Sparkline use this script:
 $('#compositeline').sparkline('html', { fillColor: false });
 $('#compositeline').sparkline([4,1,5,7,9,9,8,7,6,6,4,7,8,4,3,2,2,5,6,7], { composite: true, fillColor: false, lineColor: 'red' });

how to implement above model of script with ui-jq?

A: Try this

Use the right selector
$("#mySparkline"). ...


text:
Q: Facebook query language. Get all user live in california I am working in facebook Application MVC 4 c# SDK 6
is there any way to get the list of all Facebook User. Either friend or not, who lives in California using Facebook Query Language

A: List of your friends who live in California and have it list in their current location.
SELECT name, current_location
FROM User
WHERE uid IN (SELECT uid2 FROM Friend WHERE uid1 = me())
      AND current_location.state = "California"

Test out the query here.
I don't think it's possible to pull this information on all Facebook users since the location column is not indexed. This answer does a good job explaining why searching by location along is not possible.
Helpful links:

*

*how to write an fql query to list friends in a particular location

*From FQL we want to get users current location in php

A: The one word answer is No. But you can get access to users that have made their location public.
see similar question Facebook API: can I get detailed info about user's location?


text:
Q: How to use itemBuilder to select the last tapped ListTile widget? I am trying to change the selected property of the last tapped ListTile widget to true inside a Drawer (and then obviously the selected property of other ListTiles to false), but I do not understand how can I use itemBuilder (which is mentioned in the official flutter docs) for this.
I tried putting my ListTiles into an AnimatedListItemBuilder widget, but that was not working for me.
Widget _buildDrawer() {
    return ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child:
                Wrap(
                  alignment: WrapAlignment.center,
                  direction: Axis.vertical,
                  children: <Widget>[
                    Text(
                      _currentUser.displayName,
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white
                      ),
                    ),
                    Wrap(
                      direction: Axis.vertical,
                      children: <Widget>[
                        Text(
                        "Iskolai kategória: A",
                          style: TextStyle(
                            fontSize: 18,
                            color: Colors.white70
                          ),
                        ),
                        Text(
                          "Kollégiumi kategória: A",
                          style: TextStyle(
                            fontSize: 18,
                            color: Colors.white70
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              selected: true,
              leading: Icon(Icons.date_range_rounded),
              title: Text('Stúdium jelentkezés'),
              onTap: () {
              // Update the state of the app.
              // ...
              // Then close the drawer.
              Navigator.pop(context);
            },
            ),
            ListTile(
              leading: Icon(Icons.article_rounded),
              title: Text('Koleszhírek'),
              onTap: () {
                // Update the state of the app.
                // ...
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.account_box_rounded),
              title: Text('Profil'),
              onTap: () {
                // Update the state of the app.
                // ...
               Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.logout),
              title: Text('Kijelentkezés'),
              onTap: () => {
                _googleSignIn.disconnect(),
                Navigator.pop(context)
              },
            ),
          ],
        );
  }

A: You have to save the 'selected index' in a variable and check if the current index equals selected index to highlight the ListView. I've updated your code to make it work.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      drawer: _buildDrawer(context),
      body: Center(
        child: Text("DrawerHeader Demo"),
      ),
    );
  }

  Widget _buildDrawer(BuildContext context) {
    List<Widget> leading = [
      Icon(Icons.date_range_rounded),
      Icon(Icons.article_rounded),
      Icon(Icons.account_box_rounded),
      Icon(Icons.logout),
    ];
    List<Widget> title = [
      Text('Stúdium jelentkezés'),
      Text('Koleszhírek'),
      Text('Profil'),
      Text('Kijelentkezés'),
    ];

    return Container(
      color: Colors.white,
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            child: Wrap(
              alignment: WrapAlignment.center,
              direction: Axis.vertical,
              children: <Widget>[
                Text(
                  "A",
                  style: TextStyle(fontSize: 20, color: Colors.white),
                ),
                Wrap(
                  direction: Axis.vertical,
                  children: <Widget>[
                    Text(
                      "Iskolai kategória: A",
                      style: TextStyle(fontSize: 18, color: Colors.white70),
                    ),
                    Text(
                      "Kollégiumi kategória: A",
                      style: TextStyle(fontSize: 18, color: Colors.white70),
                    ),
                  ],
                )
              ],
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
          ),
          ListView.builder(
            itemCount: 4,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: title[index],
                leading: leading[index],
                selected: index == _selectedIndex,
                onTap: () {
                  setState(() {
                    _selectedIndex = index;
                    Navigator.pop(context);
                  });
                },
              );
            },
          ),
        ],
      ),
    );
  }
}


text:
Q: I need to access a position in an ArrayList I need to have these methods in my code this is a code for class I'm just so lost I can't remember how to do this.
But let's continue to enrich our Notebook class with the following methods

*

*addNote() will add an individual note to the ArrayList

*deleteNote() will delete a note using its position in the ArrayList

*getNoteNumber() will get the position of a note based on its value, e.g., in what position is note "Buy milk"?

*getNote() will get the note text for a given position

*setNote() will set (update) the note text for a given position

public void addNote(String note)
{
    notes.add(note);
}
public void deleteNote(int index)
{
    notes.remove(index);
}
public void getNoteNumber(String note)
{
    for(int i=1; i<(notes.size()); i++)
    {
        System.out.println(notes.get(i));
    }
}
public void getNote(String note)
{

}

I'm looking for any kind of advice i can find. Thank you.

A: You could do it like this:
public void addNote(String note)
{
    notes.add(note);
}
public void deleteNote(int index)
{
    if(index < notes.size())
         notes.remove(index);
}
public int getNoteNumber(String note)
{
    for(int i=0; i<(notes.size()); i++)
    {
        if(notes.get(i).equals(note))
            return i;
    }
    return -1;  //Note does not exist

}
public String getNote(int index)
{
     if(index < notes.size())
     return notes.get(i);
}

public void setNote(int position, String text)
{
    if(position < notes.size())
         notes.set(position,text);

}


text:
Q: Can you use "later on" to replace "next" and "then"? Example:

At first, I though it was a star, but then I realized it was an
  UFO.

Can I use "later" to replace "then" and keep the meaning more or less the same?

At first, I though it was a star, but later on I realized it was an
  UFO.

A: Then is immediate, later on means a point in the future.
using your example,

At first, I though it was a star, but then I realized it was an UFO.

implies that the thought of what the object is changed while you were looking at the object, but

At first, I though it was a star, but later on I realized it was an UFO.

implies that the initial thought was that the object was a star, but later in time, you changed your mind, having thought through what was seen.


text:
Q: How to simplify $\newcommand{\bigk}{\mathop{\vcenter{\hbox{K}}}}\prod_{p\in\mathbb{P}}\left(1+\bigk_{k=1}^{\infty }\frac{f_k(s)}{g_k(s)}\right)^{-1}$ I'd like to simplify
$$\newcommand{\bigk}{\mathop{\huge\vcenter{\hbox{K}}}}B(s)=\prod_{p\in\mathbb{P}}\left(1+\bigk_{k=1}^{\infty }\frac{f_{k}(s)}{f_{k}(s)}\right)^{-1}$$ to something of the form $$B(s)=\bigk_{k=1}^{\infty }\frac{F_{k}(s)}{G_{k}(s)}$$
This is related to the question "Arithmetic of continued fractions, does it exist?".

Motivation:
Consider the following representation of a function
$$
f(z)= 1+ \sum_{n=1}^{\infty}\left( \prod_{k=1}^{n}f_{k}(z) \right)
$$
Using Euler's continued fraction formula, this function can have the following representation
$$
  f(z)= \cfrac{1}{
          1- \cfrac{f_{1}(z)}{
          1+f_{1}(z)- \cfrac{f_{2}(z)}{
          1+f_{2}(z)- \cfrac{f_{3}(z)}{
          1+f_{3}(z) - \ddots}}}}
$$
Now consider the Jacobi theta function
$$
\frac{1}{2}(\vartheta_{4}(0,x)+1)=1-x+x^{4}-x^{9}+x^{16}\cdots
$$
and the fact that
$$
n^{2}=\sum_{k=1}^{n}(2k-1)
$$
We can represent the theta function as
$$
\frac{1}{2}(\vartheta_{4}(0,x)+1)=1-x+x^{1+3}-x^{1+3+5}+x^{1+3+5+7}\cdots
$$
or
$$
\frac{1}{2}(\vartheta_{4}(0,x)+1)= 1+ \sum_{n=1}^{\infty}(-1)^{n}\left( \prod_{k=1}^{n}x^{2k-1} \right)
$$
so $\frac{1}{2}(\vartheta_{4}(0,x)+1)$ has the following continued fraction representation
$$
  \frac{1}{2}(\vartheta_{4}(0,x)+1)= \cfrac{1}{
          1+ \cfrac{x}{
          1-x+ \cfrac{x^{3}}{
          1-x^{3}+ \cfrac{x^{5}}{
          1-x^{5} + \ddots}}}}
$$
Now remember that the Riemann's zeta function can be represented by
$$\zeta(s)=\frac{A(s)}{B(s)}$$
with
$$
B(s)=\prod_{p\in\mathbb{P}}\frac{1}{2}\left(\vartheta_{4}(0,\frac{1}{p^{z}})+1\right)
$$
and $A(s)$ convergent for $\Re{(s)}>\frac{1}{4}$
We have then that $B(s)$ is an infinite product of continued fractions
$$
  B(s)=\prod_{p\in\mathbb{P}}\left(1+\bigk_{k=1}^{\infty}\frac{p^{-(2k-1)s}}{1-p^{-(2k-1)s}}\right)^{-1}\ \
$$
where $p\in\mathbb{P}$ are prime numbers.
Finally my question, could someone find a representation for $B(s)$ as a single continued fraction?
Thanks.


text:
Q: Список регулярный выражений python Проверяю никнейм на наличие запрещёных слов обычной проверкой оператором in(запрещённое слово in никнейм)
Нашёл на хабре статью где приведём список регулярных выражений чтобы не заменяли буквы на англиские. Не могу догадатся чтобы in учитовал это тоже. Помогите разобраться пожалуйста. Прошу пример типа такого: есть к примеру лох с англиской o вместо русской, и чтоб при if bad_word in nickname это учитовалось.
Тот самый список выражений:
(
  'а' => ['а', 'a', '@'],
  'б' => ['б', '6', 'b'],
  'в' => ['в', 'b', 'v'],
  'г' => ['г', 'r', 'g'],
  'д' => ['д', 'd', 'g'],
  'е' => ['е', 'e'],
  'ё' => ['ё', 'е', 'e'],
  'ж' => ['ж', 'zh', '*'],
  'з' => ['з', '3', 'z'],
  'и' => ['и', 'u', 'i'],
  'й' => ['й', 'u', 'y', 'i'],
  'к' => ['к', 'k', 'i{', '|{'],
  'л' => ['л', 'l', 'ji'],
  'м' => ['м', 'm'],
  'н' => ['н', 'h', 'n'],
  'о' => ['о', 'o', '0'],
  'п' => ['п', 'n', 'p'],
  'р' => ['р', 'r', 'p'],
  'с' => ['с', 'c', 's'],
  'т' => ['т', 'm', 't'],
  'у' => ['у', 'y', 'u'],
  'ф' => ['ф', 'f'],
  'х' => ['х', 'x', 'h', 'к', 'k', '}{'],
  'ц' => ['ц', 'c', 'u,'],
  'ч' => ['ч', 'ch'],
  'ш' => ['ш', 'sh'],
  'щ' => ['щ', 'sch'],
  'ь' => ['ь', 'b'],
  'ы' => ['ы', 'bi'],
  'ъ' => ['ъ'],
  'э' => ['э', 'е', 'e'],
  'ю' => ['ю', 'io'],
  'я' => ['я', 'ya'],
)

A: Я бы порекомендовал не заморачиваться с подобным сопоставлением, а использовать старый добрый алгоритм soundex. Однако, поскольку его реализация в jellyfish с кириллицей работает некорректно, попытайтесь решить свою проблему с помощью модуля fonetika:
from fonetika.soundex import RussianSoundex

lst = ["корован", "караван", "К0р0ван", "километр", "кoрован"]# в последнем слове
                                                              # первая 'o' - латиница.

soundex = RussianSoundex(delete_first_letter=True)
for i in lst:
    print(soundex.transform(i))

получаем кодированные строки:
3090208
3090208
3090208
30708049
3O90208

Как видите, все коды слов "караван" в разном написании одинаковые

A: В этом случае можно просто проверять по "белому" списку а-я0-9.
import re

def check_name(name):
    return re.match('[а-яА-Я0-9]*', name)

print(check_name('Kонстантин'))
print(check_name('Константин'))

Если вы хотите преобразовать имя типа Vasilii в Василий, то возникнут проблемы отличия типа "и" от "й" или "il" это "Л" или "ил".

A: В модуле fonetika исправлена работа с латиницей. Теперь все латинские буквы, которые есть в русском алфавите, заменяются кириллицей.


text:
Q: Convert dummies into actual count in R I'm new here, a beginner in R, and struggling with the following. I have a large clickstream database with pagepaths from multiple sessions. I classified the pages into categories and counted the number of pages visited in that category.
  SessionID category     count
1    101     homepage      1
2    101     productpage   6
3    101     searchpage    4
4    102     homepage      3
6    102     searchpage    5

I know that by using the code below, I can create dummies.
df %>%
  group_by(SessionID) %>%
  mutate(homepage = +(any(grepl('homepage', category))),
         productpage = +(any(grepl('productpage', category))),
         searchpage = +(any(grepl('search', category))))

   SessionID category     count    homepage    productpage    searchpage
1    101     homepage      1          1            1              1
2    101     productpage   6          1            1              1
3    101     searchpage    4          1            1              1
4    102     homepage      3          1            0              1
6    102     searchpage    5          1            0              1

But instead of the 1/0, I want the actual number of pages visited in that category, so that I can filter out the duplicate rows, and delete the category column, leaving:
     SessionID     homepage    productpage    searchpage
1      101             1            6              4
2      102             3            0              5

There is probably an easier way to do this but for me, the important thing is that I am left with the output above. I would be nice if someone could help me out with this.

A: You can use pivot_wider from tidyr:
library(tidyr)
library(dplyr)

df %>% pivot_wider(names_from=category,values_from=count,values_fill=list(count=0))

# A tibble: 2 x 4
  SessionID homepage productpage searchpage
      <int>    <int>       <int>      <int>
1       101        1           6          4
2       102        3           0          5

The data:
df = structure(list(SessionID = c(101L, 101L, 101L, 102L, 102L), category = structure(c(1L,
2L, 3L, 1L, 3L), .Label = c("homepage", "productpage", "searchpage"
), class = "factor"), count = c(1L, 6L, 4L, 3L, 5L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "6"))

A: I would suggest using dplyr or even whole tidyverse to work with your data.
The solution would be:
library(tidyverse)

data %>%
  pivot_wider(names_from = category, values_from = count) %>%
  mutate_all(replace_na, 0)

where data is:
data <- tibble(SessionID = c(101, 101, 101, 102, 102),
              category = c("homepage", "productpage", "searchpage", "homepage", "searchpage"),
              count = c(1, 6, 4, 3, 5)
)

A: We could use xtabs from base R
xtabs(count ~ SessionID + category, df)
#        category
#SessionID homepage productpage searchpage
#   101        1           6          4
#   102        3           0          5

data
df <- structure(list(SessionID = c(101L, 101L, 101L, 102L, 102L), category = structure(c(1L,
2L, 3L, 1L, 3L), .Label = c("homepage", "productpage", "searchpage"
), class = "factor"), count = c(1L, 6L, 4L, 3L, 5L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "6"))


text:
Q: Calendar loses functionalities and design features I have a calendar that functions perfectly with a site administror.

Unfortunately, with another user, the layout is different (arrows are missing for example) and cannot add new events.
I've even given this user full control on the site but with no luck.
What could it be?

A: The problem here was that I logged in the browser with CTRL-SHIFT and run with another user. So, to change user I now use /_layouts/closeConnection.aspx?loginasanotheruser=true
the page is rendered perfectly, amd the problem is solved


text:
Q: Storing multiple variables in a single $_SESSION(PHP) How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);

if ($count == 1)
{
   $row = mysqli_fetch_array($result);
   while ($_SESSION['username'] = $row['username'])
   {
      session_start();
      header('Location: index.php');
   }
}
else
{
   echo 'Invalid Logins';
}

mysqli_close($conn);
?>

A: Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
    session_start();

    $row = mysqli_fetch_array($result);
    $_SESSION['username'] = $row['username'];
    $_SESSION['avatar'] = $row['avatar'];

    header('Location: index.php');
}
else
{
    echo 'Invalid Logins';
}


text:
Q: Sort a list of `List[Any]` by the first element using Scala I want to sort my list by the first column in scala.
I have a list of list like this:
val a0 = List(0, "a0", 23)
val a1 = List(1, "a1", 231)
val a2 = List(2, "a2", 1)
val a3 = List(3, "a3", 80)
val a4 = List(4, "a4", 33)
val a5 = List(5, "a5", 23)
val a6 = List(6, "a6", 2)
val list1 = List(a0, a6, a2, a3, a1, a5, a4)

I want to sort it by the first column, so the expected output is:
List(
  List(0, a0, 23),
  List(1, a1, 231),
  List(2, a2, 1),
  List(3, a3, 80),
  List(4, a4, 33),
  List(5, a5, 23),
  List(6, a6, 2)
)

I tried
list1.sortBy(list => list(0))

but it produces

error: No implicit Ordering defined for Any

How can I do it?

A: Here is your input again:
val a0 = List(0, "a0", 23)
val a1 = List(1, "a1", 231)
val a2 = List(2, "a2", 1)
val a3 = List(3, "a3", 80)
val a4 = List(4, "a4", 33)
val a5 = List(5, "a5", 23)
val a6 = List(6, "a6", 2)
val list1 = List(a0, a6, a2, a3, a1, a5, a4)

Here is how you sort it:
val list2 = list1.sortBy(_(0).asInstanceOf[Int])

The (0) gets the first entry, the asInstanceOf[Int] casts it to integer. The _ is the placeholder for the list, it's an abbreviation for (list: List[Any]) => list(0).asInstanceOf[Int].
If you print the result
list2 foreach println

you get
List(0, a0, 23)
List(1, a1, 231)
List(2, a2, 1)
List(3, a3, 80)
List(4, a4, 33)
List(5, a5, 23)
List(6, a6, 2)


text:
Q: Compare pixel values to replace values

I have two segmentation mask. One has only an overall face shape, has no eyes, nose, and mouth,(above - I will call this A from now on.) and one has eyes, nose, and mouth.(below - B)
So, I'm trying to give the B's information about the eyes, nose, and mouth to A.  However, I want to keep the hair information when the A hair is located at the location of the former eyes, nose, and mouth.
I am trying to transfer the information of o_mask to g_mask. At this time, transfer means to change the pixel value of 1 (skin) in A into values corresponding to eyes, nose, and mouth. 2 is the nose and 13 is the hair.
So I wrote the code like this:
np.where(B[A == 2] != 13, 2, B[A ==2])

But it didn't work the way I was hoping. Nothing has changed, and there is still no eye, nose, or mouth. Does anyone know the efficient code to handle this?

A: Pure numpy solution would however be as follows-
contains = [2,3,4,5,6,7,10,11,12,16]
np.where(np.bitwise_and(np.isin(o_mask, contains), g_mask != 13), o_mask, g_mask)

I cannot say for sure but there can be a significant time improvement I believe with this approach/


text:
Q: Future of Linq to Sql and Entity Framework I work on a project and want to use an ORM. What should I use: Linq to Sql or Entity Framework? Linq to Sql provides more opportunities, as I see, for example support for enumeration types. However, also it is said that, Linq to Sql was for playing and learning for Linq and future strategy of Microsoft lies on Entity Framework. So which one should I use?

A: As I understand it, support for LINQ to SQL isn't going anywhere, but most of the resources for ongoing development will be devoted to LINQ to Entities.  I think you're safe going whichever direction looks like the better choice.  If it's LINQ to SQL, go for it as long as it has everything you need- don't count on new features.

A: If you are deciding between those 2, and can use VS2010, definitely go with Entity Framework 4 now that is properly supports lazy loading, POCO objects, and code only models.

A: There's a stackoverflow post here that talks about the differences between the two.
What's interesting is that Zack Peterson's answer where he posted a link to article which posses the question "Is Linq to SQL truly dead?" Good fyi article.
But if you're after an ORM, have you looked at NHibernate or SubSonic? There are definately a few good non-MS ORMs out there.

A: Entity Framework is feature rich and being aggressively enhanced and promoted by Microsoft.
Linq To Sql is feature poor and not being promoted by Microsoft.
Linq To Sql does have some features that Entity Framework (v4) does not.
The risks of using Linq To Sql on a project are much higher than the risks of using EF v4, but you can choose either option.
As far as EF v1/v3.5, try to avoid it (but it's likely to be much easier to upgrade from EF 3.5 to EF 4 than from L2S to EF 4).

A: You should try PLINQO (http://www.plinqo.com).  It's LINQ to SQL with a TON of improvements.  Maybe someday EF will not suck. :-)


text:
Q: file is not getting deleted after being created by createWriteStream const createPolicyPackage = (filePath, bufferStream) => new Promise(resolve => {
  let wstream = fs.createWriteStream(filePath);
  wstream.write(bufferStream);
  resolve(bufferStream);
});

let policypath = 'pdfappl/' + submissionId + '_' + date + '_policydoc.pdf';
const resultpromise = <some api call giving .pdf file>;
let policybuf = Buffer.from(resultpromise, 'base64');
await createPolicyPackage(policypath, policybuf);

i am using node v10.16.3
with the above code i am able to create a file with data i am receiving from api call in the folder pdfappl, but after that when trying to delete the file using unlink. it is not deleting it. maybe it is getting marked for delete. bcoz the files are only visible till the node process is running.
as soon as i kill the node process, the files dissappears.
fs.unlink(file, function (err) {
 if (err) console.log("\n\n\n\n\n\n\nerr ", err)
});

maybe the createWriteStream is not completing the write process.
so, i tried writing it like.
const createPolicyPackage = (filePath, bufferStream) => new Promise(resolve => {
  let wstream = fs.createWriteStream(filePath);
  wstream.write(bufferStream);
  wstream.on('close', ()=>{
    resolve(bufferStream);
  })
});

or
const createPolicyPackage = (filePath, bufferStream) => new Promise(resolve => {
  let wstream = fs.createWriteStream(filePath);
  wstream.write(bufferStream);
  wstream.on('finish', ()=>{
    resolve(bufferStream);
  })
});

but finish and close events didn't fire, and the code got stuck.
how to properly close the writeStream, so that i can delete the file when required


text:
Q: Deleting a ManytoMany Relationship Data in Django Project I have tried to fix this issue for a while.
I have a model where there are logs entered by users and saved in Log Model. Also there is ActiveSession Model which has a ManytoMany relationship with Log Model.
In My views I am getting the POST and saving them in the Log Model. The next step is my issue where I am trying to add unqiue Logs inside the ActiveSession Model. By unique I mean by searching a field called 'log_order' in the Log Model.
The desired outcome is to:
1: Get the POST form and save the Log details in the Log Model
2: Search if the new saved Log has been previously added the many to many relation log under Active Session Model
3: If there is no Log in the ActiveSession Model to add the new Log in the Post to the activesession
4: If there are logs previously saved in ActiveSession to search for the log_order related to these logs
5: If there is no same log_order to add the new Log in the Post to the activesession
6: If the log_order is existing inside the activesession logs to delete this specific log and to add the new Log in the Post to the activesession
Models.py:
class Log(models.Model):
    ...................................
    log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True)
    date = models.DateTimeField(...........)

class LogForm(forms.Form):
    .............................
    log_order = forms.IntegerField()

class ActiveSession(models.Model):
    log = models.ManyToManyField(Log)
    ..................................

Views.py:
def addlog(request, id):
    active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id)
        if request.method == 'POST':
            form = LogForm(request.POST)
            if form.is_valid():
                data = Log()
                data.log_order = request.POST.get('log_order')
                data.log_repetitions = form.cleaned_data['log_repetitions']
                data.log_weight = form.cleaned_data['log_weight']
                data.save()
                if active_session.log.values():
                    for i in active_session.log.values():
                        existing = i['log_order']
                        new = data.log_order
                        if int(existing) == int(new):
                            active_session.delete(active_session.log)
                            active_session.log.add(data)
                            active_session.save()
                        else:
                            active_session.log.add(data)
                else:
                    active_session.log.add(data)

I have tried to save the data and update() but nothing is changing the dictionary the same exisiting outcome is printed and the new data is not replacing the existing ones. My objective is replace and avoid duplicating.
Update: I am also thought of if the keys is i['log_order'] is equal to data.log_order to delete the whole dictionary and add the new data whichever is easier
Trial:
With the below trial I got 'ManyRelatedManager' object is not subscriptable. I am not sure if I am going the wrong direction.
                if active_session.log.values():
                    for i in range(len(active_session.log.values())):
                        new = data.log_order
                        if active_session.log[i]['log_order'] == new:
                            active_session.save()
                        else:
                            active_session.log.add(data)
                else:
                    active_session.log.add(data)

Here is the current query:
<QuerySet [{'log_order': 1}, {'log_order': 1}]>

here is the requested query:
<QuerySet [{'log_order': 1}]>

A: I have tried and tested your code and found some issues with it.
Below, there is the code snippet I tested and it works.
I am not completely sure what is the purpose for the code, but I think you might find the method update_or_create useful (also works on related managers such as your log). Here is a link to Django docs.
def addlog(request, id):
    if request.method == 'POST':
        # Moved this part to the POST section of the view. It is sufficient to simplify
        # the query in this way. Also, you probably want to check if there are sessions
        # in the DB. Otherwise, the code would break. This returns a 404 in case there
        # are absolutely no sessions.
        active_session = ActiveSession.objects.last()
        if active_session is None:
            return Http404()

        form = LogForm(request.POST)
        if form.is_valid():
            data = Log()
            # Use form.cleaned_data instead of log_order. Form validates the data, POST dict doesn't.
            data.log_order = form.cleaned_data['log_order']
            # Ignored because it's missing from the model code
            # data.log_repetitions = form.cleaned_data['log_repetitions']
            # data.log_weight = form.cleaned_data['log_weight']
            data.save()

            # Use Django ORM querysets instead of values()
            # See https://www.django-antipatterns.com/antipattern/over-use-of-values.html
            active_session_logs = active_session.log.filter(log_order=data.log_order)
            if active_session_logs.exists():
                # Suggestion: try to use update() instead of a combination of delete & add.
                # It reduces two SQL queries to one.
                active_session_logs.delete()
            active_session.log.add(data)
            # After using RelatedManager.add(), no need to call save(), the changes
            # are persisted in the DB simply by using add().

            # Always redirect after successfully processing the form.
            return redirect(reverse('test_73764999:add-log', args=(data.id,)))
        else:
            # If there are errors, re-render the same form with errors
            return render(request, 'test_73764999/form.html', {
                'form': form, 'id': id,
            })
    else:
        # If this is a GET request, render an empty form
        form = LogForm()

    return render(request, 'test_73764999/form.html', {
        'form': form, 'id': id,
    })


text:
Q: How to show all windows in XFCE? In XFCE's windows settings, there is a command called Show Desktop. It minimizes all windows and well, shows the desktop. A more detailed description can be found here, for example.
Is there a command available that will show all windows again, i.e. a command that essentially serves as the counter-part by way of a toggle?

A: Given the existing ctrl+alt+d keyboard shortcut to Show Desktop, you can use xdotool to toggle show/hide of the desktop. For example, here's a test script that shows the desktop, waits five seconds, and then shows the windows again:
#!/bin/bash
xdotool key ctrl+alt+d
sleep 5
xdotool key ctrl+alt+d

But it should be noted that if any windows are shown on the desktop, the Show Desktop operation executed by the ctrl+alt+d shortcut will minimize those windows. So, if xdotool key ctrl+alt+d is run from a terminal to minimize a bunch of windows and show the desktop, and the terminal is then restored to run the command again, the other windows won't be restored; the terminal will just be minimized.

A: The default keyboard shortcut actually includes the function I  was originally looking for. I just never happened to use it, i.e. to push CTRL+ALT+D when all the windows are minimized.


text:
Q: Can't decode subclasses using Circe in Scala I have a Scala project in which I am using Circe to handle json.
I am having trouble decoding from JSON to subclasses of a hierarchy.
The code I am having trouble with is the following test:
  test("FailingResponse - Conversion between case object and Json works") {
    val caseObject = FailingResponse("Some Error", StatusCodes.INTERNAL_ERROR)
    val jsonString = caseObject
      .asJson
      .printWith(Printer.noSpaces)

    decode[ValuationResponse](jsonString) must be(Right(caseObject))
  }

I want to be able to decode to any of the subclasses of ValuationResponse, since at the point of decoding I can't know for sure if the response is a FailingResponse or a SuccessfulResponse. I would like for the decoder to be able to induce what type of ValuationReponse it is, decode it and make it available as "generic" ValuationResponse. Which I could then manipulate with a match-case or something like that to get to the actual specific type.
Instead, what I get on that test is a DecodingFailure error. What am I doing wrong?
This is the code for the hierarchy:
sealed trait ValuationResponse {
  def statusCode: StatusCode
}

case class SuccessfulResponse(values: List[StockValuation], symbol: String, function: TimeSeriesType, statusCode: StatusCode) extends ValuationResponse

case class FailingResponse(reason: String, statusCode: StatusCode) extends ValuationResponse

case class ValuationRequest(function: TimeSeriesType = TIME_SERIES_INTRADAY, symbol: String, interval: IntraDayInterval = IntraDayIntervals.MIN_5)

object derivation {

  implicit val encodeResponse: Encoder[ValuationResponse] = Encoder.instance {
    case response@SuccessfulResponse(_, _, _, _) => response.asJson
    case response@FailingResponse(_, _) => response.asJson
  }
  implicit val decodeResponse: Decoder[ValuationResponse] =
    List[Decoder[ValuationResponse]](
      Decoder[SuccessfulResponse].widen,
      Decoder[FailingResponse].widen
    ).reduceLeft(_ or _)

  implicit val encodeRequest: Encoder[ValuationRequest] = Encoder.instance {
    case response@ValuationRequest(_, _, _) => response.asJson
  }
  implicit val decodeRequest: Decoder[ValuationRequest] =
    List[Decoder[ValuationRequest]](
      Decoder[ValuationRequest].widen
    ).reduceLeft(_ or _)
}

These are the enums it uses ( Yeah I know having a enum for status codes is silly ahah):
sealed abstract class TimeSeriesType(val text: String) extends EnumEntry {}

sealed abstract class IntraDayInterval(val text: String) extends EnumEntry {}

object TimeSeriesFunctions extends Enum[TimeSeriesType] with CirceEnum[TimeSeriesType] {
  val values: immutable.IndexedSeq[TimeSeriesType] = findValues

  case object TIME_SERIES_INTRADAY extends TimeSeriesType("TIME_SERIES_INTRADAY")

  case object TIME_SERIES_DAILY extends TimeSeriesType("TIME_SERIES_DAILY")

  case object TIME_SERIES_WEEKLY extends TimeSeriesType("TIME_SERIES_WEEKLY")

  case object TIME_SERIES_MONTHLY extends TimeSeriesType("TIME_SERIES_MONTHLY")

}

object IntraDayIntervals extends Enum[IntraDayInterval] with CirceEnum[IntraDayInterval] {
  val values: immutable.IndexedSeq[IntraDayInterval] = findValues

  case object MIN_1 extends IntraDayInterval("1min")

  case object MIN_5 extends IntraDayInterval("5min")

  case object MIN_15 extends IntraDayInterval("15min")

  case object MIN_30 extends IntraDayInterval("30min")

  case object MIN_60 extends IntraDayInterval("60min")

}

object StatusCodes extends Enum[StatusCode] with CirceEnum[StatusCode] {
  val values: immutable.IndexedSeq[StatusCode] = findValues

  case object SUCCESS extends StatusCode(200)

  case object INTERNAL_ERROR extends StatusCode(500)

  case object REQUESTER_ERROR extends StatusCode(400)

}

A: When I tested your code with a few modifications (removed few things to make code compile easier):
  type StatusCode = Int
  sealed trait ValuationResponse {
    def statusCode: StatusCode
  }

  case class SuccessfulResponse(succ: String, statusCode: StatusCode) extends ValuationResponse

  case class FailingResponse(reason: String, statusCode: StatusCode) extends ValuationResponse

  case class ValuationRequest(test: String)

  object derivation {

    implicit val encodeResponse: Encoder[ValuationResponse] = Encoder.instance {
      case response@SuccessfulResponse(_, _) => response.asJson
      case response@FailingResponse(_, _) => response.asJson
    }
    implicit val decodeResponse: Decoder[ValuationResponse] =
      List[Decoder[ValuationResponse]](
        Decoder[SuccessfulResponse].widen,
        Decoder[FailingResponse].widen
      ).reduceLeft(_ or _)

    implicit val encodeRequest: Encoder[ValuationRequest] = Encoder.instance {
      case response@ValuationRequest(_) => response.asJson
    }
    implicit val decodeRequest: Decoder[ValuationRequest] =
      List[Decoder[ValuationRequest]](
        Decoder[ValuationRequest].widen
      ).reduceLeft(_ or _)
  }

  val caseObject = FailingResponse("Some Error", 200)
  val jsonString = caseObject
        .asJson
        .printWith(Printer.noSpaces)

I got
@ decode[ValuationResponse](jsonString)
res21: Either[Error, ValuationResponse] = Left(DecodingFailure(CNil, List()))

However, when I imported implicits from object
@ import derivation._
import derivation._

@ decode[ValuationResponse](jsonString)
res23: Either[Error, ValuationResponse] = Right(FailingResponse("Some Error", 200))

Thing is, by default Circe uses discrimination field to distinguish between sum type members. You can see what your value is encoded into if you don't import derivation object:
@ {
  val jsonString = (caseObject : ValuationResponse)
        .asJson
        .printWith(Printer.noSpaces)
  }
jsonString: String = "{\"FailingResponse\":{\"reason\":\"Some Error\",\"statusCode\":200}}"

So, you used automatically derived codecs when you decoded your case class - if you removed import io.circe.generic.auto._ your compilation would fail when you tried to decode things without importing codes you yourself wrote (import derivation._).
To avoid such situations in the future:

*

*don't import io.circe.generic.auto._ on production on codecs use site - it makes it possible to derive new codec for case class that should use your hand-written/manually-derived codec (which leads to bugs like this one)

*prefer io.circe.generic.semiauto._ to summon derived codecs in place where you need them (instead of Decoder[A] write deriveDecoder[A])

*put your semi-automatically derived codecs as well as hand-written codecs in companion objects of types for which you derive codecs (if possible) - this will remove the need to import them manually each time you need them

  import io.circe.generic.semiauto._

  sealed trait ValuationResponse ...
  object ValuationResponse {
    implicit val decodeResponse: Decoder[ValuationResponse] =
      List[Decoder[ValuationResponse]](
        deriveDecoder[SuccessfulResponse].widen,
        deriveDecoder[FailingResponse].widen
      ).reduceLeft(_ or _)
  }

BTW. usage of semiauto also helps you avoid other bugs, like cyclic-dependency on initialization of your implicit in your code you have:
@ derivation.decodeRequest.decodeJson("test".asJson)
java.lang.NullPointerException
  ammonite.$sess.cmd7$.<clinit>(cmd7.sc:1)

but if it used deriveDecoder:
implicit val decodeRequest: Decoder[ValuationRequest] =
    List[Decoder[ValuationRequest]](
      deriveDecoder[ValuationRequest].widen
    ).reduceLeft(_ or _)

you would get:
@ val decodeRequests: Decoder[ValuationRequest] =
      List[Decoder[ValuationRequest]](
        io.circe.generic.semiauto.deriveDecoder[ValuationRequest].widen
      ).reduceLeft(_ or _)
decodeRequests: Decoder[ValuationRequest] = io.circe.generic.decoding.DerivedDecoder$$anon$1@30570f04

@ decodeRequests.decodeJson("test".asJson)
res9: Decoder.Result[ValuationRequest] = Left(DecodingFailure(Attempt to decode value on failed cursor, List(DownField(test))))


text:
Q: The named parameter 'body' isn't defined. in flutter code I'm practising this code github to add a home screen with cards as pictures shown below. after the get started button clicks it should redirect to the home page with cards. cards are not still designed like the picture shows. the code I used to get cards is not working. can someone know how to fix this? no errors on main. dart.  error is in home_page.dart. think I'm missing some codes.
error shows ----> Missing concrete implementation of 'StatefulWidget.createState'.

home_page.dart

         import 'package:flutter/material.dart';
            import 'package:fashion_app/color_filters.dart';

         class HomePage extends StatefulWidget{
              @override
                _HomePageState createSatate ()=> _HomePageState();
              }

            class _HomePageState extends State <HomePage> {
              final double _borderRadious = 24;

              Widget build(BuildContext context) {
                return Scaffold(
                    appBar: AppBar(
                      title: Text('Fashion store'),
),
                      body: ListView(
                        padding: EdgeInsets.all(16),
                        children: [
                          buildQuoteCard(),
                          buildRoundedCard(),
                          buildColoredCard(),
                          buildImageCard(),
                          buildImageInteractionCard(),
                        ],
                      ),

                    )
                );
              }

              Widget buildQuoteCard() =>
                  Card(
                    child: Padding(
                      padding: EdgeInsets.all(12),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'If life were predictable it would cease to be life,
    and be without flavor.',
                            style: TextStyle(fontSize: 24),
                          ),
                          const SizedBox(height: 12),
                          Text(
                            'Eleanor Roosevelt',
                            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                    ),
                  );

              Widget buildRoundedCard() =>
                  Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Container(
                      padding: EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Rounded card',
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'This card is rounded',
                            style: TextStyle(fontSize: 20),
                          ),
                        ],
                      ),
                    ),
                  );

              Widget buildColoredCard() =>
                  Card(
                    shadowColor: Colors.red,
                    elevation: 8,
                    clipBehavior: Clip.antiAlias,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24),
                    ),
                    child: Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [Colors.redAccent, Colors.red],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                      ),
                      padding: EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Colored card',
                            style: TextStyle(
                              fontSize: 20,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'This card is rounded and has a gradient',
                            style: TextStyle(
                              fontSize: 20,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );

              Widget buildImageCard() =>
                  Card(
                    clipBehavior: Clip.antiAlias,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24),
                    ),
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Ink.image(
                          image: NetworkImage(
                            'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1327&q=80',
                          ),
                          colorFilter: ColorFilters.greyscale,
                          child: InkWell(
                            onTap: () {},
                          ),
                          height: 240,
                          fit: BoxFit.cover,
                        ),
                        Text(
                          'Card With Splash',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                            fontSize: 24,
                          ),
                        ),
                      ],
                    ),
                  );

              Widget buildImageInteractionCard() =>
                  Card(
                    clipBehavior: Clip.antiAlias,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24),
                    ),
                    child: Column(
                      children: [
                        Stack(
                          children: [
                            Ink.image(
                              image: NetworkImage(
                                'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1327&q=80',
                              ),
                              height: 240,
                              fit: BoxFit.cover,
                            ),
                            Positioned(
                              bottom: 16,
                              right: 16,
                              left: 16,
                              child: Text(
                                'Cats rule the world!',
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                  fontSize: 24,
                                ),
                              ),
                            ),
                          ],
                        ),
                        Padding(
                          padding: EdgeInsets.all(16).copyWith(bottom: 0),
                          child: Text(
                            'The cat is the only domesticated species in the family Felidae and is often referred to as the domestic cat to distinguish it from the wild members of the family.',
                            style: TextStyle(fontSize: 16),
                          ),
                        ),
                        ButtonBar(
                          alignment: MainAxisAlignment.start,
                          children: [
                            FlatButton(
                              child: Text('Buy Cat'),
                              onPressed: () {},
                            ),
                            FlatButton(
                              child: Text('Buy Cat Food'),
                              onPressed: () {},
                            )
                          ],
                        )
                      ],
                    ),
                  );

            }

    > main. dart

    import 'package:flutter/material.dart';

    import 'constants.dart';
    import 'home_page.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Auth Screen 1',
          theme: ThemeData(
            brightness: Brightness.light,
            primaryColor: kPrimaryColor,
            scaffoldBackgroundColor: kBackgroundColor,

            textTheme: TextTheme(
              headline4: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
              button: TextStyle(color: kPrimaryColor),
              headline6: TextStyle(color: Colors.white70, fontWeight: FontWeight.normal),
            ),
            inputDecorationTheme: InputDecorationTheme(
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(
                  color: Colors.white.withOpacity(.2),
                ),
              ),
            ),
          ),
          home: WelcomeScreen(),
        );
      }
    }

    class WelcomeScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Color(0XFFd5ae48),
          body: Column(
            children: <Widget>[
              Expanded(
                child: Container(
                  height: MediaQuery.of(context).size.height*.4,
                  padding: EdgeInsets.all(10.0),

                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("assets/images/girl.png"),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                flex: 3,
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    RichText(
                      textAlign: TextAlign.left,
                      text: TextSpan(
                        children: [
                          TextSpan(
                            text: "Let Your Styles Speaks\n",
                            style: Theme.of(context).textTheme.headline4,

                          ),
                          TextSpan(
                            text: "Discover the latest trends in women fashion and explore your personality\n",
                            style: Theme.of(context).textTheme.headline6,
                          )
                        ],
                      ),
                    ),
                    FittedBox(
                      child: GestureDetector(
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(
                            builder: (context) {
                              return HomePage();
                            },
                          ));
                        },
                        child: Container(
                          margin: EdgeInsets.only(bottom: 25),
                          padding: EdgeInsets.symmetric(horizontal: 26, vertical: 16),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(25),
                            color: Colors.black,
                          ),
                          child: Row(
                            children: <Widget>[
                              Text(
                                "Get started",
                                style: Theme.of(context).textTheme.button?.copyWith(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20
                                ),
                              ),
                              SizedBox(width: 10),
                              Icon(
                                Icons.arrow_forward,
                                color: Colors.white,
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }

A: https://api.flutter.dev/flutter/widgets/StatefulWidget/createState.html
Change this,
 class HomePage extends StatefulWidget{
              @override
                _HomePageState createSatate ()=> _HomePageState(); // change createSatate to createState
              }

To,
 class HomePage extends StatefulWidget{
              @override
                _HomePageState createState ()=> _HomePageState();
              }

A: class HomePage extends StatefulWidget{
  @override
  _HomePageState createSatate ()=> _HomePageState();
}

It's because of a typo.
Change createSatate to createState.
Your Homepage class will look like
class HomePage extends StatefulWidget{
  @override
  _HomePageState createState ()=> _HomePageState();
}


text:
Q: PHP Push notification service, feedback is empty,how can i to do The push works just fine, the problem is that the feedback is empty. I need to delete the tokens that have expired or have an invalid status.This is what I write test code,this a problem?]
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
$fp = stream_socket_client('ssl://feedback.sandbox.push.apple.com:2196', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
  return;
}
while ($devcon = fread($fp,38)) {
  $arr = unpack("H*", $devcon);
  $rawhex = trim(implode("", $arr));
  $feedbackTime = hexdec(substr($rawhex, 0, 8));
  $feedbackDate = date('Y-m-d H:i', $feedbackTime);
  $feedbackLen = hexdec(substr($rawhex, 8, 4));
  $feedbackDeviceToken = substr($rawhex, 12, 64);
}
fclose($fp);

A: Feedback services don't always return data. You will get data only if there is need to report failed deliveries.
See the documentation here.
Not sure if this is true but I have noticed feedback services don't work with the sandbox environment (at least I haven't received a response any time I checked with sandbox)


text:
Q: sql joining two tables on one string match This is my linq query -
from u in db.CardTables
   join v in db.FunRegistereds
   on new { u.IsApproved, u.FKCardID } equals new {"YES", v.UserID }

Where from this query column in first table CardTables has one with string match and column FKCardID is integer type.
I am getting troubled with this first string match.
How do I match this u.IsApproved column with string "YES" while matching both the columns in this way ??

A: Join on FKCardID equals UserID and just filter u.IsApproved:
from u in db.CardTables
join v in db.FunRegistereds
   on u.FKCardID equals v.UserID
where u.IsApproved == "YES"
...

A: You need to give names to the properties in the second anonymous type initializer:
from u in db.CardTables
join v in db.FunRegistereds
on new { u.IsApproved, u.FKCardID } equals
   new { IsApproved = "YES", FKCardID = v.UserID }


text:
Q: "Error using Keras concat to join two LSTM layers -Nan in epoch" what's the error? Newbie here. goal is to predict scores and distances based on data interdependently and so used concat, but it always results nan in epoch.
I tried following steps but still same result:

*

*Reduced the learning rate
Added regularization: by adding Dropout layers

*Checked data for NAN, NA#, Null values

What's the error ?
Here are the results:
train_X_scores.shape
Out[198]: (7299, 1, 5)
test_X_scores.shape
Out[199]: (1825, 1, 5)
train_X_distances.shape
Out[200]: (7299, 1, 3)
test_X_distances.shape
Out[201]: (1825, 1, 3)
concat.shape :Out[202]
TensorShape([None, 1, 100])
concat.shape :Out[203]
TensorShape([None, 1, 100])```
Epoch 30/30
73/73 - 1s - loss: nan - accuracy: 0.7528 - val_loss: nan - val_accuracy: 0.7381 - 563ms/epoch - 8ms/step

Here is the code
import pandas as pd
import numpy as np
import tensorflow as tf
from keras.models import Model
from keras.layers import Input, LSTM, Dense, Concatenate, Lambda, Dropout
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from keras.optimizers import Adam
from keras.optimizers import RMSprop

# Load the data
data = pd.read_csv(r'C:\score\score_dist.csv')
data.drop(['Date'], axis=1, inplace=True)

# split into input (X) and output (y) variables
scores = data[['score_1', 'score_2', 'score_3', 'score_4', 'score_5']]

distances = data[['Distance_1', 'Distance_2', 'Distance_3']]

# normalize data
scaler_scores = MinMaxScaler()
scaler_distances = MinMaxScaler()
scaled_scores = scaler_scores.fit_transform(scores)
scaled_distances = scaler_distances.fit_transform(distances)

# Amount of tests we need to take into consideration for prediction
testsize = 0.2

# split into train and test sets
train_X_scores, test_X_scores, train_y_scores, test_y_scores = train_test_split(scaled_scores, scaled_scores, test_size=testsize)
train_X_distances, test_X_distances, train_y_distances, test_y_distances = train_test_split(scaled_distances, scaled_distances, test_size=testsize)

# reshape input to be 3D [samples, timesteps, features]
train_X_scores = train_X_scores.reshape((train_X_scores.shape[0], 1, train_X_scores.shape[1]))
test_X_scores = test_X_scores.reshape((test_X_scores.shape[0], 1, test_X_scores.shape[1]))
train_X_distances = train_X_distances.reshape((train_X_distances.shape[0], 1, train_X_distances.shape[1]))
test_X_distances = test_X_distances.reshape((test_X_distances.shape[0], 1, test_X_distances.shape[1]))

train_X_scores.shape
test_X_scores.shape

train_X_scores[0]
train_X_scores[1]

test_X_scores[0]
test_X_scores[1]

train_X_distances.shape
test_X_distances.shape

# define model
drpot=0.2

input_scores = Input(shape=(train_X_scores.shape[1], train_X_scores.shape[2]))
lstm_scores = LSTM(50, return_sequences=True)(input_scores)
dropout_scores = Dropout(drpot)(lstm_scores)
dropout_scores.shape

input_distances = Input(shape=(train_X_distances.shape[1], train_X_distances.shape[2]))
lstm_distances = LSTM(50, return_sequences=True)(input_distances)
dropout_distances = Dropout(drpot)(lstm_distances)
dropout_distances.shape

concat = Concatenate()([dropout_scores, dropout_distances])
concat.shape

flatten_layer = Lambda(lambda x: x[:, -1, :])(concat)
flatten_layer.shape

output = Dense(3)(flatten_layer)
output.shape

model = Model(inputs=[input_scores, input_distances], outputs=output)

# compile model
model.compile(optimizer=RMSprop(learning_rate=0.1), loss='mse', metrics=['accuracy'])

# fit model
epoch=30
bsz=100
model.fit([train_X_scores, train_X_distances], train_y_distances, epochs=epoch, batch_size=bsz, validation_data=([test_X_scores, test_X_distances], test_y_distances), verbose=2)


text:
Q: Is there a standard about the usage of "()", "[]", "{}" in grammar formula? What does these symbols mean? How do I use them correctly? I was learning some kind of expression. When I searched that in google, I got a variety of symbols.
there are 3 main types of symbols
a pair of brackets

a little bit [adjective]

a pair of parentheses

(subject) + y u + (extent) + (adjective)

a pair of brackets inside a pair of parentheses

a little (bit [adjective])

I also saw a pair of curly braces {} somewhere else, though I cannot find it at this point.
I call this a formula

subject + verb + adjective

I don't know what it is should be called.
Anyway, some of these formulas use "()", "[]", like the examples above.
I am not asking how to use these symbols in normal english writing, I am asking the usage of these symbols in terms of grammar formula.
In information technology, specifically, in linux command/bash, each of "()", "[]", "{}" has different meaning, for instance (https://tiswww.case.edu/php/chet/bash/bashref.html),

the {} is replaced with each line read from standard input.

So, what does these symbols mean in terms of grammar formula? How do I use them correctly?

A: When writing English, the only brackets you would normally use are parenthesis: ( )
These are used for enclosing parenthetic statements (a statement that explains or qualifies something) within the text. Like I did just there. You should be able to ignore what is within the parenthesis and the sentence would still be grammatically correct. You can also use commas, a common punctuation mark, for parenthesis. Like that.
Square brackets [ ] are used to contain parenthetic words or statements added after the original text was written, perhaps by another person [such as an editor - Ed] that qualify or explain what has been said.
Braces { } are normally only used to contain number sets, for example: {1,2,3,4,5}.
These are all examples of their formal use in English grammar, and there are possibly some other uses too. Like a lot of other symbols, they have all gained different uses in computing, for example in computer programming languages.