text:
Q: Spring batch - unable to delete from BATCH_JOB_INSTANCE using H2 I'm trying to write a job to cleanup the Spring batch metadata tables (as defined here: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-core/src/main/resources/org/springframework/batch/core/schema-h2.sql) which I currently have in an embedded H2 DB. All delete queries are being executed successfully working backwards from BATCH_STEP_EXECUTION_CONTEXT, however, the last query is failing with Invalid value "1" for parameter "parameterIndex" [90008-200]
This is the query being executed to delete from BATCH_JOB_INSTANCE:
DELETE FROM BATCH_JOB_INSTANCE WHERE JOB_INSTANCE_ID NOT IN (SELECT JOB_INSTANCE_ID FROM BATCH_JOB_EXECUTION)
Any ideas why this might be failing?
List of all queries:
private static final String SQL_DELETE_BATCH_STEP_EXECUTION_CONTEXT = "DELETE FROM BATCH_STEP_EXECUTION_CONTEXT WHERE STEP_EXECUTION_ID IN (SELECT STEP_EXECUTION_ID FROM BATCH_STEP_EXECUTION WHERE JOB_EXECUTION_ID IN (SELECT JOB_EXECUTION_ID FROM BATCH_JOB_EXECUTION where CREATE_TIME < ?))";
private static final String SQL_DELETE_BATCH_STEP_EXECUTION = "DELETE FROM BATCH_STEP_EXECUTION WHERE JOB_EXECUTION_ID IN (SELECT JOB_EXECUTION_ID FROM BATCH_JOB_EXECUTION where CREATE_TIME < ?)";
private static final String SQL_DELETE_BATCH_JOB_EXECUTION_CONTEXT = "DELETE FROM BATCH_JOB_EXECUTION_CONTEXT WHERE JOB_EXECUTION_ID IN (SELECT JOB_EXECUTION_ID FROM BATCH_JOB_EXECUTION where CREATE_TIME < ?)";
private static final String SQL_DELETE_BATCH_JOB_EXECUTION_PARAMS = "DELETE FROM BATCH_JOB_EXECUTION_PARAMS WHERE JOB_EXECUTION_ID IN (SELECT JOB_EXECUTION_ID FROM BATCH_JOB_EXECUTION where CREATE_TIME < ?)";
private static final String SQL_DELETE_BATCH_JOB_EXECUTION = "DELETE FROM BATCH_JOB_EXECUTION where CREATE_TIME < ?";
private static final String SQL_DELETE_BATCH_JOB_INSTANCE = "DELETE FROM BATCH_JOB_INSTANCE WHERE JOB_INSTANCE_ID NOT IN (SELECT JOB_INSTANCE_ID FROM BATCH_JOB_EXECUTION)";

Thanks in advance!

A: Figured it out. I was passing a date parameter to all delete queries executed with jdbc template, however, as you can in the last delete query there is no parameter required.
Once I removed the parameter from the jdbc template update method the query ran fine.


text:
Q: Dropdownlist in Kendo Ui I have a dropdownlist which contain divisionName, but I want the divisionID to be in dropdownlist. Anyone know about it?
// dropdownList

function divisionDropDownEditor(container, options) {
  $('<input required name="' + options.field + '"/>')
    .appendTo(container)
    .kendoDropDownList({
      autoBind: false,
      dataTextField: "divisionName",
      dataValueField: "divisionID",
      dataSource: {
        type: "POST",
        transport: {
          read: "http://vx-dev.ehors.com:8480/najwa/getDivisionName.php"
        }
      }
    });
}

// getDivisionName.php file

<?php
    ##############################################################
    #### Fetch data from database and display into JSON format ###
    ##############################################################

    $getcheckbox = (isset($_POST['c1']) ? $_POST['c1'] : "all");   // by default select *

    $propertyID="1";
    include("../EHORS.pdo.php");
    $ehorsObj = new EHORS();
    $ehorsObj->EHORS_CONNECT($propertyID);

    $sql = "SELECT  divisionID, divisionName FROM tblAdmDivision";

/*  $sql = "SELECT  tblAdmDepartment.divisionID, tblAdmDivision.divisionName
            FROM tblAdmDepartment
            INNER JOIN tblAdmDivision
            ON tblAdmDepartment.divisionName = tblAdmDivision.ivisionID";*/

    if ($getcheckbox == "true") {
            $sql .= " WHERE active = 'y' ";
        }

        //$sql .= " ORDER BY 2 ASC " ;  // ordr by segmentName

    $array = array();

    // /* PDO */
    $GetResult = $ehorsObj->FetchData($sql, $ehorsObj->DEFAULT_PDO_CONNECTIONS);

    while ($row = $GetResult->fetch()){
            $array[] = $row;
    }

    header("Content-type: application/json");

    $result = json_encode($array);
    echo $result;

?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Beautifulsoup taking too much time to execute in the code I am trying to scrape a website:-
https://media.info/newspapers/titles
This website has a list of newspapers from A to Z. I first have to scrape all the URLs and then scrape some more information from each newspaper.
Below is my code to scrape the URLs of all the newspapers starting from A to Z:-
driver.get('https://media.info/newspapers/titles')
time.sleep(2)
page_title = []
pages = driver.find_elements(By.XPATH,"//div[@class='pages']//a")
for i in pages:
    page_title.append(i.get_attribute("href"))

names = []
for i in page_title:
    driver.get(i)
    time.sleep(1)

    name = driver.find_elements(By.XPATH,"//div[@class='info thumbBlock']//a")
    for i in name:
        names.append(i.get_attribute("href"))

len(names) :-> 1688
names[0:5]
['https://media.info/newspapers/titles/abergavenny-chronicle',
 'https://media.info/newspapers/titles/abergavenny-free-press',
 'https://media.info/newspapers/titles/abergavenny-gazette-diary',
 'https://media.info/newspapers/titles/the-abingdon-herald',
 'https://media.info/newspapers/titles/academies-week']

moving further I need to scrape some information like owner, postal_Address, email, etc and I wrote the below code.
test = []
c = 0
for i in names:
    driver.get(i)
    time.sleep(2)

    r = requests.get(i)
    soup = BeautifulSoup(r.content,'lxml')

    try:
        name = driver.find_element(By.XPATH,"//*[@id='mainpage']/article/div[3]/h1").text

        try:
            twitter = driver.find_element(By.XPATH,"//*[@id='mainpage']/article/table[3]/tbody/tr/td[1]/a").text
        except:
            twitter = None

        try:
            twitter_followers = driver.find_element(By.XPATH,"//*[@id='mainpage']/article/table[3]/tbody/tr/td[1]/small").text.replace(' followers','').lstrip('(').rstrip(')')
        except:
            twitter_followers = None

        people = []
        try:
            persons = driver.find_elements(By.XPATH,"//div[@class='columns']")
            for i in persons:
                people.append(i.text)
        except:
            people.append(None)

        try:
            owner = soup.select_one('th:contains("Owner") + td').text
        except:
            owner = None

        try:
            postal_address = soup.select_one('th:contains("Postal address") + td').text
        except:
            postal_address = None

        try:
            Telephone = soup.select_one('th:contains("Telephone") + td').text
        except:
            Telephone = None

        try:
            company_website = soup.select_one('th:contains("Official website") + td > a').get('href')
        except:
            company_website = None

        try:
            main_email = soup.select_one('th:contains("Main email") + td').text
        except:
            main_email = None

        try:
            personal_email = soup.select_one('th:contains("Personal email") + td').text
        except:
            personal_email = None

        r2 = requests.get(company_website)
        soup2 = BeautifulSoup(r2.content,'lxml')

        try:
            is_wordpress = soup2.find("meta",{"name":"generator"}).get('content')
        except:
            is_wordpress = None

        news_Data = {
                    "Name": name,
                    "Owner": owner,
                    "Postal Address": postal_address,
                    "main Email":main_email,
                    "Telephone": Telephone,
                    "Personal Email": personal_email,
                    "Company Wesbite": company_website,
                    "Twitter_Handle": twitter,
                    "Twitter_Followers": twitter_followers,
                    "People":people,
                    "Is Wordpress?":is_wordpress
                    }

        test.append(news_Data)
        c=c+1
        print("completed",c)

    except Exception as Argument:
        print(f"There is an exception with {i}")
        pass

I am using both Selenium and BesutifulSoup with requests to scrape the data. The code is fulfilling the requirements.

*

*Firstly, is it a good practice to use it in this manner like using selenium and soup in the same code?

*Secondly, the code is taking too much time. is there any alternate way to reduce the runtime of the code?

A: BeautifulSoup is not slow: making requests and waiting for responses is slow.
You do not necessarily need selenium/chromedriver setup for this task, it's doable with requests (or other python library).
Yes, there are ways to speed it up, however keep in mind you are making requests to a server, which might become overwhelmed if you send too many requests at once, or it might block you.
Here is an example without selenium, which will accomplish what you're after:
import requests
import pandas as pd
from bs4 import BeautifulSoup as bs
from tqdm import tqdm

headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
    }

s = requests.Session()
s.headers.update(headers)

r = s.get('https://media.info/newspapers/titles')
soup = bs(r.text)
letter_links = [x.get('href') for x in soup.select_one('div.pages').select('a')]
newspaper_links = []
for x in tqdm(letter_links):
    soup = bs(s.get(x).text)
    ns_links = soup.select_one('div.columns').select('a')
    for n in ns_links:
        newspaper_links.append((n.get_text(strip=True), 'https://media.info/' + n.get('href')))

detailed_infos = []
for x in tqdm(newspaper_links[:50]):
    soup = bs(s.get(x[1]).text)
    owner = soup.select_one('th:contains("Owner")').next_sibling.select_one('a').get_text(strip=True) if soup.select_one('th:contains("Owner")') else None
    website = soup.select_one('th:contains("Official website")').next_sibling.select_one('a').get_text(strip=True) if soup.select_one('th:contains("Official website")') else None

    detailed_infos.append((x[0], x[1], owner, website))
df = pd.DataFrame(detailed_infos, columns = ['Newspaper', 'Info Url', 'Owner', 'Official website'])
print(df)

Result in terminal:
Newspaper   Info Url    Owner   Official website
0   Abergavenny Chronicle   https://media.info//newspapers/titles/abergavenny-chronicle Tindle Newspapers   abergavenny-chronicle-today.co.uk
1   Abergavenny Free Press  https://media.info//newspapers/titles/abergavenny-free-press    Newsquest Media Group   freepressseries.co.uk
2   Abergavenny Gazette & Diary https://media.info//newspapers/titles/abergavenny-gazette-diary Tindle Newspapers   abergavenny-chronicle-today.co.uk/tn/index.cfm
3   The Abingdon Herald https://media.info//newspapers/titles/the-abingdon-herald   Newsquest Media Group   abingdonherald.co.uk
4   Academies Week  https://media.info//newspapers/titles/academies-week    None    academiesweek.co.uk
5   Accrington Observer https://media.info//newspapers/titles/accrington-observer   Reach plc   accringtonobserver.co.uk
6   Addlestone and Byfleet Review   https://media.info//newspapers/titles/addlestone-and-byfleet-review Reach plc   woking.co.uk
7   Admart & North Devon Diary  https://media.info//newspapers/titles/admart-north-devon-diary  Tindle Newspapers   admart.me.uk
8   AdNews Willenhall, Wednesbury and Darlaston https://media.info//newspapers/titles/adnews-willenhall-wednesbury-and-darlaston    Reach plc   reachplc.com
9   The Advertiser  https://media.info//newspapers/titles/the-advertiser    DMGT    dmgt.co.uk
10  Aintree and Maghull Champion    https://media.info//newspapers/titles/aintree-and-maghull-champion  Champion Media group    champnews.com
11  Airdrie & Coatbridge World  https://media.info//newspapers/titles/airdrie-coatbridge-world  Reach plc   icLanarkshire.co.uk
12  Airdrie and Coatbridge Advertiser   https://media.info//newspapers/titles/airdrie-and-coatbridge-advertiser Reach plc   acadvertiser.co.uk
13  Aire Valley Target  https://media.info//newspapers/titles/aire-valley-target    Newsquest Media Group   thisisbradford.co.uk
14  Alcester Chronicle  https://media.info//newspapers/titles/alcester-chronicle    Newsquest Media Group   redditchadvertiser.co.uk/news/alcester
15  Alcester Standard   https://media.info//newspapers/titles/alcester-standard Bullivant Media redditchstandard.co.uk
16  Aldershot Courier   https://media.info//newspapers/titles/aldershot-courier Guardian Media Group    aldershot.co.uk
17  Aldershot Mail  https://media.info//newspapers/titles/aldershot-mail    Guardian Media Group    aldershot.co.uk
18  Aldershot News & Mail   https://media.info//newspapers/titles/aldershot-news-mail   Reach plc   gethampshire.co.uk/aldershot
19  Alford Standard https://media.info//newspapers/titles/alford-standard   JPI Media   skegnessstandard.co.uk
20  Alford Target   https://media.info//newspapers/titles/alford-target DMGT    dmgt.co.uk
21  Alfreton and Ripley Echo    https://media.info//newspapers/titles/alfreton-and-ripley-echo  JPI Media   jpimedia.co.uk
22  Alfreton Chad   https://media.info//newspapers/titles/alfreton-chad JPI Media   chad.co.uk
23  All at Sea  https://media.info//newspapers/titles/all-at-sea    None    allatsea.co.uk
24  Allanwater News https://media.info//newspapers/titles/allanwater-news   HUB Media   allanwaternews.co.uk
25  Alloa & Hillfoots Shopper   https://media.info//newspapers/titles/alloa-hillfoots-shopper   Reach plc   reachplc.com
26  Alloa & Hillfoots Advertiser    https://media.info//newspapers/titles/alloa-hillfoots-advertiser    Dunfermline Press Group alloaadvertiser.com
27  Alloa and Hillfoots Wee County News https://media.info//newspapers/titles/alloa-and-hillfoots-wee-county-news   HUB Media   wee-county-news.co.uk
28  Alton Diary https://media.info//newspapers/titles/alton-diary   Tindle Newspapers   tindlenews.co.uk
29  Andersonstown News  https://media.info//newspapers/titles/andersonstown-news    Belfast Media Group irelandclick.com
30  Andover Advertiser  https://media.info//newspapers/titles/andover-advertiser    Newsquest Media Group   andoveradvertiser.co.uk
31  Anfield and Walton Star https://media.info//newspapers/titles/anfield-and-walton-star   Reach plc   icliverpool.co.uk
32  The Anglo-Celt  https://media.info//newspapers/titles/the-anglo-celt    None    anglocelt.ie
33  Annandale Herald    https://media.info//newspapers/titles/annandale-herald  Dumfriesshire Newspaper Group   dng24.co.uk
34  Annandale Observer  https://media.info//newspapers/titles/annandale-observer    Dumfriesshire Newspaper Group   dng24.co.uk
35  Antrim Times    https://media.info//newspapers/titles/antrim-times  JPI Media   antrimtoday.co.uk
36  Arbroath Herald https://media.info//newspapers/titles/arbroath-herald   JPI Media   arbroathherald.com
37  The Arden Observer  https://media.info//newspapers/titles/the-arden-observer    Bullivant Media ardenobserver.co.uk
38  Ardrossan & Saltcoats Herald    https://media.info//newspapers/titles/ardrossan-saltcoats-herald    Newsquest Media Group   ardrossanherald.com
39  The Argus   https://media.info//newspapers/titles/the-argus Newsquest Media Group   theargus.co.uk
40  Argyllshire Advertiser  https://media.info//newspapers/titles/argyllshire-advertiser    Oban Times Group    argyllshireadvertiser.co.uk
41  Armthorpe Community Newsletter  https://media.info//newspapers/titles/armthorpe-community-newsletter    JPI Media   jpimedia.co.uk
42  The Arran Banner    https://media.info//newspapers/titles/the-arran-banner  Oban Times Group    arranbanner.co.uk
43  The Arran Voice https://media.info//newspapers/titles/the-arran-voice   Independent News Ltd    voiceforarran.com
44  The Art Newspaper   https://media.info//newspapers/titles/the-art-newspaper None    theartnewspaper.com
45  Ashbourne News Telegraph    https://media.info//newspapers/titles/ashbourne-news-telegraph  Reach plc   ashbournenewstelegraph.co.uk
46  Ashby Echo  https://media.info//newspapers/titles/ashby-echo    Reach plc   reachplc.com
47  Ashby Mail  https://media.info//newspapers/titles/ashby-mail    DMGT    thisisleicestershire.co.uk
48  Ashfield Chad   https://media.info//newspapers/titles/ashfield-chad JPI Media   chad.co.uk
49  Ashford Adscene https://media.info//newspapers/titles/ashford-adscene   DMGT    thisiskent.co.uk

You can extract more information for each newspaper, as you wish - the above is just an example, going through the first 50 newspapers. Now if you want a multithreaded/async solution, I recommend you read the following, and apply it to your own scenario:
BeautifulSoup getting href of a list - need to simplify the script - replace multiprocessing
Lastly, Requests docs can be found here: https://requests.readthedocs.io/en/latest/
BeautifulSoup docs: https://beautiful-soup-4.readthedocs.io/en/latest/index.html
For TQDM: https://pypi.org/project/tqdm/

A: names = []
for letter in string.ascii_lowercase:
    page = requests.get("https://media.info/newspapers/titles/starting-with/{}".format(letter))
    soup = BeautifulSoup(page.content, "html.parser")
    for i in soup.find_all("a"):
        if i['href'].startswith("/newspapers/titles/"):
            names.append(i['href'])


text:
Q: ListView performance lower on 4.2 than on 4.1 I have just upgraded on Android 4.2 on my Galaxy Nexus and ListView seems to be slower than It used to be on 4.1. This bindView method was perfect fast on 4.1, on new 4.2 I see small glitches. I have tried to explicitly enable hardware acceleration in AndroidManifest.xml, but it dit not help much. People (Contacts) app works perfect on 4.2, which I guess is also implemented by extended android.support.v4.widget.CursorAdapter. I have also already tried to change android.support.v4.widget.CursorAdapter for android.widget.CursorAdapter without visible improvement.
@Override
public void bindView(View view, Context context, Cursor cursor) {
    final ViewHolder holder = (ViewHolder) view.getTag();
    holder.nameView.setText(cursor.getString(mStreetColumnIndex));
    holder.townView.setText(cursor.getString(mTownColumnIndex));
    if (mDistanceColumn != null) {
        float distance = cursor.getFloat(mDistanceColumn);
        String distanceUnit;
        if (distance >= 1000) {
            distance /= 1000;
            distanceUnit = " km";
        } else {
            distanceUnit = " m";
        }
        String decimalString = mDecimalFormat.format(distance);
        holder.distanceView.setText(decimalString + distanceUnit);
        holder.distanceView.setVisibility(View.VISIBLE);
    } else {
        holder.distanceView.setVisibility(View.GONE);
    }

    // read only brand first letter to be faster
    cursor.copyStringToBuffer(mBrandColumnIndex, mBuffer);
    if (mBuffer.sizeCopied > 0) {
        if (mBuffer.data[0] == 'a') {
            holder.logoImgView.setImageResource(R.drawable.agip);
        } else {
            holder.logoImgView.setImageResource(R.drawable.papoil);
        }
    } else {
        holder.logoImgView.setVisibility(View.INVISIBLE);
    }
}

EDIT: added row layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="@dimen/row_height"
            android:background="@drawable/bg_list_selector"
            android:layout_marginRight="@dimen/screen_padding"
            android:layout_marginLeft="@dimen/screen_padding"
            android:paddingLeft="@dimen/screen_padding">
<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="@dimen/screen_padding"
        android:layout_toLeftOf="@+id/txtDistance"
        android:orientation="vertical"
        >
    <TextView
            android:id="@+id/txtName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/list_text_primary_size"
            android:textStyle="bold"
            />
    <TextView
            android:id="@+id/txtTown"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/list_text_primary_size"
            />
</LinearLayout>
<TextView
        android:id="@+id/txtDistance"
        android:layout_toLeftOf="@+id/imgLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textColor="@color/grey_dark"
        android:textSize="13sp"
        android:textStyle="bold"
        android:layout_marginRight="@dimen/screen_padding"/>
<ImageView
        android:id="@+id/imgLogo"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/agip"
        android:background="@color/grey_dark"
        />
</RelativeLayout>

EDIT 2:
here is traceview http://goo.gl/UmS3w
which was made using http://goo.gl/Yoe1u

A: It was caused by too much complicated windowBackground, which was:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_repeat">
</item>
<item>
    <shape>
        <gradient android:startColor="#0affffff" android:endColor="#0a000000"
                  android:type="radial" android:gradientRadius="500"/>
    </shape>
</item>
<item>
    <shape>
        <gradient android:startColor="#1effffff" android:endColor="#1e000000"
                  android:type="linear" android:angle="270"/>
    </shape>
</item>
</layer-list>

and bg_repeat.xml:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/bg"
    android:tileMode="repeat"/>

Thanks all for help!


text:
Q: What is => operator in this code I am using ThreadPool with the follwoing code:-
ThreadPool.QueueUserWorkItem
                (o =>
                MyFunction()
                );

I am not sure what does o=> does in this code. Can anyone help me out.

A: This is the C# syntax for a lambda expression.

*

*http://msdn.microsoft.com/en-us/library/bb397687.aspx
It is in many ways an inline delegate definition.  It saves you the tediousness of defining an extra function to use as the delegate target.
private object Target(object state) {
  MyFunction();
}

...
ThreadPool.QueueUserWorkItem(new WaitCallback(Target));

A: It's declaring an anonymous method. Basically, you are passing a method whose body is { MyFunction(); } as a parameter to the QueueUserWorkItem method. I haven't checked, but it should also be also equivalent to:
ThreadPool.QueueUserWorkItem(MyFunction);

A: It describes a lambda (anonymous) function. In this case it's a function that takes one argument, o, and then executes MyFunction (although in this case it's basically throwing the value of o away). It's equivalent to:
void Foo(object o) //We know that Foo takes an object and returns void because QueueUserWorkItem expects an instance of type WaitCallback which is a delegate that takes and object and returns void
{
  MyFunction();
}

ThreadPool.QueueUserWorkItem(Foo) // or ThreadPool.QueueUserWorkItem(new WaitCallback(Foo));

The type of o is inferred based on whatever QueueUserWorkItem expects. QueueUserWorkItem expects type WaitCallback so in this case o should be of type object because WaitCallback is delegate for methods with one parameter of type object that return void.
As for the meaning of this particular code fragment; you're basically adding a function (work item) to a queue that will be executed by one of the threads in the pool (when it becomes available). That particular code fragment just describes a nice, succinct way of passing in the function without having to go through the trouble of fully defining a class method.
Incidentally, I, and others, tend to read => as 'such that'. Some people read it as 'goes to'.


text:
Q: Scatterplot for multiple regression in matplotlib I have four features and a dependent(X). I want to plot a graph with the predicted regression line and the feature values. I went through the documentation but I can't figure out how to represent everything in a scatter plot.

A: Here is some example code to get you started, it fits a simple quadratic and scatterplots the raw data and fitted curve along with calculation of RMSE and R-squared. The example uses a non-linear fit in case you would like to try fitting non-linear equations.
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy.stats

xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7])

def func(x, a, b, c): # simple quadratic example
    return (a * numpy.square(x)) + b * x + c

initialParameters = numpy.array([1.0, 1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)


text:
Q: What's the difference between can,could and may? What's the difference between can,could and may?
I'm an English learner,can you help me?
I'm from China,so I can't understand them...
Thanks!

A: They all have unique meanings which a dictionary will tell you. However, they can be interchangeable in certain contexts.
"Can" indicates that something is a possibility eg. "I can go to the shops for you"
"Could" indicates a possibility that is perhaps dependent on something a condition eg. "I could go to the shops for you if I can borrow your car"
"May" can indicate an uncertain possibility eg "I may go to the shops today, or maybe tomorrow"
An example where "could" and "may" are interchangeable would be:

Q. Who is knocking at the door?
  A. It could be my dad / It may be my dad


text:
Q: Java - Removing an object from an object array I am writing a large program that involves an Object called Player. The Player definition is as follows:
public class Player
{
    public static String name;
    public static Item inventory[] = new Item[10];
    public static int items;

    /* ... */

    public void addItem(String itemName, int itemType)
    {
            if ((items + 1) <= 10) {
                    inventory[items] = new Item(itemName, itemType);
                    items++;
            }
    }

    public void removeItem(int x)
    {
            for (int i = x; i < items; i++)
                    inventory[i] = inventory[i+1];
    }
}

I am adding inventory handling now because it's much easier than adding it later, but inventory isn't going to be used until much later in development. I have no way to see if removeItem works. I modified a function I wrote called strstrip to get this... Would removeItem work? If not, why?

A: Create unit tests for your classes especially if you going to build 'big and complicated program'. This will guarantee you that the code written will work later and if you change your code the failure of unit tests should indicate a problem. The unit test also gives you ability to check that your method works as expected.
As per other comments, consider using List interface instead of array, unless you have some specific requirement (I cannot imagine any). And definitely, having public static fields in your class looks suspicious.
EDIT
Just to indicate how code can look like and how to call methods from the main method.
public class Player {

    private String name;
    private List<Item> inventory;
    private int items;

    public Player() {
        this.inventory = new ArrayList();
    }

    public void addItem(String itemName, int itemType) {
        this.inventory.add(new Item(itemName, itemType));
    }

    public void removeItem(int x) {
        Item itemToRemove = this.inventory.get(x);
        if (itemToRemove != null) {
            this.inventory.remove(itemToRemove);
        }
    }

    public static void main(String[] args) {
        // create a new instance
        Player player = new Player();
        // call a method on the instance
        player.addItem("bla", 0);
    }
}


text:
Q: How to create an extension to check if an object is one of these type? Normally, when I want to check if an object is one of these types, I use the following code:
object a = "ABC";

if (a is string || a is int || a is double)
{

}

I want to create an extension method that that shorten this, such as:
if (a.IsOneOfTheseType(string, int, double)
{

}

A: Try this:
public static class ObjectExtensions {
    public static bool IsOneOfTypes(this object o, params Type[] types) {
        Contract.Requires(o != null);
        Contract.Requires(types != null);
        return types.Any(type => type == o.GetType());
    }
}

I don't have a compiler handy to test / check for stupid mistakes but this should get you pretty close. Note that this satisfies your requirement of "check[ing] if an object is one of [some given] types". If you want to check assignability, replace the lambda expression with
type => type.IsAssignableFrom(o.GetType())

See Type.IsAssignableFrom for the exact semantics.
To use:
object a = "ABC";
bool isAStringOrInt32OrDouble =
    a.IsOneOfTypes(typeof(string), typeof(int), typeof(double));

or
object a = "ABC";
bool isAStringOrInt32OrDouble =
    a.IsOneOfTypes(new[] { typeof(string), typeof(int), typeof(double) });


text:
Q: Colpitts Oscillator, hard time finding values to use I am having a hard time trying to find a logical way to find values for capacitors and inductor to build this circuit (colpitts oscillator)
I read this great tutorial
and I have simulated the circuit and its works just fine. Now I would like to build it with components I have.
I have a lot of capacitors too many values to name but I do not happen to have the values used in the example on the website. So I ask is there a way to manipulate the formulas or something that is not catching my eye as far as choosing capacitor and inductor values?
I know that:
Xc1 + Xc2 = XL
So in my mind I think ok let me choose two caps and from there figure out what
inductor I need, but in order to that i need a resonant frequency to derive my capacitive reactance values, but i cannot do that without my inductance value. So i have 3 unknowns capacitor values, inductor value and resonant frequency value. With the catch that Xc1 +Xc2 = Xl @ resonant freq. To make it even more fun the feed back given by C1/C2 cannot be too big or too small.


text:
Q: Datetime format in QGIS Points to Paths plugin At 2.18.6, I am trying to use the PointstoPaths plugin.
My input layer has a datetime string field with the following format:
2015-01-25 13:45:50  [Please note the blank between date and time.]
However, the PointstoPaths window displays a date format example of:
%Y%m%dT%H:%M:%S    [Here, please note the 'T' between date and time]
Here's a screenshot:

If I use PointstoPaths with the following datetime format (which matches my data):
%Y%m%d %H:%M:%S  [with a blank!]
This error is returned:

If I subsequently edit my datetime string field to change the blank to a 'T', the tool executes perfectly.  Thus I am led to believe that the 'T' is required.  But I don't know what the 'T' represents.  A review of the Python datetime web page turned up nothing.
Sorry if this is long winded, but I don't understand the 'T'!

A: Actually, you are almost there. In your tested case, the hyphen (short dash) between %Y, %m, %d were missing.
PointsToPath accepts both formats as below (as far as such field is string).

*

*If the string is '2015-01-25 13:45:50', the format is %Y-%m-%d %H:%M:%S

*If the string is '2015-01-25T13:45:50', the format is %Y-%m-%dT%H:%M:%S
For the latter case, the T is automatically added between date and time, replacing the space, when the string is converted to "date & time" type field (like, to_datetime() function). I agree it is a misleading description, because PointsToPaths does not accept date or datetime types.
I think the plugin author tried to emphasize that it can accept '2015-01-25T13:45:50' so that most of us (who store the datetime data in "date & time" type field) can easily use it just by to_string() conversion.
By the way, Points to path geoalgorithm is also available in the Processing Toolbox | QGIS geoalgorithms | Vector creation tools.


text:
Q: Problem with adding key to firestore documents I want to add a decimal number as key of a document in Firestore.
I tried to do it like this:
 key = 2.22
 key = key + 0.01

 db.collection('collection').doc('doc').update({ [key] : value })

but this way I get the key as {2 : { 23 : value } }.
I wanted to get it like { 2.23 : value }.
How can I achieve this?

A: The update() method interprets the . as addressing a nested field. So a.b.c would be a field c inside a field b inside field a.
There is no way (that I know of) to prevent Firestore from interpreting the . in calls to update(). Luckily calls to set() are not interpreted in the same way, and you can use set combined with merge: true to get the same update behavior without it interpreting dots.
db.collection('collection').doc('doc').set({ [key] : value }, { merge: true })

A: The problem of using . in a field ID is that it require escaping like said in the firestore documentation
So if you really want the dot you should escape it like so \. because if you don't firestore understand A.B like the item of key B in the map of key A.
Another solution if you can limit the decimals of your float key is to transform your float into an integer so you do not have the problem of the dot notation.
For example if you can have only 2 decimals: 2.22 will be 222 (2.22 * 100).


text:
Q: Loading data from an RPG game So I'm working on a simple RPG game. I want to add an option to load progress through the game, but I guess I'm not that familiar with Java to do it without issues. The idea is to save the game on checkpoints, and load a saved data when the game continues. I'm getting an error with a loadGame method, and I guess it's related to the fact that the data I'm trying to load are all different data types. health and level are integers, while equippedItem is a string.
Here are just two methods, saveGame, and loadGame, because the code is a bit too long to simply paste it in the whole. I'll put additional code if needed of course.
public static void saveGame() {
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter("savedGame.txt"));
        bw.write("Your health is " + player.getHealth());
        bw.newLine();
        bw.write("Your level is " + player.getLevel());
        bw.newLine();
        bw.write("" + player.equippedItem);
        bw.close();
    }
    catch (Exception e) {
        System.out.println("There's an error.");
    }
}

The saveGame() doing its work well, it stores the data in the file. The issue is with the loadGame() method.
public void loadGame() {
    try {
        BufferedReader br = new BufferedReader(new FileReader("savedGame.txt"));
        player.getHealth();
        player.getLevel();
        player.equippedItem;
        br.close();
    } catch (Exception e) {
        System.out.println("There's an error.");
    }
}

The result of player.getHealth() and player.getLevel() is ignored, and it's probably the data type issue I've mentioned.

A: What you're doing is creating a text file in saveGame(), 'opening' that save file in loadGame() but not accessing the data inside.
You have correctly created a BufferedReader, but you're using it incorrectly. You will need to use br.readLine() to read the text file which will return a string like "Your health is 123".
To update the state of the player with this data, you could add something like this inside loadGame():
player.setHp(parseHp(br.readLine()));
player.setLevel(parseLevel(br.readLine()));
... // and so on

The parse methods would take a String input like "Your health is 123" and return int 123.


text:
Q: Combining columns in attribute table How can I merge columns in attribute table with / as delimeters?

A: Open the field calculator then use the formula:
"column1" || '/' || "column2"

A: Also you may use the combination of array_to_string(), map_avals(), and attributes() to get all attributes concatenated with a comma:
array_to_string(map_avals(attributes()))


text:
Q: This code I use to disable ''PlayerMovement'' does not work properly So I entered a simple code:
public class PlayerCollision : MonoBehaviour {

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacle");
        {
            movement.enabled = false;
        }
    }
}

For a game I'm trying to make but the code is not working. The code is supposed to set the playermovement script to ''false'' when the player collides with an object. Every obstacle I have is tagged and I made sure not to tag the ground but every time the player touches the ground the playermovement script goes to false and it is not supposed to do that with the ground onlt with obstacles. When the player touches an obstacle though everything works good and the playermovement goes to false. I am trying to make the player stop every time it hits an obstacle. I am using unity's game engine.


text:
Q: Trouble with a simple loop in Matlab I have a logical mask of pixels e1 that need to be "blended". No matter what value I put for k, loop executes k times but image is only affected once.
Code:
for k=1:5 %I want to do it 5 times but it does the action only once.
    for i=2:rows-1
        for j=2:cols-1
            if e1(i, j) == 1 %if mask == 1, I take "marked" pixel, 8 pixel surrounding it, and avg them.
                I2(i, j, 1) = (I2(i, j-1, 1) + I2(i, j+1, 1) + I2(i-1, j, 1) + I2(i-1, j-1, 1) + I2(i-1, j+1, 1) + I2(i+1, j, 1) + I2(i+1, j+1, 1) + I2(i+1, j-1, 1))/8;
                I2(i, j, 2) = (I2(i, j-1, 2) + I2(i, j+1, 2) + I2(i-1, j, 2) + I2(i-1, j-1, 2) + I2(i-1, j+1, 2) + I2(i+1, j, 2) + I2(i+1, j+1, 2) + I2(i+1, j-1, 2))/8;
                I2(i, j, 3) = (I2(i, j-1, 3) + I2(i, j+1, 3) + I2(i-1, j, 3) + I2(i-1, j-1, 3) + I2(i-1, j+1, 3) + I2(i+1, j, 3) + I2(i+1, j+1, 3) + I2(i+1, j-1, 3))/8;
            end
        end
    end
end

A: I think you should try:
for k=1:5
  I2=convn(I2,[1 1 1;1 0 1;1 1 1]/8);
end


text:
Q: Android Java Record Video and embed Text I'm want to create a Android App that record video using Surface view. The app must record a video including an added TextView showing the Time and date like a watermark.
Tge only thing that I'm not sure is if it posible to record a SurfaceView and include in it both camera and Textview to make a video from it?


text:
Q: Redmine email notifications through Gmail I've upgraded from Redmine 1.3.2 to 2.4.2 when changing the server (moving to Ubuntu 14 from 12) and managed to restore my old database, so I'm now having all my data back. But I still can't get email notifications to work. After looking around quite a bit I can't find any pointers.
When I send a test mail form Redmine's settings page I get the message:
Erreur lors de l'envoi de l'email (SSL_connect returned=1 errno=0 state=unknown state: unknown protocol)

The configuration.yml looks fine as far as I can tell from what I've read on multiple sources (I checked and there's no tab in it):
default:
  # Outgoing emails configuration (see examples above)
  email_delivery:
    delivery_method: :smtp
    smtp_settings:
      enable_starttls_auto: true
      openssl_verify_mode: 'none'
      address: "smtp.gmail.com"
      port: 587
      domain: "smtp.gmail.com"
      authentication: :plain
      user_name: "xxxxxx@yyyyyy"
      password: "password"

Whether I use "default" or "production" block makes no difference, same with "openssl_verify_mode" whether present or not (and I do the restart the apache2 service each time).
Redmine log file (production.log) is not helping much even with
log_level= :debug

as it doesn't show what's actually wrong with sending the mail (it shows the mail content but that's it).
Like on many posts asking about this my setting was fine with Redmine 1.3.
From what I read Redmine uses Action mailer so there's no need to install and setup any mail server (mail, postfix, etc), right?
As I'm going in loops (again), I'd be grateful to get some pointers.
Thanks,

A: Here is another article saying gmail and other webmail get blocked... https://www.mailjet.com/blog/news/dmarc-gmail-changes/
There doesnt seem to be any simple Free email solutions documented for Redmine.  My easy solution to getting Redmine email to work is using a SMTP service provider such as Mailjet, Mailgun, Sendgrid, etc.  Some of these SMTP service providers offer their service for Free up to 12,000 Free emails/mo. or more.  All you have to do is sign up for one of these services, have SSH access to your Redmine setup, and edit the configuration.yml file at /opt/bitnami/apps/redmine/htdocs/config/ to reflect something like below. Using Mailjet as an example...
delivery_method: :smtp
smtp_settings:
  enable_starttls_auto: true
  address: "in-v3.mailjet.com"
  port: 587
  domain: 'enter your domain here'
  authentication: :plain
  user_name: 'enter your master api key here'
  password: 'enter your secret key here'

Save the configuration.yml file and restart redmine with "sudo /opt/bitnami/ctlscript.sh restart" without quotes.
Thats all!  Real easy.

A: Try this. Maybe it can help. Redmine 3.2.3-2
# default configuration options for all environments
default:
  # Outgoing emails configuration (see examples above)
  email_delivery:
    delivery_method: :smtp
    smtp_settings:

      address: smtp.gmail.com
      port: 587
      domain: smtp.gmail.com
      authentication: :login
      user_name: redmine@domain.com
      password: pass

A: I was able to get Redmine to login to Gmail to send Redmine Notifications, but those notifications stop at Gmail and never gets to the recipient.  This is evident as all notifications were recorded in my "Sent Mail" box but those emails never get to my separate Redmine Admin email account.  I believe Google closed ports 25, 465, and 587 for Apps so the solution then would be to use another email provider, service, or G Suite mail.  My conclusion is also based on information from Google Cloud https://cloud.google.com/compute/docs/tutorials/sending-mail/


text: Q: select latest version of document from document library i am converting word document in library to html document using event receiver it is working fine. but when i update the document and upload it.Event receiver code convert older document to html not my latest document .i am using SharePoint2010.


text:
Q: Point-set topology - derived sets, boundaries, etc.
Consider the metric space $(\mathbb R^2,\sigma)$, where $\sigma$ is the discrete metric. Let $$E=\lbrace(x,y)\in \mathbb R^2 : x^2+y^2<1 \rbrace$$ i.e. the unit disc. Find the following sets [note that $E'$ denotes the derived set, not the complement]:
i) $E^\circ$
ii) $E_{ext}$
iii) $\partial E$
iv) $E'$
v) $E_{isol}$

Since we are dealing with the discrete metric, the $\delta$-balls about an element $a$ are either the whole metric space [$\mathbb R^2$ in this case], or the singleton set $\lbrace a \rbrace$, depending on the $\delta$.
Thus it seems to me that any set where the logic includes "for all $\delta$" should be empty, while the sets that only mention "some $\delta$" should be as big as possible.
So for i), the points that can be contained in $E$ with a suitable $\delta$ should be the entire set $E$, since we can just pick a $\delta$ such that the ball around it is the singleton set.
Similarly for ii), this should be all points in $E^c$ [the complement], since there certainly exists a suitable $\delta$.
iii) I claim is $\emptyset$; given any point, there exists a $\delta$ where the $\delta$-ball around it is the point itself. So no point can intersect both $E$ and $E^c$ simultaneously for each $\delta$.
iv), I think, should also be $\emptyset$. Given any point we can pick a $\delta$ such that the ball is the point itself, meaning that not every ball will include other points of $E$.
v) is confusing to me, assuming I've got the others right. By what I've deduced earlier on my own, $E_{isol}=E \cap \partial E \implies E_{isol}=\emptyset$. But this is a contradiction, because taking an arbitrary point in $E$, there always exists a $\delta$ where the $\delta$-ball is the point itself. So $E_{isol}$ should be $E$.


text:
Q: Angular, Http Error blocks any further requests After an error-response from the server my app does not send any further requests.
I'm sending a request with:
getMachineRules(rules: Array<string>): Observable<RulesResults> {
    return this.http.post<RulesResults>('/rules', { nodes: rules })
      .pipe(
        catchError(this.handleError)
      );
  }

My  errorHandler:
  handleError(error) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${JSON.stringify(error.error)}`);
    }
    return throwError('Something bad happened; please try again later.');
  }

And my pipeline looks like this:
  ngAfterViewInit() {
    this.rulesChanged
      .pipe(
        startWith({}),
        switchMap(() => {
          this.isLoadingResults = true;
          return this.settings.getMachineRules(this.currentRules);
        }),
        map(data => {
          this.isLoadingResults = false;
          this.resultsLength = data.inputs?.length || 0;
          return data;
        }),
        catchError(e => {
          console.log("Error caught");
          this.isLoadingResults = false;
          this.resultsLength = 0;
          return observableOf({ inputs: [] } as RulesResults);
        })
      ).subscribe(
        data => { return this.updateRules(data); },
      );
  }

I can see the "Error caught" message in the console and the method updateRules() seems to work properly even in the error case.
However after a 404-Error-Response the ngAfterViewInit() method is
not called anymore. The UI steel reacts on interactions.

A: Once an Obsevable is failed there is nothing you could do to make it active again, catchError is used to handle errors by returning a new observable or throwing an error. observableOf({ inputs: [] } as RulesResults) is served as substitute in case the main stream fails, meaning your main Observable will never emit again.
Consider using retry at the end of your pipeline, or optionally have your
catchError return the source Observable itself, as demonstrated below:
catchError((error, source) => {
 ....
  return source;
})

Alternately put the catchError operator inside a switchMap so that only the inner stream will fail while the the outer (main) stream will remain active, as below:
ngAfterViewInit() {
  this.rulesChanged
    .pipe(
      startWith({}),
      switchMap(() => {
        this.isLoadingResults = true;
        return this.settings.getMachineRules(this.currentRules).pipe(
          map(data => {
            this.isLoadingResults = false;
            this.resultsLength = data.inputs?.length || 0;
            return data;
          }),
          catchError(e => {
            console.log("Error caught");
            this.isLoadingResults = false;
            this.resultsLength = 0;
            return observableOf({ inputs: [] } as RulesResults);
          })
        )
      })
    ).subscribe(
      data => { return this.updateRules(data); },
    );


text:
Q: Look at elements in an array I have two arrays of size 4,1,2
 array1  [[[   1.    2.]]
          [[   3.    4.]]
          [[   5.    6.]]
          [[   7.    8.]]]

 array2  [[[   8.    4.]]
          [[   7.    3.]]
          [[   6.    2.]]
          [[   5.    1.]]]

I need to put them into an array that looks like
 merged  [[[   1.    2.]]
          [[   3.    4.]]
          [[   5.    6.]]
          [[   7.    8.]]
          [[   8.    4.]]
          [[   7.    3.]]
          [[   6.    2.]]
          [[   5.    1.]]]

I then need to find the min and max of column1 and column2. I had this, but it does not appear to be doing what I think it should be.
mergedArray = concatenate((array1,array2),axis=1)

x_min = np.amin(mergedArray[:,0])
x_max = np.amax(mergedArray[:,0])
y_min = np.amin(mergedArray[:,1])
y_max = np.amax(mergedArray[:,1])

Is there a better way to do this?

A: I'd be tempted to remove the 'extra' dimension first, to keep the subsequent code simple.
Initialise the arrays:
>>> array1 = np.array([[[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]]])
>>> array2 = np.array([[[8, 4]], [[7, 3]], [[6, 2]], [[5, 1]]])

>>> array1
array([[[1, 2]],

       [[3, 4]],

       [[5, 6]],

       [[7, 8]]])

Simplify the arrays:
>>> array1b = array1[:,0,:]
>>> array2b = array2[:,0,:]

>>> array1b
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

Concatenation and min/max are now a little simpler:
>>> merged = np.concatenate((array1b, array2b))
>>> merged
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8],
       [8, 4],
       [7, 3],
       [6, 2],
       [5, 1]])

>>> np.amin(merged, axis=1)
array([1, 3, 5, 7, 4, 3, 2, 1])

Does this give you what you need?


text:
Q: combineReducers for better redux store naming Does it make sense to combineReducers simply to rename a key-value pair in the redux store? Something like this
const userReducer = combineReducers({
  login: loginReducer,
  session: sessionReducer,
});
const rootReducer = combineReducers({
  user: userReducer,
});

Accessing state.user using useSelector feels more intuitive.
Currenty, I have a login and session reducer for grabbing user information from a backend API and populating the store.
const rootReducer = combineReducers({
  login: loginReducer,
  session: sessionReducer,
});

However, I found myself accessing the user object returned by this react-redux hook
const { user } = useSelector((state: RootState) => ({
  user: state.session,
  // or user: state.login,
}));

my login and session reducers both return the same user data but different API calls are made to get this user data. If the user data looks the same, I was wondering if I could just combine the session and login reducers for a userReducer


text:
Q: SwipeView in Qt 5.10.0 Crashes when compiled with MSVC2017x64 I recently was asked to migrate my application from x32 to x64. Upon changing the compiler from MSVC 2015 x32 to MSVC 2017 x64, the application crashed as soon as it started. After some code commenting I've arrived at a minimal working example of the error code.
the main.cpp is like this:
#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

While my main.qml is like this:
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Window 2.2

Window {
    visible: true
    id: mainWindow

    SwipeView {

        id: swiperControl
        interactive: false
        anchors.fill: parent

        Item {
            Rectangle {
                width: 100
                height: 100
                color: "#ff0000"
            }
        }

    }

}

It seems to be the SwipeView what crashes the application. Any idea on how I can solve this issue without having to remove it? It is pretty integral to my application.
Commenting the Item makes the program work (it doesn't crash).

A: In case it helps anyone it is definitely a problem with the QML version used in Qt 5.10.0. I've upgraded to Qt 5.12.4 and now the problem is gone without changing any code.


text:
Q: Зачем запрещать переопределение виртуальных функций? Используя ключевое слово final мы можем запретить переопределение виртуальной функции в классах наследниках. Зачем тогда вообще делать функцию виртуальной?

A: Делать функцию виртуальной в родителе, и сразу final - нет смысла, да.
Ее можно сделать final в потомке, который ее переопределеяет, чтобы уже следующий потомок ее не трогал.

A: final имеет смысл использовать, чтобы

*

*в любых классах: запретить дальнейшее наследование

*в классах-наследниках: предоставить компилятору дополнительную возможность оптимизировать вызов виртуальной функции через указатель или ссылку на финальный класс-наследник


text:
Q: A group of order less than $60$ I'm given a theorem (call it Theorem 1) which states that $G$ is solvable iff there exists a chain of normal subgroups $\{e\} = G_0 \unlhd \ldots \unlhd G_n = G$ such that $G_i / G_{i-1}$ is abelian for $1 \le i \le n$. I am also given (call it Theorem 2) that $G$ is solvable iff it contains a normal subgroup $N$ such that $N$ and $G/N$ are also solvable. With these information, particularly Theorem 2, how do I go to show that a group of order less than $60$ is solvable?
I tried working with a group $G_i$, which is somewhere in the chain of normal subgroups. Since $G_i \unlhd G$, then $|G_i| < 60$. Also, $G_i$ contains a normal subgroup $G_{i-1}$, and $G_i / G_{i-1}$ is abelian, which means $G_i / G_{i-1}$ is also solvable. Is this sufficient to show that $G_i$ is solvable, which is what I want?

A: Step 1: If $\# G =2^n 3^m<60$ then $G$ is solvable. (Proof by induction)
Step 2: General case: Consider $p$ to be the maximum prime factor of $\# G$. If $p=3$ then this case is covered in Step 1. If $p\geq7$ then write $\# G = pk$ with $k<p$ then the number of Sylow p-subgroups of $G$ is 1, and we can go to the quotient and proceed by induction on the order of $G$.
If p = 7. The only case that we have more than one 7-Sylow subgroup is when $\# G=56$. In this case the number of 7-subgroups are 8 and so there are 48 elements of order 8 and hence there is one 2-Sylow subgroup, which is normal.
If p = 5. The only case that we have more than one 5-Sylow subgroup is when $\# G=30$. In this case there are six 5-Sylow subgroups so we have 24 elements of order 5. The remaining elements form a 3-Sylow subgroup, which is normal.
Source: Check a complete proof here.


text:
Q: Column / Text - Go to the next line I want to create a navigation menu with multiple columns / rows. And for the parent element i have a fixed height. How to make the columns / text that overflow the height goes on the next line ? see the visual representation below.

A: You can use columns property for auto column layouts.
columns: 4;

.container {
  columns: 4;
}

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

You can set width for columns if you want. How many columns fit with 300px, it puts that much. For example 4 columns fit on a 1200px screen.
columns: 300px auto;

.container {
  columns: 300px auto;
}

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

Title

Some Category

Some Category

Some Category

Some Category

Some Category

Some Category

You can find more information from MDN.


text:
Q: Advanced stylsheet in rails
I want to implement a similar design for my blog so for the first post I have do this in my view <%if @posts.first == post %> class="first-post" <%end%>now I want to differentiate the third 5 7 ... posts from the 2 4 .. posts how can I do that?

A: Edited for clarity and simplicity:
<% @posts.each_with_index do |p, index| %>

  <% position = index+1 %>

  <% if position == 1 then %>
    FIRST
  <% elsif (position.even?) then %>
    EVEN
  <% else %>
    ODD
  <% end %>

<% end %>

A: You can pop the first object out of the array:
post = @posts.pop

Then you can do what you like with it. Maybe render a partial. Then you can loop over the remaining posts. If you need granular control you can use array slice:
<% @posts.each_slice(2) do |slice| %>

    <% slice.each do |post| %>

        show item here

    <% end %>

<% end %>

This will split the array in groups of two, giving you more granular control over the layout.
Or, a suggested improvement to msanteler's answer:
<% @posts.each_with_index do |post, i| %>
  <% if i == 0 %>
    show stuff
  <% elsif i.even? %>
    show stuff
  <% else %>
    show stuff
  <% end %>
<% end %>


text:
Q: Determine all complex number z which satistfy the equation $|z + 1| = |z - i|$ I am trying to solve the aforementioned problem but have previously only worked with complex number inequalities where the resulting set is (the inside/outside of) a circle.
I am asked to determine all complex numbers z which satisfy the equation
$$|z + 1| = |z - i|$$
I have tried writing $z$ as $x + iy$ and grouping the real and imaginary parts together:
$|x + iy + 1| = |x + iy - i|$
but this just leads to
$|(x + 1) + i(y - 0)| = |(x + 0) + i(y - 1)|$
$\sqrt{(x + 1)^{2} + (y - 0)^{2}} = \sqrt{(x + 0)^{2} + (y - 1)^{2}}$
$(x + 1)^{2} + (y - 0)^{2} = (x + 0)^{2} + (y - 1)^{2}$
$x^2 + 2x + 1 + y^2 = x^2 + y^2 - 2y + 1$
$x + y = 0$

A: Let $z=x+iy$ with $x, y\,\in\,\bar{\mathbb{R}}$. We have:
$$|(x+1)+iy|=|x+i(y-1)|$$
So, using the definition of modulus:
$$\sqrt{(x+1)^2+y^2}=\sqrt{x^2+(y-1)^2}\implies x^2+2x+1+y^2=x^2+y^2-2y+1\implies 2x+1=-2y+1\implies x+y=0$$
Simply, we have a line that is the bisector of II and IV quadrant.
Also, there is a very nice geometrical interpretation, shown in this graph:

A: The points equidistant from two points in the plane - in this case, $-1,\,i$ - form a line perpendicular to the line segment joiing those points. Treating $\Bbb C$ as $\Bbb R^2$ in the usual way, the segmene is from $(-1,\,0)$ to $(0,\,1)$ with gradient $1$, so the desired locus is a line of gradient $-1$. Clearly $-1,\,0,\,i$ are the vertices of an isosceles right-angled triangle, so $0$ is on this new line. That gives it the equation $x+y=0$, no fiddling with square roots needed.


text:
Q: Certificate for SSL decryption policy on NGFW I am trying to understand SSL decryption before planning to implement it in the network.
For the SSL forward proxy, as I read we will be installing some CA certificate or similar on the NGFW in order to use it while intercepting the connection.
Now if I do so how can I avoid any error with certificate, even if I put the certificate in my trust store I might see the error.
For example to make you understand:
I have installed or created a certificate on my NGFW for SSL purpose, and have even installed in my end machine trust store but won't it cause error because parameter like Subject alternative name or else Subject name where we define common name will not match the domain/url we are trying to reach.
From my machine I am trying to reach let say "www.abc.com" or any other site. Here the certificate I am use might have different information under "Subject Name" and not the URL I am trying to visit. So this would lead to certificate error due to the field mismatch.
Just want to understand on SSL decryption in complete detail and how we handle certificate related issues.

A: The certificate provided by the SSL intercepting firewall is dynamically generated. It matches the expectation of the client, i.e. matches the expected hostname etc. The main difference compared to the original server certificate is that it is not issued by the original (publicly trusted) CA but by the CA on the firewall. Since this CA is trusted by the client and since the information in the certificate match the clients expectations, the certificate issued on the firewall will be trusted by the client.

A: I want to enhance Steffen Ullrich's answer by speaking a word of warning: You are effectively breaking the security of the end-to-end encryption. While this is the only way to allow the firewall to inspect the content and filter out possibly malicious content, it comes at a great cost:
You are deploying a working man-in-the-middle "attack" for all of your customers SSL connections. If your firewall ever gets compromised, all your SSL traffic is readable by the attacker, without your clients noticing it.


text:
Q: How to convert the whole html page in to an image with filled controls?
Here the difficulty is that i also need the texts that has been filled by the user in html controls.

It will be appreciative if HTML5 or JavaScript is used.

A: That sounds like fun!
I would look into something like flash.
Or you could post the form back to a server and process it on the sever side to send the image back.
Check out this answer:
Programatically create image from web-page or a single DIV
I can only assume you have access to PHP or something similar.


text:
Q: How to submit jquery jwysiwyg on enter I am using jquery rich text editor jwysiwyg  , i am able to submit the content on pressing enter key, by adding line
if(event.keyCode == 13) {
     jQuery('#submit_button_id').focus().click();

}

in function $(this.editorDoc).keyup(function (event)
Problem now is shift+ENTER key also submit the value , cursor is not going to new line.
Is there any way such that on pressing shift+ENTER goes to new line.
Thanks in advance.

A: I think you'll have to store whether shift is down in a variable. So in keydown you'll have (in pseudocode):
if(event.keyCode === KEYCODE_SHIFT) shiftDown = true;

and in keyup the opposite
if(event.keyCode === KEYCODE_SHIFT) shiftDown = false;

and then in keyup check:
if(event.keyCode === 13 && !shiftDown) {
    ...

EDIT
Actually, you can probably just use the event.shiftKey property:
if(!event.shiftKey && event.keyCode === 13) {
    ...


text:
Q: How to set label according to text but i want background color also How to set UILabel according to text but I want backGroundColor also in it, if text is small then it will display background small label with background color black and text and vice-versa.How to do?

In image the black background color came according to the  dynamic text. I want black background color till the text India.

A: for UILabel to fit all text use sizeToFit
[label sizeToFit];

If you want to have pic background make its size as the label size, take an imageview
imageView.frame = CGRectMake(0, 0, label.frame.size.width, label.frame.size.height);

or if want only background color of the label then use
[label setBackgroundColor:[UIColor blackColor]];

A: Try this
NSString *sample = @"...";
CGSize txtSz = [sample sizeWithFont:[UIFont fontWithName: @"Helvetica" size: 16]];
CGRect lblFrame = CGRectMake(10,50, txtSz.width, txtSz.height);
yourLabel.frame = lblFrame;
yourLabel.backgroundColor = [UIColor blackColor];

A: Calculate the width of the text and assign it to Label frame width.

A: this is am done in my app you must like did this
    label.text = @"Some text" ;

                        CGSize textSize = [label.text sizeWithFont:label.font];

                        backView.frame=CGRectMake(startPointX, startPointY, textSize.width, 1);

here you must create a new view on back of the label and that name is backview and set the frame of that view and then show it it work perfectly in my app :-)

A: The following code may be help you
        UILabel *biotitlelb = [[UILabel alloc]initWithFrame:CGRectMake(0,0,100,16)];
        [biotitlelb setTextColor:[UIColor whiteColor]];
        [biotitlelb setBackgroundColor:[UIColor blackColor]];
        biotitlelb.textAlignment = UITextAlignmentLeft;
        biotitlelb.font = [UIFont fontWithName:@"ArialMT" size:12];
        biotitlelb.text = @"sometext";
        CGSize textSize = [biotitlelb.text sizeWithFont:[UIFont fontWithName:@"ArialMT" size:12]];
        CGFloat strikeWidth = textSize.width;
        [biotitlelb setframe:CGRectMake(0,0,strikeWidth,16)];


text:
Q: Mismatch of return datatype i am facing a problem regrading specifying the return data type. I have the FOComp class which implements callabale, the call() method of the 'FOComp' returns data type List<ArrayList<Mat>> as shown in the code of 'FOComp' class below.
and the method 'getResults()' returns data of type ArrayList<Mat> as shown in the code below. and currently, at run time, when I execute the code, I receive the folowing error:
Multiple markers at this line

*

*The return type is incompatible with  Callable<ArrayList<Mat>>.call()

*The return type is incompatible with  Callable<List<Mat>>.call()
kindly please let me know how to fix it.
'FOComp' class:
    static class FOComp implements Callable<List<Mat>> {//should return list contains 4 mats(0,45,90,135)

    private ArrayList<Mat> gaussianMatList = null;
    private List<ArrayList<Mat>> results_4OrientAngles_List = null;

    public FOComp(ArrayList<Mat> gaussianMatList) {
        // TODO Auto-generated constructor stub
        this.gaussianMatList = gaussianMatList;
        this.results_4OrientAngles_List = new ArrayList<ArrayList<Mat>>();
    }
    public List<ArrayList<Mat>> call() throws Exception {
        // TODO Auto-generated method stub
        try {
            featOrient = new FeatOrientation(this.gaussianMatList);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            featOrient.start();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        this.results_4OrientAngles_List.add(featOrient.getResults());

        return results_4OrientAngles_List;
    }
}

'getResults':
public ArrayList<Mat> getResults() {
    if (this.crossAddOrientMapsList != null) {
        if (!this.crossAddOrientMapsList.isEmpty()) {

            if (this.crossAddOrientMapsList.size() == 4) {
                double[] theta = new double[4];

                theta[0] = 0;
                theta[1] = 45;
                theta[2] = 90;
                theta[3] = 135;

                for (int i = 0; i < this.crossAddOrientMapsList.size(); i++) {
                    MatFactory.writeMat(FilePathUtils.newOutputPath("FinalCrossAdd_" + theta[i]+"_degs"), this.crossAddOrientMapsList.get(i));
                    //ImageUtils.showMat(this.crossAddOrientMapsList.get(i), "OrientMap_" + theta[i] + " degs");
                }

                return this.crossAddOrientMapsList;

            } else {

                Log.WTF(TAG, "getResults", "crossAddOrientMapsList != 4 !!");
                return null;
            }

        } else {
            Log.E(TAG, "getResults", "crossAddOrientMapsList is empty.");
            return null;
        }
    } else {
        Log.E(TAG, "getResults", "crossAddOrientMapsList is null");
        return null;
    }
}

A: class FOComp implements Callable<List<Mat>>

and
public List<ArrayList<Mat>> call()

aren't really compatible... Your call() method should be
@Override public List<Mat> call()

Also, it is good practice to avoid implementation classes in method signatures, use the interfaces instead (in this case, use List rather than ArrayList). That will also fix your problem with one of the "multiple markers" :-)
Cheers,

A: You class declaration says that you are going to return a List of Mat (FOComp implements Callable<List<Mat>>), but your call method signature says you are going to return a List of ArrayList of Mat (List<ArrayList<Mat>>).
You will need to make them consistent.


text:
Q: fill array from json file without knowing the keys I have the following Json file and I want to create list of array ,i don't know the keys name (like person ,lastname etc ) it can be
many entities like employes users etc but the structure of the file must be exactly the same ,how can i do that ?
the file is
{
    "Person": [
        {
            "name": "Peter",
            "lastname": "ta",
            "age": 43,
            "sex": "male"
        },
        {
            "name": "Zara",
            "lastname": "treg",
            "age": 25,
            "sex": "female"
        }
    ]
}

what I need is to create list of array like this
person ,name,peter ,lastname,ta,age,43,sex,male
person ,name,zara ,lastname,treg,age,23,sex,female

....
I started with the following code to get the file but since i dont know the name of the keys I dont know how to proceed.
JSONObject jsonObject= (JSONObject) parser.parse(new FileReader("C:\\General\\jsonperson.txt"));

A: You can use
String[] keyNames= JSONObject.getNames(jsonObject);

to get the names of the keys.
Javadoc
Using this, you can get the values using getJSONObject
Looping these you can construct the array you are looking for.

A: Check Example 4 on this page: https://code.google.com/p/json-simple/wiki/DecodingExamples
Specifically, this part:
Map json = (Map)parser.parse(jsonText, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
while(iter.hasNext()){
  Map.Entry entry = (Map.Entry)iter.next();
  System.out.println(entry.getKey() + "=>" + entry.getValue());
}

System.out.println("==toJSONString()==");
System.out.println(JSONValue.toJSONString(json));

That's how you might iterate over the entries of a JSONObject. By the way, with this library, if it's the one I think you're using, a JSONObject is just a java.util.Map, and you can use all of its methods - that's why it works for this example to cast the parse result to a Map.
All of the JSON <-> Java object mappings for this lib: https://code.google.com/p/json-simple/wiki/MappingBetweenJSONAndJavaEntities

A: You can also try the below code:
public void performExecute() throws IOException {
        JsonFactory jsonFactory = new JsonFactory();
        ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
        File file = new File("json.txt");
        TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {};
        HashMap<String, Object> jsonMap = objectMapper.readValue(file, typeReference);
        System.out.println("JSON DATA: " + jsonMap);
    }

Make sure the Jackson library is in your class path & you imports the following classes while using the code:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;


text:
Q: How can I increase the size of the console inside the code I'm doing some code in pascal using lazarus IDE v1.8.4, as the question says I need to be able to edit the console size in the code, I also preferably need to get the max possible console width they can have. If you do know how please also let me know the uses you.. used. Thanks!

A: Assuming you're targeting Windows:

*

*Use GetLargestConsoleWindowSize to retrieve the largest possible console size depending on the console font and display settings,

*Use SetConsoleScreenBufferSize to set the console screen buffer to the largest possible size,

*Use SetConsoleWindowInfo to set the size and position of the console's window, so that no scrollbars would be visible by default etc..
At this point the console's window should be positioned as you've set. With my tests, however, while the window complies with the sizing request, the position is ignored.
In that case use any API function to move the window, the below examples uses SetWindowPos. I had to declare GetConsoleWindow as it was not declared in Lazarus 1.6.

program Project1;

{$APPTYPE CONSOLE}

uses
  windows;

function GetConsoleWindow: HWND; stdcall external 'kernel32';

var
  Con: THandle;
  Size: TCoord;
  Rect: TSmallRect;
  Wnd: HWND;
begin
  Con := GetStdHandle(STD_OUTPUT_HANDLE);
  Size := GetLargestConsoleWindowSize(Con);

  SetConsoleScreenBufferSize(Con, Size);

  Rect.Left := -10;
  Rect.Top := -10;
  Rect.Right := Size.X - 11;
  Rect.Bottom := Size.Y - 11;
  SetConsoleWindowInfo(Con, True, Rect);

  Wnd := GetConsoleWindow;
  SetWindowPos(Wnd, 0, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOZORDER);

  Readln;
end.

And don't forget to add error checking.

A: This seems to work fine in Lazarus for me on Win10Pro.
program ResizeConsoleWin;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Windows;

procedure SetConsoleWindowSize;
var
  Rect: TSmallRect;
  Coord: TCoord;
begin
  Rect.Left := 1;
  Rect.Top := 1;
  Rect.Right := 300;  // notice horiz scroll bar once the following executes
  Rect.Bottom := 30;
  Coord.X := Rect.Right + 1 - Rect.Left;
  Coord.y := Rect.Bottom + 1 - Rect.Top;
  SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), Coord);
  SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), True, Rect);
end;

begin
  SetConsoleWindowSize;
  readln;
end.

It's copied from this answer with only the window dimensions changed.


text:
Q: Calculation in Tableau gives wrong result I have a calculation to make
For each club and Operator I want to create Revenues with the following formula
Revenue = successfulbillinghits * pricePerBilling * Rate * Multiple Factor

Components are:

*

*Successfulbillinghits = Number of billings for a customer

*PricePerBilling = Price of per billing (Keep changing)

*Currency Exchange Rate = Currency Rate from local currency to dollar (Keep changing)

*Multiple Factor = Constant for each club and operator
I have tried:
Revenue = SUM([successfulbillinghits])*ATTR([pricePerBilling])*AVG([Rate])*ATTR([Multiple Factor])

Result:
Successfulbillinghits is fine (Gives sensible result)
Multiple factor is fine (Gives sensible result)
Problem is with the following where it gives *
PricePerBilling
Currency Exchange Rate
What I want:
I want each PricePerBilling and exchange rate of the row! e.g. if there are 10 rows and there are 3 different price billings and 10 different exchange rates, i want tableau to check the 10 individual rows and get the corresponding exchange rate and the billing rate.
Using tableau desktop
Here is the sample (Column names are shortened)
Op  Cl  billinghits Price/Billing Ex-Rate   MultipleFactor  Revenue
1   2   5           2             0.27      1               2.7
1   2   6           2.5           0.27      1               4.05
1   2   3           2.5           0.28      1               2.1
1   2   4           2             0.27      1               2.16
                                                     Total: 11.01

Result should look like:
  Operatpr  Club    Revenue
    1        2       11.01

A: In this case, you should calculate revenue as a new column, and for each row compute the following formula, without any aggregation.
Revenue = [successfulbillinghits] * [pricePerBilling] * [Rate] * [Multiple Factor]

And then you can plot Operatpr, Club, and SUM(Revenue), which will automatically aggregate (group by) Operatpr and Club and print the sum of the revenue per group.

A: create a calculated field as
{fixed [Cl],[Op] : SUM(([Billingnights][Ex-Rate][MultipleFactor]*[Price/Billing]))}. Name it Revenue
and Drag this Op, Cl and Revenue to the view.


text:
Q: how to display 2 tables from mysql in visual studio 17 this is in my controller
 string connStr = "server=" + IpAddress + ";user=" + UserName + ";database=" + DatabaseName + ";port=" + PortNumber + ";password=" + Password + ";SslMode=none;";
 MySqlConnection conn = new MySqlConnection(connStr);
 conn.Open();
 string query = " select * from Cities,Regions";
 MySqlCommand com = new MySqlCommand(query, conn);

 MySqlDataAdapter da = new MySqlDataAdapter(com);
 DataTable ds = new DataTable();
 da.Fill(ds);
 conn.Close();

I use a view model for displaying data from mysql and i fill them as below.
 List<Models.ViewModels.city> CT = new List<Models.ViewModels.city>();
 SftpClient sftpclient = new SftpClient("port", "root", "name");
 sftpclient.Connect();

 foreach (DataRow item in ds.Rows)
 {
     city ct = new city
     {
         CityName = item.itemArray[1].ToString(),
         CityNumber = Convert.ToInt32(item.itemArray[2])
     }
     region rg = new region
     {
         RegionName = item.itemArray[1].ToString(),
         RegionNumber = Convert.ToInt32(item.itemArray[2])
     }
 }
 CT.Add(ct);
 return View(CT.ToList());

How  could i show regions in my razor. i already used viewbag for sending a list form my region viewmodel. but it doesn't fill the viewmodel obviously but how should i fill the region viewmodel


text:
Q: "peeked over the balcony," "peeked out the balcony," or "peeked out of the balcony"? What's the correct construction? Say, you're inside the house and are peeking to see what's in the balcony?
Example sentence:

Faking courage, I peeked over/out/out of the balcony.

A: The three examples in your title all mean that you are on the balcony and looking somewhere else from there. I think that what you mean to say is

Faking courage, I peeked out (of the house) onto the balcony

or even

Faking courage, I peeked into the balcony

if it's more of an enclosed space and almost like a room.


text:
Q: Actionscript 3 - Parsing an XML file to load assets I'm fairly new to file loading in Flash and while i'm used to the ease and comfort of C#'s serialization for xml file, i'm completely lost with how I need to approach this in Flash. I have two types of xml files I need to be able to load and I was hoping you could help me set up my code properly!
Lets start with the first xml file. It will look something like this (with more Level elements in later on):
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Level>
    <filepath>../Assets/Level.xml</filepath>
  </Level>
</Root>

And the code to load it is below
public function loadLevelFilePaths():void
{
    trace("Loading XML");
    var XMLData:XML = new XML(new URLRequest("../Assets/LevelFilePaths.xml"));

    for each (var node:XML in XMLData.Level)
    {
        levelFilePaths.push(node.filepath.text());
        trace("Level " + levelFilePaths[levelFilePaths.length - 1] + " loaded!");
    }
}

The second type of XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Level xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <level>
    <Room>
      <tiles />
      <IsEmpty>true</IsEmpty>
    </Room>
  </level>
</Level>

For the sake of space, I didn't include the largest possible room, but the tiles node could contain up to about 100 "Tiles" each with their own set of data and there could be up to 100 Rooms inside of this level.
I haven't yet written the code to load this because I don't quite understand how to load the simple xml file I posted above.
If someone would be willing to also explain how this process works in Flash, I would also be grateful!

A: To load an xml file, you can use a URLLoader to load the data as a String, then pass that to the XML constructor.
Note that it's typically a good idea to put a try/catch around new XML in order to catch malformed xml.
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;

var urlLoader:URLLoader = new URLLoader(new URLRequest("LevelFilePaths.xml"));

urlLoader.addEventListener(Event.COMPLETE, dataLoadCompleteHandler);

function dataLoadCompleteHandler(event:Event) {
    var urlLoader:URLLoader = URLLoader(event.currentTarget);

    var xml:XML;
    try {
            // urlLoader.data contains the file contents as a String.
        xml = new XML(urlLoader.data);
    } catch (e:Error) {
        trace("The xml was malformed.");
    }

    if (xml) {
        trace("XML Loaded");
        for each (var level in xml.level) {
            for each (var room in level.Room) {
                trace("Room: " + room.toXMLString());
                trace("is empty: " + room.IsEmpty.text());
            }
        }
    }
}


text:
Q: Way to choose a "default" navbar of a Bootstrap Material theme? I'm using the Bootstrap Material Design Template for a website. It has three different colored navbars of which I want to use the last one. But I'm unsure how to use that last one. Do I need to manually change the color of the navbar, or can I change one thing somewhere so that the color of all the buttons and radio buttons also changes?
I found a piece on the github page which points out how to change the primary color to a cusom one. But I don't want that, I simply want to use the blue color which you see in the third navbar option here.
Any ideas how I can do that? All tips are welcome!

A: Actually you just have to use different classes for change in colors, by default a Bootstrap theme have navbar-default and navbar-inverse
But in the very theme you're using have a class called navbar-material-light-blue-300 which needs to be added in following manner.

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-material-light-blue-collapse">

              </button>
              Brand

Active

Link

                  Dropdown

Action

Another action

Something else here

Dropdown header

Separated link

One more separated link

              <form class="navbar-form navbar-left">
                <input type="text" class="form-control col-lg-8" placeholder="Search">
              </form>

Link

                  Dropdown

Action

Another action

Something else here

Separated link

Happy Coding :)

A: .navbar-inverse is the class that affecting its color.

  ....

Other two above than the third have .navbar-default and .navbar-warning classes respectively.
Use below code:

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">

    </button>
    Brand

Active

Link

        Dropdown

Action

Another action

Something else here

Dropdown header

Separated link

One more separated link

    <form class="navbar-form navbar-left">
      <input class="form-control col-lg-8" placeholder="Search" type="text">
    </form>

Link

        Dropdown

Action

Another action

Something else here

Separated link


text:
Q: XSLT Logic for each Below is the input. In the Loop-1,2,3 elements are unbounded. If we use for each loop  in the transformation we will get output as like A A,B B,C C. But I want the output to be same like as input.
Please see below output.
input:
<LOOP-1><!-- unbounded -->
<element1>A</element1>
<LOOP-1>

<LOOP-2><!-- unbounded -->
<element2>B</element2>
<LOOP-2>

<LOOP-3><!-- unbounded -->
<element3>C</element3>
<LOOP-3>

<LOOP-1>
<element1> A</element1>
<LOOP-1>

<LOOP-2>
<element2>B</element2>
<LOOP-2>

<LOOP-3>
<element3>C</element3>
<LOOP-3>

for the above input if we put for each we will get the out put as like
A
A
B
B
C
C

but i want the below output.how we can achieve this.the solution should be generic.appreciate your help.
output
<LOOP-1>
<element1>A</element1>
<LOOP-1>

<LOOP-2>
<element2>B</element2>
<LOOP-2>

<LOOP-3>
<element3>C</element3>
<LOOP-3>

<LOOP-1>
<element1> A</element1>
<LOOP-1>

<LOOP-2>
<element2>B</element2>
<LOOP-2>

<LOOP-3>
<element3>C</element3>
<LOOP-3>

XSLT:
<xsl:for-each select="LOOP-1">
  <xsl:element1>
    <xsl:value-of select="element1"/>
  </xsl:element1>
</xsl:for-each>

<xsl:for-each select="LOOP-2">
  <xsl:element2>
    <xsl:value-of select="element2"/>
  </xsl:element2>
</xsl:for-each>

<xsl:for-each select="LOOP-3">
  <xsl:element3>
    <xsl:value-of select="element3"/>
  </xsl:element3>
</xsl:for-each>

A: <xsl:for-each> is not necessary, and makes things more complicated and difficult in this instance.
If you simply want to produce an exact copy of the source XML in your output, then you can use <xsl:copy-of>:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>

<xsl:template match="/">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

Another option is to use an identity transform:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

The advantage of the identity transform is that if/when you do want to customize the output and transform any of the content, you can simply add a template to match that node or attribute to handle that special case.
For instance, if you wanted to produce different output for the second B, you could add this template:
<xsl:template match="LOOP-2[2]/element2[.='B']">
    <xsl:copy>
        <xsl:text>This is a special case for the second LOOP-2/element2 who's text() equals 'B'</xsl:text>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>


text:
Q: Is this normal bluebird/node.js/express error handling? So, I made this dumb typo and it took me quite some time to find it, because I always got an empty error from an executed mongoose query. I recreated the behavior to be a little more generic.
var express = require('express');
var router = express.Router();
var Promise = require('Bluebird');

router.patch('/test', function (req, res, next){
    var testPromise = new Promise(function (resolve, reject) { resolve(); })
    .then(function(result){

        if(thisIsAnExampleTypo){}

        res.status(200).json({
            message: 'this will no be executed because of the typo',
            object: result
        });
    })
    .catch(function(err){
        //console.log(err);
        return res.status(500).json({
            title: 'This will execute because of the typo in the then-function',
            error: {message: 'but it will also crash the node.js server if I log the error before this return statement'}
        });
    });
});

The code above will not crash the server but will execute the catch-function. If I uncomment the console.log(err); line it will crash the node server, which makes no sense to me. Also, it will only crash if I log the err, if I make it console.log('test'); it will continue running.
I'm on Node.js v8.1.4, "express": "~4.14.0" and "bluebird": "^3.5.0".
Thanks in advance for any explanation/advice/help, it is not really a problem to me anymore, but this behavior really bugged me and I did not know where I should report this.


text:
Q: Mock an attribute within an HttpServlet through the WebApplicationContext Suppose I have an HttpServlet with an attribute (MyAttribute). I want to replace the latter with a mock, after the servlet has been initialized.
I'm instantiating my attribute in the overridden MyServlet.init() method like this:
WebApplicationContext wac = getWebApplicationContext();
this.myAttribute = (MyAttribute) wac.getBean("myAttribute");

Now, in my unit test all I got is a WebApplicationContext object.1
I planned mocking the attribute like this:
MyServlet myServlet = (MyServlet) WebApplicationContext.getServletContext().getServlet("myServlet");
myServlet.setMyAttribute(EasyMock.createStrictMock(MyAttribute.class));

Unfortunately, the ServletContext().getServlet() method is deprecated, currently returns always null and will be permanently removed in future versions. Hence my question:
How to mock an attribute of an HttpServlet through a WebApplicationContext?
1: This is due to my unit test starting a Tomcat'ish Server instance in an own thread returning me the WebApplicationContext of my application after it's up and running.


text:
Q: Why intensity of light reaching the sensor or film with a particular lens directly proportional to $\frac{D^2}{f^2}$? The following is quoted from my book:
"The intensity of light reaching the sensor or film is proportional to the area viewed by the camera lens and to the effective area of the lens. The size of the area that the lens "sees" is proportional to the square of the angle of view of the lens, and so is roughly proportional to $\frac{1}{f^2}$. The effective area of the lens is controlled by means of an adjustable lens aperture, or diaphragm, a nearly circular hole with variable diameter $D$; hence the effective area is propor tional to $D^2$. Putting these factors together, we see that the intensity of light reaching the sensor or film with a particular lens is proportional to $\frac{D^2}{f^2}$."
My question is how did they conclude that the area that the lens "sees" is roughly proportional to the square of angle of view of the lens and $\frac{1}{f^2}$ and how is the effective area proportional to $D^2$? Ultimately, my question is how is the intensity of light proportional to $\frac{D^2}{f^2}$? Can someone please explain? I did not understand what the paragraph explained. Please help.

A: The first term, proportional to $D^2$, is rather simple: The larger your lens aperture, i.e. the larger the area that collects light, the more photons you get.
The second term is a bit misleading. Actually, the smaller the focal length $f$, the larger the angle of view $\alpha$ that the camera sees, both in the horizontal and vertical:
$$
\alpha = 2 \cdot \arctan \left(\frac{d}{2 f} \right)
$$
(see https://en.wikipedia.org/wiki/Angle_of_view). $d$ is either the width or height of your camera chip, $\alpha$ the corresponding angle (so there is $\alpha_w$ and $\alpha_h$).
The width of the observed scene is proportional to $\tan(\alpha_w)$, the height is proportional to $\tan(\alpha_h)$. Thus according to the equation above you see that both width and height are proportional to $\frac{1}{f}$. The total amount of photons your camera collects is of course proportional to the image area, therefore to the product of width and height and thus proportional to $\frac{1}{f^2}$.

A: Since we are talking about a camera, it's more appropriate to talk about the illumination of an image which translates to the amount of light per unit area of the image. The dependence on D$^2$ is straightforward as that is proportional to the area of the lens aperture.
The magnification due to the camera lens is given approximately by the image distance divided by the object distance. For a far away object, the image distance is approximately equal to f. So the linear extent of the image depends on f and the area of the image depends on f$^2$. The smaller the area, the more concentrated is the light on the image.
So the image brightness depends, for a distant object, on D$^2$/f$^2$. This is just the inverse of the f/number and as we know the smaller the f/number (hence the larger D$^2$/f$^2$), the brighter the image.


text:
Q: Prevent direct manipulation of html5 input number field I created an html5 input number field as follows:
<input type="number" min="1" max="51" value="1"/>

Now I want the user to be able to cycle through the numbers using the up and down arrow buttons. However I don't want the user to be able to directly enter a new number in the field. How do I do this?
I tried setting readonly="true", but as expected, that also disabled the user's ability to cycle through the numbers using the up and down arrow buttons.

A: You can try with
<input type="number" min="1" max="51" value="1" onkeydown="return false"; />

but you have to check the value on server side, anyway!

A: You can call preventDefault on keypress unless it's the arrow keys:
var numInput = document.getElementsByTagName('input')[0];

numInput.addEventListener('keypress', function (event) {
    if (event.keyCode !== 38 && event.keyCode !== 40) {
      event.preventDefault();
    }
});

Here's the jsfiddle to demonstrate. If you don't care about the arrow keys on the keyboard, then you can omit that part of the check and just preventDefault on any keypress.

A: event.preventDefault is a costly operation compared to return so jsbin_example
<input type="number" min="1" max="51" value="1"/>

      $("input").on("keydown",function update(event)
{
   var keyCod,
   srcObj = event.src||event.originalTarget||event.target;
   if(event.keycode || event.which)
      {
         keyCod = event.keycode || event.which;
      }
      else
     {
        keyCod = event;
     }
     if(!(keyCod  == 38 || keyCod  == 40))
     {
         return false;

      }
  console.log('after false');
      if(keyCod == 38)
      {
         srcObj.value = parseInt(srcObj.value)+1;
      }
      if(keyCod == 40)
      {
         srcObj.value = parseInt(srcObj.value)-1;
      }
});


text:
Q: Setting Toolbar in a fragment I have a toolbar in my fragment that I need to set the activity's action bar, however, I get null whenever I call getSupportActionBar() method, anyone can help?
My activity:
public class MainActivity1 extends AppCompatActivity {

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

    Fragment fragment = new HomeFragment();
    FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction().replace(R.id.main, fragment).commit();

  }

}

Style.xml the activity is using the AppTheme.NoActionBar theme
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

Fragment code:
public class HomeFragment extends Fragment {

DrawerLayout drawer;
Toolbar toolbar;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    setupToolbar();

    return view;
}

public void setupToolbar() {
    Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
    ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
    if (actionBar != null) {
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
  }
}

 ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); this line in the fragment will always return null.