text:
Q: Layout error due to ListView and PageView Widget build(BuildContext context) {
    super.build(context);

    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      ),
      child: Scaffold(
          key: _scaffoldKeyProfilePage,
          backgroundColor: Colors.white,
          body: user == null
      ? Center(
          child: CircularProgressIndicator(),
        )
      : RefreshIndicator(
          onRefresh: _onRefresh,
          child: ListView(
              shrinkWrap: true,
              padding: EdgeInsets.all(0),

                  children: [
                    BuildMainProfile(
           ....//build profile (with heiht = ScreenHeight/1.4)
          ),

                    Container(
                   ...//to build bio section
                    ),

                    Flexible(
                            child: PageView(

            children: [
              ListView.builder(

                        shrinkWrap: true,
                          itemCount: 30,
                          itemBuilder: (BuildContext context, int index) {
                          return Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Container(color: index%2==0?Colors.red:Colors.green,height: 30.0,width: double.infinity,),
                          );
                         },
                        ),
           Container(height: 400,width: 200,color: Colors.green,),
            Container(height: 400,width: 200,color: Colors.blue,),
             Container(height: 400,width: 200,color: Colors.pink,)
            ],
                  ),
                    )
                  ],
                ),
        ),
        ),
    );

I am getting an error saying :

The ParentDataWidget Flexible(flex: 1) wants to apply ParentData of
type FlexParentData to a I/flutter ( 9926): RenderObject, which has
been set up to accept ParentData of incompatible type ParentData.
I/flutter ( 9926): Usually, this means that the Flexible widget has
the wrong ancestor RenderObjectWidget. Typically, I/flutter ( 9926):
Flexible widgets are placed directly inside Flex widgets. I/flutter (
9926): The offending Flexible is currently placed inside a
RepaintBoundary widget. .... Another exception was
thrown: Horizontal viewport was given unbounded height. I/flutter (
9926): Another exception was thrown: RenderBox was not laid out:
RenderViewport#4dd2b NEEDS-LAYOUT NEEDS-PAINT
NEEDS-COMPOSITING-BITS-UPDATE I/flutter ( 9926): Another exception was
thrown: RenderBox was not laid out: RenderViewport#4dd2b NEEDS-PAINT
NEEDS-COMPOSITING-BITS-UPDATE

How can this error be removed, I have even used Flexible over PageView and shrinkWrap in listView.

A: You cannot directly use Flexible in ListView. Maybe you must try something like this
return DefaultTabController(
  length: 3,
  child: Scaffold(
    appBar: AppBar(
      title: Text(Translator.of(context).translate("ratingsandreviews"),),
      bottom: TabBar(
        indicator: UnderlineTabIndicator(),
        tabs: <Widget>[
          Tab(child: Icon(Icons.grid_on_outlined),),
          Tab(child: Icon(Icons.timeline),),
          Tab(child: Icon(Icons.account_box),),
        ],
      ),
    ),
    body: TabBarView(
      children: <Widget>[
        ListView(
          children: [
            BuildMainProfile(),
            Container(
              //to build bio section
            ),
            Expanded(
              child: GridView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: POSTLIST.length,
                itemBuilder: (context, index) {
                  return Container(); // or what you want
                },
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  childAspectRatio: 1.0,
                ),
              ),
            ),
          ],
        ),
        SecondPage(), // second page
        ThirdPage(), // third page
        Fourth(), // fourth page
        // RideSharingReviewsPage(),
      ],
    ),
  ),
);

A: PageView(
        children: [HomeScreen(), XodimlarScreen(), SizedBox(
            height: MediaQuery.of(context).size.height,
            child: DavomatScreen()),HomeScreen(),],
        controller: _pageControllerrr,

       // physics: BouncingScrollPhysics(),
        onPageChanged: (page) {

            index = page;

        },
      ),


text:
Q: How to map number specific color from gradient Let's say I have a div with a smooth linear gradient (left to right) background from green to red and given a number between 0 and 1 I want to know the specific color that percentage from the left.
Ie 0 would map to green and 1 would map to red. .5 would map to the reddish greenish middle etc. so the return of such a function would be the color representation (e.g hex, rgba).
I'm not sure how to get the color of a specific spot of the background within a div. if I could figure that out I think I'd be ok.

A: If you could convert Hex into integers for the number I think you should be able to get the average number between 2 colors.
Assuming you already have the color codes
Green: #33FF33
Red: #FF0000
function ConvertToInt(colorHex){
    if(colorHex.length != 6){return 0;}
    var R = colorHex.substring(0,2);
    var G = colorHex.substring(2,4);
    var B = colorHex.substring(4,6);

    return [parseInt(R,16),parseInt(G,16),parseInt(B,16)];
}

Then call this function for both of your colors giving you an array of ints.
function GetColorAtPos(color1,color2,position){
    color1Multiplier = position;
    color2Multiplier = 1-position;
    finalRGB = [];
    for(i =0;i<=2;i++){
        finalRGB.push(parseInt((color1[i] * color1Multiplier) + (color2[i] * color2Multiplier)))
    }
     return finalRGB
}

This should return the average color.
If you could post the background value you have for an element, I can post the selecting of colors.
This is how you would call it GetColorAtPos(ConvertToInt("FFFFFF"), ConvertToInt("000000"), .5)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Friend class accessing protected member only C++ class A;

class B {
private:
    int x = 3;
protected:
    int y = 4;
public:
    int k = 5;
};

I would like A to be able to access B's public and protected members, but not its private members.
I do not want A to derive from B.
-In my program, I have class A which manipulates class B. I have built a system using these two classes, and thus B should only be able to manipulate A's private variables through A's protected functions.
What is the most elegant way to do this? Is it good practice to lay expose the variables in such a way?

A: The only solution I can think of is to take advantage of the non-associativity of friends relationships. If you contain the private members of B in another class and make B its friend, it would work.
Here's an example of what I say.
class B{
    private:
        class private_of_B{
        private:
            friend class B;
            int x = 3;
        };
        private_of_B private_members;
        friend class A;

    protected:
        int y = 4;

    public:
        int k = 5;
};
class A{
    public:
        void f(B& b) const{
            cout << b.y << endl;
            // good
            cout << b.k << endl;
            // good
            cout << b.private_members.x << endl;
            // error
        }
};

Anyways, this workaround seems like bad design... maybe the best thing you can do is redesign your class architecture.
Also, you might find this question useful.

A: If you don't want to change B, you can create a sort of a proxy class:
class B {
private:
  int x = 3;
protected:
  int y = 4;
public:
  int k = 5;
};

class C : public B {
  friend class C_Proxy;
  // constructors...
};

class C_Proxy {
public:
  friend class A;
  C_Proxy(C& c) : y(c.y), k(c.k) { }
private:
  int& y;
  int& k;
}

(You can also arrange C_Proxy to handle proxying constant B's but that's not the focus of the question.)


text:
Q: How to click to specific coordinate of a page I need to click a link in a page with Selenium-webdriver , but i can't access the element using the value of href like below:
var link = WebDriver.FindElements(By.XPath("//a[@href='example.html']"));

because elements in the page is in a frame and in the source of another page. So I need to click to a specific coordinate where the link is. How can I make it by using selenium webdriver.

A: It sounds like what you need to be able to do is switch to a different frame then look in that frame for the element you want rather than using co-ordinates. the problem with co-ordinates is that if you run it on a different machine the co-ordinates could be different.
IWebElement frame = driver.FindElement(By.CssSelector("xxx"));
driver.SwitchTo().Frame(frame);

then search for your element as normal. then once you are done call
driver.SwitchTo().DefaultContent();

and you will be back to the original page.

A: You can do that through the Actions class.
Actions builder = new Actions(driver);
builder.MoveByOffset(x, y).Click().Perform();

Or alternatively via JavascriptExecutor, just pass to it JS code needed to move to the link and click it.


text:
Q: line gets thick when scaling I draw a line in Android canvas with the thickness of 1 (paint.setStrokeWidth(1)). When scaling the canvas with canvas.scale(2,2), then the line gets thicker. How can I draw the line only one pixel thick, even if I am scaling in (e.g. zooming in)?

A: Set the width for stroking.
Pass 0 to stroke in hairline mode. Hairlines always draws a single pixel independent of the canva's matrix.

A: If you are using the Paint objects setStrokeWidth-method you can use the value 0 to draw a single-pixel line.
From the API docs:

Set the width for stroking. Pass 0 to stroke in hairline mode.
  Hairlines always draws a single pixel independent of the canva's
  matrix.


text:
Q: Unamanged memory struct i'm pretty confused.
I've these structs.
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 4 + 64 * 3)]
public struct MapBlock
{
    public readonly uint Header;
    public unsafe MapCells* Cells;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MapCells
{
    public ushort TileID;
    public sbyte Z;
}

the "MapCells" param into MapBlock is an array of 64 MapCells.
I've to access to a specific index of a mapcell and to do this i'm doing:
 MapBlock* mp = (MapBlock*) blockIndex.MapAddress;
 MapCells* cells = (MapCells*) &mp->Cells;
 var z = cells[my * 8 + mx].Z;

That's works.
Why if i try to do this, it doesnt work?
MapBlock* mp = (MapBlock*) blockIndex.MapAddress;
MapCells* cells = &mp->Cells[0];
var z = cells[my * 8 + mx].Z;

I don't want use marshalling.
EDIT:
Error message: memory access violation


text:
Q: Find $c$ if $a,b, \; c$ satisfy $c = (a+bi)^3 - 107i$
Find $c$ if $a,b, \; c$ are positive integers which satisfy $c = (a+bi)^3 - 107i$

I can try expanding the cube, but that seems too direct. What other ways are there to go about this?

A: Since $c \in \mathbb Z$, the right-hand side must have an imaginary component of $0$. Expanding, we get
$$c = (a+bi)^3 - 107i = (a^3-3ab^2) + (3a^2b-b^3-107)i$$
Therefore $3a^2b-b^3-107 = 0$, which implies that $(3a^2-b^2)b=107$. Since $107$ is prime, we conclude that $b$ is either $1$ or $107$.
Case 1: $b=1$. Then $3a^2 -1 = 107$, so $a=6$.
Case 2: $b=107$. Then $3a^2 - 107^2 = 1$. But there is no integer solution to this equation.
Therefore the unique solution is $(a,b,c) = (6,1,198)$.

A: $$\Im((a+bi)^3-107i)=3a^2b-b^3-107=0,$$
$$(3a^2-b^2)b=107.$$
$107$ is a prime, so $b=1\lor b=107$.
$$b=1\implies a=6,$$
$$b=107\implies 3a^2=11450\text{ (reject)}.$$
$$c=(a+bi)^3-107i=198.$$


text:
Q: Customize toolbar's menu items
I have this in my toolbar, the text comes from toolbar's xml layout, while the magnifier icon comes from menu.xml for the page,
I have set android:layout_alignParentRight="true" to this 'change city' RelativeLayout but still there is too much space between magnifier and Change city,
How will I be able to remove this gap?
<RelativeLayout
        android:id="@+id/location_change_RL"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@+id/logo_icon">

menu.xml
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.discover.fitternity.activities.HomeScreenActivity">

    <item
        android:id="@+id/search"
        android:icon="@drawable/search"
        android:menuCategory="secondary"
        android:orderInCategory="2"
        android:title="@string/fitternity_search"
        app:showAsAction="ifRoom" />
</menu>

A: I don't know if this is advisable or not but it does the trick for me several time. Try for yourself once.
Add this to your relative layout.
android:layout_marginRight="-20dp"

Change 20 to whatever dimension fits for you.


text:
Q: Folder Dialog Box in C# I want to show "Folder Dialog Box" in C#/JavaScript, using which user can select their local system directories and not the server directories.
I have already tried with the below code, but it is retrieving me the server directories.
string[] objList = Directory.GetDirectories("D:");

A: Yep.
Drop a folder browser dialog onto your form and show it.
folderBrowserDialog1.ShowDialog();

Thanks


text:
Q: datetime subtract .net i want to get datetime for 2days before. i.e) how to subtract 2 days from datetime.now

A: or try:
DateTime.Now.Subtract(TimeSpan.FromDays(2));

A: I think you are just looking for:
DateTime.Now.AddDays(-2);

A: Yet another solution:
DateTime twoDays = DateTime.Now.Subtract(new TimeSpan(2,0,0,0));


text:
Q: longtable (and xltabular), enumerated list in cells and \@minipagetrue From egreg answer to this question, I have learned to redirect \@minipagetrue into table cells to get rid of the extra space above enumerate-environments (and itemize and description). However, if I try this trick in a longtable, it will not work. I can set the enumerate in a \parbox, but then I do not need the redirection. Here is an MWE (taken from the referred answer and modified).
Is this a feature, a bug or is it me misunderstanding (i.e. user error)?

\documentclass[fontsize=11pt]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{array, longtable}
\usepackage{enumitem}
\makeatletter
\newcolumntype{P}[1]{>{\@minipagetrue}p{#1}}
\makeatother

\begin{document}

\noindent\begin{tabular}{|P{0.2 \linewidth}|P{0.2 \linewidth}|}
\hline
lipsum &
\begin{itemize}[nosep, leftmargin=*]
\item A
\item B
\end{itemize}
lipsum \\
\hline
lipsum & lipsum\\
\hline
\end{tabular}

\bigskip

\begin{longtable}[l]{|P{0.2 \linewidth}|P{0.2 \linewidth}|}
\hline
lipsum &
\begin{itemize}[nosep, leftmargin=*]
\item A
\item B
\end{itemize}
lipsum \\
\hline
lipsum &
\parbox[t]{\linewidth}{\begin{itemize}[nosep, leftmargin=*]
\item A
\item B
\end{itemize}}
lipsum \\
\hline
lipsum & lipsum\\
\hline
\end{longtable}

\end{document}

A: I found that the problem noted in your question partly can be solved with following definition of column type:
\newcolumntype{M}[1]{>{\minipage{\hsize}\arraybackslash}p{#1}<{\endminipage}}

Interestingly is, that above column type definition doesn't work if you remove \arraybackslash from it. For test try the following MWE:
\documentclass[fontsize=11pt]{article}
\usepackage{array, longtable}
\usepackage{enumitem}
\newcolumntype{M}[1]{>{\minipage{\hsize}\arraybackslash}p{#1}<{\endminipage}}
\makeatletter
\newcolumntype{P}[1]{>{\@minipagetrue}p{#1}} %this not work as expected :-(
\makeatother

\begin{document}

\begingroup
    \centering
    \setlist[itemize]{nosep, leftmargin=*}
\begin{tabular}{|P{0.2\linewidth}|P{0.2\linewidth}|}
    \hline
lipsum  &   \begin{itemize}
        \item A
        \item B
            \end{itemize}
            lipsum \\
    \hline
lipsum  &   lipsum\\
    \hline
\end{tabular}

\medskip
\begin{longtable}{|P{0.2\linewidth}|P{0.2\linewidth}|}
    \hline
lipsum  &   \begin{itemize}
        \item A
        \item B
            \end{itemize}
            lipsum \\
    \hline
lipsum  &   lipsum\\
    \hline
    \end{longtable}

\medskip
\begin{longtable}{|M{0.2\linewidth}|M{0.2\linewidth}|}
    \hline
lipsum  &   \begin{itemize}
        \item A
        \item B
            \end{itemize}
            lipsum \\
    \hline
lipsum  &   lipsum\\
    \hline
    \end{longtable}
\endgroup
\end{document}

which gives the following result:


text:
Q: Python Requests module - Strip back dictionary content I'm trying to call a web request from the link specified below (may have changed slightly depending when you read this) but I only want a specific part of it, it's all one line. From the part "build":"++Fortnite+Release-12.50-CL-13193885-Windows" I want to keep the ++Fortnite+Release-12.50-CL-13193885-Windows part.
What code would I need to use? This is what I have so far...
url = "https://fortnite-api.com/v2/aes"
response = requests.get(url)
updateloop = response.json()["build"]

LINK: https://fortnite-api.com/v2/aes

A: Just do
updateloop = response.json()["data"]["build"].replace("++Fortnite+Release-", "")

output
'12.50-CL-13193885-Windows'


text:
Q: Data load from pandas to snowflake rolling back I am trying to push data into a snowflake table using pandas but something weird is happening. The data loads into the snowflake table(I can see it) and after a couple of seconds(like 2 seconds) then I can see no records. I have no idea what's happening here
This is my code block. I'd really appreciate it if I can get some help.
connection = create_engine(
    'snowflake://{user}:{password}@{account}/{database}/{schema}?warehouse={warehouse}'.format(
        user=''xxxxx,
        password='xxxxx',
        account='xxxx.xxxx-xxxxxxxx-1',
        warehouse='xxxx',
        database='xxxxx',
        schema='xxxxxx'
    )
)

Transformation

with connection.connect().execution_options(autocommit=True) as conn:
  check_sql = "select * from subscription_changes_new"
  check_df = pd.read_sql(check_sql, conn)
  if len(check_df) > 0:
    conn.execute(text("delete from subscription_changes_new'"))
    subscription_changes.to_sql('subscription_changes_new', conn, if_exists='append', index=False, index_label=None)
  elif len(check_df) == 0:
    subscription_changes.to_sql('subscription_changes_new', conn, if_exists='append', index=False, index_label=None)
  else:
    None

I am using python 3.7

A: I am unable to reproduce the issue using python 3.7.9, and I don't see any issue with your code. Is there any other code in your program not shown that could be having an effect?
To troubleshoot I would recommend checking the History tab in Snowflake to see if any other processes are causing the deletion. I would also recommend changing your logic to use something like this:
with connection.connect().execution_options(autocommit=True) as conn:
    check_sql = "select count(*) as cnt from subscription_changes_new"
    check_df = pd.read_sql(check_sql, conn)

    if check_df.iloc[0, 0] > 0:
        conn.execute(text("delete from subscription_changes_new"))
        subscription_changes.to_sql('subscription_changes_new', conn, if_exists='append', index=False, index_label=None)
        print('I deleted and inserted')
    elif check_df.iloc[0, 0] == 0:
        subscription_changes.to_sql('subscription_changes_new', conn, if_exists='append', index=False, index_label=None)
        print('I just inserted')
    else:
        print('I did nothing')

This will have the same effect but won't require compute for the check query, and depending on the size of the table will improve performance by only hitting the metadata cache in Snowflake.


text:
Q: Delete ubuntu partition (dual boot windows 7) I deleted ubuntu partition from windows 7 hard disk partitions. But i fear when i restart my machine it will go into grub rescue. Any solution to avoid this.? Mix mbr /grub

A: You should boot from windows 7 dvd then run:
# diskpart
# list volume

Determine your windows installation drive its always volume C: then go to your volume path
# cd /d C:

Run this :
# attrib +h +s C:\bootmgr
# bootrec /fixboot
# bootrec /fixmbr
# bootrec /rebuildbcd

After this few steps you should make repair for your master boot record


text:
Q: Post my public IP address somewhere I would like to access my PC remotely without using any dedicated service (i.e. teamviewer) for that. Ideally some installed script installed on this PC would detect if its internet public IP changes and post it anywhere I could grab it. Then I could remotely interact with it (ssh for instance). Is that even possible?

A: There's an existing system for this: Dynamic DNS.
There shouldn't be any need to roll your own solution.

A: Personally (a developer answer), I would create a simple react REST API and run that on a cloud server somewhere. (or in PHP if I was being lazy)
This REST API would take in an IP address POSTed to it, update the value, then display to the user on a GET request. Meaning you can easily obtain this IP address when you are external from your network.
Then get your machine to post it's IP address to that REST API endpoint on a timed basis, or when it detects and external IP change. This could be done with a simple cronjob or task schedule.


text:
Q: Redirect Subdomain That is Not on SSL I have a SSL certificate that is installed on the server that only covers the domain, not subdomains
All traffic is redirected using apache config file
When I set up the subdomain to redirect a subdomain you get the browser alerting you that the site isn't safe because the SSL doesn't match the domain. I want to catch the subdomain before it gets forced to  HTTPS and redirect it to where I need it to go because once its forced to HTTPS it throws an error
My apache config
<VirtualHost *:80>
   ServerName aliahealthcare.com
   Redirect permanent / https://aliahealthcare.com/
</VirtualHost>
<VirtualHost *:443>
     //blah
</VirtualHost>

A: Thankfully, SSL doesn't work that way.  Every new domain you go to will have a new DNS lookup and a new SSL handshake and the certificate will be verified each time.  If you think about it, that's a really good thing for security!  (Despite inconveniencing you in this situation)
Your best bet is to get a wildcard cert or use Subject Alternate Names.


text:
Q: How do I Configure AWS Distro for OpenTelemetry to send data to Datadog in Pulumi? I want to send logs, metrics, and trace data from my Java code that are placed inside the steinko/helloworld-backend docker container to Datadog. I am using AWS Distro for OpenTelemetry container as a side car. To configure the Datadog exporter with a YAML file config.yaml.
I place these two components in an ECS Fargate Service by using Pulumi code:
export const service = new awsx.ecs.FargateService("backend", {
  taskDefinitionArgs: {
    containers: {
      otelCollector: {
        image:"docker.io/amazon/aws-otel-collector"
      },
      backend: {
        image: 'steinko/helloworld-backend',

      },
      dependsOn: [ {
        containerName: "otelCollector",
        condition: "START"
      } ]
    }
  }

How do I configure a config.yaml file  to docker.io/amazon/aws-otel-collector in Pulumi code?

A: ADOT PM here, thanks for raising this topic. In our ECS integration we support configurations for AWS X-Ray (traces) and Amazon Managed Service for Prometheus/Amazon CloudWatch (metrics), that is, your use case is currently not supported out-of-the-box. You would need to explicitly set up the ADOT collector (incl. volume for the config; see the examples as a starting point).
If you'd like to create a feature request for out-of-the-box support, please use our public roadmap. Also, note that ADOT at the moment does not yet support logs.


text:
Q: How to use random to choose if you want to go to an bonus question or not to go to the bonus question For some reason if I start this code and if the Random choose "no" it would still go with the "yes" and go through the bonus question if you need more details ask.
Its python just saying
import random

a = "yes"
b = "no"
mylist = [a, b]

def keuze():
    print(random.choices(my_list))
    if "yes" in mylist:
        print("je krijgt een bonus vraag")
        print("Bonus vraag")
        print("In which year was Google launched")
        print("a. 2005")
        print("b. 1995")
        print("c. 1969")
        print("d. 1998")
        answer4 = input("Type here your answer: ")
        if answer4 == "d" or antwoord4 == "D":
            print ("Good your answer is right you get 1 extra chance")
            chance = chance + 1
        else:
            print("Ow sorry, your answer is wrong")
            chance = chance - 1
    else:
         print("The computer didn't chose to give you an bonus question")
example()

A: That's because "yes" is always in mylist (you are asking if "yes" is in ["yes", "no"]).
You may try it saving the random.choices(mylist) result into a variable and testing if that variable equals ['yes'].

A: I have tryed it but couldnt get what i needed so i chanced it to if the contestant wants even an bonus question.
like this.
def example():
    print("Do you want an bonus question?")
    bonuss = input("Type here yes or no: ")
    if  bonuss == "yes" or bonuss == "Yes":
        print("U will get an bonus question")
        time.sleep(3)
        print("Bonus question 1")
        time.sleep(2)
        print("In wich year is google launched")
        time.sleep(2)
        print("a. 2005")
        time.sleep(1)
        print("b. 1995")
        time.sleep(1)
        print("c. 1969")
        time.sleep(1)
        print("d. 1998")
        time.sleep(1)
        antwoord4 = input("Type hier je antwoord: ")
        if antwoord4 == "d" or antwoord4 == "D":
            print ("Amazing your answer is right you get 1 extra chance")
            chance = chance + 1
        else:
            print("Ow your answer is wrong")
            chance = chance - 1
    else:
        print("U have chosen to not have an bonus question on to the next question")
example()

A: the problem was that i used random.choices(list)
so what i did to solve it was just to remove the s of choices
and i chanced the list to just an string
import time
import random
a = "yes"
b = "no"

list = a, b

rdm = random.choice(list)

def example():
    print(rdm)
    if  rdm == "yes":
        print("U will get an bonus question")
        time.sleep(3)
        print("Bonus question 1")
        time.sleep(2)
        print("In wich year is google launched")
        time.sleep(2)
        print("a. 2005")
        time.sleep(1)
        print("b. 1995")
        time.sleep(1)
        print("c. 1969")
        time.sleep(1)
        print("d. 1998")
        time.sleep(1)
        antwoord4 = input("Type hier je antwoord: ")
        if antwoord4 == "d" or antwoord4 == "D":
            print ("Amazing your answer is right you get 1 extra chance")
            chance = chance + 1
        else:
            print("Ow your answer is wrong")
            chance = chance - 1
    else:
        print("U have chosen to not have an bonus question on to the next question")
example()


text:
Q: The rational sum Let $x=\frac{a}{b}$ and $y=\frac{c}{d}$ be two rational numbers with fractions in simplest form.
Can we express $\frac{a+c}{b+d}$ in terms of $x$ and $y$ only.
Also, Can $\frac{a+c}{b+d}$ be a binary operation in set $Q$ of rational numbers?


text:
Q: How should one implement "is.error()" for R, to identify and parse errors? I am trying to test if objects are the results of errors.  The use case primarily arises via a foreach() loop that produces an error (although, for testing, it seems enough to just assign a simpleError() to a variable), and I'm puzzled about how to identify when that has occurred: how can I test that a given object is, in fact, an error?  Once I've determined that it is an error, what else can I extract, besides a message?  Perhaps I'm missing something about R's error handling facilities, as it seems necessary to write an error object testing function de novo.
Here are two examples, one using foreach, with the .errorhandling argument set to pass.  I have begun to use that as the default for large scale or unattended processing, in the event of an anomaly in a slice of data.  Such anomalies are rare, and not worth crashing the entire for loop (especially if that anomaly occurs at the end, which appears to be the default behavior of my murphysListSortingAlgorithm() ;-)). Instead, post hoc detection is desired.
library(foreach)
library(doMC)
registerDoMC(2)
results = foreach(ix = 1:10, .errorhandling = "pass") %dopar%{
    if(ix == 6){
        stop("Perfect")
    }
    if(ix == 7){
        stop("LuckyPrime")
    } else {
        return(ix)
    }
}

For simplicity, here is a very simple error (by definition):
a = simpleError("SNAFU")

While there does not seem to be a command like is.error(), and commands like typeof() and mode() seem to be pointless, the best I've found is to use class() or attributes(), which give attributes that are indicative of an error.  How can I use these in a manner guaranteed to determine that I've got an error and to fully process that error?  For instance a$message returns SNAFU, but a$call is NULL.  Should I expect to be able to extract anything useful from, say, res[[6]]$call?

Note 1: In case one doesn't have multicore functionality to reproduce the first example, I should point out that results[[6]] isn't the same as simpleError("Perfect"):
> b = simpleError("Perfect")
> identical(results[[6]], b)
[1] FALSE
> results[[6]]
<simpleError in eval(expr, envir, enclos): Perfect>
> b
<simpleError: Perfect>

This demonstrates why I can't (very naively) test if the list element is a vanilla simpleError.
Note 2.  I am aware of try and tryCatch, and use these in some contexts.  However, I'm not entirely sure how I can use them to post-process the output of, say, a foreach loop.  For instance, the results object in the first example: it does not appear to me to make sense to process its elements with a tryCatch wrapper.  For the RHS of the operation, i.e. the foreach() loop, I'm not sure that tryCatch will do what I intend, either.  I can use it to catch an error, but I suppose I need to get the message and insert the processing at that point.  I see two issues: every loop would need to be wrapped with a tryCatch(), negating part of the .errorhandling argument, and I remain unable to later post-process the results object.  If that's the only way to do this processing, then it's the solution, but that implies that errors can't be identified and processed in a similar way to many other R objects, such as matrices, vectors, data frames, etc.

Update 1.  I've added an additional stop trigger in the foreach loop, to give two different messages to identify and parse, in case this is helpful.
Update 2.  I'm selecting Richie Cotton's answer.  It seems to be the most complete explanation of what I should look for, though a complete implementation requires several other bits of code (and a recent version of R). Most importantly, he points out that there are 2 types of errors we need to keep in mind, which is especially important in being thorough.  See also the comments and answers by others in order to fully develop your own is.error() test function; the answer I've given can be a useful start when looking for errors in a list of results, and the code by Richie is a good starting point for the test functions.

A: The only two types of errors that you are likely to see in the wild are simpleErrors like you get here, and try-errors that are the result of wrapping some exception throwing code in a call to try.  It is possible for someone to create their own error class, though these are rare and should be based upon one of those two classes.  In fact (since R2.14.0) try-errors contain a simpleError:
e <- try(stop("throwing a try-error"))
attr(e, "condition")

To detect a simpleError is straightforward.
is_simple_error <- function(x) inherits(x, "simpleError")

The equivalent for try catch errors is
is_try_error <- function(x) inherits(x, "try-error")

So here, you can inspect the results for problems  by applying this to your list of results.
the_fails <- sapply(results, is_simple_error)

Likewise, returning the message and call are one-liners.  For convenience, I've converted the call to a character string, but you might not want that.
get_simple_error_message <- function(e) e$message
get_simple_error_call <- function(e) deparse(e$call)

sapply(results[the_fails], get_simple_error_message)
sapply(results[the_fails], get_simple_error_call)

A: From ?simpleError:

Conditions are objects inheriting from the abstract class condition.
  Errors and warnings are objects inheriting from the abstract
  subclasses error and warning. The class simpleError is the class used
  by stop and all internal error signals. Similarly, simpleWarning is
  used by warning, and simpleMessage is used by message. The
  constructors by the same names take a string describing the condition
  as argument and an optional call. The functions conditionMessage and
  conditionCall are generic functions that return the message and call
  of a condition.

So class(a) returns:
[1] "simpleError" "error"       "condition"

So a simple function:
is.condition <- function(x) {
  require(taRifx)
  last(class(x))=="condition"
}

As @flodel notes, replacing the function body with inherits(x,"condition") is more robust.

A: Using @flodel's suggestion about inherits(), which gets at the abstract class inheritance mentioned by @gsk3, here's my current solution:
is.error.element <- function(x){
    testError   <- inherits(x, "error")
    if(testError == TRUE){
        testSimple  <- inherits(x, "simpleError")
        errMsg      <- x$message
    } else {
        testSimple  <- FALSE
        errMsg      <- NA
    }
    return(data.frame(testError, testSimple, errMsg, stringsAsFactors = FALSE))
}

is.error <- function(testObject){
    quickTest <- is.error.element(testObject)
    if(quickTest$testError == TRUE){
        return(quickTest)
    } else {
        return(lapply(testObject, is.error.element))
    }
}

Here are results, made pretty via ldply for the results list:
> ldply(is.error(results))
   testError testSimple     errMsg
1      FALSE      FALSE       <NA>
2      FALSE      FALSE       <NA>
3      FALSE      FALSE       <NA>
4      FALSE      FALSE       <NA>
5      FALSE      FALSE       <NA>
6       TRUE       TRUE    Perfect
7       TRUE       TRUE LuckyPrime
8      FALSE      FALSE       <NA>
9      FALSE      FALSE       <NA>
10     FALSE      FALSE       <NA>

> is.error(a)
  testError testSimple errMsg
1      TRUE       TRUE  SNAFU

This still seems rough to me, not least because I haven't extracted a meaningful call value, and the outer function, isError(), might not do well on other structures.  I suspect that this could be improved with sapply or another member of the *apply or *ply (plyr) families.

A: I use try and catch as described in this question:
How do I save warnings and errors as output from a function?
The idea is that each item in the loop returns a list with three elements: the return value, any warnings, and any errors.  The result is a list of lists that can then be queried to find out not only the values from each item in the loop, but which items in the loop had warnings or errors.
In this example, I would do something like this:
library(foreach)
library(doMC)
registerDoMC(2)
results = foreach(ix = 1:10, .errorhandling = "pass") %dopar%{
  catchToList({
    if(ix == 6){
        stop("Perfect")
    }
    if(ix == 7){
        stop("LuckyPrime")
    } else {
        ix
    }
  })
}

Then I would process the results like this
> ok <- sapply(results, function(x) is.null(x$error))
> which(!ok)
[1] 6 7
> sapply(results[!ok], function(x) x$error)
[1] "Perfect"    "LuckyPrime"
> sapply(results[ok], function(x) x$value)
[1]  1  2  3  4  5  8  9 10

It would be fairly straightforward to give the result from catchToList a class and overload some accessing functions to make the above syntax easier, but I haven't found a real need for that yet.


text:
Q: Деградация скорости анимации turtle Python import turtle
import time

def main():
    window = turtle.Screen()
    window.bgcolor('blue'), window.setup(500, 500)
    turtle.tracer(0)
    moon = turtle.Turtle()
    moon.speed(0), moon.hideturtle(), moon.penup(), moon.color('orange')

    dark = turtle.Turtle()
    dark.hideturtle(), dark.speed(0), dark.penup(), dark.color('blue')
    while True:
        start = time.time()
        for x in range(230,  -231, -1):
            moon.dot(230)
            dark.goto(x, 0)
            dark.dot(230)
            turtle.update()
            dark.clear()
        else:
            print(f'Время {time.time() - start}')

main()

Происходит деградация скорости после каждого прохождения круга. Почему такое происходит? Параметры speed(), tracer() менять пробовал, но появляются мерцания. Можно ли как-то это исправить? Первый тест проходит за 7-8 секунд, а второй раз уже 21 секунду, постоянно идет такой линейный упадок скорости.

A: Дело в том, что Вы не очищаете объект moon. Если запустить Вашу программу и открыть диспетчер задач, будет видно, как быстро растут затраты ОЗУ. Из-за этого и происходит деградация времени.
В итоге, такой код работает корректно:
import turtle
import time

def main():
    window = turtle.Screen()
    window.bgcolor('blue'), window.setup(500, 500)
    turtle.tracer(0)
    moon = turtle.Turtle()
    moon.speed(0), moon.hideturtle(), moon.penup(), moon.color('orange')

    dark = turtle.Turtle()
    dark.hideturtle(), dark.speed(0), dark.penup(), dark.color('blue')
    while True:
        start = time.time()
        for x in range(230,  -231, -1):
            moon.dot(230)
            dark.goto(x, 0)
            dark.dot(230)
            turtle.update()
            dark.clear()
            moon.clear()
            time.sleep(0.005)  # Для замедления анимации
        else:
            print(f'Время {time.time() - start}')

main()


text:
Q: How do you place controllers and related views in separate folders in ASP.NET MVC I would like to group all my Controllers with related Views in separate folders. How can I achieve this?

A: *

*Don't.

*But if you must, write a custom ViewEngine to locate the views. I wrote a (now out of date) example here. ViewLocator has since been renamed to ViewEngine.

*See (1)

Update: If you actually meant you're looking for an "areas" feature, try this.


text:
Q: Removing printer marks from a PDF file I need to remove the printer marks from a PDF file. I am using Acrobat 9 Professional to open the PDF, but there is no option for removing the printer marks although there is option to add new printer marks.
I googled and found that there is a third-party plugin "Enfocus PitStop" which when installed is added to Adobe Acrobat and provides an option to remove the print marks, but that software is quite costly.
Is there any way I can remove the printer marks programmatically or through the Adobe Acrobat 9.0 interface?

A: Using the View > Navigation Panels > Content box worked well for me. I was able to delete the cut lines without an issue.

A: In Acrobat Professional, go to Document > Crop Pages and select "Trim Box" from the dropdown menu. If the document doesn't have this dimension built in, you can also manually enter it.
You can also edit PDFs in Adobe Illustrator, if available.

A: How to Manually Remove Printers Marks in Adobe Acrobat
Open File
Save File As (rename to preserve original)
Go to: Document > Crop Pages
    In the first drop down box, select trim box (or other as necessary)
    Adjust the margin numbers as needed to save required bleeds
    Note the margin numbers.
Close the window
Go to: View > Navigation Panels > Content
    Move window out of your way so you can see your .pdf and this box
    Zoom in on .pdf so you can see detail
    Go back to Content window
    Click the + next to .pdf name
    Click the + next to the page number
        *This will now show the various parts of the .pdf.
    Select any component and right click
    Select highlight content.
        *Your page will now jump to that item and put a small box around it.
Scroll through content to find all printer marks to be removed. (I suggest starting at the bottom and viewing each item to identify a group.  (the bottom 5 "paths) for example.  Select them all and delete them)
All Printer Marks should now be removed. Close the Content window
Go to: Document > Crop Pages
    Type in the top crop dimension you obtained earlier and hit ENTER.
    Continue for the Bottom, Left and Right Sides.
*Note – I was not able to enter all dimensions at once and have the crop actually executed.
Save File

A: I had red registration lines that were NOT crop lines and finally found out how to remove then as follows (I'm using Acrobat Professional 7):
View >> Navigation Tabs >> Content
A window opens with 4 tabs (Fields/Tags/Content/Order)
Stay on Content Tab
Click on File Name (Pages Open)
Click on Page in Question (Details open)
Click on items called "Path" and delete one at time
 - If the wrong line dissappears press Ctrl-Z to get it back
Through trial and error I was able to eliminate the lines.

A: I know this is an old question, but I just had to remove the registration/bleed marks on a 155 page PDF file, and figured I'd share my solution.  This is in Acrobat Pro 10.1
Since the document was meant for 8.5 x 11 paper, I went

*

*File > Print

*Printer: Adobe PDF

*Pages: All

*Size Options: Actual size

As long as the registration marks are accurate for the size of the paper you're "printing" to, the result should be a new PDF with pages that fall within the registration marks, effectively cropping them all off.

A: I Just automated this process for a 40 page PDF in Acrobat Pro without plug-ins.
Open your Tools pane click Pages > Crop > Draw a box around your content, double click and apply to all pages. Quick and easy!

A: I was able to remove them by directly editing the pdf file in Textpad (Notepad might work also) and changing the values for the /cropbox setting.
It has 4 values after it for left, top, right and bottom crop positions and mine were set the same as the preceeding /mediabox values.
I was able to add 120 to the first two values and take 120 off the second two and that cropped the page when it was next opened in Acrobat Reader.
It might need a bit of trial and error to get the correct values but it did the trick for me.  Just change the first one and once it's correct you can do a scan/replace to change the value for the other pages.
Could be an option for people if you have no way of editing it via Acrobat, either because the file is protected or because you don't have access to the pro version.

A: In case anyone also has the issue, that they need to have the contents outside of the dropbox really removed, I came across this post: http://www.proficiografik.com/2009/11/17/acrobat-9-when-the-crop-tool-is-not-cropping-and-how-to-fix-it.html
It includes a preflight setting which completely removes ANY objects outside of the crop / trim / media box and sets the boundary to the trim box.
Any other solution just HIDES the contents, but does not remove them, which cause them to re-appear in e.g. Ipad applications.
I prefer to do the cropping in Acrobat, because Ghostscript sometimes has problems in processing certain PDFs.

A: If you mean registration watermarks, either you have to crack the software (which I am not telling you to do) or you have to buy it. Usually, free pdf writers/editors include a watermark unless you buy the product. If however you wanted a free pdf printer, try CutePDF. I at least think this is what you are asking about.


text:
Q: How can I change my regEx so that it is correctly applied to the URLs I'm trying to scrape? I'm using Selenium for this and my code is the following:
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
omegaBase = "https://www.omegawatches.com/de/"
productRegex = re.compile(r'[https://](w){3}')

driver.get(omegaBase + "watches/" + "constellation")
links = driver.find_elements_by_tag_name("a")
for link in links:
    pageUrls = link.get_attribute("href")
    print(pageUrls)
    productRegex.findall(pageUrls)

If I comment out the regEx and just print(pageUrls) I get all the links on the page, which is fine, but I'm trying to get only a select few specific links from the page in the format https://www.omegawatches.com/de/watch/name_of_product
I'm not that great using Regular Expressions, I definitely need to practice and learn more but I've been playing around just to see if it will apply at all and I keep getting the error TypeError: expected string or bytes-like object
Does anyone know how I can fix the regEx, so that it is at least applied correctly? The regEx I am using in the above example is only really to remove a couple of links so I can see that it is working at least.

A: You don't need a regex to do what you are attempting. You can use a simple CSS selector.
a[href^='https://www.omegawatches.com/de/watches/']

This just looks for an A tag that has an href that starts with the URL you want.
You can further modify this to focus on specific links, like only the watch links in the footer, e.g.
div.footer-main-table a[href^='https://www.omegawatches.com/de/watches/']

...and so on

A: Firstly, let's look at your regular expression. You're doing this:
productRegex = re.compile(r'[https://](w){3}')

When you're building a regular expression, things in square brackets match one of the set of characters which it includes. For example, [aeiou] matches a, e, i, o or u only. Here you want to match the string https:// so just put it in without square brackets:
productRegex = re.compile(r'https://(w){3}')

You could change it further by using ^ to match just the beginning of the expression, and simplify (w){3} to www:
productRegex = re.compile(r'^https://www')

Now let's look at how you're using your regular expression:
for link in links:
    pageUrls = link.get_attribute("href")
    print(pageUrls)
    productRegex.findall(pageUrls)

Here you're getting the linked URL using get_attribute(). This gets the one URL, so I'd suggest changing the variable name from pageUrls to pageUrl. Then you'll need to check whether the URL matches the regular expression, which you do like this:
if productRegex.match(pageUrl):
    print(pageUrl)
else:
    print('No match')

(Of course, now we've got this far, we note that we don't need ^ in the regular expression if we're using match() which only looks for a match at the beginning of the string.)


text:
Q: English tenses forms What is the difference in meaning between the following sentences:

*

*living cost has increased every year.

*living cost increases every year.

A: As is often the case, there is no difference in the objective circumstances described by the two sentences. The difference is in how the speaker is choosing to structure events in time.
"Has increased" says that the speaker is referring to a period of several years in the past and up to the present. It says nothing about what may happen in the future.
"Increases" is referring to a process that is over some period including the present. It is not specifically referring to the past, but conceives the relevant period as timeless, stretching past and forward.
In this case, there is little practical difference, since we can't predict the future, so "increases" must literally be talking about only the past. But there is a difference in how the speaker is choosing to present the events.


text:
Q: When using fscanf, what is happening inbetween lines being scanned? I have an input file that I scan each line until the end. I use the first character as an indicator as what I want to do:  1. paused for x cycles, 2. write a 16-bit word serially, 3. write one bit at a time, 4 end of file.
The issue is that I see an extra mode in between the first p to w transition.
I tried printing out the string value of my variable "mode" but what I see is printed on the wave in between the first p and w is an additional mode not specified in my case statement.
at time = 0: mode equals " " (blank, nothing, all fine)
at time = A: mode now equals "p" (paused 4 cycles long, sure fine, I can fix this later)
at time = B: mode now equals "[]" (ERROR! this is not the next line)
at time = C: mode now equals "w" (back to normal)
input file:
p 10
w DEAD
w BEEF
p 5
b HHLL
p 100
eol

I have my systemverilog code that is suppose to scan the input file:
$fscanf(fd, "%c %h", mode, mystr);

case(mode)
  "p": begin
    wait_v = mystr.atoi();
    repeat ( wait_v) begin
      //turns bits on or off, but only modifies wire outputs and not mode
    end
  end

  "w": begin
    data = mystr.atohex();
    // writes data, each character is 4 bits. each word is 16 cycles
  end

  "b": begin
    lastsix = mystr.atobin();
    // writes data outputs either high or low, each character is 1 cycle long
  end

  "eol": begin
    $fclose(fn);
    $stop;
  end

Expected:
time => 0: mode equals " " (blank, nothing, all fine)
time => A: mode now equals "p" (paused for 3 cycles)
time => C: mode now equals "w" (back to normal)

Actual:
time => 0: mode equals " " (blank, nothing, all fine)
time => A: mode now equals "p" (paused 4 cycles long, sure fine, I can fix this later)
time => B: mode now equals "[]" (ERROR! this is not the next line)
time => C: mode now equals "w" (back to normal)

A: When you use %c in scanf it will read the very next character.  When you use %h it will read a hex value, stopping after the last valid hex digit, and not reading what is next.  So after your first fscanf call, the input will be pointing at the newline a the end of the first line, and the next fscanf call will read that newline with %c, and you'll get mode == "\n"
What you probably want is to use " %c%h" as your format -- note the  (space) before the %c.  The space causes fscanf to read and discard whitespace.  Since %h automatically skips whitespace before reading a number, you don't need the space before it.


text:
Q: Function inside a function: why does this echo statement only display once? In the following code, why does the phrase "example" only output once if both foo() and bar() are called>
<?php
function foo()
{
    function bar()
    {
        echo "example\n";
    }
}

foo();

bar();

?>

A: You want to be declaring your functions separately like so:
<?php
function foo()
{
    bar();
}

function bar()
{
    echo "example\n";
}

foo();

bar();

?>

Nesting your functions inside each other doesn't really serve any purpose that i can think of.


text:
Q: Properly decode Get Blob data string to ArrayBuffer I have the following code that receives blob's data from Azure Storage:
$.ajax({
        headers: {
            'x-ms-range': 'bytes=' + from + '-' + to,
            'x-ms-version': '2015-07-08',
            'x-ms-client-request-id': guid()
        },
        url: uri,
        type: "GET",
        success: function (data) {
            /* data is a string! */
        },
        error: function (error, textStatus) { }
});

The call works fine and I receive the data in a textual form.
The problem is that I need to convert it to an ArrayBuffer.
Now I've tried lots of ways, such as:
new TextEncoder().encode(data);

and the following converter:
function stringToUint(string) {
    var charList = string.split(''),
    uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint16Array(uintArray);
}

But the data string isn't converted properly to binary (I've checked against the real binary value of the blob).
Should I use a different ArrayBuffer type? or am I using the wrong encoding (I've tried utf-8, utf-16, utf-32) when converting with the TextEncoder?
Please help :(

A: What finally worked for me was to use this jquery extension
and change the request to:
$.ajax({
        headers: {
            'x-ms-range': 'bytes=' + from + '-' + to,
            'x-ms-version': '2015-07-08',
            'x-ms-client-request-id': guid()
        },
        url: uri,
        type: "GET",
        dataType: 'binary',
        responseType:'arraybuffer',
        processData: false,
        success: function (data) {
            /* data is an arraybuffer! */
        },
        error: function (error, textStatus) { }
});

Hopefully, it will help other people as well...


text:
Q: How can I boot a bootable windows 7 installer usb I have a bootable usb windows 7 installer. It is working in another computer with windows 7. I want to boot it from a computer with zorin OS but I can't. I can see it from my bios menu and I can set it first in the priority list but it is not working. I think (and I may be wrong) that I have to tell zorin the usb is bootable but I don't know how. Any ideas please??
Thank you!!
I attach you a screen of the root files in my usb.

A: This is not a Unix question, though I can see why you think it is. You do not have to tell the installed OS about it.
How things work:

*

*Computer is switched on.

*Computer starts running program in boot ROM (often mistakenly called BIOS, on PCs).

*ROM based boot-loader, loads 2nd stage boot-loader from disk (or USB, or …).

*2nd stage boot-loader, loads 3rd stage boot-loader from disk (or USB).

*3rd stage boot-loader, loads operating system kernel and init process.

*init process loads the rest of the operating system.

*Operating system loads video player.

*Video player loads minecraft videos.

*User watches minecraft videos.

As you can see, the operating system does not load another operating system (except it can load a virtual-machine). The solution to you problem will be in the boot loader settings (often labelled bios settings).


text:
Q: Putting a circle in a 2d grid using arrays, for loops first question here. Im simply trying to put this circle I've created into this 2d array grid. The idea is that it becomes sort of an island.
Currently only the first few outputs matter, so ignore the particles and waterline with regular ints. It currently prints a grid, and a separate circle. Please help me put the circle in the grid. Thank you!
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;

int** makeParticleMap(int width, int height, int windowX, int windowY, int radius, int numParticles, int maxLife) {

    int** map = new int* [height];
    for (int k = 0; k < height; ++k) {
        map[k] = new int[width];
    }
    for (int y = (height - 1); y >= 0; y--) {//height of map
        cout << "\n";
        for (int x = 0; x < width; x++) {//width of map

            map[x][y] = 0;
            map[windowX - 1][windowY - 1] = 1;
            cout << map[x][y]; //creation of map on a 2D grid
        }
    }
    for (int y = 0; y <= 2 * radius; y++) {          //this loop creates the circle
        cout << "\n";
        for (int x = 0; x <= 2 * radius; x++) {
            float distanceCenter = sqrt((y - radius) * (y - radius) + (x - radius) * (x - radius));
            if (distanceCenter) {//>radius-0.5 && distanceCenter<radius+.5){
                cout << '*';
            }
            else {
                cout << 0;
            }
        }
    }
    cout << "\n";
    return map;
}

int main() {

    int width, height, windowX, windowY, radius, numParticles, maxLife, water;
    srand((unsigned int)time(NULL));

    cout << "Enter Grid Width:";
    cin >> width;
    cout << "Enter Grid Height:";
    cin >> height;

    cout << "Enter drop-zone x-coordinate (0 - <width>):";
    while (true) {
        cin >> windowX;
        if (windowX > width) {
            cout << "Dropzone cannot be outside the map,reenter:\n";
        }
        else break;
    }

    cout << "Enter drop-zone y-coordinate (0 - <height>):";
    while (true) {
        cin >> windowY;
        if (windowY > height) {
            cout << "Dropzone cannot be outside the map,reenter:\n";
        }
        else break;
    }

    cout << "Enter drop-zone radius (minimum 2):";
    while (true) {
        cin >> radius;
        if (radius<2 || radius>width || radius > height) {
            cout << "Radius cannot be larger than the map or is too small,reenter:\n";
        }
        else break;
    }

    cout << "Enter number of particles to drop:";
    cin >> numParticles;
    cout << "Enter max life of particles: ";
    cin >> maxLife;

    cout << "Enter value for waterline (40-200): ";
    while (true) {
        cin >> water;
        if (water < 40 || water >200) {
            cout << "Invalid water level,reenter:\n";
        }
        else break;
    }

    int ** map = makeParticleMap(width, height, windowX, windowY, radius, numParticles, maxLife);
    //Dropzone(windowX,windowY,radius);

    for (int k = 0; k < height; ++k)
        delete [] map[k];
    delete map;
}


text:
Q: update-database command fails in code first migrations I am trying to follow the tutorial http://www.asp.net/web-forms/tutorials/data-access/model-binding/retrieving-data.
When I am trying the update-database command in PM console, i get the following error.
Cannot attach the file 'D:\ASPdotNet\ContosoUniversity\ContosoUniversity\App_Data\ContosoUniversity.Models.SchoolContext.mdf' as database 'ContosoUniversity.Models.SchoolContext'.

A: Just ran into the exact same issue. To resolve I used,
Open the "Developer Command Propmpt for VisualStudio" under your start/programs menu and
run the following commands:
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0

Rebuild the solution and try to update the database again.


text:
Q: How to return a value from nested javascript function? window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel("");
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(ice){
  if(!ice || !ice.candidate || !ice.candidate.candidate)  return;
  ice.candidate.candidate.split('\r\n').forEach(function (line) {
    if (line.indexOf("candidate")!==-1) {
      var parts = line.split(' '),
      addr = parts[4],
      type = parts[7];
      if (type === 'host') {
        console.log(addr);
        return addr;
      }
    }
  });
  pc.onicecandidate = noop;
};

In the above javascript, the console.log(addr) works but not the return. Please point me where I am doing wrong. I tried to wrap this in a function and that doesn't work it either.

A: As long as your code in synchronous, you can write variables outside of the immediate function scope like so:
let result = null;
ice.candidate.candidate.split('\r\n').forEach(function (line) {
    if (line.indexOf("candidate")!==-1) {
      var parts = line.split(' '),
      addr = parts[4],
      type = parts[7];
      if (type === 'host') {
        console.log(addr);
        // Save value
        result = addr;
      }
    }
  });
// ...
console.log(result);

This can be further improved by using a for (let .. of ..) loop and break to stop the loop after finding the value you're looking for.
You should also consider Array.prototype.find() for this.

A: pc.onicecandidate = function(ice){
  if(!ice || !ice.candidate || !ice.candidate.candidate)  return;

  const hosts = [];

  ice.candidate.candidate.split('\r\n').forEach(function (line) {
    if (line.indexOf("candidate")!==-1) {
      var parts = line.split(' '),
      addr = parts[4],
      type = parts[7];
      if (type === 'host') {
        console.log(addr);

        hosts.push(addr)

      }
    }
  });
  pc.onicecandidate = noop;

  return hosts;
};

Is something like that what you are after?
You want to return each host address?
This stores the hosts locally. Foreach is synchronous so when it has completed working on the collection then your function will reach the return statement.
If you want to find the first address then you might want to use .find instead of .forEach, or check that a value exists and bail from the forEach when it does (note that you're still calling that function on each item, it'll just return straight away). You can break out of a forEach but its not idiomatic, you'd have to throw an exception and you try..catch, a bit nasty in JS and not really the intended use for the syntax.
pc.onicecandidate = function(ice){
  if(!ice || !ice.candidate || !ice.candidate.candidate)  return;

  const line = ice.candidate.candidate.split('\r\n').find(function (line) {
    if (line.indexOf("candidate")!==-1) {
      var parts = line.split(' ');
      var type = parts[7];
      return type === 'host'
    }
  });
  pc.onicecandidate = noop;
  return line.split(' ')[4]
};

Something like this I think should work for .find.
.find will return the item, which you can then pull the addr from. Alternatively you could let addr outside, update that inside, then ignore the return value from .find.
Oh, you'll want to add something if your .find returns nothing, or things will break when you try to split it and pull something out.


text:
Q: How to make a function to analyse a sentence? I have two lists:
grammarNonterminal = {{VP,{V,NP}},{NP,{D,N}},{S,{NP,VP}}}
sentence = {{D,"the"},{N,"man"},{V,"hit"},{D,"the"},{N,"table"}}

I want to make a function which changes sentence into the followings when the function takes grammarNonterminal and sentence as arguments.
⇒  {{NP, {D, "the"}, {N,"man"}}, {V, "hit"}, {D, "the"}, {N, "table"}}} , {{{D, "the"}, {N, "man"}, {V, "hit"}, {NP, {{D, "the"}, {N, "table"}}},

⇒  {{NP, {D, "the"}, {N, "man"}}, {V, "hit"}, {NP, {D, "the"}, {N, "table"}}}},{{D, "the"}, {N, "man"}, {VP, {{V, "hit"}, {NP, {D, "the"}, {N, "table"}}}

⇒ {{{NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}

⇒ {{{S, {NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}}

I know I have to use ReplaceList, Map and Union to achieve this.
Is there a simple way to do this?

What I wanted to do is something like below.
First, you make a function applyRule:
applyRule[sentence_, r_] := ReplaceList[sentence,{x___,c : Apply[PatternSequence, {#, _} & /@ r[[2]] ], y___} -> {x, ReplacePart[r, 2 -> {c}], y}];

r = {NP,{D,N}}

applyRule[sentence,r] = {{{NP, {{D, "the"}, {N, "man"}}}, {V, "hit"}, {D, "the"}, {N, "table"}}, {{D,"the"}, {N, "man"}, {V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}

And then make a function to change sentence into
{{{S, {NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}}

by using applyRule, Map, and Union.
I tried
Union[Map[applyRule[sentence, #] &, grammarNonterminal]

but this doesn't give me the result that I want.

A: Anyway, despite all of my comments, here's my best go at this problem. It's not general, and it doesn't exactly match your syntax, so perhaps someone else will come along and fix it, but this is at least a good start.
I've taken the liberty of changing your notation in a number of ways.

*

*Lower-case letters for the parts-of-speech.

*Instead of {d, "the"} I will use d["the"].

Let's define our parser as the following (neatened up per a comment from Simon Woods):
parseList[sentence_] := Delete[FixedPointList[
    # /. {
      {a___, x : PatternSequence[_np, _vp], b___} :> {a, s[x], b},
      {a___, x : PatternSequence[_v, _np], b___} :> {a, vp[x], b},
      {a___, x : PatternSequence[_d, _n], b___} :> {a, np[x], b}
     } &
    , sentence
   ]
   , -1]

Due to the way that ReplaceAll works, once it replaces an entire expression, it doesn't replace sub-expressions of that expression. I'm taking advantage of that to replace one thing at a time so that we can get out a list of steps. I have also made the more global rules first; for instance, the rule that puts together the whole sentence comes first in the list. Finally, we use FixedPointList in order to replace phrases in this sentence until it doesn't change anymore.
If you don't care about the steps taken to get to the end, we can instead use ReplaceRepeated:
parse[sentence_] := sentence //. {
   {a___, x : PatternSequence[_np, _vp], b___} :> {a, s[x], b},
   {a___, x : PatternSequence[_v, _np], b___} :> {a, vp[x], b},
   {a___, x : PatternSequence[_d, _n], b___} :> {a, np[x], b}
  } // First

The sentence is
sentence = {d["the"], n["man"], v["hit"], d["the"], n["table"]};

Then,
parSen = parse[sentence]
(* s[np[d["the"], n["man"]], vp[v["hit"], np[d["the"], n["table"]]]] *)

or
(list = parseList[sentence]) // MatrixForm

It doesn't exactly do things in exactly the order you requested, but it gets this simple job done.
The nice thing about this particular syntax (e.g. using d["the"] instead of {d, "the"}) is that we can display the final parsed sentence in a nice TreeForm:
TreeForm@parSen


text:
Q: Why doesn't my JS add an HTML class? I've been messing with this code for a while now, and I can't seem to make it work.  I made a div that is a green box and I want it to do my CSS transform when it is clicked on (by using JS to add a class), however that is not what it is doing right now.  What rookie mistake did I make with this one?

Here's my code:  There is also a JSFiddle here!

function box() { document.getElementById('box')[0].setAttribute("class", "box_ready");
}
body {
    margin: 0;
    padding: 0;
}

.container {
    width: 800px;
    margin: 0 auto;
}

#box {
    width: 200px;
    height: 200px;
    background-color: #393;
}

#box:hover {
  cursor: pointer;
}

.box_ready {
    -webkit-animation: slide 2s;
            animation: slide 2s;
            animation-fill-mode: forwards;
}

@keyframes slide {
  to {
    -webkit-transform: translate(600px, 0px);
        -ms-transform: translate(600px, 0px);
            transform: translate(600px, 0px);
            transform: rotateY(90deg);
 }

}

/* Add WebKit when done*/

A: I was able to get it to work by removing the [0] from your function:
function box(){
    document.getElementById('box').setAttribute("class", "box_ready");
}

Remember, getElementById() returns one element, but getElementsByClassName() returns an array of elements.
Also, although this may be obvious, you can only use getElementById() when the element has that as an ID. Ditto with getElementByClassName().

A: You are removing the existing class when you set the class HTML attribute. This removes the existing box class styling which makes the box disappear. You are also overriding the translate transform with the second transform CSS property.
Fixed JSfiddle: https://jsfiddle.net/zn2nhbnt/20/
Edit: notice, I changed the translate and removed the prefixed properties for clarity.

A: Your code should change to
document.getElementById('box').setAttribute("class", "box_ready");
getElementById returns only a single matching element, not an array, since a single document can not have an ID repeating more than once, according to HTML standards.

A: it is not getElementsById it should be getElementById


text:
Q: QTextBrowser Hyperlinks in PyQt4 I have a QTextBrowser where I've entered that sample text:
Column1    Column2
1 2 3 4    www.google.com

Between the columns there are tabs and between the numbers there are spaces. plainText=QTextBrowser.toPlainText() gives:
Column1    Column2
1 2 3 4    www.google.com

Now, i want to make the link clickable. By this, I'll set the text as html.
I wrote some string operations with
WORDS = re.split("(\W+)",plainText)

That gives
['Column1', '\t', 'Column2', '\n', '1', ' ', '2', ' ', '3', ' ', '4', '\t', 'www', '.', 'google', '.', 'com', ' ', '']

and replaced "www" with the hyperlink in html-format
www.google.com

Then, I deleted the items in WORDS: ".", "test", ".", "com".
['Column1', '\t', 'Column2', '\n', '1', ' ', '2', ' ', '3', ' ', '4', '\t', 'www.google.com', ' ', '']

Then I rebuild all the WORDS-parts again to a string, replacing the linebreak \n with

.

Now, when I set the string to the QTextBrowser, the link is displayed correctly and also clickable. Problem is: The entered text, as it is now html, ignores/removes all spaces (if more than one) and tabs!
The output looks like (with the link now being blue and underlined)
Column1 Column2
1 2 3 4 www.google.com

How can I just make a hyperlink without the formatting being destroyed?
Perhaps I am on the wrong train??

A: I think I got it. In case it might be useful, here is my solution:
A html file does respect your format, if you put the style in the css to "pre", and not like QTextBrowser to "pre-wrap".
Moreover, in the end the typed links can directly be replaced by the created hyperlinks.
The html file that is generated and setted to the QTextBrowser then partwise looks like:

Column1        Column2


text:
Q: Using pixi-multistyle-text Pixi.js - change char color within a string I'm very new to this and am seeking some explanation/brief guide.
I'm using Pixi.js. I only want to effect certain characters within a string, altering the colour and making some of the characters bold, but not effecting the string as a whole.
I understand this repo GitHub.com/tleunen/pixi-multistyle-text allows you to add XML tags to strings to do this.
What I don't understand is how I can use it on my machine. (I have a moderate understanding of git) but do not know how to use this repo within my currently separate project.
Do I simply need to clone the repo, then copy paste its source file to my project?
I also am not familiar with
$ yarn install
Or
$ yarn build
And when I try to use these within the terminal in code I get many errors!
Anything is appreciated.
(I have limited experience doing gamedev personal projects as a hobby, have never attempted a full 'web dev' project before)

A: Not sure why you do not want to build it, but you can access or download the distribution files from here:
https://www.jsdelivr.com/package/npm/pixi-multistyle-text


text:
Q: Elasticsearch: Updating Nested Object via script I am using ES1.4.4 and wanted to run an update script with the Update API that iterated over a ctx._source.nested_object and updated only the nested objects that fulfilled the requirements of the script. It seems relatively very simple but for some reason I am not getting an update.
script : 'for(i in ctx._source.nested_object){ if(ctx._source.nested_object[i].user.id == id){ ctx._source.nested_object[i].user = merge }  }',
params : { "id" : "SEL123" , "merge" : { "key1" : "value1" } }

All the fields that are being added/set to the new object match the field types of the existing source. Scripts are enabled in my cluster instance. The script language is Groovy.

A: Try the script:
for(i in ctx._source.nested_object){
    if (i.user.id == id) {
        i.user = merge
    }
}


text:
Q: Eclipse plugin install error I'm trying to install the google plugin for eclipse but the installer keeps telling me :

An error occurred during the
  org.eclipse.equinox.internal.p2.engine.phases.CheckTrust phase

I've tried firstly to install from internet but then canceled it because of the poor speed. Then I download it and tried to install locally, then I have this problem. I'm using Eclipse 3.7.1 and the google plugin is also for version 3.7.
I've tried also to clean up the configuration folder by deleting anythings has the name equinox but that's no use.
Any suggestions? Thanks!
Here goes the error log:
!SESSION 2012-02-03 06:30:06.977 -----------------------------------------------
eclipse.buildId=M20110909-1335
java.version=1.6.0_22
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_US
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os linux -ws gtk -arch x86 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.equinox.p2.engine 4 4 2012-02-03 06:33:17.752
!MESSAGE An error occurred during the org.eclipse.equinox.internal.p2.engine.phases.CheckTrust phase.
!SUBENTRY 1 org.eclipse.equinox.p2.engine 4 0 2012-02-03 06:33:17.752
!MESSAGE session context was:(profile=epp.package.java, phase=org.eclipse.equinox.internal.p2.engine.phases.CheckTrust, operand=, action=).
!SUBENTRY 1 org.eclipse.equinox.p2.engine 4 0 2012-02-03 06:33:17.752
!MESSAGE Error reading signed content.
!STACK 0
java.io.IOException: The file "/home/darkjh/eclipse/plugins/com.google.appengine.eclipse.core_2.5.1.v201201120043-rel-r37.jar" does not exist
    at org.eclipse.osgi.baseadaptor.bundlefile.ZipBundleFile.<init>(ZipBundleFile.java:61)
    at org.eclipse.osgi.baseadaptor.bundlefile.ZipBundleFile.<init>(ZipBundleFile.java:55)
    at org.eclipse.osgi.internal.signedcontent.SignedBundleHook.getSignedContent(SignedBundleHook.java:253)
    at org.eclipse.equinox.internal.p2.engine.phases.CertificateChecker.checkCertificates(CertificateChecker.java:67)
    at org.eclipse.equinox.internal.p2.engine.phases.CertificateChecker.start(CertificateChecker.java:49)
    at org.eclipse.equinox.internal.p2.engine.phases.CheckTrust.completePhase(CheckTrust.java:50)
    at org.eclipse.equinox.internal.p2.engine.Phase.postPerform(Phase.java:216)
    at org.eclipse.equinox.internal.p2.engine.Phase.perform(Phase.java:84)
    at org.eclipse.equinox.internal.p2.engine.PhaseSet.perform(PhaseSet.java:44)
    at org.eclipse.equinox.internal.p2.engine.Engine.perform(Engine.java:75)
    at org.eclipse.equinox.internal.p2.engine.Engine.perform(Engine.java:44)
    at org.eclipse.equinox.p2.operations.ProvisioningSession.performProvisioningPlan(ProvisioningSession.java:174)
    at org.eclipse.equinox.p2.operations.ProfileModificationJob.runModal(ProfileModificationJob.java:79)
    at org.eclipse.equinox.p2.operations.ProvisioningJob.run(ProvisioningJob.java:177)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

A: Ok, I think it's a failure inside Eclipse. Now I've downloaded a clean one and the installation was all ok.

A: Looks like you're missing a file with the given name. (com.google.appengine.eclipse.core_2.5.1.v201201120043-rel-r37.jar) Try searching for it using your favorite search engine and placing it manually in the specified location. (/home/darkjh/eclipse/plugins/)


text:
Q: ruby on rails website on two language how to make a website in two languages on rails?
use gem or create two projects or register two domains?
help me, please. Link or quick explanation of the ideas as it is accepted to do

A: Rails Internationalization (I18n) API
  is what you looking for, is already built in Rails no gem needed  http://guides.rubyonrails.org/i18n.html


text:
Q: How reset jquery dynamically select option? I am using dynamically select option, everything works but when I get result and changing select option it not reset result. (its adding result and not updates it).

var a = {
    Cars: [{
        "id": 1,
            "make": "Acura",
            "model": "RDX",
            "size": "Car 1"
    }, {
        "id": 12,
            "make": "Acura",
            "model": "RDX",
            "size": "Compact SUV"
    }, {
        "id": 10,
            "make": "Acura",
            "model": "MDX",
            "size": "Large SUV"
    }, {
        "id": 74,
            "make": "BMW",
            "model": "128",
            "size": "Car"
    }]
};
$("#make").change(function () {
    $('#model').empty().append($('<option></option>').val('Select Model').html('Select Model'));
    var matchVal = $("#make option:selected").text();
    a.Cars.filter(function (car) {
        if (car.make == matchVal) {
            $("#model").append($('<option></option>').html(car.model));
                            //Remove Duplicate Elements
                var seen = {};
                $('option').each(function() {
                    var txt = $(this).text();
                    if (seen[txt])
                        $(this).remove();
                    else
                        seen[txt] = true;
                });
                //

        }
    });
});

$("#model").change(function () {
    var matchVal = $("#model option:selected").text();
    a.Cars.filter(function (car) {
        if (car.model == matchVal) {
            $("#mydiv").append($('

').html(car.make));
            $("#mydiv").append($('

').html(car.model));
            $("#mydiv").append($('

').html(car.size));
        }
    });
});

<select name="make" id="make">
    <option value="0">Select Make:</option>
    <option value="1">Acura</option>
    <option value="2">BMW</option>
</select>
<select name="model" id="model">
    <option value="model">Select Model</option>
</select>

If after result I change  "Select Make" or  "Select Model" it add result e but not update.
How can i fix this ?

A: You can remove the previous result by using empty():

var a = {
    Cars: [{
        "id": 1,
            "make": "Acura",
            "model": "RDX",
            "size": "Car 1"
    }, {
        "id": 12,
            "make": "Acura",
            "model": "RDX",
            "size": "Compact SUV"
    }, {
        "id": 10,
            "make": "Acura",
            "model": "MDX",
            "size": "Large SUV"
    }, {
        "id": 74,
            "make": "BMW",
            "model": "128",
            "size": "Car"
    }]
};
$("#make").change(function () {
    $('#model').empty().append($('<option></option>').val('Select Model').html('Select Model'));
    var matchVal = $("#make option:selected").text();
    a.Cars.filter(function (car) {
        if (car.make == matchVal) {
            $("#model").append($('<option></option>').html(car.model));
                            //Remove Duplicate Elements
                var seen = {};
                $('option').each(function() {
                    var txt = $(this).text();
                    if (seen[txt])
                        $(this).remove();
                    else
                        seen[txt] = true;
                });
                //

        }
    });
});

$("#model").change(function () {
$("#mydiv").empty();
    var matchVal = $("#model option:selected").text();
    a.Cars.filter(function (car) {
        if (car.model == matchVal) {

            $("#mydiv").append($('

').html(car.make));
            $("#mydiv").append($('

').html(car.model));
            $("#mydiv").append($('

').html(car.size));
        }
    });
});

<select name="make" id="make">
    <option value="0">Select Make:</option>
    <option value="1">Acura</option>
    <option value="2">BMW</option>
</select>
<select name="model" id="model">
    <option value="model">Select Model</option>
</select>


text:
Q: how to copy a data class This is a duplicator, I want to copy the data class

data class A(
    val name:String
)

data class B(
    val name:String
)

class Replicator{
    companion object {
        fun copy(source:Any):Any?{
            if(source::class.isData){
                return source.copy()
            }
            return null
        }
    }
}

var copyList = arrayOf(A("1"),A("2"),B("1"),B("2")).map {
    Replicator.copy(it)
}

source.copy()could not be compiled
Is there any good way to achieve it?
I have a list of data class and I need a copy of it


text:
Q: How do I import data from a .xlsx file to Filemaker Pro if the "matching" field has trailing zeros? I am importing data from an Excel file into a Filemaker Pro database (FMP 12.0 v5 for Mac). I am using the imported data to "Update matching records in found set". However, the field that I am using to match occasionally contains trailing zeros.
When importing, FMP does not match the fields correctly, because it ignores the trailing zeros.
To explain further: the field in the database is a calculated text field, "courseID.personID", determined by concatenating the numerical "courseID" and "personID" fields (with a dot in between them). The field in my Excel file is formed similarly, using Excel formulae. Some "personID" values end in a zero, e.g. 120, and so courseID.personID becomes something like "123.120". I am matching the Excel field to the FMP field.
I first noticed this was happening, and was very careful to go back to Excel and make a new file (to start fresh), select all cells and set format to Text. Then, I did a Paste Special from my original data, and selected Paste as Values. All the cells in the courseID.personID column gave a "number stored as text error", with the option to convert the text to numbers. I selected the option to ignore the error, to leave all the data stored as text, with the intention of preserving the trailing zeros.
Alas, the issue persists. So, does anyone have any ideas of how to force Excel to format and communicate the proper values? Or, is it an issue of making FMP interpret the data properly, maybe by adjusting field types?

A:
the field in the database is a calculated text field,
  "courseID.personID", determined by concatenating the numerical
  "courseID" and "personID" fields (with a dot in between them). The
  field in my Excel file is formed similarly, using Excel formulae.

Come to think of it, the simplest solution would be to eliminate the calculation fields and use the original values for the import:


text:
Q: Transform multivariate Gaussian into to multivariate t-distribution A multivariate t-distribution random variable $X \sim St(\mu_X, C_X, \nu_X) \in \mathbb{R}^n$ can be constructed as follows:
\begin{equation}
 X = \sqrt{\frac{u}{\nu_X}} Y + \mu_X
\end{equation}
where $u \sim \chi^2_{\nu_X}$ and $Y \sim \mathcal{N}(0, C_X) \in \mathbb{R}^n$
Can we construct a map $T$ that transforms $Y$ into $X$ without using $u$. In other words, can we find $T$ such that $X = T(Y)$?
Tank you for your help.


text:
Q: How does the shell translate * into a list of files/dirs? When I type ls * what goes on behind the scenes in the shell?
What system calls are made?
How does the shell translate * into a list of files and directories?

A: The only involved syscalls are opendir and readdir (or whatever equivalents your local operating system provides). Actual pattern matching does not require syscall/kernel support, and is done in userland.
That said, you may find the standard C library function fnmatch -- which evaluates whether a string matches a glob-style pattern of interest.
That said, bash does not use that function call, but implements globbing internally.

A:
If ls * is a shell command line, then the shell will expand that *
according to the corresponding shell's globbing (also referred to as
Filename Generation or Filename Expansion) rules.
While different shells support different globbing operators, most of
them agree on the simplest one *. * as a pattern means any number
of characters, so * as a glob will expand to the list of files in
the current directories that match that pattern. There's an exception
however that a leading dot (.) character in a file name has to be
matched explicitly, so * actually expands to the list of files and
directories not starting with . (in lexicographical order).

check the original post https://unix.stackexchange.com/questions/62660/the-result-of-ls-ls-and-ls


text:
Q: FTP or NFS for large number of files? What is the best option between FTP and NFS if I have 1 million files (~1 TB) to transfer? I want to make sure that files don't get corrupted during the transfer.

A: FTP tends to be problematic, especially with its text file features, it's not a remote filesystem implementation. But for simple copying of a large set of files I would also recommend rsync.
For moving the data over the network, rsync is the way to go. If you get disconnected or any other problem occurs, rsync will scan through the files and only copy the differences. You can even change the original data and run rsync to synchronize again. When you're done, you can simply remove the original if you don't need it any more.
FTP is sometimes trying to be too clever and differentiate between binary and text files and possibly recode the text files. You can turn that off in your client, though. NFS is being used by lots of businesses as a network filesystem for critical data which makes it more tested than FTP whose common purpose is download data from anonftp and push data to websites, etc. If you're careful, you can just use any of the protocols but rsync is careful for you ;).


text:
Q: Remove attribute from component tag in Angular? Learning Angular components here. Their tutorial has the following example of "injecting" the custom tag for a component into html:

  Hero

  <hero-detail hero="ctrl.hero"></hero-detail>

I, however, want to achieve what I've seen many people do: remove the hero="ctrl.hero" part and end up having just:
<hero-detail></hero-detail>

How do I remove all the "extras"? I was trying to find some tutorials but it all end up being the same as above... :( Suggestions?


text:
Q: How do I clean up the messy output from the DOS/cmd shell PATH command so I can read it? Problem: When I type PATH at the command line of a DOS or Windows cmd shell, I have to squint to see if the directory I'm interested in is included. Example from my system:
PATH=C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\ActiveState Komo
do Edit 9\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\;C
:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86
)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\W
indows\System32\Wbem;C:\hp\bin\Python;C:\Program Files (x86)\IVI Foundation\VISA
\WinNT\Bin\;C:\Program Files (x86)\IVI Foundation\VISA\WinNT\Bin;C:\Program File
s\IVI Foundation\VISA\Win64\Bin\;C:\PROGRA~2\IVI Foundation\VISA\WinNT\Bin;C:\Pr
ogram Files (x86)\National Instruments\Shared\System\;c:\Program Files (x86)\Mic
rosoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tool
s\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\
WindowsPowerShell\v1.0\;C:\Program Files\Internet Explorer;C:\Program Files (x86
)\Calibre2\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\My
SQL\MySQL Utilities\;C:\Program Files (x86)\MySQL\MySQL Utilities\Doctrine exten
sions for PHP\;C:\Program Files (x86)\Pinnacle\Shared Files\;C:\Program Files (x
86)\Pinnacle\Shared Files\Filter\;C:\Program Files (x86)\nodejs\;C:\RailsInstall
er\Git\cmd;C:\RailsInstaller\Ruby2.1.0\bin;C:\RailsInstaller\Ruby2.1.0\lib\ruby\
gems\1.9.1\bin;C:\RailsInstaller\DevKit\bin;C:\xampp;C:\xampp\bin;C:\xampp\mysql
\bin;C:\Users\Owner\AppData\Roaming\npm
OUCH !!

A: come on - that much code?
echo %path:;=&echo/%

or for a file:
(for %%i in ("%path:;=";"%") do @echo(%%~i)>cleanpath.txt

and as a Bonus:
echo %path:;=&echo/%|sort

or
(for %%i in ("%path:;=";"%") do @echo(%%~i)|sort>cleanpath.txt

A: Solution: Batch file that prints one directory per line to the console. As a bonus, it also prints the same output into a file in the current directory.

@echo off
setlocal EnableDelayedExpansion

@echo off

set "str=%PATH%"

REM unREM this next line to see the raw PATH output
REM echo %str%

REM use substr to replace every ';' with (the equivalent of) ';\n'
set "CleanPath=%str:;=;&echo.% "
echo.
echo %CleanPath%

echo.
set LF=^

REM !! Above blank lines are important - DO NOT DELETE THEM !!
REM Next, copy same clean path to a file, should it be desired.
REM Quietly create a file if it does not exist.
copy /y NUL CleanPath.txt >NUL
FOR /F "tokens=* delims=;" %%i IN ("%str:;=!LF!%") DO echo %%i  >> CleanPath.txt

Result:
C:\ProgramData\Oracle\Java\javapath
C:\Program Files (x86)\ActiveState Komodo Edit 9\
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
C:\Python27\
C:\Program Files\Common Files\Microsoft Shared\Windows Live
C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\hp\bin\Python
C:\Program Files (x86)\IVI Foundation\VISA\WinNT\Bin\
C:\Program Files (x86)\IVI Foundation\VISA\WinNT\Bin
C:\Program Files\IVI Foundation\VISA\Win64\Bin\
C:\PROGRA~2\IVI Foundation\VISA\WinNT\Bin
C:\Program Files (x86)\National Instruments\Shared\System\
c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\
c:\Program Files\Microsoft SQL Server\100\Tools\Binn\
c:\Program Files\Microsoft SQL Server\100\DTS\Binn\
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Program Files\Internet Explorer
C:\Program Files (x86)\Calibre2\
C:\Program Files (x86)\Windows Live\Shared
C:\Program Files (x86)\MySQL\MySQL Utilities\
C:\Program Files (x86)\MySQL\MySQL Utilities\Doctrine extensions for PHP\
C:\Program Files (x86)\Pinnacle\Shared Files\
C:\Program Files (x86)\Pinnacle\Shared Files\Filter\
C:\Program Files (x86)\nodejs\
C:\RailsInstaller\Git\cmd
C:\RailsInstaller\Ruby2.1.0\bin
C:\RailsInstaller\Ruby2.1.0\lib\ruby\gems\1.9.1\bin
C:\RailsInstaller\DevKit\bin
C:\xampp
C:\xampp\bin
C:\xampp\mysql\bin
C:\Users\Owner\AppData\Roaming\npm
Aaaaaaahhhhhhhhh !! That's better.

My thanks to @jeb, @ephemient and others on this site and elsewhere for ideas and snippets that allowed me to put this together. Hope it helps.


text:
Q: How to get parameter value from StackTrace From within a method call I need to "jump" three layers up the stack and retrieve the type and value of the parameters passed to that method.
Getting the parameter type is easy but I couldn't find a way to get the value passed to a certain method on the stack.
var st = new StackTrace();
var frames = st.GetFrames();
var methodParameters = frame[2].GetMethod().GetParameters;
// get each parameter value

Note: using StackTraceis not mandatory.
Is there a wayto find a value of a parameter passed to a method during runtime?

A: I do not think there is a method unless you develop your own system for storing the values.
The reflection namespace represents static data about an assembly, and you would need to retrieve values at runtime.
I found PostSharp mentioned in MSDN forums, but I have never tried it.


text:
Q: Artifactory local nuget repository yields MethodNotAllowed error Trying to retrieve packages from JFrog Artifactory via Nuget.  When running "nuget restore" it marches through the sources in my nuget.config (e.g. remote, local, etc).  When it tries to fetch from the local repo, it throws MethodNotAllowed.  No errors/warnings when retrieving from other sourcesjust fine.
ex:
MethodNotAllowed https://{company}.jfrog.io/{company}/api/nuget/it-nuget-prd-local/nuget/Packages(Id='NLog',Version='4.5.10') 212ms

Thanks in advance for any help.
jason

A: Looks like your config is pointing to incorrect URL i.e. with extra 'nuget' in the URL path.
Correct path should be something like below:
https://{company}.jfrog.io/{company}/api/nuget/it-nuget-prd local/Packages(Id='NLog',Version='4.5.10')

A: Turns out it was an issue with our firewall and a bug with the vendor on top of that.  Security team worked around it and all is well now.
Thanks!


text:
Q: error 1004, Method "Locked" on "Range" failed: VBA if cell1="" Then cell2=x I am creating macro that should take values from one range and if blank, lock cells in another range.
I am still getting error 1004, Method "Locked" on "Range" failed.
Sub function_one()
    Dim cell As Range
    For Each cell In Range("Table[[Column1]:[Column2]]")
        Dim cell2 As Range
        For Each cell2 In Range("Table2[[Column1]:[Column2]]")
            If cell.Value = "" Then
                cell2.Locked = True
            End If
        Next cell2
    Next cell
End Sub

What am I missing?

A: You cannot lock a locked cell.
So either unlock it first to be sure, or check it first and only lock it if not already locked.
To unlock first, one line of code added to do this, your original becomes:
Sub function_one()
    Dim cell As Range
    For Each cell In Range("Table[[Column1]:[Column2]]")
        Dim cell2 As Range
        For Each cell2 In Range("Table2[[Column1]:[Column2]]")
            If cell.Value = "" Then
                cell2.Locked = False
                cell2.Locked = True
            End If
        Next cell2
    Next cell
End Sub

Or, you could check if unlocked and only then lock it:
Sub function_one()
    Dim cell As Range
    For Each cell In Range("Table[[Column1]:[Column2]]")
        Dim cell2 As Range
        For Each cell2 In Range("Table2[[Column1]:[Column2]]")
            If cell.Value = "" Then
                If cell2.Locked <> True then cell2.Locked = True
            End If
        Next cell2
    Next cell
End Sub

In both examples, your code is not otherwise modified. There are a few things I too would do differently, including the Table[[Column1]:[Column2]] part, the nested loops, etc. but all that may be beyond the scope of your question.

A: First, if you want to loop through a collection of cells, a single
'For Each' loop is enough.
Secondly, Range("Table[[Column1]:[Column2]]") can be the reason why the bug occured. It is easy to use VBA find function to locate the range.
You might try the following code to see if it works:
Sub function_one()
    'By changing searchOrder, searchDirection, .Row and .Column to locate the firstRow, firstColumn and lastColumn
    lastRow = ActiveSheet.Cells.Find("*", searchOrder:=xlByRows, searchDirection:=xlPrevious).Row
    For Each cell In Range("A1", "C" & lastRow)
        If cell.Value = "" Then
            cell.Locked = True
        End If
    Next cell
End Sub


text:
Q: Append to element is not working I have the following HTML:
<textarea class="input" placeholder="Tap to enter message" maxlength="160"></textarea>

!

?

,

:

;

q

1

w

2

e

3

r

4

t

5

y

6

u

7

i

8

o

9

p

0

a

s

d

f

g

h

j

k

l

⇧_

z

x

c

v

b

n

m

?123

,

.

with the following javascript:
$('.keyboard ul li').click(function() {
  var data = $(this).data('letter');
  $('.input').append(data);
});

What I want to have happen is when I click on one of the list items, I want the data-letter to insert itself into the input, sorta like an onscreen keyboard. But it isn't working. Can someone help me?
Here is a Fiddle
Update
This works now
My next problem is the uppercase button. When I click the button, the characters turn to uppercase. How would I use the data to inject an uppercase letter into the input?
The final problem is the first row of letters won't inject into the input. How do I fix this?

A: Try the below
Enable Jquery file instead of mootools in the fiddle
Thanks

A: Try:
Demo
$('.keyboard ul li').click(function() {
    var data = $(this).data('letter');
    $('.input').val( $('.input').val()+ data);
});

A: All you have to do is remove the margin on the .input element (it's offscreen for me), and enable jquery on the jsfiddle.  After that it works fine for me.

A: Not sure why jquery .data() not work, but you can use below "this.dataset.xxx"
var data = this.dataset.letter;

A: This is the solution I came up with
keys = $(".keyboard ul li");
keys.on("click", function() {
  var let = $(this).text(),
    upperlet = let.toUpperCase(),
    lowerlet = let;
  if (keys.hasClass("uppercase")){
    input.append(upperlet);
  }else {
    input.append(lowerlet);
  }
});

Instead of having the data-letter attribute for every single list-item, I got the text using this function, and appended it on click. This now also accounts for the uppercase letters as well.


text:
Q: How to properly store UTC datetime and work with local offset? I am storing data as UTC, but I am very confused on how to properly retrieve it. I store the value as UTC in a datetime column in MSSQL. Currently the way I retrieve it is by setting the GMT offset to the start datetime range and end datetime range. I am also needing to apply aggregation to that datetime field (group by) and display it in the user's proper local timezone.  The issue I am having is say if I look for a range today it will pull up columns that match correctly, but the datetime value in those columns can be different UTC days; I am grouping by day. So for example when someone selects a range for the beginning of the day and the end (for today) they are presented with UTC datetime values from yesterday and today; but if I try to apply the GMT offset to the display value it still comes out as possibly 2 different dates. How can I properly coordinate the range and the display?
Thanks

A: Converting UTC format date to Standard time of CST or EST (for example) is straight forward. We have to store the offset value in a separate column or table for each timezone which we need in our application.
For example: UTC to CST is -6 hrs. Similarly UTC to EST is -5 hrs.
DECLARE @UTC_Date DATETIME
SET @UTC_Date = GETUTCDATE()

SELECT
 @UTC_Date AS [UTC],
 DATEADD(hh, -6, @UTC_Date) AS [CST - Standard Time],
 DATEADD(hh, -5, @UTC_Date) AS [EST - Standard Time]

It gets complicated once we bring in Daylight saving into calculation. But if the given date falls under daylight saving then the above calculation won't work.
So how is Daylight saving calculated?

*

*If the year <= 2006 then daylight saving is between:
2 am on First Sunday in April till 2 am on Last Sunday in October

*If the year >= 2007 then daylight saving is between:
2 am on Second Sunday in March till 2 am on First Sunday in November

*UTC to CST (Standard Time) = -6

*UTC to CDT (Daylight Time) = -5

*UTC to EST (Standard Time) = -5

*UTC to EDT (DayLight Time) = -4

Check out the solution for handling daylight saving here - http://vadivel.blogspot.com/2011/10/timezone-conversion-utc-to-cst-with.html


text:
Q: Colors in treemap it would be great to clarify how colors are calculated when ploting treemap (I use gvisTreeMap function from R googleVis library).

*

*Documentation is not very informative. What is it meant by "The color value is first recomputed on a scale from minColorValue to maxColorValue"? Usually I use treemap to display sales (size) and sales difference (color). So ideally I would like to color rectangles so that I can distinguish positive from negative growth, which as I understand is not possible at the moment.

*What bothers me most right now is that "... colors are valued relative to all other nodes in the graph". Is there any way to fix colors, so that sales difference, say -25 always gets the same color.

A: If I have understood your problem correctly, I believe the following will solve it:
Let's say your data is percentages, so can go from 0 to 100.  Set minColorValue=-100 and maxColorValue=100
(Or if using a different range, just set it so that the min value is the negative of the max value so that the average is 0.)
Then, if you set the colours to, for example, minColor='red' and maxColor='green', this should solve part 1 (negative values will be displayed in red, and positive in green)
Also, it seems that setting maxColor and minColor fixes the average value the colors are calculated from, so that this also solves part 2 (that is, -25 will then always have the same color in the graph)

A: Color is computed as the average color value of all child nodes of a branch.  A branch with no child nodes uses the color value from the DataTable.  This color value is then scaled on the minColorValue to maxColorValue scale, and a color is computed between minColor and maxColor based on the scale.
Colors are not relative to other nodes on the graph - the size of the node is relative.