text:
Q: How to get topOffset with a class named 'dropdown' in Angular I need the same result in Angular as like jQuery/HTML.
Using jQuery, I'm getting the same topOffset value if I scroll or not.
// get the top offset of the dropdown (distance from top of the page)
var topOffset = $(".dropdown").offset().top;

For your information, in Angular I am using template variable with @ViewChild, but the topOffset value got changed and is not giving the same required result as like jQuery.
  @ViewChild('dp') dropdown: ElementRef
  functionName() {
     let topOffset = this.dropdown.nativeElement.getBoundingClientRect().top;
  }

Please let me know in the comment, what I have to do to achieve the required result.

A: Just add .top
offsetTop is relative to it's place in the document, not relative to the view port
You can get offsetTop from the top of the document using this
 this.dropdown.nativeElement.getBoundingClientRect().top

A: jQuery is opensource, if you look for in github (this link) you see
offset: function( options ) {
    ...
    rect = elem.getBoundingClientRect();
    win = elem.ownerDocument.defaultView;
    return {
        top: rect.top + win.pageYOffset,
        left: rect.left + win.pageXOffset
    };
 }

As you see you need add win.pageYOffset
So you can create a function
  getOffset(element:HTMLElement){
    const rect = element.getBoundingClientRect();
        const win = element.ownerDocument.defaultView;
        return {
            top: rect.top + win.pageYOffset,
            left: rect.left + win.pageXOffset
        };
  }

And use
this.offset= this.getOffset(this.dropdown.nativeElement)

You can see in this stackblitz

A: You can use offsetTop instead of getBoundingClientRect().top
 @ViewChild('dp') dropdown: ElementRef
  functionName() {
     let topOffset = this.dropdown.nativeElement.offsetTop;
  }

Check a simple sample here:
https://stackblitz.com/edit/angular-ivy-6jmua2?file=src%2Fapp%2Fapp.component.html


text:
Q: Lost my changes in git after branch and stash? I guess I did something I shouldn't have.  I tried to use stash, but thought that I should branch off, and do it there.  Anyway, so these are the commands I did:
git branch test     # created my test branch
git checkout test   # moved to my test branch
git status          # showed that the files were still changed.
git stash           # testing stash
git stash list      # showed that the stash was there
git status          # showed that the files were still changed?
git diff            # showed that the differences were only file permissions.
git stash apply     # Tried to get back my changes. States:
                    #   error: Your local changes to the following files would be overwritten by merge:
                    #   ...
                    #   Please, commit your changes or stash them before you can merge.
                    #   Aborting
git commit file -m "- committing test code that doesn't work."
git status          # Shows that it's clean

So, I'm thinking that the problem is that branching and checking out wiped my changes instead of preserving them.  Is that correct?  If not, can I get my changes back?

A: git stash apply     # Tried to get back my changes. States:
                    #   error: Your local changes to the following files would be overwritten by merge:
                    #   ...
                    #   Please, commit your changes or stash them before you can merge.
                    #   Aborting
git commit file -m "- committing test code that doesn't work."
git status          # Shows that it's clean

This suggests that the stash wasn't applied (the attempt was aborted because you had local changes that would have been overwritten by the stash).
The last two commands commit the changes that existed in the working directory (at least, I assume they did - you've cut the git add step from your list of commands-run). You never re-apply the stash, so it should still exist.
Check what git stash list says.
From the comment, git stash list says stash@{0}: WIP on test: 0581365 Added. This means you've got a stashed commit, which you can apply (for example git stash apply).

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS combining public accessible RDS with Lambdas accessing Internet? I have a VPC with 3 private and one public subnets. In the 3 private subnets i host the RDS and the Lambda functions. In the public subnet i host a NAT Gateway. The 3 private subnets point via a routing table to the NAT Gateway. Within this setup my Lambda functions successfully communicate with my RDS and the Internet, but I cannot access the RDS from my home computer as the NAT is blocking external access to the VPC. My question is now:
How do I let the Lambda functions access the RDS within the VPC and make the RDS public accessible from my computer at the same time?
P.S.: Until now I always have to change manually the routing of my 3 private subnets to the IGW to make the RDS accessible.

A: First a clarification: The NAT is not blocking external access to the VPC. A NAT Gateway simply provides Internet access to resources in your VPC that don't have public IP addresses. The NAT is unrelated to your being able to access the VPC externally. In fact you haven't done anything to allow external access yet.
You have the following options to access your RDS instance externally:

*

*Add a VPN server to your VPC, in the public subnet, which would allow you to connect to the RDS server after establishing a VPN connection.

*Move your RDS server to the public subnet and enable the "publicly accessible" flag, which would allow you to connect to the RDS server directly.

*Create a Linux Bastion Host in the public subnet, which would allow you to connect to the RDS server via SSH port forwarding.

In any of these scenarios, as long as the Lambda function and the RDS instance are in the same VPC, then the Lambda function will have access to the RDS instance. And as long as the Lambda function remains in the private subnet(s) with a NAT Gateway it will have Internet access.

A: You need to create a Bastion Host in your public subnet. A Bastion Host provides connectivity from the public Internet to your private VPC subnets.
A common Bastion Host for AWS is OpenVPN. You can find preconfigured AMIs in the AWS Marketplace.
AWS Security: Bastion Host, NAT instances and VPC Peering
OpenVPN

A: There is a guide on gist.github by user reggi titled How to setup AWS lambda function to talk to the internet and VPC. The guide walks you through the steps for setting up a AWS Lambda to talk to the internet and a VPC.
You can find there in the comments solutions for the complexities of connecting lambdas to RDS and the internet whilst maintaining a publicly accessible RDS without a VPN, some of this information is in the comments. I have added this information here in case the information becomes unavailable.

To allow lambdas to have internet access, RDS access and to allow the
  RDS to be publicly available (hopefully within a specific ip range -
  i.e your static IP), your RDS's subnet group must contain only public
  subnets; that is subnets which have a route table that points
  0.0.0.0/0 to an IGW which is attached to your VPC. You must create a subnet group in Amazon RDS > Subnet Groups which contains the public
  subnets and then launch an RDS instance with this new subnet group (or
  configure your current system to these specifications).

https://gist.github.com/reggi/dc5f2620b7b4f515e68e46255ac042a7


text:
Q: How do I set the TERM environment variable for the Gnome Terminal Emulator app? The TERM environment variable defaults to xterm so the .bashrc file does not provide full color in the shell by default.
How to I change the TERM environment variable to xterm-color for the gnome terminal emulator app only?
Update: By full color I mean changes the command prompt to use color in addition to displaying output such as directory listing in color too.

A: There are two issues here.
One is how to detect if you're running inside gnome-terminal (or any other app using the same vte widget for the current terminal emulation). Assuming you're on a recent enough Ubuntu, the presence of the $VTE_VERSION variable tells you this. You could edit your .bashrc to contain something like
if [ -n "$VTE_VERSION" ]; then
    # Gnome-terminal and other vte3-based emulators
    color_prompt=yes
fi

The other issue is that for some reason Ubuntu's default .bashrc tries to look for xterm-color which is not really used nowadays. Either the standard xterm (which supports colors anyways), or the more modern xterm-256color are the popular choices, the default slowly moving towards the latter. (gnome-terminal changed its default from xterm to xterm-256color in 3.16, which is present in Ubuntu 15.10 beyond)
If you would like to move forward and already enjoy plenty of colors in several applications, I recommend that you already switch to TERM=xterm-256color, which you could also do in the if-branch above.
Ubuntu's .bashrc is obsolete for using xterm-color. I much rather recommend modifying these bits in the script around whatever $TERM you already have (xterm) or would prefer to have (maybe xterm-256color), rather than the other way around, modifying $TERM to match .bashrc's requirement.

A: For gnome-terminal
Edit the profile settings in gnome-termninal:

Replace /bin/bash with your shell command and use your parameter for TERM.
You can also edit the entries with dconf. Open a terminal and start dconf-editor:
dconf-editor

Open the entry org/gnome/terminal/legacy/profiles: and select your profile. Change the value for custom-command.


text:
Q: Why does slicing decrease capacity by one So I was testing slices and thought that go won't decrease the capacity.  But from what i see it does.  Does anyone know the reason for the drop in capacity of 1?   (go version go1.8 linux/amd64)
package main

import "fmt"

func main() {
    name := make([]int, 0, 100000000)
    fmt.Printf("%d | %d\n", cap(name), len(name))
    for x:= 0; x < 1000; x++ {
        name = append(name, x)
    }
    fmt.Printf("%d | %d\n", cap(name), len(name))
    name2 := name[1:500]
    fmt.Printf("%d | %d\n", cap(name2), len(name2))
}

The output is
100000000 | 0
100000000 | 1000
99999999 | 499

Changing the size to 1000 changes the output to this
1000 | 0
1000 | 1000
999 | 499

A: By changing your code to the following (starting at index 0), then the capacity is unchanged inline with what you expected.  By using index 1 in the slice you have lost the first item (item at 0) which is why there is an apparent capacity change.
  name2 := name[0:500]
  fmt.Printf("%d | %d\n", cap(name2), len(name2))

Producing the output:
100000000 | 500

A: When you shrink a slice from the left (increasing the slice's start index in the underlying array), you reduce its capacity, because it can never grow to the left. When you shrink a slice from the right (reducing the slice's length), the capacity is unchanged, because a slice can grow to the right. For example:
name := make([]int, 100)
fmt.Printf("%d | %d\n", cap(name), len(name))
name2 := name[:50]  // Won't shrink because left side is unchanged
fmt.Printf("%d | %d\n", cap(name2), len(name2))
name2 = name[50:]   // WILL shrink because left side is moved up
fmt.Printf("%d | %d\n", cap(name2), len(name2))

Outputs:
cap 100 | len 100
cap 100 | len 50
cap 50 | len 50

Playground demo: https://play.golang.org/p/jbGRmexV5d-


text:
Q: can you set a default value to a custom field I'm looking to set a default value to a specific custom field, in case the client doesn't add into the custom field it already has a specific number associated with it.
one step deeper, I'd like it so if cat =22 is selected this custom field is automatically added into the post with a default that hopefully the client will add the proper number
I think this can be accomplished by a global function but my brain is just not processing this right now

A: You can check it by adding a hook to save_post action. In this way all your posts will have default value for a custom field.
add_action( 'save_post', 'wpse8170_save_post', 10, 2 );
function wpse8170_save_post( $post_id, WP_Post $post ) {
    if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || !current_user_can( 'edit_post' ) ) {
        return;
    }

    if ( has_category( 22, $post_id ) && !get_post_meta( $post_id, 'my-custom-field', true ) ) {
        update_post_meta( $post_id, 'my-custom-field', 'my default value' );
    }
}

A: You would not do this via a global, you simply use the default functionality of add_post_meta.
// your loop
if ( in_category(22)) {

    //check if the meta field has a value
    $meta_values = get_post_meta($post->ID, 'your_meta_key', true);

    if(empty($meta_values)){
    //add a default value
    add_post_meta($post->ID, 'your_meta_key', 'some default value');
    }
}

Reference:  http://codex.wordpress.org/Custom_Fields


text:
Q: JavaFX Accordion doesn't collapse when in tab pan Ok, so I have an accordion which doesn't close properly when it's a child of a Tab Pane but works as expected outside it. I don't know where the problem stems from.
Also, I just found out that resizing the window causes the layout to display properly.
Is there a way to fix this?
Here is the FXML:
<AnchorPane maxWidth="350" minWidth="350.0" prefWidth="350.0">
            <TabPane fx:id="tabPane" tabClosingPolicy="UNAVAILABLE" AnchorPane.bottomAnchor="0"
                     AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0">
                <Tab text="Friends">
                    <AnchorPane>
                        <Accordion fx:id="accordion2" AnchorPane.bottomAnchor="45" AnchorPane.leftAnchor="0"
                                   AnchorPane.rightAnchor="0"
                                   AnchorPane.topAnchor="0" expandedPane="$friendsPane">
                            <panes>
                                <TitledPane fx:id="friendsPane" animated="false" styleClass="myClass" text="Friends">
                                    <ScrollPane fitToWidth="true" hbarPolicy="NEVER" AnchorPane.bottomAnchor="0"
                                                AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0"
                                                AnchorPane.topAnchor="0">
                                        <VBox fx:id="friends" fillWidth="true" styleClass="vbox">
                                            <children>
                                            </children>
                                        </VBox>
                                    </ScrollPane>
                                </TitledPane>
                                <TitledPane fx:id="groupsPane" animated="true" styleClass="myClass" text="Groups">
                                    <ScrollPane fitToWidth="true" hbarPolicy="NEVER" AnchorPane.bottomAnchor="0"
                                                AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0"
                                                AnchorPane.topAnchor="0">
                                        <VBox fx:id="groups" fillWidth="true" styleClass="vbox">
                                            <children>
                                            </children>
                                        </VBox>
                                    </ScrollPane>
                                </TitledPane>
                            </panes>
                        </Accordion>
                        <Button fx:id="activateCheck" mnemonicParsing="true" onAction="#activateCheck" text="New Group"
                                AnchorPane.bottomAnchor="10" AnchorPane.leftAnchor="10"/>
                        <Button fx:id="createGroup" mnemonicParsing="false" onAction="#createGroup" text="Create Group"
                                visible="false" AnchorPane.bottomAnchor="10" AnchorPane.leftAnchor="10"/>
                    </AnchorPane>
                </Tab>
                <Tab text="Received Requests">
                    <ScrollPane fitToWidth="true" hbarPolicy="NEVER" prefHeight="200.0" prefWidth="200.0">
                        <VBox fx:id="requestsRecv" minHeight="0.0" minWidth="0.0" prefHeight="200.0" prefWidth="200.0"
                              styleClass="vbox">
                            <children>
                            </children>
                        </VBox>
                    </ScrollPane>
                </Tab>
                <Tab text="Sent Requests">
                    <ScrollPane fitToWidth="true" hbarPolicy="NEVER" prefHeight="200.0" prefWidth="200.0">
                        <VBox fx:id="requestsSent" minHeight="0.0" minWidth="0.0" prefHeight="200.0" prefWidth="200.0"
                              styleClass="vbox">
                            <children>
                            </children>
                        </VBox>
                    </ScrollPane>
                </Tab>
            </TabPane>
        </AnchorPane>

Here is what it looks like:

A: It was caused by a conflict between setting tab pane max and min width and having the controller set up a listener forcing the split pane that contained the tab pane divider to a set position.


text:
Q: Remove XML tags with Regex tools Here is a snippet of my XML file
<layoutItems>
            <behavior>Edit</behavior>
            <field>ID</field>
</layoutItems>
<layoutItems>
            <page>lastViewedAccount</page>
            <showLabel>false</showLabel>
            <showScrollbars>false</showScrollbars>
            <width>100%</width>
</layoutItems>
<layoutItems>
            <behavior>Required</behavior>
            <field>Name</field>
</layoutItems>

I want to remove the section in the middle i.e
<layoutItems>
            <page>lastViewedAccount</page>
            <showLabel>false</showLabel>
            <showScrollbars>false</showScrollbars>
            <width>100%</width>
</layoutItems>

This section can appear anywhere inside the file along with other tags.
What is the best way of using some string manipulation tool to remove this? I have been been trying my luck with sed but no success. Any help would be appreciated.

A: Please note: you should provide as much information as you can. Speaking generally parsing of html, xml, json and so on with regex it not a good idea, use always a html-parsing- and  xml-parsing -tool! The following sed code may help you in the mean time. And so please also note: it may FAIL with other files and other structures! Do not use in production! I assume NO warranty!
sed -r '/<layoutItems>/{:ka;N;s#(</layoutItems>)#\1#;Tka;s/lastViewedAccount//;T;d}' file

Inputfile with 2 lastViewedAccount tags:
    <?xml version="1.0" encoding="UTF-8"?>
    <Layout xmlns="http://test.com/2006/04/metadata">
        <emailDefault>false</emailDefault>
        <headers>PersonalTagging</headers>
        <headers>PublicTagging</headers>
        <layoutSections>
            <customLabel>false</customLabel>
            <detailHeading>false</detailHeading>
            <editHeading>true</editHeading>
            Account Information
            <layoutColumns>
                <layoutItems>
                    <page>lastViewedAccount</page>
                    <showLabel>false</showLabel>
                    <showScrollbars>false</showScrollbars>
                    <width>100%</width>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>OwnerId</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Required</behavior>
                    <field>Name</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>ParentId</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>AccountNumber</field>
                </layoutItems>
                <layoutItems>
                    <page>lastViewedAccount</page>
                    <showLabel>false</showLabel>
                    <showScrollbars>false</showScrollbars>
                    <width>100%</width>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>Site</field>
                </layoutItems>
            </layoutColumns>
      </layoutSections>
    </Layout>

Outputfile, lastViewedAccount tags removed:
    <?xml version="1.0" encoding="UTF-8"?>
    <Layout xmlns="http://test.com/2006/04/metadata">
        <emailDefault>false</emailDefault>
        <headers>PersonalTagging</headers>
        <headers>PublicTagging</headers>
        <layoutSections>
            <customLabel>false</customLabel>
            <detailHeading>false</detailHeading>
            <editHeading>true</editHeading>
            Account Information
            <layoutColumns>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>OwnerId</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Required</behavior>
                    <field>Name</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>ParentId</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>AccountNumber</field>
                </layoutItems>
                <layoutItems>
                    <behavior>Edit</behavior>
                    <field>Site</field>
                </layoutItems>
            </layoutColumns>
      </layoutSections>
    </Layout>

A: GNU sed:
sed -nr 'H; \#</layoutItems>#{x;s/(lastViewedAccount)/\1/;Tk;p;:k;x;s/.*//;x;s///;x;d}' file

$sed -nr 'H; \#</layoutItems>#{x;s/(lastViewedAccount)/\1/;Tk;p;:k;x;s/.*//;x;s///;x;d}' file

    <layoutItems>
            <page>lastViewedAccount</page>
            <showLabel>false</showLabel>
            <showScrollbars>false</showScrollbars>
            <width>100%</width>
    </layoutItems>


text:
Q: php data on crud doesn't inserted im making an insert function on php, everything is ok, there is no error but the data doesnt show up in the database, here is my php file
<?php
include 'koneksi/koneksi.php';

if(isset($_POST['Submit'])) {
    $id_koperasi = $_POST['id'];
    $nama_koperasi = $_POST['nama'];
    $alamat = $_POST['alamat'];
    $telp = $_POST['telp'];
    $hp = $_POST['hp'];
    $nama_cp = $_POST['kontak'];
    $email = $_POST['email'];
    $nama_cp = $_POST['kontak'];
    $tanggal = $_POST['tgl'];
    $ket_fu = $_POST['ket'];
    $hasil_pembahasan = $_POST['hasil'];
    $status = $_POST['stat'];

    $query = "INSERT INTO t_koperasi(id,id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES ('',
            '$id_koperasi',
            '$nama_koperasi',
            '$alamat',
            '$telp',
            '$hp',
            '$nama_cp',
            '$tanggal',
            '$ket_fu',
            '$hasil_pembahasan',
            '$status')"
    ;

    if (mysqli_query($con,$query)) {
        header("location:index.php");
    }else {
        error_log( "This code has errors!" );

    }
}

include 'views/v_form.php';

?>
and this is my database t_koperasi structure

A: The id is auto increasing, so you should remove id column in you insert sql. Also, the method you are using is dangerous, you should not totally trust what pass to you by other users in you website page, instead, you need to add filter functions.

A: You Query Should Look Like this. At Least in postgresql and MySql
$query = "INSERT INTO t_koperasi(id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES (
        '".$id_koperasi."',
        '".$nama_koperasi."',
        '".$alamat."',
        '".$telp."',
        '".$hp."',
        '".$nama_cp."',
        '".$tanggal."',
        '".$ket_fu."',
        '".$hasil_pembahasan."',
        '".$status."')"
;

You do not need to insert  value into ID .Because ID expected to be the primary key with default value (auto increment).
Hope This works for you!

A: Simple remove id and ' ' .  i hope work fine.
or
You just copy this code and past your project
<?php
include 'koneksi/koneksi.php';

if(isset($_POST['Submit'])) {
$id_koperasi = $_POST['id'];
$nama_koperasi = $_POST['nama'];
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$hp = $_POST['hp'];
$nama_cp = $_POST['kontak'];
$email = $_POST['email'];
$nama_cp = $_POST['kontak'];
$tanggal = $_POST['tgl'];
$ket_fu = $_POST['ket'];
$hasil_pembahasan = $_POST['hasil'];
$status = $_POST['stat'];

$query = "INSERT INTO t_koperasi(id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES ('$id_koperasi',
        '$nama_koperasi',
        '$alamat',
        '$telp',
        '$hp',
        '$nama_cp',
        '$tanggal',
        '$ket_fu',
        '$hasil_pembahasan',
        '$status')"
;

if (mysqli_query($con,$query)) {
    header("location:index.php");
}else {
    error_log( "This code has errors!" );

}
}  include 'views/v_form.php';


text:
Q: Do cycle graphs determine groups up to isomorphism? This erroneous version of the wikipedia article for Cycle Graphs stated that the cycle graph of different groups could be the same. The immediate error is that it stated that the cycle graph of $\mathbb Z_2 \times \mathbb Z_8$ is the same as $\mathbb Z_{16}$.
My question is, in general, if a group $G$ and $H$ are not isomorphic, can they have isomorphic cycle graphs?

A: Let $p$ be an odd prime and let $G$ and $H$ be two non-isomorphic $p$-groups of order $p^a$ and of exponent $p$. (These always exists for $a\geq 3$.)
If I understood the definition correctly, $G$ and $H$ will both have the same cycle graph.


text:
Q: What is the static link used for? (before any misconceptions may arise, I'm not talking about the linkage of libraries.)
In my textbook (about MIPS assembly), the following is stated:

Procedure/Function frame (aka activation record)

*

*Used by some compilers to manage stack storage

*In addition to Stack Pointer, use Frame Pointer register $fp
  to keep track of all pertinent information on the stack pertaining
  to a procedure/function invocation.

  Caller side:

*

*Caller pushes arguments on the stack
  (or passes them via $a0 - $a3 if not more than 4 arguments)

*Caller reserves space on the stack for return values
  (or they are returned via $v0 - $v1)

*Caller passes static link (address on the stack of the nearest
  occurrence of the next lexically enclosing procedure/function)
  via $v0

  (goes on about callee side etc...)

It was hard for me to understand the dynamic links in MIPS (frame pointers etc) because
I couldn't find out why one would need that. Eventually I found out that they are not needed at all, it just comes in handy when debugging.
I feel similar about these static links, can someone explain to me what they are used for (preferably with an example)?

A: The static link, lexically enclosing scope, or static parent, is needed in languages where you can declare functions inside functions.
E.g., in the following pseudo-code
int foo(int s, int t) {
    int x;
    ...
    int bar(int a) {
        return a + x;
    }
}

in bar, the variable x is accessed relative to the static link.
With the stack frame layout
------------------------
arg 1: s
arg 2: t
return address
local variable: x
...
-------------------------

assuming 32 bit values for all,  the address for accessing  x in bar would be static_link + 12

A: It's about scope. Some languages allow functions to be nested within functions; in those the static link is a link up to the stack frame of the function that includes that language. It's called the static link because to what it will link is known at completive (though not exactly to where, since that'll be wherever on the stack the parent function established its frame).
Compare and contrast with the dynamic link, which always just points to the stack frame above. That's dynamic because (usually) any of a number of functions may have called in so an instance of which function owns the frame pointed to isn't known at compile time.
Imagine a function F, with sub functions Fa, Fb, Fc. F calls Fa, Fa calls Fb, Fb calls Fc. Fa, Fb and Fc can all access the local storage of F according to the semantics of the language.
Then Fa's dynamic and static links will point to a stack frame associated with F.
Fb's dynamic link will point to Fa's frame; its static link will point to F's.
Fc's dynamic link will point to Fb's frame; its static link will point to F's.


text:
Q: How are multiple symbols displayed as one called and what is the purpose of them? How do you call characters like this annoying one below? What are they supposed to do, or more importantly - why do they even exist? :) Can I somehow add them to my HTML source (and is it valid) and eventually don't let the users put them into comments etc.?
̷̲̙̲͇̲̙̲̹̲̙̲͇̲̙̲̲̙̲͇̲̙̲͇̲̙̲͇̲̙̲᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅a̲̙̲͇̲̙̲͈̲̙̲͇̲̙̲̪̲̙̲͇̲̙̲̲̙̲͇̲̙̲᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷅᷉᷅᷅᷅᷅᷅᷅᷅᷅

See: http://jsfiddle.net/10q44c74/

A: They're simply a sequence of unicode combining diacritics. In this case about 118 meaningless ones in a row.
What is their purpose? The wikipedia article explains it just fine, but let's combine the letter n and the combining tilde diacritic. Hurray, now we can write out añejo (as a six unicode codepoints string, that is rendered as five letters).
Of course, you can be silly and just combine a hundred combining marks to produce nonsense. Usually there's no point in restricting this: even if it looks like one letter, it's still 118 code points, and anything with a character limit will count each diacritic as one fewer real letters you can type.
It's also good for writing awesome crazy stuff,  l̙̣͇ͦ̈́ͫ͌ͤ͊̿i̻̱͍̽͐̂̑ͪk̹̞̼̫͔ẻ̫̯ ̦͔͎̿t̼̼͔̰̿͋̈́ͬͨhͯ͛̚i̖ͤs͙͓̻̝̗̼̈́͂ ̠̮͉̙̲̺̿ͅk͖ͤ͆̒̅̾́̉ì̪͎̗͓̻̪ͤn͍̥̱̠̲̳̖̓ͤ̿d̟̮̍̾ͩ̂ ̜͖͉̠o͚̠̾ͥ͌̔f̭̖ͥͤͦ̉ͨ ̦̌t̳̩͐͐ͤẹ̉̃x̟̙̌ͥͯ̈͂̆͌t.


text:
Q: Problem with caption numbering custom float after renewing section command How can I avoid this extra dot in caption that appears without removing     \renewcommand{\thesection}{\arabic{section}.}
\documentclass[12pt,a4paper]{article}
\usepackage[croatian]{babel}
\usepackage{float}

\renewcommand{\thesection}{\arabic{section}.}

\floatstyle{plain}
\newfloat{graphic}{thp}{lop}[section]
\floatname{graphic}{Grafikon}

\begin{document}

\begin{graphic}
\caption{some fancy \texttt{caption} }
\label{fig:flowchart}
\end{graphic}

\end{document}

A: You don't want to add the period to \thesection, but rather to modify how the section titles are typeset, adding a period after the number; unfortunately there's no "official" user interface for this, but it's not difficult either.
\documentclass[12pt,a4paper]{article}
\usepackage[croatian]{babel}
\usepackage{float}

\makeatletter
\renewcommand{\@seccntformat}[1]{\csname the#1\endcsname.\quad}
\makeatother

\floatstyle{plain}
\newfloat{graphic}{thp}{lop}[section]
\floatname{graphic}{Grafikon}

\begin{document}
\section{Grafikon}
\begin{graphic}
\caption{some fancy \texttt{caption}}
\label{fig:flowchart}
\end{graphic}

\end{document}


text:
Q: Clear parent element css properties for children element I have two elemnt, for example:

    parent

child

I want, that child element not haves parent CSS properties, please tell, how can make this?

A: You can

*

*Put all of the children into an . The parent window's CSS won't be reflected within the iframe.

*You can modify a CSS reset like http://meyerweb.com/eric/tools/css/reset/ to suit your needs (ie. edit and prefix each section of the reset with the selector to your children as necessary).

  parent

child

(just using the last line of the reset above as an example), you could do something like
#children table {
  border-collapse: collapse;
  border-spacing: 0;
}

to reset
 elements within #children. You have to test and tweak this for your own needs.

A: a child div will always inherit the styling of its parent div, that is what css is all about. You could consider something like this

  parent text

       child text

then in your styles (somwhere in your html, or prefarbly in a linked stylesheet) you could do something like this:
body, .parent div {
  color: #000;
  ...
}
.parent {
  color: #f00;
  ...
}

note that if you add more styling to the .parent, you would have to set an alternative for the child divs  (.parent div) to prevent that property from beeing inherited by the children


text:
Q: AngularJS - can't detect event on click I am making my first steps with angular, I just want to simply clear the content of a input text when I click on it. this is the markup

First Name: <input id="123" type="text" ng-click="unsetValue($e)" ng-model="firstName">

Last Name: <input id="456" type="text" ng-click="unsetValue($e)" ng-model="lastName">

Full Name: {{firstName + " " + lastName}}

this is the js in an external file
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";

$scope.unsetValue = function($event) {
    console.log($event);
}

when I click the control, $event is undefined, any idea why?
thanks
M

A: You have to call ng-click in this way: ng-click="unsetValue($event)"
Update
Later in the function you can name parameter as you like for example:
$scope.unsetValue = function(e) {
    console.log(e);
}

A: The name of the variable passed in is $event, not $e
so you need to use ng-click like this
ng-click="unsetValue($event)"

the rest of your code is fine.


text:
Q: RegexLike code won't return numbers that start with 0 I am trying to return numbers from strings that are either whole numbers (positive or negative) or numbers to two decimal places, however the code seems to be ignoring numbers that start with 0, I am hoping for some help on how to fix this issue, the code is as follows :
WITH A AS(
SELECT CURRENT_BALANCE, ( CASE WHEN (REGEXP_LIKE(CURRENT_BALANCE,'^-?[0-9]+(\.[0-9]{1,2})?$')) then 1 ELSE 0 end ) AS T FROM BALANCE_TABLE )

SELECT * FROM A
WHERE T = 0
LIMIT 1

-- The regexp_like is where the issue lies, the code above just returned to me the numbers that weren't being picked up
Edit: Example of what is not returned: 0.00, -0.07, 0.04
Thank you

A: Please try with WHERE T = 1
WITH A AS(
SELECT CURRENT_BALANCE, ( CASE WHEN (REGEXP_LIKE(CURRENT_BALANCE,'^-?[0-9]+(\.[0-9]{1,2})?$')) then 1 ELSE 0 end ) AS T FROM BALANCE_TABLE )

SELECT * FROM A
WHERE T = 1
LIMIT 1


text:
Q: Sharing styles with document to print I'm helping someone who is creating a newsletter. Their layout requirements are fairly simple, but will be best served by using some new styles to give a uniform appearance to the text.
The sticking point, where my knowledge reaches its limits, is that it will be sent to a commercial printer. I am assuming that it will go as a Word document, but if that is so, then - even if I have sent a new template to the editor - she will send the basic document to the print shop and they will not interpret the styles correctly and the result will be a dog's breakfast and not the simple, but clear, layout which I have created.
How do I get the document with the instructions from these styles (which will only be used for this project) to the outside printer?
One additional wrinkle is that the document contains pictures which have captions attached. These pictures+captions need to be placed so that the text flows round them on the "square" basis. I have no problem with getting this to look right in the Word document, but any method which will give me the right results in Word 2016 may adversely affect these pictures.
I have looked at the options suggested in
Automatically remove custom styles from Word document, but save formatting
and some seemingly promising methods e.g. copy and paste into WordPad to strip styles whilst retaining formatting, fall down on this matter of the pictures and their formatting.

A: Send the document to the Commercial Printer as a PDF not as a Word document format. The PDF will have the necessary formatting.


text:
Q: Why false != false? I have a method that check if 2 arguments are equal:
using System;

class Program{
    static void Main(string[] args){
        CheckEquality(false, false);
        Console.ReadKey();
    }
    public static void CheckEquality(object a, object b)
    {
        if (a == b){
            Console.WriteLine("yes");
        }else{
            Console.WriteLine("no");
        }
    }
}

As you can see, 2 arguments are "false", but when I run the program, the console says:
no

A: You're actually not comparing values here.
You are comparing references. In this case references to object containing bool values.
So while the values inside the objects might be the same, the equals (==) operator for the object only compares the references, not the values. Since you have two distinct boxes the references are different, hence the result is false.


text:
Q: Windows Forms Aplication-converting string to canvas drawing The following is all in c#:
I'm using various graphic methods to draw on a canvas(LevelPanel), which I then save to an XML file. I do so by converting it to a string:
 private void Save_Click(object sender, EventArgs e)
    {
        string filename = FileNameBox.Text;

         Bitmap bmp = new Bitmap(LevelPanel.Width, LevelPanel.Height);
         Graphics g = Graphics.FromImage(bmp);
         Rectangle rect = LevelPanel.RectangleToScreen(LevelPanel.ClientRectangle);
         g.CopyFromScreen(rect.Location, Point.Empty, LevelPanel.Size);
         g.Dispose();
        string picString = "";

        using (MemoryStream m = new MemoryStream())
        {
            bmp.Save(m, ImageFormat.Png);
            picString = Convert.ToBase64String(m.ToArray());
            m.Close();
        }
        File.WriteAllText(@filename, picString);

    }

Is there any way I could load the file (take the string and convert it back to the image). I looked around, but couldn't find anything on this. Any help is gratefully recived. If it is impossible, could anybody suggest alternative methods of saving/loading the image as an xml file.

A: If you're just saving the XML with File.WriteAllText("somefile.xml", picString);
Read the xml like this
string base64String = File.ReadAllText("somefile.xml");

After reading the XML file you can convert it back to an image by calling this method
public static Image ImageFromBase64String(string base64String)
{
    byte[] imageBytes = Convert.FromBase64String(base64String);

    using (MemoryStream ms = new MemoryStream(imageBytes))
    {
        return new Bitmap(Image.FromStream(ms, true));
    }
}


text:
Q: moving live php application to local server wamp I tried moving my live php website to local server WAMP ver 2.4 on windows 7 but my index.php is not rendering correctly and giving errors. I tried doing it on other hosting server and it worked fine there.
The errors or rendering issues which i am getting are
1. Script in index file is getting displayed as it is for e.g.
$msg = "";
if ($_REQUEST['submit']) {
    $date_cont_new_object = new WebsiteDate();
    $date_cont_new_object_array = $date_cont_new_object->curntDate();
    $date = $date_cont_new_object_array['DATE_TIME'];
    $value = new validate_contact();
    $name = $value->check_input($_POST['name']);
    $email = $value->check_input($_POST['email']);
    $phone = $value->check_input($_POST['phone']);
    $query = $value->check_input($_POST['query']);
    $captcha = $_POST['captcha'];
    $msg = $value->check_cont_form($name, $email, $phone, $query, $captcha, $date);
} ?>

*script getting displayed as it is

'.$bbsectortbl['sectname'].' ('.$numberofsectorid.')'; } ?>

*Notice: Undefined variable: bb3 in ...\index.php on line 306

*Notice: Undefined variable: bb1 in ...\index.php on line 309

few more...
I think that the problem is of setting on local server.
Any help on this is appreciated as i trying to solve this past 1 week with not much luck.
Thanks

A: Your problem is not WAMPServer, your problem is badly written PHP code.
I would imaging that your LIVE server has got display_errors = Off so you dont see the result of the bad code.
As WAMPServer is a developers tool, it comes configured for developers to see and hopefully correct their errors so it has display_errors = On.
So to get your code running with the errors made invisible to the client you need to edit php.ini and change that setting
Edit php.ini using the wampmanager menus
wampmanager -> PHP -> php.ini

Find
display_errors = On

and change to
display_errors = Off

You may also need to change this setting as well
From
error_reporting = E_ALL

to
error_reporting = E_ALL & ~E_DEPRECATED

A: Finally i was able to solve the problem
The issue was with tags i.e. , when i changed from

Hope this helps to someone looking of similar issue.
Thanks to all for your contribution and helping.

A: I'm pretty much sure that you need something like this: setting wamp


text: Q: Redis - Creating Data Integrity or Constraint Does redis provide users to create data integrity or constraint? Like giving primary keys and foreign keys in sql. I can't seem to find it in the user manual. Thanks!


text:
Q: Magento - update magento from 1.6.2 to 1.7.0.2 Hi when i update my magento 1.6.2 to 1.7.0.2 the files update work fine ...
(i am all trieing this on my testserver)
I, get the same errors when is try to update through the diff files or the magento connect (updating the mage_all_latest)
But when i log in for the first time on the webshop it's trying to update the mysql table.
But i get error after error.
Here a list of the errors:
a:5:{i:0;s:237:"Error in file: "/var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/SalesRule/sql/salesrule_setup/upgrade-1.6.0.2-1.6.0.3.php" - SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'salesrule_website' already exists";i:1;s:1122:"
#0 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/Resource/Setup.php(645): Mage::exception('Mage_Core', 'Error in file: ...')

and the same for:

*

*catalog_product_entity_group_price

*salesrule_customer_group

*report_viewed_product_aggregated_daily

*report_viewed_product_aggregated_monthly

*report_viewed_product_aggregated_jearly

*oauth_consumer

To solve this i deleted these keys. (although this doesn't seem right)
But the last key i can't remove. I get #1217 - Cannot delete or update a parent row: a foreign key constraint fails
Who can tell me what i am doing wrong ...
UPDATE 01-08-2012
I repaired the database using the reapir tool of magento.
Afterward i updated magento through updating the mage_all_latest to 1.7.0.2.
All works fine except in the end i get:
"Exception during cache and session cleaning", but there are no other errors during installing.
Then i return to the admin i get a white screen.
After waiting a while i cleared the var/cache and apc.
Now i get this message:
a:5:{i:0;s:255:"Error in file: "/var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Catalog/sql/catalog_setup/upgrade-1.6.0.0.9-1.6.0.0.10.php" - SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'catalog_product_entity_group_price' already exists";i:1;s:1132:"
#0 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/Resource/Setup.php(645): Mage::exception('Mage_Core', 'Error in file: ...')
#1 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/Resource/Setup.php(437): Mage_Core_Model_Resource_Setup->_modifyResourceDb('upgrade', '1.6.0.0.8', '1.6.0.0.14')
#2 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/Resource/Setup.php(320): Mage_Core_Model_Resource_Setup->_upgradeResourceDb('1.6.0.0.8', '1.6.0.0.14')
#3 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/Resource/Setup.php(235): Mage_Core_Model_Resource_Setup->applyUpdates()
#4 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/App.php(417): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#5 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/code/core/Mage/Core/Model/App.php(343): Mage_Core_Model_App->_initModules()
#6 /var/www/vhosts/liefstoereigenwijs.nl/site1/app/Mage.php(683): Mage_Core_Model_App->run(Array)
#7 /var/www/vhosts/liefstoereigenwijs.nl/site1/index.php(87): Mage::run('', 'store')
#8 {main}";s:3:"url";s:1:"/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:7:"default";}

I do notice that after the upgrade the file permissions of a lot of files have changed, like index.php changed to 666.
Who can help me?

A: Based on your install it seems that it doesn't have a DROP TABLE IF EXISTS command preceeding it. This is actually helping you. I would log in to the db server as admin or root and execute the following commands:
create table catalog_product_entity_group_price_backup like catalog_product_entity_group_price;

insert into catalog_product_entity_group_price_backup select * from catalog_product_entity_group_price;

drop table catalog_product_entity_group_price;

This should create everything from the catalog_product_entity_group_price table into a backup, and drop it so that Magento can complete the upgrade. After the upgrade is complete you can compare the two tables and merge the information in - if the table isn't structurally different you may even be able to execute an insert into catalog_product_entity_group_price select * from catalog_product_entity_group_price_backup;
Cheers.


text:
Q: Gaining an understanding of performance implications of shader stages, particularly the GS I am confused about what's faster versus what's slower when it comes to coding algorithms that  execute in the pipeline.
I made a program with a GS that seemingly bottlenecked from fillrate, because timer queries showed it to execute much faster with no rasterisation enabled.
So then I made a different multi-pass algorithm using transform feedback, still using a GS every time but theoretically does much less work overall by executing in stages, and it significantly reduces the fill rate because it renders much less triangles, but in my early tests of it, it appears to run slower.
My original thought was that the bottleneck of fillrate was traded for the bottleneck of calling multiple draw calls. But how expensive is another draw call really? How much overhead is involved in the cpu and gpu?
Then I read the answer of a different stack question regarding the GS:

No one has ever accused Geometry Shaders of being fast. Especially when increasing the size of geometry.
Your GS is taking a line and not only doing a 30x amplification of vertex data, but also doing lighting computations on each of those new vertices. That's not going to be terribly fast, in large part due to a lack of parallelism. Each GS invocation has to do 60 lighting computations, rather than having 60 separate vertex shader invocations doing 60 lighting computations in parallel.
You're basically creating a giant bottleneck in your geometry shader.
It would probably be faster to put the lighting stuff in the fragment shader (yes, really).

and it makes me wonder how it's possible for a geometry shaders to be slower if their use provides an overall less work output. I know things execute in parallel, but my understanding is that there is only a relatively small group of shader cores, so starting an amount of threads much larger than that group will result in the bottleneck being something proportional to program complexity (instruction size) times the number of threads (using thread here to refer to invocation of a shader). If you can have some instruction execute once per vertex on the geometry shader instead of once per fragment, why would it ever be slower?
Help me gain a better understanding so I don't waste time designing algorithms that are inefficient.


text:
Q: Ubuntu terminal cant type special characters like backslash (\), slash(/), semicolon (:), etc properly I'm running Ubuntu 14.04 without GUI and i'm having problems entering characters like backslash, slash, semicolon and so forth. The keys which would normally enter these characters print out all kinds of different characters instead.
How can i change this, so that i can actually type out the characters which are listed on the keys on my keyboard. I suppose this is some kind of problem with the layout of the keyboard, but i can't seem to figure out how to fix it.
Furthermore, ctrl+x doesn't work either (which makes it hugely problematic when i want to edit files using sudo nano).
Any help would be greatly appreciated!
Thanks.

A: You're probably using the wrong keyboard layout. You can change this by using the following command:
sudo dpkg-reconfigure keyboard-configuration


text:
Q: Why my clients send the HTTP requests before getting Kerberos tickets from KDC I have been trying to get squid running with kerberos for a few days, but I'm in big pain. I have double checked all the configuration files they all seems OK.
Here is my question, today I have captured the packets with wireshark and I saw that my client browser sends and get the HTTP packets before getting the tickets from KDC.
I can connect the Internet over squid, but it uses NTLM instead of Kerberos, I am thinking that authorization fallsback to NTLM, because it tries Kerberos Auth before it gets the ticket from KDC. (it can get the tickets later)
What could cause to KDC that it is not able to send the tickets while the authentication period?
If needed; you can get the full wireshark log from here.
update: updated wireshark logs, please check this instead of first one
update2: squid conf file: http://pastebin.com/k1pafHfH
Thanks a lot.

A: I see no challenge from the proxy for authentication in the trace you sent. The only Kerberos traffic I see is a TGT for Realm: LABRISTEST.COM issued to test1.
If the proxy were enforcing authentication, I would expect a trace with "StatusCode: 407, Proxy authentication required" returned by proxy. See http://technet.microsoft.com/en-us/library/bb984870.aspx for example of a likely trace where proxy requires auth.
I dont see any NTLM or Kerberos based auth to the proxy.
The client will only request tickets if it has to (i.e. proxy says auth required). Until then it does not know what tickets to request and tries anonymously. So you should see a ticket request after accessing proxy anonymously. And that too, only if there is no cached ticket locally at the client side. Its also possible that despite no ticket locally cached, you see no request because of a negative cache (cached the fact that previous request for ticket failed).
I also note you are not using IE (UserAgent:  Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0) for testing this. I suggest you use IE for testing unless you are certain firefox is configured to respond to auth requests correctly.
Update (16th Jan):
You should always flush DNS cache (ipconfig /flushdns) and kerberos cache before collecting traces. This allows seen KDC detection related DNS traffic and kerberos ticket requests success/failure.
Its also important to know how you configure the proxy settings in the browser as this has some say in the tickets requested. The proxy port appears to be 3128 and the name is labris-1. So, you will likely need to register http/labris-1:3128 and http/labris-1.labristest.com:3128 SPN on the AD object used by the proxy service. You also need to add the reg key from http://support.microsoft.com/default.aspx?scid=kb;EN-US;908209 for all IE greater than V6. Make sure the keytab is updated and accessible on the squid server.


text:
Q: Regex Expression in R to match a word with only non-word characters Trying to remove all words(characters surrounded by a whitespace) that contain only non-word characters or only punctuation.
**My string:**  df <-c("****+++++01293-0129-= *& ==============( ----------------( hi 102938=-0 123ho123")

**Intended output:"****+++++01293-0129-= hi 102938=-0 123ho123"

Tried:
df <- gsub(pattern = "[[:punct:]]*span[[:punct:]]*", "", df)

df <-gsub(pattern = "\\<\\W*\\W*\\>", "", df)

df <-gsub(pattern = "^\\W*\\W*$", "", df)

None of these work for removing each word that contains purely punctuation characters.

A: You could try searching for the pattern:
(?<=^|\s)[^A-Za-z0-9_]+(?=$|\s)

and then replace with empty string.  For example:
input <-c("****+++++01293-0129-= *& ==============( ----------------( hi 102938=-0 123ho123")
output <- gsub("(?<=^|\\s)[^A-Za-z0-9_]+(?=$|\\s)", "", input, perl=TRUE)
output

[1] "****+++++01293-0129-=  hi 102938=-0 123ho123"

The secret sauce in the regex pattern is the use of lookarounds as proxies for what we would normally do using word boundaries (\b).  This issue here is that the interface between a non word character and a space isn't actually a word boundary.  So instead, we can define our boundaries as being an interface between a non word character and one of the following:

*

*The start of the string

*The end of the string

*A space character

A: Not the cleanest but this should work
paste(grep("[[:alnum:]]",strsplit(df," ")[[1]],value=TRUE),collapse=" ")
[1] "****+++++01293-0129-= hi 102938=-0 123ho123"

Here we are splitting the string by " " and checking if there is at least one alphanumeric value. Those that do are then pasted again with " " as separator.


text:
Q: Insertion point blink interval in macOS I am working on an NSTextView subclass and now need to draw text insertion points by myself during the formal NSTextView's insertion point timer stops. I succeed to draw my own, but could not find the way to obtain the time interval for the text insertion point blinking.
According to my observation on NSTextView, an NSTextView (subclass) manages the cursor blink using a private NSTimer, but this timer deactivates when the textView has only nonempty selections (because there is no insertion point to draw) or while dragging. Therefore, I need to have my own timer with a proper interval to draw my fake insertion points.
Digging the source code of the ancient OpenStep, the magic number for it seems to be 0.5 seconds. However, nowadays, users can customize the interval or even disable blinking. Likewise, the system also may change the interval for specific situations or in the future. I'd like to respect those preferences but I could not find the proper way for it.
Does anyone know how to get it (without accessing private API)?

What I do so far is:
private struct BlinkPeriod {

    var on: Int
    var off: Int
}

private extension UserDefaults {

    var textInsertionPointBlinkPeriod: BlinkPeriod {

        let onPeriod = self.integer(forKey: "NSTextInsertionPointBlinkPeriodOn")
        let offPeriod = self.integer(forKey: "NSTextInsertionPointBlinkPeriodOff")

        return BlinkPeriod(on: (onPeriod > 0) ? onPeriod : 500,
                           off: (offPeriod > 0) ? offPeriod : 500)
    }

}

But I feel it's dirty and no idea when the system changed the period :/

A: Here's my solution:
class NSTextViewExt : NSTextView {
  public var insertionPointInterval: Double?;

  override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
    super.drawInsertionPoint(in: rect, color: color, turnedOn: flag);

    guard let interval = insertionPointInterval else {
        insertionPointInterval = NSDate().timeIntervalSince1970;
        return;
    }

    if interval > 1676669420 { // seconds at time of writing this
        insertionPointInterval = NSDate().timeIntervalSince1970 - interval;
    } else {
        print(insertionPointInterval!);
    }
  }
}

The drawInsertionPoint method gets called on each flash of the insertion point — not just the initial drawing. If you record the intervals between them, you can reasonably determine the blink interval and store it for use on the NSTextView or in an environment variable, perhaps.
Of course, this requires that the insertion point processes through at least one cycle, but you can decide where you want to intercept that.

As a general note, I'm very new to Swift and Obj-C, so if you find something wrong with the implementation, please feel free to suggest modifications to this answer.


text:
Q: What is the proper way to pass a reactive pinia state as axios params? I am trying to use two pinia stores for my axios params but when I send the axios request, the state is sent as a whole proxy object.
stores/product-filter.js
import { defineStore } from "pinia";

export const useProductFilterStore = defineStore("productFilter", {
  state: () => ({
    id: undefined,
    title: undefined,
    ...
  }),
});

stores/product-pagination.js
import { defineStore } from "pinia";

export const useProductPaginationStore = defineStore("productPagination", {
  state: () => ({
    pagination: {
      page: 1,
      rowsPerPage: 15,
      rowsNumber: false,
    },
  }),
});

stores/product.js
import { defineStore } from "pinia";

import { useProductFilterStore } from "./product-filter";
import { useProductPaginationStore } from "./product-pagination";

const paginationStore = useProductPaginationStore();
const filterStore = useProductFilterStore();

export const useProductStore = defineStore("product", {
  state: () => ({
    products: [],
  }),

  actions: {
    fetchProducts() {
      return axios.get(process.env.API_URL + "product", {
        params: {
          limit: paginationStore.pagination.rowsPerPage,
          page: paginationStore.pagination.page,
          filter: filterStore,
        },
      });
    },
  },
});

So when I fetchProducts I get the whole object like
limit: 15
page: 1
filter[$id]: productFilter
filter[_isOptionsAPI]: true
filter[router][currentRoute][__v_isShallow]: true
filter[router][currentRoute][dep][w]: 0
filter[router][currentRoute][dep][n]: 0
filter[router][currentRoute][__v_isRef]: true
filter[router][currentRoute][_rawValue][fullPath]: /product
filter[router][currentRoute][_rawValue][hash]:
filter[router][currentRoute][_rawValue][name]: api.product.index
filter[router][currentRoute][_rawValue][path]: /product
filter[router][currentRoute][_rawValue][matched][][path]: /
filter[router][currentRoute][_rawValue][matched][][name]: api.default

Trying the following doesn't work either:
...
const { filter } = storeToRefs(filterStore);
...

params: {
  limit: paginationStore.pagination.rowsPerPage,
  page: paginationStore.pagination.page,
  filter: filterStore,
},

What is the best way to do this (reactively) ?

A: In stores/product.js, you are passing the entire store to Axios.
It seems you want to pass just the state of the store, so try this:
fetchProducts() {
  return axios.get(process.env.API_URL + "product", {
    params: {
      limit: paginationStore.pagination.rowsPerPage,
      page: paginationStore.pagination.page,
      filter: filterStore.$state, // This
    },
  });
},

P.S. This was independently pointed out by Michal Levý in a comment on your question.


text:
Q: Deferred exception after populating global variable from ajax method with $.when I have an asp.net page that loads a chart and some tables.
When the page loads I retrieve some data from a server & make a few ajax calls as shown in the code below.
I have two global variables, RainFall and RainDates that I need to populate.
When the page loads I have a function CalcSummaryStats that makes use of these global values to calculate some statistics.
My understanding (AJAX & Jquery are new to me) is that the ajax requests run asynchronously so the $.ajax method returns before the request is finished, and therefore before the success callback runs.
So after some reading I could use $.when method like the line below,

$.when(methodRainCont(), methodRainSingle()).then(calcData);

In methodRainCont the chart is draw and in this function at the same time RainDates is populated.
In methodRainSingle my other global variable is populated.
And my understanding is that this means that once both methods have finished running (assuming that includes the success callback) my function calcData is then called. calcData calls another function outside of the $(document).ready block called CalcSummaryStats & this is where my error happens.
It tries the line below

var cM = RainDates[0].getMonth();

but get this error

jQuery.Deferred exception: Cannot read property 'getMonth' of undefined TypeError: Cannot read property 'getMonth' of undefined

So it seems like RainDates is not populated? I thought using $.when would make sure both functions had run successfully before calling calcData?
My JS file
// my two global variables
var Rainfall = [];
var RainDates = [];

$(document).ready(function () {

 var $opts = $('#optList');

 $.ajax({
    type: 'GET',
    url: 'api/UserOptions',
    dataType: 'json',
    success: function (codes) {
        $.each(codes, function (i, code) {
            $opts.append('
' + code + '
');
        });
    },
    error: function () {
        alert("Error ");
    }
});

 function methodRainCont() {
    $.ajax({
        type: 'GET',
        url: 'api/RainContr',
        dataType: 'json',
        success: function (data) {
            DrawChart(data);
        },
        error: function () {
            alert("Error");
        }
    });
}

function methodRainSingle() {
    $.ajax({
        type: 'GET',
        url: 'api/RainSingle',
        dataType: 'json',
        success: function (data) {
            Rainfall = data;                // setting my global variable values
        },
        error: function () {
            alert("Error");
        }
    });
}

$.when(methodRainCont(), methodRainSingle()).then(calcData);

function calcData()
{
    var cords = {
        x: {
            min: RainDates[0],
            max: RainDates[RainDates.length - 1]
        }
    };

    CalcSummaryStats(cords);
}

});

A: Your functions methodRainCont() and methodRainSingle() do not return a promise to be used by $.when(), so calcData() executes immediately and ajax calls are not finished.
So, inside these functions, replace$.ajax({ with return $.ajax({


text:
Q: проблема со счетчиком товара в корзине Не правильно работает счетчик товара, чем больше товаров тем больше счетчик +-.
Структура кода.
При нажатии кнопки добавить в корзину:
$('.btn-add-cart').click(function(e){
createCartElement(); });

Идет вызов функции в которой, при каждом нажатии, создается карточка с товаром:
out += '<button class="btn-counter minus">
-
</button>';
out += '<input class="counter" value="1">';
out += '<button class="btn-counter plus">
+
</button>';

cartItem.innerHTML = out;
cartItems.append(cartItem);

Внутри этой же функции обрабатывается нажатие на кнопки + и - с выводом счетчика:
$('.btn-counter.plus').click(function(e) {

  let input = parseInt(e.target.parentElement.parentElement.children[1].value);
  input = input + 1;
  e.target.parentElement.parentElement.children[1].value = input;
});

$('.btn-counter.minus').click(function(e) {
  let input = parseInt(e.target.parentElement.parentElement.children[1].value);
  input = input - 1;
  e.target.parentElement.parentElement.children[1].value = input;
  if (input == 0) {
    input = 1;
  }
});

И так, суть проблемы заключается в том, что при первом нажатии на кнопку (добавить в корзину)- добавляется один товар и все работает хорошо, счетчик добавляет +1 и -1, создали еще одну, старая карточка +2 -2, а новая +1 -1 итд (+3 -3), скорее всего при создании нового элемента оно передает значение старому, прошу помочь с данной проблемой, пробовал уже разные варианты, ничего толкового не нашел.

A: это просто пример, но он показывает что надо

const wrapItems = document.querySelector('#list');

const createButton = (isAdd, elementInput) => {
  let operation;
  let cssClass;

  const btn = document.createElement('button');
  if (isAdd === true) {
    operation = '+';
    cssClass = 'plus'
    btn.onclick = () => elementInput.value = parseInt(elementInput.value, 10) + 1;
  } else {
    operation = '-';
    cssClass = 'minus';
    btn.onclick = () => elementInput.value = parseInt(elementInput.value, 10) - 1;
  }
  btn.classList.add('btn-counter', cssClass);

  btn.innerHTML = `<p class="btn-text">${operation}</p>`;

  return btn;
}

document.querySelector('#add-item').addEventListener('click', () => {
  const itemDiv = document.createElement('div');
  const input = document.createElement('input');
  input.setAttribute('type', 'text');
  input.value = 1;
  const btnPlus = createButton(true, input);
  const btnMinus = createButton(false, input);

  itemDiv.append(btnMinus, input, btnPlus);

  wrapItems.appendChild(itemDiv);
});
<button id="add-item">add</button>

а еще, если это допустимо, можно использовать
<input type="number" step="1" min="0">

A: На один и тот же DOM-элемент можно вешать сколько угодно слушателей событий.
Проблема твоего решения в том, что ты вешаешь обработчики события при каждом добавлении нового счетчика, используя при этом общий селектор.
То есть, создал кнопку -> повесил события на все кнопки с селектором .btn-counter.plus.
В твоем случае ход действий получился такой
1. Создать счетчик 1
2. Добавить в DOM.
3. Повесить событие на счетчик 1. (1 х1)
4. Создать счетчик 2
5. Добавить в DOM.
6. Повесить событие на счетчик 1 и 2 (1 х2, 2 х1)
7. Создать счетчик 3
8. Добавить в DOM.
9. Повесить событие на счетчик 1, 2 и 3 (1 х3, 2 х2, 3 х1)

... и тд.
Есть еще общая проблема с производительностью кода. Добавление через innerHTML заставляет лишний раз напрягаться браузерный парсер, чтобы разделить весь текст на токены и сгенерировать исполняемый код.
Лучше упростить задачу браузеру:
const createButton = (className, text, clickListener) => {
    const btn = document.createElement('button');
    btn.className = className;
    const label = document.createElement('p');
    label.className = 'btn-text';
    label.appendChild(document.createTextNode(text));
    btn.addEventListener('click', clickListener);
    btn.appendChild(label);
    return btn;
};

const createInput = () => {
    const input = document.createElement('input');
    input.className = 'counter';
    input.value = 1;
    return input;
};

const createCartElement = () =>
    cartItems.append(
        createButton('btn-counter minus', '-', removeFromCart); // TODO: implement removeFromCart
        createInput(),
        createButton('btn-counter plus', '+', addToCart); // TODO: implement addToCart
    );
}


text:
Q: How to sort JavaScript string array I have the following array:
    var arr = ["COL10","COL5",
                "COL4","COL3",
                "COL8","COL9",
                "COL2","COL7",
                "COL1","COL6"];

    console.log("After sort:"+arr.sort());

The output is:
After sort:COL1,COL10,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9

But I want it to be:
After sort:COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10

How should I do this?

A: Use the following approach with Array.sort and String.slice functions:

var arr = ["COL10","COL5","COL4","COL3","COL8","COL9","COL2","COL7","COL1","COL6"];

arr.sort(function (a,b) {
    return a.slice(3) - b.slice(3);
});

console.log(arr);

A: You could split the items and sort the parts separate.

var arr = ["COL10", "COL5", "COL4", "COL3", "COL8", "COL9", "COL2", "COL7", "COL1", "COL6"];

arr.sort(function (a, b) {
    var aa = a.split(/(\d+)/g),
        bb = b.split(/(\d+)/g);
    return aa[0].localeCompare(bb[0]) || aa[1] - bb[1];
});

console.log(arr);

A: Try out the alphanumerical sort from Brian Huisman:
Article

var arr = ["COL10", "COL5",
  "COL4", "COL3",
  "COL8", "COL9",
  "COL2", "COL7",
  "COL1", "COL6"
];

console.log("After sort:" + arr.sort(alphanum));

function alphanum(a, b) {
  function chunkify(t) {
    var tz = [],
      x = 0,
      y = -1,
      n = 0,
      i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >= 48 && i <= 57));
      if (m !== n) {
        tz[++y] = "";
        n = m;
      }
      tz[y] += j;
    }
    return tz;
  }

  var aa = chunkify(a);
  var bb = chunkify(b);

  for (x = 0; aa[x] && bb[x]; x++) {
    if (aa[x] !== bb[x]) {
      var c = Number(aa[x]),
        d = Number(bb[x]);
      if (c == aa[x] && d == bb[x]) {
        return c - d;
      } else return (aa[x] > bb[x]) ? 1 : -1;
    }
  }
  return aa.length - bb.length;
}

A: var arr = ["COL10","COL5",
                "COL4","COL3",
                "COL8","COL9",
                "COL2","COL7",
                "COL1","COL6"];

arr.sort(function(a,b) {
  var a1 = parseInt(a.split('COL')[1]);
  var b1 = parseInt(b.split('COL')[1]);
  return a1 - b1;
});


text:
Q: How to submit the custom form data in database in WordPress without plugin? I have a created a contact form in the function.php and added short code on my page and it's working. I am getting my form.
function st_contact_form(){
ob_start();
    ?>

         <form action="" method="post" name="contact_form" id="contact_form" autocomplete="off">

               <input type="text" name="name" placeholder="Name" class="form-control" required>

               <input type="email" name="email" placeholder="Email Id" class="form-control" required>

            <input type="text" name="mobileno" placeholder="Phone no" class="form-control" required>

            <select class="form-control" name="type_of_services" required>
                <option selected disabled>Select Service</option>
                <option value="1">Testing one</option>
                <option value="2">Testing two</option>

            </select>

            <textarea class="form-control" placeholder="Message" name="message" rows="2" required></textarea>

            <input type="submit" name="send" value="Submit" class="btn_st btn_maroon form_submit_btn">

      </form>

<?php
return ob_get_clean();
}
add_shortcode( 'contact_form', 'st_contact_form' );

I added below script in script file and validation is working. Now I want to know how to submit the form in wordpress? Should I create a table? or I have to create process.php file and add some logic?
$("#contact_form").validate({
rules: {
    name: {
        required:true
    },
    email: {
        required:true,
        email: true,
        emailExt: true
    },
    mobileno: {
        required:true,
        minlength: 10,
        maxlength: 10,
        number: true
    },
    type_of_services: {
        required:true
    },
    message: {
        required:true
    }
},
submitHandler: function(r) {
     if(isReqInprogress){
        return;
       }
    isReqInprogress = true;
    $.ajax({
                url:base_url+"/wp-content/themes/mytheme/process.php",

        type: "post",
        data:{name:name,email:email,mobileno:mobileno,type_of_services:type_of_services,message:message},
        dataType:"JSON",
        success: function(response) {
           alert("success");

    isReqInprogress = false;
        }

    })
}
});

Process.php
<?php
global $wpdb;
$data = $_POST;
$to = $data['email'];
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');

//$mail = wp_mail($data['email'], $subject, $body, $headers );
//if ($mail) {
    $wpdb->insert('wp_contact',
        array(
            'name' => $data['name'],
            'email' => $data['email'],
            'mobileno' => $data['mobileno'],
            'message' => $data['message'],
        ),
        array(
            '%s',
            '%s',
            '%s',
            '%s',
        )
    );
//}

?>

Would you help me out?

A: Finally, I got my solution,
I added below code in function.php and using shortcode I am getting my form on webpage
function st_contact_form(){
ob_start();
    ?>

         <form action="" method="post" name="contact_form" id="contact_form" autocomplete="off">

               <input type="text" name="name" placeholder="Name" class="form-control" required>

               <input type="email" name="email" placeholder="Email Id" class="form-control" required>

            <input type="text" name="mobileno" placeholder="Phone no" class="form-control" required>

            <select class="form-control" name="type_of_services" required>
                <option selected disabled>Select Service</option>
                <option value="1">Testing one</option>
                <option value="2">Testing two</option>

            </select>

            <textarea class="form-control" placeholder="Message" name="message" rows="2" required></textarea>

            <input type="submit" name="send" value="Submit" class="btn_st btn_maroon form_submit_btn">

      </form>

<?php
return ob_get_clean();
}
add_shortcode( 'contact_form', 'st_contact_form' );

Now next step is, JQuery validation and Ajax. Also I created a process.php file in my theme
$("#contact_form").validate({
rules: {
    name: {
        required:true
    },
    email: {
        required:true,
        email: true
    },
    mobileno: {
        required:true,
        minlength: 10,
        maxlength: 10,
        number: true
    },
    type_of_services: {
        required:true
    },
    message: {
        required:true
    }
},

submitHandler: function(form) {
    if(isReqInprogress){
        return;
       }
        $.ajax({
        url:"/wp-content/themes/themename/process.php",
        type: "post",
        data:$('#contact_form').serialize(),
        dataType:"JSON",
        success: function(response) {

        alert("Your message has been received and we will be contacting you shortly to follow-up.");
            isReqInprogress = false;
             }
    });
}
});

Process.php
Note: I have created a contact table in my database
<?php
define( 'BLOCK_LOAD', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

global $wpdb;        // <--- making $wpdb as global
$data = $_POST;
$query=$wpdb->insert('contact',
        array(
             'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['mobileno'],
            'type_of_services' => $data['type_of_services'],
            'message' => $data['message']
        ),
        array(
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
        )
);

 if ($query) {
    $response['error'] = "true";

    }else{
    $response['error'] = "false";
    }
echo json_encode($response);
exit();
    // $wpdb->show_errors();

?>

that's it. It's working perfectly for me.

A: Yes you have to write code for inserting data in your process.php
global $wpdb;
$name=$_POST['name'];
$email= $_POST['email'];
$mob=$_POST['moblieno'];
$service_type=$_POST['type_of_service'];
$msg=$_POST['message'];
$wpdb->insert('tbl_name',array('name_field'=>$name,'email_field'=>$email,'service-field'=>$service_type,'message_field'=>$msg));


text:
Q: Batch file, how to remove the first word in a text file and only in the first line? I have a .txt file that may contain various words on various lines and I just want to remove the first word in the first line. (ex: I have 2 lines in my text file containing 2 words each (abc, bcd on the first line and cde, def on the second) annd I want the output to be bcd on the first line and cde and def on the second).  I researched this and I only came across to how to remove the first word in all the lines but I only need in the first line. Thanks in advance.
This was the closest answer I could find out but it removes the first word from all the lines and I only need the first line.
Remove First Word in text stream

A: Although you did not show us your own efforts on the problem at hand, I decided to provide some code, because the task seems not that particularly trivial to me...
The scripts below remove the first word from the first line.
The following one reads the given text file using a for /F loop and splits off the first word in the first line by another nested for /F loop; the remaining lines are returned unedited:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "FLAG=" & rem // (this marks the first line)
for /F "delims=" %%L in ('findstr /N /R "^" "%~1"') do (
    set "LINE=%%L"
    rem // (toggle delayed expansion to not lose `!`)
    setlocal EnableDelayedExpansion
    set "LINE=!LINE:*:=!"
    if defined FLAG (
        rem // (this is executed for all but the first lines)
        echo(!LINE!
    ) else (
        rem // (this is executed for the first line only)
        if defined LINE (
            rem // (an empty line skipped over the loop)
            for /F "tokens=1,*" %%E in ("!LINE!") do (
                endlocal
                rem // (return line with first word removed)
                echo(%%F
                setlocal EnableDelayedExpansion
            )
        ) else echo/
    )
    endlocal
    rem // (set this after the first loop iteration)
    set "FLAG=#"
)

endlocal
exit /B

This one reads the given text file via redirection, splits off the first word of the first line again by a for /F loop and returns the remaining lines by a findstr command line:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

< "%~1" (
    rem // (capture first line here)
    set /P "LINE="
    rem /* (the `echo` in the pipe below runs in Command Prompt context,
    rem     so an empty variable `LINE` literally returned `!LINE!) */
    if defined LINE (
        rem /* (this is executed for the first line only;
        rem     delay variable expansion as much as possible) */
        for /F "tokens=1,*" %%I in ('cmd /V /C echo(!LINE!^| findstr /N /R "^"') do (
            rem // (return line with first word removed)
            echo(%%J
        )
    ) else echo/
    rem // (this is executed for all but the first lines)
    findstr /R "^"
)

endlocal
exit /B

Both scripts expect the input text file to be provided as a command line argument. Supposing either script is stored as remove-first-word.bat and the text file is called sample.txt, the command line to be used is as follows:
remove-first-word.bat "sample.txt"

or:
remove-first-word.bat "\path\to\sample.txt"

To write the output into another file, say return.txt, rather than to the console, use redirection:
remove-first-word.bat "sample.txt" > "return.txt"

or:
remove-first-word.bat "\path\to\sample.txt" > "\path\to\return.txt"


text:
Q: Why do two molecules of an element attract each other? I was thinking about molecular attraction and a question suddenly struck in my mind which is 'Why do two molecule of an element attract each other?'
The answer is easy when we discuss about compound materials. The molecules of a compound have dipoles that can attract each other. But what happens about elements? The molecules of an element don't have dipoles.
After so many attempts, I thought there are only two particles in those molecules that can attract each other — Neucleus and Electron. But also there works repulsive forces between the electrons and between the neucleus of two molecules. It seems like the repulsion is stronger attraction.
So how the attraction force get stronger than the repulsion force so that two molecules of an element attract each other?

A: There are only seven elements which naturally form stable molecules, namely hydrogen, oxygen, nitrogen, fluorine, chlorine, bromine and iodine. At room temperature only iodine is a solid. When they do liquify or solidify, they do so as a result of Van Der Waals forces, which are electromagnetic in nature, acting at short range between the individual molecules. See https://en.wikipedia.org/wiki/Van_der_Waals_force

A: Van der Waals interaction causes mutual attraction of many if not all of the following elemental molecules H$_2$, Na$_2$, K$_2$, noble gas atomic molecules, S$_8$, O$_3$, O$_8$, F$_2$, Cl$_2$, buckyballs, carbon nanotubes, cyclocarbons. O$_2$ is magnetic, so here probably magnetic attraction dominates.


text:
Q: Adding building/woodland elevation data to existing OS Terrain 5 DTM in ArcGIS Desktop Would someone be able to give me the stepped process showing how to add building/woodland elevations to an existing DTM raster in ArcMap?
I seek this in order to prepare a surface model for a viewshed analysis.
I have run a viewshed analysis on a series of points using a DTM raster derived from UK OS Terrain 5. This creates the bare-earth model and is working well.
I now need to overlay this with buildings (at 8m) and woodlands (at 15m) from UK OS Open Map Local, and then add this elevation data to my existing Terrain 5 DTM. This is the bit I'm struggling with:

*

*Adding the elevation data to the UK OS Open Map shapefiles for buildings and woodland. The method to do this would be to add an extra field in the attributes table and assign the 8m/15m elevation to this field. What field type/properties should the new field have?

*Converting the shape file to a raster dataset using the Polygon to Raster tool on each raster created.

*Merging with the existing Terrain 5 DTM using the Raster Calculator tool. How do you assign the cells with no trees/buildings a value of '0'?

I've seen the question answered for QGIS but not ArcGIS Desktop.

A: If I have understood you correctly I think this is fairly straightforward.
Add a new field to the attribute table of your building and woodland shapefiles, I would call it elevation. Use Field Calculator to assign the value of 8 and 15 respectively.
Use the Polygon to Raster tool on each to convert them to rasters.

Value field is your elevation attribute.
The Cellsize option allows you to point to your existing raster and use that as a template. The new rasters you make will then match up.
So now you have 3 rasters: Existing, Buildings and Woodland. You can now simply add them together using the Raster Calculator tool.


text:
Q: Statistics Quiz Help Can anyone take a look and let me know if I'm doing this right?
This year I am the advisor of a 29 member chapter of The Honor Society.

*

*How many different 8 member teams can I create.
My Answer 8! 8x7x6x5x4x3x2x1=40320

*Elections must be 4 4 positions. All current members can be considered, how many different slates of officers can there be?
Answer--I don't think the 29 students comes into play, I think it's just 4x3x2x1=24

*Jake really wants to be treasurer, and he is the only one interested. How many different slates of officers will there be if Jake is Treasurer?
Answer: Again I don't think the 29 comes into play, but the first number is not a 4, but a 3. So 3x3x2x1=18

A: *

*What you give, $8!$, is the number of different ways of ordering/ranking $8$ people. You aren't ranking them, you are selecting $8$ people from among $29$ available members. So this should be a "n-choose-k" answer; there are $29$ things to choose from, you have to pick $8$ things, so the answer is $\binom{29}{8} = \frac{29!}{21!8!}$.
Alternatively: you have complete choice for the first person, $29$ possibilities; then $28$ left for the second, $27$ for the third, etc. So, a priori, you have $29\times28\times27\times26\times25\times24\times23\times 22=\frac{29!}{21!}$ ways. But the order in which you pick the team members is immaterial to who is on the team; each team can be ordered in $8!$ different ways, so you counted each tem $8!$ times. Dividing by $8!$ gives you the correct answer, $\frac{29!}{21!8!}$.

*This time, you have to select four people, but order matters because there are four different positions. So a slate can have anyone in the first position (29 possibilities), anyone left in the second position (28 possibilities), anyone else for the third (27), and any of the remaining 26 people for the final position. That gives $29\times 28\times 27\times 26$ possible slates.

*One of the positions is taken by Jake. That leaves three positions to be filled by the remaining 28 people in the club: proceeding as in 2, $28\times27\times26$ different ways of doing it.


text:
Q: Error in Main.xml I am getting the error: error: No resource identifier found for attribute 'showAsAction' in package:
I cannot find out why I am getting this error but I have been at it for hours without any sort of break through. I have searched google with many different resolutions but none that appear to work for me.
I would be grateful if someone could help direct me towards a fix to the error.
<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="org.nibbler.zoe.liteplayer.MainActivity" >

<item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>

</menu>

A: Most likely showAsAction is not your attribute, hence not available in app: namespace. Did you mean android:showAsAction?

A: If u are having min ver below 14 and u want to add showAsAction for below 14 api devices, then u can use this.
1.)U need support library to be added in build path.
2.)Need to add app theme as Theme.appcompat.
3)Rest are as u are using means add ur own namespace with .../res-auto value and use that name with showAsAction
You can add support lib res like this http://developer.android.com/tools/support-library/setup.html
You need to extends ActionBarActivity instead of Activity.
For complete Action bar guide follow the link http://developer.android.com/training/basics/actionbar/setting-up.html


text:
Q: How To Capture Unit Testing Metrics I'm not sure how to capture the testing result data related to unit tests each time a unit test is run. I use Bamboo as a continuous integration server. It works great, basically makes a build of your project every time you submit code, and send you an email if the build failed / you screwed up somewhere. I would like to begin having Bamboo running full unit tests as well as builds. I would also like to begin gathering data about said unit tests.
My question is, I know in a lot of dif programs you can track the number of lines of code changed, and the total lines of code period in the entire program. I also know that with unit testing, it gives you data such as the number of passes / failures. What I would like to do is automatically gather this data, among other data such as defect density, etc.


text:
Q: Populate a flutter DataTable with data from Firestore using a StreamBuilder I am attempting to use a StreamBuilder in Flutter to dynamically populate a DataTable using data in Firestore. A similar quesiton was asked by Gustavo which was helpful, but I still can't seem to get my code to work.
The error I receive is 'package:flutter/src/material/data_table.dart': Failed assertion: line 429 pos 15: '!rows.any((DataRow row) => row.cells.length != columns.length)': is not true. This error is obviously indicating that my DataTable seems to have an incongruent number of cells and columns, but I can't see why this is the case because I have used three of each.
Here is my code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class SkillsMatrixOverall extends StatefulWidget {
  @override
  _SkillsMatrixOverallState createState() => _SkillsMatrixOverallState();
}

@override
class _SkillsMatrixOverallState extends State<SkillsMatrixOverall> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Baby Name Votes')),
      body: new StreamBuilder(
        stream: FirebaseFirestore.instance.collection('baby').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return new Text('Loading...');
          return new DataTable(
            columns: <DataColumn>[
              new DataColumn(
                label: Text('Suggestions'),
              ),
              new DataColumn(label: Text('Name')),
              new DataColumn(label: Text('Votes')),
              new DataColumn(label: Text('Rapper name')),
            ],
            rows: _createRows(snapshot.data),
          );
        },
      ),
    );
  }

  List<DataRow> _createRows(QuerySnapshot snapshot) {
    List<DataRow> newList =
        snapshot.docs.map((DocumentSnapshot documentSnapshot) {
      return new DataRow(cells: [
        DataCell(Text(documentSnapshot.data()['Name'].toString())),
        DataCell(Text(documentSnapshot.data()['Votes'].toString())),
        DataCell(Text(documentSnapshot.data()['Rapper name'].toString())),
      ]);
    }).toList();

    return newList;
  }
}

Thank in advance for your advice!

A: I don't know if you notice or not, but the no of columns in your code is 4 while no of cells is 3. You can see
columns: <DataColumn>[
              new DataColumn(
                label: Text('Suggestions'),
              ),
              new DataColumn(label: Text('Name')),
              new DataColumn(label: Text('Votes')),
              new DataColumn(label: Text('Rapper name')),
            ],

Here the no of columns is 4, Suggestion, Name, Votes, and Rapper Name. While providing the no of cells you are providing 3 cells.
return new DataRow(cells: [
        DataCell(Text(documentSnapshot.data()['Name'].toString())),
        DataCell(Text(documentSnapshot.data()['Votes'].toString())),
        DataCell(Text(documentSnapshot.data()['Rapper name'].toString())),
      ]);

If you look at your code, its oblivious that the no of columns and no of cells are not matching.


text:
Q: Request location coordinates after user has blocked access in javascript How can I prompt a user for their geo-location in javascript if they've blocked my request in the past? (using navigator.geolocation.getCurrentPosition).
For example,  my web app requires location services, and the user accidentally clicks "block", or they change their mind. What can I do to prompt them again?

A: You can't.
The user must manage their browser settings manually because your site is added to a blacklist when denied location permissions.
Here are instructions for Chrome users to manage their location permissions: https://support.google.com/chrome/answer/142065?hl=en

A: As mentioned by @matthew-shwery, you can not change the permission.
the best you could do is check for the permission and notify the user is the permission is denied
navigator.permissions.query({
     name: 'geolocation'
 }).then(function(result) {
     if (result.state == 'granted') {
         report(result.state);
         geoBtn.style.display = 'none';
     } else if (result.state == 'prompt') {
         report(result.state);
         geoBtn.style.display = 'none';

         navigator.geolocation.getCurrentPosition(revealPosition, positionDenied, geoSettings);
     } else if (result.state == 'denied') {
         report(result.state);
         geoBtn.style.display = 'inline';
     }
     result.onchange = function() {
         report(result.state);
     }
 });

Geolocation docs


text:
Q: Taking the data array in the array in JSON How do I retrieve "bundle file" data (in the image below that I give a red circle) in the json below?

I try:
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData1 = jsonObject["data"].GetArray();

foreach (JsonValue groupValue in jsonData1)
{
    JsonObject groupObject = groupValue.GetObject();
    string nid = groupObject["sku"].GetString();
        string title = groupObject["judul"].GetString();
        string deskripsi = groupObject["deskripsi"].GetString();
        string tanggal = groupObject["tgl"].GetString();
        string tipe = groupObject["tipe"].GetString();
        string namaTipe = groupObject["nama_tipe"].GetString();
        string gratis = groupObject["gratis"].GetString();
        string dataFile = groupObject["nfile"].GetString();
        string harga = groupObject["hrg"].GetString();
    JsonArray bundle = groupObject["bundle"].GetArray();
        foreach(JsonValue groupValue1 in bundle)
        {
        JsonObject groupObject1 = groupValue1.GetObject();

                 string bundleName = groupObject1["bundle_file"].GetString();
                 string pathFile = groupObject1["path_file"].GetString();
         }
}

but in the code JsonArray bundle = groupObject["bundle"].GetArray();, display an error message as shown below:

whereas "bundle_file" type is an Array.
How to solve this?

A:
This is not an Array Value. Use ValueType property to get the type.

From the error message we can know that this is a type error. I downloaded the Json File and found out that the problem lies in the data, some "bundle"s of this Json File are of string type:

So when you call groupObject["bundle"].GetArray(). It went wrong.
To fix this problem, just wrap part of your codes with a if-statement like below:
var bundleObj = groupObject["bundle"];
if (bundleObj.ValueType == JsonValueType.Array)
{
       JsonArray bundle = bundleObj.GetArray();
       foreach (JsonValue groupValue1 in bundle)
       {
           JsonObject groupObject1 = groupValue1.GetObject();
           string bundleName = groupObject1["bundle_file"].GetString();
           string pathFile = groupObject1["path_file"].GetString();
       }
}

And the error will be gone.


text:
Q: How to go to another activity after execute camera Android Studio I'm trying to go to other activity after execute the camera but, the camera is an activity so, I try to execute StartActivity After this but doesn't work, I've tried using startactivities but neither works. Could you help me please? How can I do this
This is my try

A: you could create a variable to listen when you start camera, then in you onresume of activity, check this variable and start new activity here


text:
Q: Socket Hangup error Http-Proxy NodeJS I am getting following error in my server console when user click signout button.
Error: socket hang up
    at createHangUpError (http.js:1472:15)
    at Socket.socketCloseListener (http.js:1522:23)
    at Socket.EventEmitter.emit (events.js:95:17)
    at TCP.close (net.js:466:12)

Here is my proxy_server:
var fs=require('fs');
var options = {
    key: fs.readFileSync('key/xxxxxxxxx.pem'),
    cert: fs.readFileSync('key/xxxxx.pem'),
    ca: fs.readFileSync('key/gd_bundle-g2-g1.crt')
};

var express=require('express'),
    https=require('https'),
    httpProxy = require('http-proxy'),
    http=require('http'),
    app=express(),
    app1=express(),
    server=https.createServer(options,app),
    serverhttp=http.createServer(app1);

var proxy = httpProxy.createProxy({ target: 'http://localhost:9898',secureOptions:'constants.SSL_OP_NO_TLSv1_2'});
var proxySig = httpProxy.createProxy({target:'http://localhost:8881',secureOptions:'constants.SSL_OP_NO_TLSv1_2'});
var callSig = httpProxy.createProxy({target:'http://localhost:6666',secureOptions:'constants.SSL_OP_NO_TLSv1_2'});
var proxyCdn = httpProxy.createProxy({target:'http://localhost:3030',secureOptions:'constants.SSL_OP_NO_TLSv1_2'});
// var proxyhttps= new httpProxy.createProxy({ target: 'https://localhost:443',secure:false});
var errorhandler = require('errorhandler');

app.all('*', function(req,res){
    if(req.hostname=='xxxxxxxx.in')
    {
        proxy.web(req, res);
    }
    else if(req.hostname=='xxxx.in')
    {
        proxyCdn.web(req, res);
    }
    else if(req.hostname=='xxxxxx.in')
    {
        proxySig.web(req, res);
    }
    else if(req.hostname=='xxxxx.in')
    {
        callSig.web(req, res);
    }
});

app1.all('*', function(req,res){
    res.redirect('https://'+req.hostname);;
});

serverhttp.listen(80);
server.listen(443);

A: Add changeOrigin: true, to the options when you set up the proxy. It changes the origin of the host header. When the proxy is "name based" /not an ip/, its a requirement.
Short summary:
Technical prerequisite needed for name-based virtual hosts is a web browser with HTTP/1.1 support (commonplace today) to include the target hostname in the request

A: You need to handle errors on each of your httpProxy objects. For example:
proxy.on('error', function (error, req, res) {
    var json;
    console.log('proxy error', error);
    if (!res.headersSent) {
        res.writeHead(500, { 'content-type': 'application/json' });
    }

    json = { error: 'proxy_error', reason: error.message };
    res.end(JSON.stringify(json));
});

This thread was useful to me: https://github.com/nodejitsu/node-http-proxy/issues/527


text:
Q: In a normal space, $E\subset U\subset \overline{U}\subset V$, or $E\subseteq U\subseteq \overline{U}\subseteq V$? I'm trying to understand the proof of Urysohn's lemma (just to get some pespective).
This article says that "A topological space $X$ is normal iff for each closed subset $E$ of $X$ and each open set $W$ containing $E$, there exists an open set $U$ containing $E$ such that $\overline{U}\subset E$."
Shouldn't it be $\overline{U}\subseteq E$? What if $E$ is a clopen set?

A: The author of that PDF is sloppy: he uses both $\subset$ and $\subseteq$ indiscriminately to mean $\subseteq$. And you're quite right: here it has to be $\subseteq$ to accommodate the case in which $E=W$ is clopen.


text:
Q: I can't get flatc installed into my yocto based SDK I am doing bitbake image -c populate_sdk to get my SDK but I can't find a way to get the flatc binary included in the SDK.
I have tried a do_install_append in my flatbuffers.bb file and I have put dependencies on various flatbuffers things in another .bb file. I have added to TOOLCHAIN_HOST_TASK_append in my machine .conf file.
I do get the flatbuffers header files in the SDK but only the ARM flatc not the native one.
Here is the dependency I put in the .bb file for a custom binary we have:
DEPENDS += "yaml-cpp libevent protobuf python3 nativesdk-flatbuffers flatbuffers-native flatbuffers"
DEPENDS_append_class-nativesdk = " flatbuffers"

Here is my flatbuffers   .bb file
SUMMARY = "Memory Efficient Serialization Library"
HOMEPAGE = "https://github.com/google/flatbuffers"
SECTION = "console/tools"
LICENSE = "Apache-2.0"

PACKAGE_BEFORE_PN = "${PN}-compiler"

RDEPENDS_${PN}-compiler = "${PN}"
RDEPENDS_${PN}-dev += "${PN}-compiler"

LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=a873c5645c184d51e0f9b34e1d7cf559"

SRCREV = "c0698cc33f1e534bb59c455909b88cc2726089af"

SRC_URI = "git://github.com/google/flatbuffers.git"

# Make sure C++11 is used, required for example for GCC 4.9
CXXFLAGS += "-std=c++11"
BUILD_CXXFLAGS += "-std=c++11"

# BUILD_TYPE=Release is required, otherwise flatc is not installed
EXTRA_OECMAKE += "\
    -DCMAKE_BUILD_TYPE=Release \
    -DFLATBUFFERS_BUILD_TESTS=OFF \
    -DFLATBUFFERS_BUILD_SHAREDLIB=ON \
"
#    -DFLATBUFFERS_BUILD_FLATC=ON

#do_install_append() {
#    install -d ${$D}/${bindir}
#    install ${B}/flatc ${D}${bindir}
#}

inherit cmake

S = "${WORKDIR}/git"

FILES_${PN}-compiler = "${bindir}"
FILES_${PN} += "/usr/lib/*"
FILES_${PN} += "/opt/ousteros/2019.7/sysroots/*"
#FILES_${PN} += "${WORKDIR}/${SDK_ARCH}/usr/bin/flatc"

BBCLASSEXTEND = "native nativesdk"

I get the ARM flatc but not the x86_64 flatc which I need to build a header file that my other binary will need. My other binary doesn't yet require that header file, I first want to generate an SDK with flatc in it.

A: Don't mix target and nativesdk packages in DEPENDS.
To add native tools to the SDK you need to add nativesdk-flatbuffers-compiler to TOOLCHAIN_HOST_TASK in the image recipe that the SDK is created from.