text:
Q: Inductive colimits of free groups Is every group isomorphic to an inductive colimit (that is, directed colimit, also called inductive limit, or directed limit) of free groups?
I guess, the answer is no. In that case: Is there a characterization of the groups that are isomorphic to inductive colimits of free groups?

A: Let $G$ be a group. Equivalences:

*

*$G$ is locally free (i.e., all its finitely generated subgroups are free)

*$G$ is a filtering inductive limit of free groups with injective connecting homomorphisms

*$G$ is a filtering inductive limit of free groups.

The equivalence between (1) and (2) is clear (given that subgroups of free groups are free - otherwise "locally free" would be a bit imprecise); (3) is tautologically implied by (2).
Conversely suppose (3), and let's prove (1). Passing to a finitely generated subgroup of $G$ reduces to $G$ finitely generated. Then passing to a cofinal subsystem allows to assume that the filtering system has an initial element $H$ with $H\to G$ surjective. Then some finitely generated subgroup $K$ of $H$ has onto image in $G$ and then replacing each group in the filtering system, we realize $G$ as a filtering inductive limit of finitely generated free groups with surjective connecting homomorphisms. Then the rank of these free groups decreases until it stabilizes, and since finitely generated free groups are Hopfian, this means that there's a cofinal subsystem made up of isomorphisms. So $G$ is free.
Note: for more other classes of groups, usually such an implication as (3)$\Rightarrow$(2) fails. For instance, every group is a filtering inductive limit of finitely presented groups (this is not specific to groups!), but usually this cannot be done with injective connecting homomorphisms (e.g., for an infinitely presented finitely generated group).


text:
Q: Why aren't any of my view components appearing? I have been trying to complete the assignment of making the screen a rainbow color. I inserted view components and inserted the stylesheet, but nothing is showing up.
import React, { Component } from 'react';
import { AppRegistry, Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

export default class App extends Component {
    render() {
        return (
            <View style={styles.container}>

                <View style={styles.violet}>
                </View>

                <View style={styles.indigo}>
                </View>

                <View style={styles.blue}>
                </View>

                <View style={styles.green}>
                </View>

                <View style={styles.yellow}>
                </View>

                <View style={styles.orange}>
                </View>

                <View style={styles.red}>
                </View>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'stretch',
    },
    violet: {
        height: 58,
        backgroundColor: '#94OOD3',
    },
    indigo: {
        backgroundColor: '#4BOO82',
        height: 58,
    },
    blue: {
        backgroundColor: '#OOOOFF',
        height: 58,
    },
    green: {
        backgroundColor: '#OOFFOO',
        height: 58,
    },
    yellow: {
        backgroundColor: '#FFFFOO',
        height: 58,
    },
    orange: {
        backgroundColor: '#FF7FOO',
        height: 58,
    },
    red: {
        backgroundColor: '#FFOOOO',
        height: 58,
    }
});

I have been trying to fix this for quite some time; if any of you could please point out an issue, I would much appreciate the help.

A: This is because you are using the wrong syntax for colors. Change all O with 0 (zero).
violet: {
    height: 58,
    backgroundColor: "#9400D3"
  },
  indigo: {
    backgroundColor: "#4B0082",
    height: 58
  },
  blue: {
    backgroundColor: "#0000FF",
    height: 58
  },
  green: {
    backgroundColor: "#00FF00",
    height: 58
  },
  yellow: {
    backgroundColor: "#FFFF00",
    height: 58
  },
  orange: {
    backgroundColor: "#FF7F00",
    height: 58
  },
  red: {
    backgroundColor: "#FF0000",
    height: 58
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serving static files in flask with and without www subdomain? I have a Flask-based app on google app engine: http://gyroplane.io
Root domain is the app itself, subdomains like foobar.gyroplane.io are dynamic user-generated content.
Thus single Flask app is configured to catch both gyroplane.io and *.gyroplane.io requests and makes decisions on what to serve.
However, some people will likely type "www.gyroplane.io" in the browser and I want them to have exactly same experience as if they've typed "gyroplane.io".
To do that, I have to duplicate every routing rule for both top-level domain and the www. subdomain:
@root_app.route("/")
@root_app.route("/", subdomain='www')
def root_home():
    return render_template('admin/index.html', context=dict(
        SERVER_NAME=SERVER_NAME,
    ))

And also have to copy-paste the /static/ rule:
root_app.add_url_rule(root_app.static_url_path + '/<path:filename>',
                  endpoint='static',
                  view_func=root_app.send_static_file,
                  subdomain='www')

Is there a not so hacky solution to tell Flask to treat two different subdomains as same?


text:
Q: How to get CKEditor to save locally. I've been looking for a Word Processor to put on a web OS I'm creating and CKEditor was the easiest out of all the ones I found on the internet to implement. (The OS runs in any of the major browsers).
The problem is, I looked all over the internet to see how to save anything put into it by the end user locally in a .txt or .html file and not on a server. But, that's all I'm seeing (how to save to a server). I have no server and I don't plan on making one any time soon.


text:
Q: Is there a series satisfies $a_n>0,\sum a_n$ converges but $\sum a_n^{r}$ diverges for all $0\leq r<1$
Is there a series satisfies $\displaystyle a_n>0 \forall n\in \mathbb{N},\sum_{n=1}^{\infty} a_n$ converges but $\displaystyle \sum_{n=0}^{\infty} a_n^{r}$ diverges for all $0\leq r<1$?

Context:
It originally comes out of a complex analysis problem where if I can find one I can find a series of holomorphic functions converges uniformly on a closed disc but not any open disc includes it.
There is no p-series satisfies this condition, and the series can not be something like geometric series either(otherwise by root test either both converge or both diverge).
Is such a series exists? If not I might approach my original problem wrong...

A: A start: Let $a_n=\frac{1}{(n+1)\ln^2 (n+1)}$.


text:
Q: Is it possible to allow Windows to reclaim memory when Skype is minimized? With every update, Skype has started consuming huge amounts of memory. I somewhere heard that when programs are minimized Windows can reclaim some of the memory from the program.
For example, I somewhere read an article which told about how to instruct Firefox to allow Windows to reclaim memory when minimized, by changing something in about:config and it worked for me.
Is there something that can be done for Skype so that it consumes less memory when minimized (when it sits almost silently in the system tray)

A: Minimizing a window might free a little memory, but it depends on the application, and it won't amount to much. In any case, minimizing won't make more difference than any other form of hiding.
Even if an application's window is minimized, it's still running. The application isn't going to need to keep less data in memory just because one of its windows is minimized.
An application is notified whenever one of its windows is minimized or restored. It's also notified whenever part of its window becomes visible or hidden. It is possible, but unlikely, that the application would react differently to various reasons its window may be hidden:
It can be minimized, meaning the window is not shown and an icon is shown in its place.
It can be hidden behind other windows (including the full-screen window of a screensaver).
It can be displayed on a different desktop, workspace, viewport, or whatever your window manager calls these.
It can be hidden in some other manner, for example "shaded" (meaning only a title bar is shown), or simply unmapped (meaning the window manager has decided for whatever reason that the window shouldn't be displayed).

If an application's window is completely hidden, then the application doesn't need to refresh the window contents. If it needs to allocate memory to refresh that content, it won't be doing it while the window is hidden. Also, if a window is hidden (for any reason), the application might free a little memory inside the X server.
What makes more of a difference in practice is that if a window isn't being displayed, then the application doesn't make computations to redraw the contents, and therefore the data needed to draw the contents can be swapped out. If RAM is tight and there's a window you aren't going to iteract with for a while, it's better if the window is not mapped. Again, the reason why the window is not mapped (hidden behind others, minimized, shaded, …) is unimportant.


text:
Q: 504 Gateway error on huge sql query in php Hello I've a project in which I'm storing some data from xml file into my database, which the data is so huge that it takes some time, few data is inserted like 30thousands and then I get 504 gateway timeout.
I've tried increasing max_execution_time from php.ini but that didnt work. Im using cpanel
myscript
$xml=simplexml_load_file($url) or die("Error: Cannot create object");
        $totalproducts = $xml->shop->offers->offer->count();
        for($x=0 ; $x < $totalproducts; $x++){
            if(!empty($xml->shop->offers->offer[$x])){
                $name = $xml->shop->offers->offer[$x]->name;
                $price = $xml->shop->offers->offer[$x]->price;
                $description = $xml->shop->offers->offer[$x]->description;
                // $description = preg_replace('#[^a-zA-Z0-9 ]#', "", $description);
                $description = str_replace('"', "", $description);
                $description = str_replace("'", "", $description);
                // $description = mysqli_real_escape_string($description);
                $imglink = $xml->shop->offers->offer[$x]->picture;
                $url = $xml->shop->offers->offer[$x]->url;
                $catname = 'shoes';
                $program = $_POST['programname'];
                $sql = "INSERT into products(categoryname,productname,productdiscription,price,url,program,image) VALUES('$catname','$name','$description','$price','$url','$program', '$imglink')";
                if ($conn->query($sql) === TRUE) {
                    // echo "New record created successfully";
                } else {
                    // echo "Error: " . $sql . "
" . $conn->error;
                }
            }
        }

A: I think problem comes from "simplexml_load_file()" function. probably loading xml takes much time.
If you sure about the function, I add a few code line to prevent timeout, but not decreasing time:
<?php
if (isset($_GET['offset'])){$offset=$_GET['offset'];}
else {$offset=0;}

$xml=simplexml_load_file($url) or die("Error: Cannot create object");
        $totalproducts = $xml->shop->offers->offer->count();
        for($x=$offset ; ($x < $totalproducts && ($x < (($offset+1)*100)); $x++){
            if(!empty($xml->shop->offers->offer[$x])){
                $name = $xml->shop->offers->offer[$x]->name;
                $price = $xml->shop->offers->offer[$x]->price;
                $description = $xml->shop->offers->offer[$x]->description;
                // $description = preg_replace('#[^a-zA-Z0-9 ]#', "", $description);
                $description = str_replace('"', "", $description);
                $description = str_replace("'", "", $description);
                // $description = mysqli_real_escape_string($description);
                $imglink = $xml->shop->offers->offer[$x]->picture;
                $url = $xml->shop->offers->offer[$x]->url;
                $catname = 'shoes';
                $program = $_POST['programname'];
                $sql = "INSERT into products(categoryname,productname,productdiscription,price,url,program,image) VALUES('$catname','$name','$description','$price','$url','$program', '$imglink')";
                if ($conn->query($sql) === TRUE) {
                    // echo "New record created successfully";
                } else {
                    // echo "Error: " . $sql . "
" . $conn->error;
                }
            }
        }
Header("Location: yourpage.php?offset=".($offset+100));
echo ($offset+100).' items inserted';
?>

This splits inserting to 100 items by 100 items. you can change 100 to more items at each time.


text:
Q: removeVolatile doesn't clear all value in UserDefaults.registrationDomain Today I learn that iOS has a volatile and a persistent store for UserDefaults.
I register a value (value) with key (key) using the register method.
let key = "key"
let value = "value"
UserDefaults.standard.register(defaults: [key: value])

In my application code, I try to delete the key using the removeObject(forKey:) method.
UserDefaults.standard.removeObject(forKey: key)

I expect that the next time I try to fetch the value of key, the object(forKey:) will return nil (but it doesn't not).
Full Code:
let key = "key"
let value = "value"

UserDefaults.standard.register(defaults: [key: value])
UserDefaults.standard.setValue(value, forKey: key)
UserDefaults.standard.removeObject(forKey: key)
UserDefaults.standard.object(forKey: key) // "value" - why?

*

*From my understanding, the register method "registers" values in the registrationDomain, which is temporary until a real value is set (using the setValue(forKey:) method). But in this case, even once I set a real value and then delete the value, object(forKey:) returns the value from the registrationDomain. Why did Apple decide to do it this way? I can't think of an obvious why when once explicitly asks a valued to be removed, it should still return the value registered using the register method? Is this just a matter of persistent vs. volatile domains?

*Does this mean that once a key is registered using the register method, it is always expected to have a value?

Why can't I use removeVolatileDomain(forName:) to empty the entire registrationDomain?
let key = "key"
let value = "value"

UserDefaults.standard.register(defaults: [key: value])

// This doesn't work? registrationDomain = ["key": "value"]
UserDefaults.standard.removeVolatileDomain(forName: UserDefaults.registrationDomain)

// Why do I have to do this?
var registeredDefaults = UserDefaults.standard.volatileDomain(forName: UserDefaults.registrationDomain)
registeredDefaults[key] = nil
UserDefaults.standard.setVolatileDomain(registeredDefaults, forName: UserDefaults.registrationDomain)
// registrationDomain = [:]


text:
Q: dataframe plot - remove the column names average_curves_norm_T2

   fig, ax= plt.subplots(1,1, figsize=(18,10))
    average_curves_norm_T2.xs(0, level=1).T.plot(ax=ax, legend=True, alpha=0.05, color='blue', label= f'Cluster {cluster}')
    average_curves_norm_T2.xs(0, level=1).median().plot(ax=ax, color='blue', alpha=0.9)

    ax.set_xticks(np.arange(1,96))
    ax.set_ylabel('Normalized kilowatts')
    ax.set_xlabel('Quarter Hour')
    ax.set_title('Blue - Cluster 0 | Red - Cluster 1 | Green - Cluster 2',
                 fontweight ="bold")
    ax.legend()

See picture for my dataframe & the chart I'm trying to plot.
The chart below contains all the MT_*** for the cluster 1.
But the small box( MT_012,MT_013,MT_014, etc) on the right hand side of the chart is too long to fit into the graph. Any idea how to remove that from the plot to make the plot looks cleaner?


text:
Q: stripe checkout client only integration in reactjs . how to handle the callback urls . how to subscribe for recurring payments? I am trying to integrate stripe check out (client only integration) in my reactjs application and i see there's lots of confusion about this which are listed below
(i) : first thing is "react-stripe-checkout" , a react library to implement checkout. i could not find any example of how to pass the plan Id to this "react-stripe-checkout" . As in client only integration you create the plans on stripe dashboard and pass the plan id to checkout , but there is no example of how to pass my plan id to "react-stripe-checkout". For example without using this library this is how i use the stripe.js directly in my react app
 const stripe = window.Stripe('pk_test_my tst key');
 stripe.redirectToCheckout({
      clientReferenceId:"abc",
    items: [
      {plan: 'my-plan-id', quantity: 1}
    ],
    successUrl: '',
    cancelUrl: '',

  }).then((result) => {

    console.log(result)
  });

in above code i am passing my plan id to stripe's "redirectToCheckout" method and it redirects me to a new form hosted by stripe and customer can subscribe for the plan there. but how do we accomplish this functionality using "react-stripe-checkout".
(ii) I assume that "react-stripe-checkout" can't be used for client only integration and it just can be used for client server integration , i need a confirmation on that . moreover like "react-stripe-checkout" pops up the form for collecting user card information on the same page whereas stripe.redirectToCheckout() takes the user to a new page to enter his card info. is there a way to collect the user card info on same page in a popup like we do with "react-stripe-checkout".
(iii) Assuming that "react-stripe-checkout can't be used for client only integration" . I have decided to use stripe.redirectToCheckout() anyways. I have already posted the code above and i am confused about how to use callback urls there.  I have not seen a single example all over the internet anywhere for handling these callback urls in reactjs. i wonder if anybody has implemented the client only checkout integration in reactjs until now , if so why isn't there any example available to follow.
(iv) I am following the stripe documentation for implementing webhooks on my backend (Nodejs) server.
this is the link https://stripe.com/docs/payments/checkout/fulfillment#webhooks . and there's this line there
"If Stripe does not receive successful acknowledgement after 10 seconds have passed from a successful payment, your customer will be automatically redirected to the success_url page."
what does it mean ?  how do i be sure about inside "success_url page" that customer has successfully subscribed to the plan or not ?
(v) from stripe documentation i also do not understand this following line
"If you'd like to access the Checkout Session ID you can add the {CHECKOUT_SESSION_ID} template variable to the success_url (e.g. success_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}). When your customer is redirected on successful payment, the success_url will contain the Checkout Session ID in place of the {CHECKOUT_SESSION_ID} template variable."
can anyone explain what this {CHECKOUT_SESSION_ID} template variable  is for , and what would i pass in it from my frontend ?
kindly help .


text:
Q: Java and PostgreSQL stored procedure - return registered as out parameter, causing issues with in parameters I'm trying to call a PostgreSQL stored procedure from a Java app; the procedure has a DATE type parameter so I'm using a java.sql.Date type with CallableStatement.setDate().  However, executing the statement always results in an exception and the SQL logs show this:
LOG:  execute <unnamed>: select * from athlete.create_athlete($1,$2,$3,$4,$5,$6,$7) as result
DETAIL:  parameters: $1 = '', $2 = 'foo@bar.com', $3 = 'Joe', $4 = 'Blow', $5 = 'foobar', $6 = 'M', $7 = '1979-03-22 -04:00:00'
ERROR:  column "dob" is of type date but expression is of type text at character 122
HINT:  You will need to rewrite or cast the expression.
QUERY:  INSERT INTO athlete.athlete (email, first_name, last_name, password, gender, dob) VALUES ( $1 ,  $2 ,  $3 ,  $4 ,  $5 ,  $6 )
CONTEXT:  PL/pgSQL function "create_athlete" line 2 at SQL statement
STATEMENT:  select * from athlete.create_athlete($1,$2,$3,$4,$5,$6,$7) as result

The stored procedure actually has 6 parameters (and should receive values $2 through $7 above) - the 7th comes from registering the return value as an out parameter.  This has me confused - is it correct that it appears as 7 parameters when I register an out parameter for the return value?
From all the docs I've read I'm under the impression that the return value has to be registered as the first parameter:
registerQuery = "{? = call athlete.create_athlete(?,?,?,?,?,?)}";
...
CallableStatement cs = conn.prepareCall(registerQuery);
cs.registerOutParameter(1, Types.BOOLEAN);
cs.setString(2, email);
...

The error above suggests to me that there's a mismatch between stored procedure parameters and the parameters supplied to the insert statement.  I've been following documentation for all of this but am clearly doing something wrong.  How do I supply the proper parameters to the stored procedure and retrieve the return value after the call?

A: Depends on signature of your stored procedure type (function/procedure).
For function like one below, out parameter will be first one and will have param1 and param2 as second and third parameters.
DB Procedure (for function):
CREATE FUNCTION my_func (
param1 INT,
param2 INT)
    RETURNS INT
AS
    :
    :

Java code (for function):
registerQuery = "{? = call my_func(?,?)}";
...
CallableStatement cs = conn.prepareCall(registerQuery);
cs.registerOutParameter(1, Types.INTEGER);
cs.setInteger(2, 10);
cs.setInteger(3, 10);
...

.
However for procedure like one below, out parameter will be third one and will have param1 and param2 as first and second parameters.
DB Procedure (for procedure):
CREATE PROCEDURE my_proc (
param1 INT,
param2 INT,
OUT param3 INT)
BEGIN
    :
    :
END;

Java code (for procedure):
registerQuery = "{call my_func(?,?,?)}";
...
CallableStatement cs = conn.prepareCall(registerQuery);
cs.registerOutParameter(3, Types.INTEGER);
cs.setInteger(1, 10);
cs.setInteger(2, 10);
...

.
Note that you can have multiple out parameters while only one return value.

A: Postgresql server supports named parameters but the jdbc driver does not support it(well not yet to my knowledge), so until such time only positional parameters is supported.

A: It turns out the issue was that the order of parameters passed to the stored procedure did not match the order those parameters were passed to the insert statement.  I don't understand why PostgreSQL would use named parameters if order is significant.
For example, the signature of the stored procedure was as follows:
CREATE FUNCTION insert_Person (IN in_name TEXT, IN in_gender CHAR(1), IN in_bdate DATE) RETURNS BOOLEAN...
The INSERT statement contained within that stored procedure was as follows:
INSERT INTO Person (name, bdate, gender) VALUES (in_name, in_bdate, in_gender);
Changing the order of the parameters such that they matched in either the stored procedure signature or insert statement (I went with the former) resolved the issue.

A: Due to a restriction in the OCI layer, the JDBC drivers do not support the
passing of BOOLEAN parameters to PL/SQL stored procedures. If a PL/SQL
procedure contains BOOLEAN values, you can work around the restriction by
wrapping the PL/SQL procedure with a second PL/SQL procedure that accepts
the argument as an INT and passes it to the first stored procedure. When
the second procedure is called, the server performs the conversion from
INT to BOOLEAN.


text:
Q: C# Reading only specific lines without reading line by line I been googling for the last hour and can not find an answer to this.
I have a large text file (1GB) and I also have a file which has this all mapped so I know that on line x to line y it contains the data I am after.
My question is how do I take only the lines I am interested in without iterating through all the lines in the file?
The main reason I am interested in doing it this way is for performance reasons, I imagine it be quicker to take rows 503,432 to row 504,432 than cycle from row 1 to 504,432 to find these rows.
Any tips much appreciated

A: If you are looking for a specific row number, you need to read all rows to count them anyway. You can't count the rows without reading the file except if the lines are fixed length. You do not need to save the lines when you read them. Only save the linenumber you need, or handle them without keeping them in memory for later.

A: I think this is a case of premature optimization.
I'm processing ~6GB files using FileHelpers AsyncEngine and 'reading of the file' part is not the slowest part of the process by any means.
How long does is take to read first 500k lines and do nothing? How much time are you going to save?


text:
Q: Getting more than 1 object from session.createQuery in hibernate I have a composite key which houses 3 keys.
Composite key =>
@Embeddable
public class CompositeId implements Serializable{

    @Column(unique = true)
    private int deliveryId;
    @MapsId
    @OneToOne
    @JoinColumn(name = "invoiceId",unique = true)
    private Invoice invoiceId;
    @MapsId
    @ManyToOne
    @JoinColumn(name = "customerId",nullable = false)
    private Customer customerId;
}

Delivery Class=>
@Entity
public class Delivery {
    @EmbeddedId
    private CompositeId compositeId;
}

That's how the composite ID is used. deliveryId is for delivery entity itself and other keys are for shared primary keys.
When I write a session.createQuery
Query query = session.createQuery("from Delivery where compositeId.deliveryId=?");
query.setParameter(0,1);

and when it runs, it throws an exception:

javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 1, for class: example.test.Delivery

So I though of overriding equals and hashcode methods
@Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (obj instanceof Invoice) {
            Invoice invoice = (Invoice) obj;
            if (invoice.getInvoiceId() == this.invoiceId.getInvoiceId()) {
                return true;
            }
            if (invoice.getDeliveryId() == this.invoiceId.getDeliveryId()) {
                return true;
            }
        }
        if (obj instanceof Customer) {
            Customer customer = (Customer) obj;
            if (customer.getCustomerId() == this.customerId.getCustomerId()) {
                return true;
            }
            if (customer.getDeliveryId() == this.customerId.getDeliveryId()) {
                return true;
            }
        }
        return false;
    }

but still I get the same error. And I thought It will fix it. But it didn't. I found the reason by following SQL and the reason is this gets 2 Customer and Item objects because of bidirectional relations. So how can I solve it?
Thanks :)

A: For your primary issue, the HibernateException, please switch on the hibernate.show_sql = true and see what is the SQL being fired and the results coming back.
The mapping however looks fine and works for with same structure and different class/table names.
For the second part, the equals method, I would suggest to use auto-generated method from Eclipse and include all the properties. Your Invoice and Customer class must also implement equals and hashCode methods. The implementation of equals here wil not be useful since hibernate will not pass instance of Invoice and Customer to compare with instance of CompositeId.


text:
Q: Delete packagecloud repository and key So I've ran a sudo apt update and got some errors:
N: Skipping acquisition of configured file 'main/binary-i386/Packages', as repository N:
Skipping acquisition of configured file 'main/binary-i386/Packages', as repository
'https://download.mono-project.com/repo/ubuntu stable-focal InRelease' doesn't support
architecture 'i386'
 W: GPG error: https://packagecloud.io/shiftkey/desktop/any any InRelease: The following
 signatures couldn't be verified because the public key is not available: NO_PUBKEY
B7E65990E879472F
E: The repository 'https://packagecloud.io/shiftkey/desktop/any any InRelease' is not
signed.
'https://download.mono-project.com/repo/ubuntu stable-focal InRelease' doesn't support
architecture 'i386'
 W: GPG error: https://packagecloud.io/shiftkey/desktop/any any InRelease: The following
  signatures couldn't be verified because the public key is not available: NO_PUBKEY
 B7E65990E879472F
E: The repository 'https://packagecloud.io/shiftkey/desktop/any any InRelease' is not signed.

I've searched for information on how to remove that repository but haven't found any clear answer
When I try to remove the GPGkey I get "no data found" so can't delete they key also. Does anyone know how to get rid of those errors?

A: *

*ls /etc/apt/sources.list.d/
Look for the name of the repo you want to remove, or if you're unsure, open the file with any text editor, if it mention the name of the repo you want to remove (in my case it has 'packagecloud.io' and 'git-lfs') then you should be good to go

*rm /etc/apt/sources.list.d/<insert file name here>
hope this helps


text:
Q: Is there any built-in control (or maybe someone has coded one) to select an image from Google Images and put in an ImageView for Android? The title speaks for itself really. I was wondering if there is some simple way (similar to opening the Photo Gallery) to select an image in Google Images and then passing it back to an ImageView for Android?
Has anyone done this?

A: It's a fairly commong task within android. You can take a look to the following tutorial to accomplish exactly what you need.
http://viralpatel.net/blogs/pick-image-from-galary-android-app/
Good luck!


text:
Q: random function in scheme I am trying to get a random string from a list of strings in scheme.
Example List ( "this" "that" "today" "yesterday")
So based on length of the list a random number is created and that word is output. But keep getting error!
I tried it like this:
;; produces random number that should be input to the random-function

(define (random-num list)

(random-function ((random (length (list))) list)))

;; loops the number of times till random number is 0 and outputs the list value

(define (random-function num list )
  (cond
    [(zero? num) (car list)]
    [else (random-function (- num 1) (cdr list))]))

Error:
procedure application: expected procedure, given:
("this" "that" "today" "yesterday") (no arguments)

When I try to do :
(random-function (random (length list))

on the console I get a random number.
Do not understand why it is crashing here when done inside my program???
Could I do this in a better way rather than looping so many times.
In Java I would have used an array and given the position directly.
Anyway to do it in scheme too ?

A: (define (random-element list)
  (list-ref list (random (length list))))


text:
Q: Updating Field value in multiple documents in same collection in Firebase I have created a chat app. In the app there is a collection named Chat and in it there are documents. Each document is a message that was sent and it contains fields such as Message, SentTime, IsButton.
Once something happens in the app (someone clicks a button), I had like to change in all of my documents at that chat the value of IsButton from False to True.
The data looks as follows:

Is there a way to change all of the Field values in one hit instead of using a loop?
I saw there is something called Batch however I'm not sure if it is limited to a maximum 500 updates.
Thank you

A: The two approaches you've found are pretty much the way to update a bunch of document.
You can:

*

*either update each document individually, which is not nearly as slow as you may think.

*or you can update the documents in one of more batches.

Having to update many documents with the same value may be a sign that you should reconsider your data structure. For example, maybe you can store the IsButton in a single, separate document that all clients then read/listen to.


text:
Q: How do I extract space separated floating numbers from string into another array in c? I have this code. The user should input something like this "10.0 10.0 4.0 7.0". And, I want my program to put these floating point numbers into an array so that each of these is accessible through floats[0] = 10.0, floats[1] = 10.0  floats[2] = 4.0 floats[3] = 7.0. I would make them floating point types later. In this code I'm trying to use two-dimensional array, but something is definitely wrong.
Can you put me on the right track?
#include <cs50.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>

int main(void)
{
    // prompt the user to enter two inputs
    string input1 = get_string();

    // declare and initialize essential variables
    int len1 = strlen(input1);
    int j = 0;

    // declare an array where the next lines of code should put floats separately
    string floats[100][100];

    // put each floating point number into an array character by character
    for (int i = 0; i < len1; i++) {
        if (isspace(input1[i])) {
            j++;
        } else {
            floats[j][i] = input1[i];
        }
    }
}

A: strtod() is the best tool for parsing floating point numbers.
To separate sub-strings using whitespace, at a minimum OP's code is not appending a needed null character.  Further the copying from input1[] needs to copy more than just one character.
// Avoid magic numbers, using define self-documents the code
#define FLOAT_STRING_SIZE 100
#define FLOAT_STRING_N 100

int main(void) {
  string floats[FLOAT_STRING_N][FLOAT_STRING_SIZE];
  string input1 = get_string();
  char *p = input1;

  int count;
  for (count = 0; count < FLOAT_STRING_N; count++) {
    while (isspace((unsigned char) *p) p++;

    // no more
    if (*p == '\0') break;

    int i;
    for (i = 0; i<FLOAT_STRING_SIZE-1; i++) {
      if (isspace((unsigned char) *p) || *p == '\0') break;
      floats[count][i] = *p++;  // save character and advance to next one.
    }
    floats[count][i] = '\0';
  }

  int count;
  for (int c = 0; c < count; c++) {
    puts(floats[c]);
  }

  return 0;
}

A: You can use stringstream (although that's a c++ way) like this
std::stringstream ss;
ss.str (input1);
int i = 0;
string t;
while ( ss >> t)
{
     floats[i++] = std::stof(t); //fill your array one by one
}

For pure C way, you can use sscanf.

A: You can use strtod() to parse the string one floating point number at a time:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // prompt the user to enter two inputs
    char *input1 = get_string();

    // declare the destination array for the floating point numbers
    double numbers[100];
    int n;

    char *p = input1;
    char *q;

    for (n = 0; n < 100; n++) {
        numbers[n] = strtod(p, &q);
        if (p == q) {
            // no more numbers to parse
            break;
        }
        p = q;
    }

    // print the array contents
    for (int i = 0; i < n; i++) {
        printf("%f\n", numbers[i]);
    }

    return 0;
}


text:
Q: android.view.InflateException: Error inflating class  I'm a beginner in android and i want to program a calculator (press here to see the project), but i get this error.
Can someone help me?

A: hello Kevin you are using wrong constraint i.e widget the error tells you that it occurred in line to change your constraint layout from
<androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

to
<androidx.constraintlayout.ConstraintLayout>
</androidx.constraintlayout.ConstraintLayout>


text:
Q: Select in form returning name/value array instead of just value I am attempting to use AngularJS to display three select dropdowns in a form (to indicate a birthday - month, day and year). This form then needs to post these values to my API.
I have an array of each of the months, days and years and I populate the controller like so:
$scope.months = myMonthArray;
$scope.user.birthMonth = $scope.months[0];

$scope.days = myDayArray;
$scope.user.birthDay = $scope.days[0];

$scope.years = myYearArray;
$scope.user.birthYear = $scope.years[0];

$scope.register = function(user) {
  $scope.errors = [];
  repository.register(user).$promise.then(
    function() { $location.url('/'); },
    function(response) { $scope.errors = response.data;});
};

My repository factory method looks like this:
register: function(user) {
  var reg = $resource('/api/registration', null, {
    register: { method: 'POST'}
  });
  return reg.save(user);
}

Finally, the view (for the select looks like the following:
<select id="birthMonth" ng-model="user.birthMonth" ng-options="c.name for c in months"></select>
<select id="birthDay" ng-model="user.birthDay" ng-options="c.name for c in days"></select>
<select id="birthYear" ng-model="user.birthYear" ng-options="c.name for c in years"></select>

The view looks great as each of the select boxes properly populate and show the first value. However, when I submit it, my .NET APT model failed to capture the values - looking at the Fiddler request, it looks like the following:
{"birthMonth":
    {"name":"November","value":11},
  "birthYear":
    {"name":1988,"value":1988},
  "birthDay":
    {"name":23,"value":23}}

All the other fields in the form capture correctly (given that they're just text inputs) so I believe the problem lies in the fact that Angular is providing the array of values rather than simply posting the Value of each select control.
Is it a matter that I'm specifying the model for each of these incorrectly? Or what do I need to be doing differently so it only passes the value of each of these select fields?
Thanks!

A: With your ng-options expression, you're binding to the whole object. If you need to get only the value field, try:
ng-options="c.value as c.name for c in months"

Your JS could be changed to:
$scope.months = myMonthArray;
$scope.user.birthMonth = $scope.months[0].value;

Do the same for days and years.


text:
Q: My flair has turned against me I usually keep a copy of my "combined flair" in the "About me" part of my profile, and I noticed yesterday that it has turned into something rather different:

Here's my usual flair link, with image:
https://stackexchange.com/users/flair/d0c456330b54457d8bd65294962afb12.png

(I guess one way to tell whether the problem has been solved is if you see flair instead of the warning image there when you read the question.)
Anyway, seems like a bug or temporary problem.


text:
Q: Why so many [not cacheable] files with webpack recompile? I have a fairly small project. Around 800 modules. When I change one of the files, and the webpack-watch recompiles everything, it takes much longer than I would like. And I think that the main reason is that when it is done, it lists hundreds of files that are [not cacheable].

There are hundreds of these files each time I save even a single-char change.
Any ideas on what could be causing these files to be not cacheable? Any ideas on where I can start looking to figure it out? I have poked around and been unsuccessful so far. The only loader for my .js files is ts-loader. Other than that, I don't use other loaders.
I just need some ideas on where to start. This github issue has been around for years, with no answer on it. People need help figuring out how to know why a certain file isn't cacheable. Any ideas here would be much appreciated. I can show samples from my webpack.config.js. I am on webpack 1 for now. I don't think that is the issue.
Let me know.

A: I don't have an answer that will solve this for everyone. But, for my case, I was using a loader that made my stuff not-cacheable. Once I fixed that, I was good to go. The loader I was using is mark-loader. Once I took that out, all the files were immediately cacheable again.


text:
Q: How to make extension unionWith for Hashset I am trying to make an extension for the custom type. This is my code. I don't know how my source becomes zero in this code. Even in the debug part hashset temp is giving me a list of 10 logevents. But in the final the source is becoming zero.
public static void UnionSpecialWith(this HashSet<LogEvent> source, List<LogEvent> given,IEqualityComparer<LogEvent> comparer)
{
    List<LogEvent> original = new List<LogEvent>(source);
    List<LogEvent> second = given.Condense(comparer);

    source = new HashSet<LogEvent>(original.Condense(comparer),comparer);

    foreach (LogEvent logEvent in second)
    {
        if (original.Contains(logEvent, comparer))
        {
            int index = original.FindIndex(x => comparer.Equals(x, logEvent));
            original[index].filesAndLineNos.MergeFilesAndLineNos(logEvent.filesAndLineNos);
        }
        else
            original.Add(logEvent);
    }
#if DEBUG
    String content = String.Join(Environment.NewLine, original.Select(x => x.GetContentAsEventsOnly()));
    HashSet<LogEvent> temp = new HashSet<LogEvent>(original, comparer);
#endif
    source = new HashSet<LogEvent>(original, comparer);
}

Can anybody point me out  what is wrong?
EDIT:
     This is my custom type. Whenever I found a duplicate , I want to merge it's "filesAndLineNos" with the original one. This is what I am trying to achieve with the above code.
public class LogEvent
{
    public String mainEventOriginal;
    public String subEventOriginal;
    public String mainEvent;
    public String subEvent;
    public int level;
    public Dictionary<String,HashSet<int>> filesAndLineNos;
}

The usage is something like
HashSet<LogEvent> required = new HashSet<LogEvent>(initialUniqueSet);
required.UnionSpecialWith(givenListOfLogEvents);

A: This is simply a matter of parameters being passed by value in .NET by default. You're changing the value of source to refer to a different HashSet, and that doesn't change the caller's variable at all. Assuming that Condense doesn't modify the list (I'm unaware of that method) your method is as pointless as:
public void TrimString(string text)
{
    // This changes the value of the *parameter*, but doesn't affect the original
    // *object* (strings are immutable). The caller won't see any effect!
    text = text.Trim();
}

If you call the above with:
string foo = "   hello   ";
TrimString(foo);

... then foo is still going to refer to a string with contents "   hello   ". Obviously your method is more complicated, but the cause of the problem is the same.
Either your extension method needs to modify the contents of the original HashSet passed in via the source parameter, or it should return the new set. Returning the new set is more idiomatically LINQ-like, but HashSet.UnionWith does modify the original set - it depends which model you want to be closer to.
EDIT: If you want to modify the set in place, but effectively need to replace the contents entirely due to the logic, then you might want to consider creating the new set, then clearing the old and adding all the contents back in:
public static void UnionSpecialWith(this HashSet<LogEvent> source,
                                    List<LogEvent> given,
                                    IEqualityComparer<LogEvent> comparer)
{
    List<LogEvent> original = new List<LogEvent>(source);
    List<LogEvent> second = given.Condense(comparer);

    foreach (LogEvent logEvent in second)
    {
        if (original.Contains(logEvent, comparer))
        {
            int index = original.FindIndex(x => comparer.Equals(x, logEvent));
            original[index].filesAndLineNos
                           .MergeFilesAndLineNos(logEvent.filesAndLineNos);
        }
        else
        {
            original.Add(logEvent);
        }
    }
    source.Clear();
    foreach (var item in original)
    {
        source.Add(item);
    }
}

However, note:

*

*This does not replace the comparer in the existing set. You can't do that.

*It's pretty inefficient in general. It feels like a Dictionary would be a better fit, to be honest.


text:
Q: Facebook ignores "Default Activity Privacy" for application I set my app's Default Activity Privacy to "Everyone", but when showing an auth dialog for installing the app, Facebook ignores this setting and always shows "Friends".
I have tried that with several apps and is still the same.
A bug regarding this case is also reported in this link:  https://developers.facebook.com/bugs/268481063205627
Default Activity Privacy is described by Facebook here :  https://developers.facebook.com/docs/opengraph/authentication/
Can anyone help me with that? Or can you tell me if there is any other way to set the Activity Privacy through PHP code instead?

A: Depends on the user default settings, you can set an Activity Privacy,
but if the user have make any changes (Friends Only), you can't do something for this.

If the user changes it to Friends, the permission will be updated to
  friends only. If the user changes that to Public, your app activity
  will turn into public actions. Possible settings: None, Friends, Me
  only, or Public. The user can also change the Activity Privacy setting
  through the Auth Dialog.


text:
Q: Why does slapd say "bdb_equality_candidates: (objectClass) not indexed" when the indices actually exist? I have slapd 2.4.31-1+nmu2ubuntu8.3 installed on Ubuntu 14.04 and running as master to a secondary sync.  It works well for all things LDAP, but I notice these errors in /var/log/debug every so often:
May 19 09:19:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (uid) not indexed
May 19 09:20:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (objectClass) not indexed
May 19 09:20:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (objectClass) not indexed
May 19 09:20:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (uid) not indexed
May 19 09:20:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (objectClass) not indexed
May 19 09:20:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (objectClass) not indexed
May 19 09:20:01 ldap1 slapd[9507]: <= bdb_equality_candidates: (uid) not indexed

Don't these indices already exist (created via https://wiki.debian.org/LDAP/OpenLDAPSetup )? I can see them when I run slapcat -n 0. Do I need to create them for both master and slave? (the entry olcDatabase={2} and /var/lib/ldap/accesslog seem to indicate they only exist for the slave setup)
dn: olcDatabase={1}hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {1}hdb
olcDbDirectory: /var/lib/ldap
...
olcDbIndex: entryCSN eq
olcDbIndex: entryUUID eq
...
dn: olcDatabase={2}hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {2}hdb
olcDbDirectory: /var/lib/ldap/accesslog
olcSuffix: cn=accesslog
olcRootDN: cn=admin,dc=xxxxxx,dc=xxxxx,dc=xxx
olcDbIndex: default eq
olcDbIndex: entryCSN,objectClass,reqEnd,reqResult,reqStart
olcDbIndex: entryUUID eq
olcDbIndex: memberUid eq
olcDbIndex: uniqueMember eq
olcDbIndex: cn pres,sub,eq
olcDbIndex: sn pres,sub,eq
olcDbIndex: uid pres,sub,eq
olcDbIndex: displayName pres,sub,eq
olcDbIndex: default sub
olcDbIndex: uidNumber eq
olcDbIndex: gidNumber eq
olcDbIndex: mail,givenName eq,subinitial
olcDbIndex: dc eq
structuralObjectClass: olcHdbConfig


text:
Q: Isn't there a PRIMARY selection clipboard in windows First of all, its a windows question. Let me introduce you to the linux counterpart.

*

*In Linux, when I select a text anywhere in X Windows System, its gets copied to PRIMARY clipboard.

*Selecting a clipboard & explicitly copying it using Ctrl+C causes it to be copied to secondary keyboard.
In linux, I made a dictionary that automatically searches for word that is selected in current window. For that, I just copied the value of primary clipboard.
What's the equivalent of PRIMARY selection in windows? I want to retrieve the current selection in the current window using python.

A: There is no equivalent in Windows. There is just the single global clipboard which contains a single item, albeit in potentially multiple formats.

I want to retrieve the current selection in the current window.

That's not trivial in Windows. You can do it using, for example, UI Automation, for apps that support UI Automation. Most modern apps do support that but more obscure ones will not readily yield the information you are after.


text:
Q: Initialize a class on top level that's defined bottom level in the same header file Might be a dumb question. My apologies, but I would like to do the below,
connectionState currentState;

class connectionState {
    public:
        .......
        .......
};

rather
class connectionState {
    public:
        .......
        .......
};

connectionState currentState;

The former doesn't compiles at all while the latter does. So, no way to do this?

A: There are forward declarations for this. Forward declarations also resolve the problem of circular dependencies:
class connectionState; // forward class declaration
extern connectionState currentState; // forward global extern variable declaration, now possible because connectionState is declared as a typename/class name
static connectionState currentState; // forward global static variable declaration

class connectionState { ... }; // implementation/definition, can access currentState
connectionState currentState = ...; // definition/initialization
connectionState currentState {...}; // definition/initialization


text:
Q: d3.js - labeling ticks with linear x-axis i am plotting multiple line graphs. i am not using a .csv file, instead i have a two-dimensional array.
every line has an own array that contains its values. i have another array for the x-axis which contains the indices of the values from the value arrays.
right now i am using a liear x-axis and a linear y-axis.
my problem is that i can determine how many thicks the x-axis should have but not the labeling.
the labeling is always the index from the x-axis array on that position.
i want to have a different number there.
do i have to use an ordeal x-axis?
thank you!


text:
Q: How to find the Bayesian equivalent of of $\bar{X}-\bar{Y}$ Let $X_1, \dots, X_n$ i.i.d. from $N(\mu, \sigma^2)$; $Y_1, \dots, Y_m$ i.i.d. from $N(\eta, \tau^2)$. $X_1, \dots, X_n$ are independent of $Y_1, \dots, Y_m$. And $\tau^2$ and $\sigma^2$ are considered known.
I want to show that $\bar{X}-\bar{Y}$ is a minimax estimator for estimating $\Delta=\mu-\eta$ under the square loss.
I can show that the risk function of $\bar{X}-\bar{Y}$ is $R(\bar{X}-\bar{Y}, \mu-\eta)=\frac{\sigma^2}{n}+\frac{\tau^2}{m}$
If I can find the Bayes estimator $\delta_\Lambda$, so I can get the Bayes risk $r_\Lambda$. When the variance terms go to infinity if $r_\Lambda \rightarrow R(\bar{X}-\bar{Y}, \mu-\eta)$, then $\bar{X}-\bar{Y}$ is a minimax estimator by Theorem 1.12.
But I do not know how to derive the Bayes estimator $\delta_\Lambda$ for $\bar{X}-\bar{Y}$.
I know how to get it for $\underline{X}~N(\theta, \sigma^2)$, which is $$\delta_n=\frac{\frac{n}{\sigma^2}\bar{X}+\frac{\mu^*}{b^2}}{\frac{n}{\sigma^2}+\frac{1}{b^2}}$$ As prior distribution for $\theta$, the conjugate normal distribution $N(\mu^*, b^2)$.
So, the Bayes risk is $r_\Lambda = \frac{1}{\frac{n}{\sigma^2}+\frac{1}{b^2}}$. So, $r_\Lambda \overset{b\to\infty} \to \frac{\sigma^2}{n} = \underset{\theta}SUP R(\theta, \bar{X})$
Could anybody teach me how to get the Bayes risk for $\bar{X}-\bar{Y}$. Thanks!
{From Theory of Point Estimation, E.L. Lehmann p.343
Theorem 1.12: Suppose that $\{\Lambda_n\}$ is a sequence of prior distributions with Bayes risks rn satisfying $r_\Lambda \le r = \lim_{n\to\infty} r_{\Lambda_n}$, where $r_{\Lambda_n}=\int R(\theta, \delta_n)d\Lambda_n(\theta)$ is a Bayes risk under $\Lambda_n$, and that $\delta$ is an estimator for which $\underset{\theta}SUP R(\theta,\delta)=r$
Then
(i) $\delta$ is minimax and
(ii) the sequence $\{\Lambda_n\}$ is least favorable.}

A: It seems like you already know how to calculate the Bayes estimator for a single normal random variable. Now let $Z = \bar{X} - \bar{Y}$. By the property of the independent normal random variables, $Z \sim N\left(\mu - \eta, \frac{\sigma^2}{n} + \frac{\tau^2}{m}\right)$. Now simply work with $Z$ and apply the formula for the Bayes estimator of a normal normal conjugate family to this. (i.e put the $\theta = \mu- \eta$ and the proper $\sigma^2$ in the bayes estimator formula you have in the question)


text:
Q: Knockout.js example equivalent of holla Is there a more complicated example of knockout.js along the lines of Holla https://github.com/maccman/holla/commits/master/app ?
I would like to have a list/tree on a left pane that would populate a form on a right side pane.

A: Here's a skeleton for a master/details app. You can see it live on this jsfiddle. In the JSFiddle, I simplified the code a bit, but it's probably better to have a separate select function rather than using $parent.selectedItem directly. If you're doing other stuff as well, you'll want the var self = this; variable to use in functions where this may not be bound to the right object.

        Item list
        Details

Item:

Price:

and the javascript:
function Item(title, amnt) {
    var self = this;

    this.label = ko.observable(title);
    this.price = ko.observable(amnt);
}

var items = [ new Item('foo', 27.30), new Item('fruity foo', 30.12), new Item('foo bar', 12.34)];

function viewModel(list) {
    var self = this;

    this.items = ko.observableArray(list);

    this.selectedItem = ko.observable();

    // You could call $parent.selectedItem from the binding directly, but it's a bit of a hack
    this.select = function(item) {
        self.selectedItem(item);
    }
}

ko.applyBindings(new viewModel(items));


text:
Q: Catching Exceptions Inside Include/Eval/Require for PHP If I have an include.php file with the contents of;
<?php
    try {
        // something that causes an exception
    }
    catch (Exception $e) {
        // catch the exception and continue code
    }
    print "Something after Exception caught, but it doesn't print.";
?>

And the main PHP file is main.php with;
<?php
    include ('include.php');
?>

I get an uncaught exception error?
I've tried using eval() as well, but no matter what, I can't get the code to continue inside the included file.  It appears as tho you cannot catch an Exception inside include/eval and continue executing the code you have included.
I can wrap the include/eval in a Try Catch inside the main.php and allow the main.php to continue, but the rest of the php in include.php doesn't evaluate.
Is this not possible?  I have different scenarios of how I want the code to react on the included file.  For example, I'm using Selenuim WebDriver that always errors out with an Exception if the code files halting the script.  So I need to catch the Exceptions to logically continue.  Or is there a better way?

A: I found the problem, I guess since I had to use a namespace in the included content to get the WebDriver to function, I also needed to carry over my "use \Exception" in the included file. So as now Exception is being used. So the code executes as expected. I tested a basic example like I provided and that worked, so I looked at it as it had to be something in my code unique.


text:
Q: AttributeError: 'module' object has no attribute 'writer' I am trying to execute this following program to read csv file in sublime text2 gets error message "AttributeError: 'module' object has no attribute 'writer'"
Any Solution.
import sys
import csv
def readcsv():
  f = open("F://xyz.csv",'r')
  readerr=csv.reader(f)
  for row in readerr():
      print row
  f.close()
readcsv()

FULL ERROR MESSAGE

The current working directory is F:\ Traceback (most recent call
  last):  File "F:\readfiles.py", line 12, in     readcsv()
  File "F:\readfiles.py", line 7, in readcsv    readerr=csv.reader(f)
       AttributeError: 'module' object has no attribute 'reader'
       [Finished in 1.4s with exit code 1]

A: Debugging steps:-
Ideally csv should have reader module. My best guess is you have some other module named csv which is being imported. Can you try the following on python console:-'
>>>import csv
>>>dir(csv)

If you do not find the reader, writer etc. modules, chances are you are importing a wrong module with same name. Now try >>>csv.__file__, Rename this file and follow previous step once again.
In general your code could look pythonic the following way:-
with open('csvfile.csv', 'rb') as csvfile:
     rows = csv.reader(csvfile)
     for row in rows:
         print row

A: The syntax is slightly off.
for row in readerr():
The parenthesis is function syntax.
The command should only be acting on an object.
If you change that line to this, it will work
for row in reader:

A: you must have named the file as csv.py, renaming it would troubleshoot the error.

A: I had this same error and the reason was my file name was also called 'csv.py'
Try changing it to something else and try again. Should work !! :)


text:
Q: Custom meta box using OOP way doesn't save data This is the first time I'm building meta box using OOP way, the problem is when I save the post (product) or update it the input text is not saved to the database. Here is my code:
<?php

/**
*
*/
class Custom_Meta_Boxes{

    public function __construct(){

        add_action( 'add_meta_boxes', array( $this, 'iam_add_meta_box' ) );
        add_action( 'save_post', array( $this, 'iam_save_meta_box_data' ) );

    }

    /**
     * Adds a meta box to the post editing screen
     */
    public function iam_add_meta_box(){

        add_meta_box(
            'custom_meta_box',
            __( 'Meta Box Title', 'iamtheme' ),
            array( $this, 'iam_display_custom_meta_box' ),
            'post',
            'normal',
            'high'
        );

    }

    /**
     * Render Meta Box content.
     */
    public function iam_display_custom_meta_box() {

        $html = '';

        // Add an nonce field so we can check for it later.
        wp_nonce_field( 'iam_nonce_check', 'iam_nonce_check_value' );

        $html = '<label for="link-text" class="prfx-row-title">Link: </label>';
        $html .= '<input type="text" name="link-text" id="link-text" value="' . get_post_meta( get_the_ID(), 'link-text', true ) . '" placeholder="Enter your link here." />';

        echo $html;
    }

    /**
     * Save the meta when the post is saved.
     */
    public function iam_save_meta_box_data( $post_id ){

        var_dump( $post_id );

        if ( $this->iam_user_can_save( $post_id, 'iam_nonce_check_value' ) ){

            // Checks for input and sanitizes/saves if needed
            if( isset( $_POST[ 'link-text' ] ) && 0 < count( strlen( trim( $_POST['link-text'] ) ) ) ) {

                update_post_meta( $post_id, 'link-text', sanitize_text_field( $_POST[ 'link-text' ] ) );

            }

        }

    }

    /**
     * Determines whether or not the current user has the ability to save meta
     * data associated with this post.
     *
     * @param       int     $post_id    The ID of the post being save
     * @param       bool                Whether or not the user has the ability to save this post.
    */
    public function iam_user_can_save( $post_id, $nonce ){

        var_dump( $post_id );

        // Checks save status
        $is_autosave = wp_is_post_autosave( $post_id );
        $is_revision = wp_is_post_revision( $post_id );
        $is_valid_nonce = ( isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ], 'iam_nonce_check' ) ) ? 'true' : 'false';

        // Return true if the user is able to save; otherwise, false.
        if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
            return;
        }

    }

}

// Instantiate theme
if ( class_exists( 'Custom_Meta_Boxes' ) ){
    $i_am = new Custom_Meta_Boxes();
}

?>

Please could you tell me what is the problem in this code.

A: You method iam_user_can_save is incorrectly used as you are returning nothing to check in that method. Try this (not sure what behaviour you really want, the following code is just a working example from your code):
public function iam_user_can_save( $post_id, $nonce ){

    // Checks save status
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ], 'iam_nonce_check' ) ) ? 'true' : 'false';

    if ( $is_autosave || $is_revision || !$is_valid_nonce ) {

        return false;

    }

    return true;

}


text:
Q: Convert string to array or object is there possible to convert this string to array or object? It is not a valid stringify JSON data, not sure how to tackle this.
"{"subject":"Test Comment"},{"message":"Test Message."}"

Thank in advance!

A: Like this:
JSON.parse('[' + '{"subject":"Test Comment"},{"message":"Test Message."}' + ']')


text:
Q: Create nested object from 3 arrays I have a 3 sets of data:
let data1 = [ {key: value1}, {key: value2}, {key:value3} ]
let data2 = [ {key: value1}, {key: value2}, {key:value3}, {key: value4} ] //same structure, different values
let data3 = [ [1,1,1,1], [1,1,1,1], [1,1,1,1] ]

I would like the following data structure:
result = {
           data1[0][key] : {
              data2[0][key2] : data3[0][0],
              data2[0][key2] : data3[0][0],
              data2[0][key2] : data3[0][0]
         }

I would like to do something like this, but it's not working:
let result = {};
data1.map( (d, i) => {
     data3[i].map(
       (x,idx) => (
        result[d.key] = {
          data2[i]['key'] : x
         }
       )
      )
})

A: Oops, fixed:
let result = {};
data1.map((d, i) => {
  result[d.key] = {};
  data3[i].map((x, idx) => (result[d.key][data2[idx]["key"]] = x));
});


text:
Q: How to ask for user mail I can't find any example of apps asking for user email adress. I think of a UIAlertView with a textfield to fill... But I can't find this kind of thing.
Is there a guideline for this prupose ?
Is there a dedicated UI element that could help ?
If I could avoid having to create a whole view stacked in navigation controller it would be better
Thanks again for you help

A: Maybe presentModalViewController:animated: method of UIViewController class will be a better solution. It takes an arbitrary controller and shows its view. You can select an animation type and other options.
UIAlertView purpose is to show alerts, but not to handle user input. But it depends on the concrete task and a lot of other factors.


text:
Q: Sorting multidimentional array by its value and size I have this array. I have used usort and able to do alphabetical order but I need to sort based on sizing too. please see the below sample example and the expected output. any suggestion
[
   0 => ['b','a','n','a','n','a'],
   1 => ['a','n','a','n','a'],
   2 => ['n','a','n','a'],
   3 => ['a','n','a'],
   4 => ['n','a'],
   5 => ['a']
]

Need sorting like below:

[
   0 => ['a'],
   1 => ['a','n','a'],
   2 => ['a','n','a','n','a'],
   3 => ['b','a','n','a','n','a'],
   4 => ['n','a'],
   5 => ['n','a','n','a']
]

A: Sort them as strings
usort($arr, function($a,$b) { return strcmp(implode('', $a), implode('', $b)); });

demo


text:
Q: Microsoft Edge bug, empty href and base tag Microsoft's new browser Edge doesn't seem to accept empty hrefs like . In all other browsers, this can be used to link to the base tag. Though in Edge this doesn't seem to be the case.
I found a solution to this problem by setting the href to ./ in this question.
But having to change this on many sites is quite a hassle. Are there any other alternatives that do not require to change all the href's themselves?
Thanks in advance.

A: Use a utility function to rewrite the empty hrefs. For example:

function rewrite_empty_hrefs()
  {
  var dom_parser = new DOMParser();

  var xml_serializer = new XMLSerializer();

  var old_html_dom = dom_parser.parseFromString(document.body.innerHTML,"text/html");

  var base_href = old_html_dom.querySelector("base").href;

  var old_xhtml_string = xml_serializer.serializeToString(old_html_dom);

  var new_xhtml_string = old_xhtml_string.replace(/(href=")(")/g, "$1"+base_href+"$2");

  document.body.innerHTML = new_xhtml_string;
  }

rewrite_empty_hrefs();
<base href="http://www.example.com">
example.com
example.org
example.net

References

*

*DOMParser and XMLSerializer in IE9 Beta – IEBlog


text:
Q: Getting values from a Pyqt5 chart Trying to pull values from a pyqt5 chart when hovering the mouse over a position.
The Series is a Candlestick series with values Adj_Open, Adj_High, Adj_Low, Adj_Close.
def call_sym_data(self):
    self.chartlayout.removeWidget(self.chartviewer)
    sym = self.sym_input.text()
    sym_raw = quandl.get("EOD/"+sym, start_date = sdate, end_date = edate)
    self.symlabel.setText(self.sym_input.text())
    can_data = pd.DataFrame( columns = ['Adj_Open','Adj_High','Adj_Low','Adj_Close'])
    can_data['Adj_Open'] = sym_raw['Adj_Open']
    can_data['Adj_High'] = sym_raw['Adj_High']
    can_data['Adj_Low'] = sym_raw['Adj_Low']
    can_data['Adj_Close'] = sym_raw['Adj_Close']

    print(can_data)
    sym_date = sym_raw.index

    series = QCandlestickSeries()
    series.setDecreasingColor(Qt.red)
    series.setIncreasingColor(Qt.green)

    for  index, row in can_data.iterrows():
        series.append(QCandlestickSet(row['Adj_Open'], row['Adj_High'], row['Adj_Low'], row['Adj_Close']))

    self.sym_chart = QChart()

    self.sym_chart.addSeries(series)

    self.sym_chart.setAnimationOptions(QChart.SeriesAnimations)
    self.sym_chart.createDefaultAxes()
    self.sym_chart.legend().hide()

    self.sym_chart.axisX(series).setCategories(sym_date.strftime("%Y-%m-%d"))

    self.chartviewer = QChartView(self.sym_chart)
    self.chartlayout.addWidget(self.chartviewer)

The objective is to hover the mouse over the specific bar and have it change the label of Open, High, Low, and Close on the output in the picture.  The labels are bar_open, bar_high, bar_low, and bar_close.
Symbol Chart

I can't figure out how to get hovered to work and show each value, and mapToPosition doesn't seem to help.

A: There is a QCandlestickSeries signal available - hovered. This returns the underlying QCandlestickSet upon emission due to hovering over the corresponding Candlestick Set.
A slot can be added and connected to this signal. In the slot, the data from the QCandlestickSet can be extracted and used to update the labels.
Though there is one problem - the addition of pyqtSlot decorator for the slot.
It errors out with following signal
QObject::connect: Incompatible sender/receiver arguments  QtCharts::QCandlestickSeries::doubleClicked(QCandlestickSet*)


text:
Q: Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing? The indexer into Dictionary throws an exception if the key is missing.  Is there an implementation of IDictionary that instead will return default(T)?
I know about the TryGetValue() method, but that's impossible to use with LINQ.
Would this efficiently do what I need?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);

I don't think it will as I think it will iterate the keys instead of using a Hash lookup.

A: Collections.Specialized.StringDictionary provides a non-exception result when looking up a missing key's value. It is also case-insensitive by default.
Caveats
It is only valid for its specialized uses, and — being designed before generics — it doesn't have a very good enumerator if you need to review the whole collection.

A: If you're using .Net Core, you can use the CollectionExtensions.GetValueOrDefault method. This is the same as the implementation provided in the accepted answer.
public static TValue GetValueOrDefault<TKey,TValue> (
   this System.Collections.Generic.IReadOnlyDictionary<TKey,TValue> dictionary,
   TKey key);

A: If you're using .NET Core 2 or above (C# 7.x), the CollectionExtensions class is introduced and you can use the GetValueOrDefault method to get default value if key is not there in a dictionary.
Dictionary<string, string> colorData = new Dictionary<string, string>();
string color = colorData.GetValueOrDefault("colorId", string.Empty);

A: public class DefaultIndexerDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    private IDictionary<TKey, TValue> _dict = new Dictionary<TKey, TValue>();

    public TValue this[TKey key]
    {
        get
        {
            TValue val;
            if (!TryGetValue(key, out val))
                return default(TValue);
            return val;
        }

        set { _dict[key] = value; }
    }

    public ICollection<TKey> Keys => _dict.Keys;

    public ICollection<TValue> Values => _dict.Values;

    public int Count => _dict.Count;

    public bool IsReadOnly => _dict.IsReadOnly;

    public void Add(TKey key, TValue value)
    {
        _dict.Add(key, value);
    }

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        _dict.Add(item);
    }

    public void Clear()
    {
        _dict.Clear();
    }

    public bool Contains(KeyValuePair<TKey, TValue> item)
    {
        return _dict.Contains(item);
    }

    public bool ContainsKey(TKey key)
    {
        return _dict.ContainsKey(key);
    }

    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        _dict.CopyTo(array, arrayIndex);
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return _dict.GetEnumerator();
    }

    public bool Remove(TKey key)
    {
        return _dict.Remove(key);
    }

    public bool Remove(KeyValuePair<TKey, TValue> item)
    {
        return _dict.Remove(item);
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        return _dict.TryGetValue(key, out value);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _dict.GetEnumerator();
    }
}

A: Carrying these extension methods can help..
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key)
{
    return dict.GetValueOrDefault(key, default(V));
}

public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key, V defVal)
{
    return dict.GetValueOrDefault(key, () => defVal);
}

public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key, Func<V> defValSelector)
{
    V value;
    return dict.TryGetValue(key, out value) ? value : defValSelector();
}

A: Indeed, that won't be efficient at all.
As per comments, in .Net Core 2+ / NetStandard 2.1+ / Net 5, MS added the extension method GetValueOrDefault()
For earlier versions you can write the extension method yourself:
public static TValue GetValueOrDefault<TKey,TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key)
{
    TValue ret;
    // Ignore return value
    dictionary.TryGetValue(key, out ret);
    return ret;
}

Or with C# 7.1:
public static TValue GetValueOrDefault<TKey,TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key) =>
    dictionary.TryGetValue(key, out var ret) ? ret : default;

That uses:

*

*An expression-bodied method (C# 6)

*An out variable (C# 7.0)

*A default literal (C# 7.1)

A: One could define an interface for the key-lookup function of a dictionary.  I'd probably define it as something like:
Interface IKeyLookup(Of Out TValue)
  Function Contains(Key As Object)
  Function GetValueIfExists(Key As Object) As TValue
  Function GetValueIfExists(Key As Object, ByRef Succeeded As Boolean) As TValue
End Interface

Interface IKeyLookup(Of In TKey, Out TValue)
  Inherits IKeyLookup(Of Out TValue)
  Function Contains(Key As TKey)
  Function GetValue(Key As TKey) As TValue
  Function GetValueIfExists(Key As TKey) As TValue
  Function GetValueIfExists(Key As TKey, ByRef Succeeded As Boolean) As TValue
End Interface

The version with non-generic keys would allow code that was using code using non-structure key types to allow for arbitrary key variance, which would not be possible with a generic type parameter.  One should not be allowed to use a mutable Dictionary(Of Cat, String) as a mutable Dictionary(Of Animal, String) since the latter would allow SomeDictionaryOfCat.Add(FionaTheFish, "Fiona"). But there's nothing wrong with using a mutable Dictionary(Of Cat, String) as an immutable Dictionary(Of Animal, String), since SomeDictionaryOfCat.Contains(FionaTheFish) should be considered a perfectly well-formed expression (it should return false, without having to search the dictionary, for anything that isn't of type Cat).
Unfortunately, the only way one will be able to actually use such an interface is if one wraps a Dictionary object in a class which implements the interface.  Depending upon what you're doing, however, such an interface and the variance it allows might make it worth the effort.

A: If you are using ASP.NET MVC, you could leverage the RouteValueDictionary class that do the job.
public object this[string key]
{
  get
  {
    object obj;
    this.TryGetValue(key, out obj);
    return obj;
  }
  set
  {
    this._dictionary[key] = value;
  }
}

A: I used encapsulation to create an IDictionary with behavior very similar to an STL map, for those of you who are familiar with c++. For those who aren't:

*

*indexer get {} in SafeDictionary below returns the default value if a key is not present, and adds that key to the dictionary with a default value. This is often the desired behavior, as you're looking up items that will appear eventually or have a good chance of appearing.

*method Add(TK key, TV val) behaves as an AddOrUpdate method, replacing the value present if it exists instead of throwing. I don't see why m$ doesn't have an AddOrUpdate method and thinks throwing errors in very common scenarios is a good idea.

TL/DR - SafeDictionary is written so as to never throw exceptions under any circumstances, other than perverse scenarios, such as the computer being out of memory (or on fire). It does this by replacing Add with AddOrUpdate behavior and returning default instead of throwing NotFoundException from the indexer.
Here's the code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class SafeDictionary<TK, TD>: IDictionary<TK, TD> {
    Dictionary<TK, TD> _underlying = new Dictionary<TK, TD>();
    public ICollection<TK> Keys => _underlying.Keys;
    public ICollection<TD> Values => _underlying.Values;
    public int Count => _underlying.Count;
    public bool IsReadOnly => false;

    public TD this[TK index] {
        get {
            TD data;
            if (_underlying.TryGetValue(index, out data)) {
                return data;
            }
            _underlying[index] = default(TD);
            return default(TD);
        }
        set {
            _underlying[index] = value;
        }
    }

    public void CopyTo(KeyValuePair<TK, TD>[] array, int arrayIndex) {
        Array.Copy(_underlying.ToArray(), 0, array, arrayIndex,
            Math.Min(array.Length - arrayIndex, _underlying.Count));
    }

    public void Add(TK key, TD value) {
        _underlying[key] = value;
    }

    public void Add(KeyValuePair<TK, TD> item) {
        _underlying[item.Key] = item.Value;
    }

    public void Clear() {
        _underlying.Clear();
    }

    public bool Contains(KeyValuePair<TK, TD> item) {
        return _underlying.Contains(item);
    }

    public bool ContainsKey(TK key) {
        return _underlying.ContainsKey(key);
    }

    public IEnumerator<KeyValuePair<TK, TD>> GetEnumerator() {
        return _underlying.GetEnumerator();
    }

    public bool Remove(TK key) {
        return _underlying.Remove(key);
    }

    public bool Remove(KeyValuePair<TK, TD> item) {
        return _underlying.Remove(item.Key);
    }

    public bool TryGetValue(TK key, out TD value) {
        return _underlying.TryGetValue(key, out value);
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return _underlying.GetEnumerator();
    }
}

A: It could be a one-liner to check TryGetValue and return default value if it is false.
 Dictionary<string, int> myDic = new Dictionary<string, int>() { { "One", 1 }, { "Four", 4} };
 string myKey = "One"
 int value = myDic.TryGetValue(myKey, out value) ? value : 100;

myKey = "One" => value = 1
myKey = "two" => value = 100
myKey = "Four" => value = 4
Try it online

A: Since .NET core 2.0 you can use:
myDict.GetValueOrDefault(someKeyKalue)

A: What about this one-liner that checks whether a key is present using ContainsKey and then returns either the normally retreived value or the default value using the conditional operator?
var myValue = myDictionary.ContainsKey(myKey) ? myDictionary[myKey] : myDefaultValue;

No need to implement a new Dictionary class that supports default values, simply replace your lookup statements with the short line above.

A: Here is a version of @JonSkeet's for the world of C# 7.1 that also allows for an optional default to be passed in:
public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default) => dict.TryGetValue(key, out TV value) ? value : defaultValue;

It may be more efficient to have two functions to optimize the case where you want to return default(TV):
public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
public static TV GetValueOrDefault2<TK, TV>(this IDictionary<TK, TV> dict, TK key) {
    dict.TryGetValue(key, out TV value);
    return value;
}

Unfortunately C# doesn't (yet?) have a comma operator (or the C# 6 proposed semicolon operator) so you have to have an actual function body (gasp!) for one of the overloads.

A: This question helped to confirm that the TryGetValue plays the FirstOrDefault role here.
One interesting C# 7 feature I would like to mention is the out variables feature, and if you add the null-conditional operator from C# 6 to the equation your code could be much more simple with no need of extra extension methods.
var dic = new Dictionary<string, MyClass>();
dic.TryGetValue("Test", out var item);
item?.DoSomething();

The downside of this is that you can't do everything inline like this;
dic.TryGetValue("Test", out var item)?.DoSomething();

If we'd need/want to do this we should code one extension method like Jon's.

A: Modern Answer
As of .NET Core 2.0, there is a built-in extension method with 2 overloads:
TValue GetValueOrDefault<TKey,TValue>(TKey)
TValue GetValueOrDefault<TKey,TValue>(TKey, TValue)

Usage:
var dict = new Dictionary<string, int>();

dict.GetValueOrDefault("foo");     // 0: the datatype's default
dict.GetValueOrDefault("foo", 2);  // 2: the specified default

The first version returns null for nullable types, of course.
See the documentation for more detail.

A: No, because otherwise how would you know the difference when the key exists but stored a null value?  That could be significant.

A: In general I would support the answer from Jon Skeet, however I prefer an implementation where I can give the default value as parameter:
public static TValue GetValueOrDefault<TKey, TValue> (this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
    if (dictionary.ContainsKey(key))
        return dictionary[key];
    else
        return defaultValue;
}


text:
Q: How to assign specific colors to specific cell values in a raster file? I have a raster file with values ranging from 1 to 64, I want to assign specific colors to specific values, for example, I want that cells equal to 1 be painted as rgb 96,0,232, cells equal to 2 as 141,0,255, and so on.
Thank you very much for your help.

A: Seems like something like below, see https://www.rdocumentation.org/packages/raster/versions/2.5-8/topics/colortable
# raster
r <- raster(matrix(sample(1:2, size=16, replace=T),nrow=4))
# color
col <- matrix(c(96,0,232, 141,0,255),ncol=3)
col <- apply(col,1, function(x) paste('#', paste( as.hexmode(x), collapse=''), sep='')
# colortable
colortable(r) <- col


text:
Q: Form submit variables are lost when dealing with jquery variables in PHP I have a starting page, where the user gives some information (Email and Name) and press submit. When the second page is entered, jquery sends some variables (dateStr) to that second page from within that second page. However, I notice that doing so makes the form submit variables disappear. I have shown the relevant part of the code here. YourEMail and YourName turn out to be empty strings here. What mistake am I doing?
<?php
$YourEMail = $_REQUEST['YourEMail'];
$InputName = $_REQUEST['YourName'];

$dateAndTime = '';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
    $dateAndTime = $_POST["dateStr"];
    // $dateAndTime is fine, but $YourEMail and $InputName are empty here!
    ......
}
?>

The jquery code to post $dateStr from within the second page is shown below.

A: I just changed your Jquery code a bit. Try it:-

A: OK, I solved the problem. For anybody interested, here is the solution. I would like to thank ADyson for his advice on session variables.
<?php
// Start the session
session_start();
?>
....
<?php
if (isset($_POST['submit']))
{
    $YourEMail = $_REQUEST['YourEMail'];
    $InputName = $_REQUEST['YourName'];

    $_SESSION["email"]  = $YourEMail;
    $_SESSION["name"]   = $InputName;
}

$dateAndTime = '';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
    $YourEMail = $_SESSION['email'];
    $InpuName  = $_SESSION['name'];
    $dateAndTime = $_POST["dateStr"];
    ......
}
?>


text:
Q: MongoDB $lookup to replace only the ID in an array of objects I have the following example JSON-object saved in my mongodb-collection named "Profile"
{
   name: "Test",
   relations: [
      {
          personid: <MongoDB-ID>,
          type: "Friend",
          duration: 5
      },
      {
          personid: <MongoDB-ID>,
          type: "Family",
          duration: 9
      },
   ]
}

I've used the mongoose-Aggregate function because i need to add artificial fields based on caluclation in the documents saved. At the end of my aggregation i use the $lookup-function to replace the property "personID" in the objects inside of the "relations"-array.
{
   $lookup:
     {
       from: PersonModel.collection.name,
       localField: 'relations.personid',
       foreignField: '_id',
       as: "relations.personid"
     }
}

Because i want each "person" in the array of objects to replaced within the populated from the specific person-document.
This does not work as expected.
I also tried to call ".populate()" on the result returned by the aggregate function which also not worked.

A: Setting localField to relations.personid is not supported. localField either needs to point to an array where each member is used for the join or be a plain value. The usual way of getting around this is to $unwind first, perform the lookup, and then $group back if needed.


text:
Q: Composite and Terms Aggregations on a field with a high cardinality I am facing a huge performance problem with ES which results in more than 2 min response.
I have an index that has more than 25M files and composes of the next 4 fields (among others):
...

       "group_write": {
            "type": "text",
            "fields": {
                "raw": {
                    "type": "keyword"
                }
            }
        },
        "user_write": {
            "type": "text",
            "fields": {
                "raw": {
                    "type": "keyword"
                }
            }
        },
        "group_read": {
            "type": "text",
            "fields": {
                "raw": {
                    "type": "keyword"
                }
            }
        },
        "user_read": {
            "type": "text",
            "fields": {
                "raw": {
                    "type": "keyword"
                }
            }
        }
    }

...

I have something like 100K unique users and groups and each field is a list of users/groups that holds ~100 values. For example:
"user_read": ["user_1", "group_1", ...],
"user_write": ["user_1", "group_2", ...]
...

I have 2 kinds of aggregation I am using, composite and terms. Composite aggregations for getting only first X results to display and terms aggregation for prefix search.
Composite aggregation:
{
    "size": 0,
    "aggs": {
        "Group_Read_Permissions": {
            "composite": {
                "sources": [
                    {
                        "Group Read": {
                            "terms": {
                                "field": "group_read.raw"
                            }
                        }
                    }
                ],
                "size": 10
            }
        },
        "Group_Write_Permissions": {
            "composite": {
                "sources": [
                    {
                        "Group Write": {
                            "terms": {
                                "field": "group_write.raw"
                            }
                        }
                    }
                ]
            }
        },
        "User_Write_Permissions": {
            "composite": {
                "sources": [
                    {
                        "User Write": {
                            "terms": {
                                "field": "user_write.raw"
                            }
                        }
                    }
                ]
            }
        },
        "User_Read_Permissions": {
            "composite": {
                "sources": [
                    {
                        "User Read": {
                            "terms": {
                                "field": "user_read.raw"
                            }
                        }
                    }
                ]
            }
        }
    }
}

Terms aggregation:
{
    "size": 0,
    "aggs": {
        "Group_Read_Permissions": {
            "terms": {
                "field": "group_read.raw",
                "include": ".*[Ss].*"
            }
        },
        "Group Write Permissions": {
            "terms": {
                "field": "group_write.raw",
                "include": ".*[Ss].*"
            }
        },
        "User Read Permissions": {
            "terms": {
                "field": "user_read.raw",
                "include": ".*[Ss].*"
            }
        },
        "User Write Permissions": {
            "terms": {
                "field": "user_write.raw",
                "include": ".*[Ss].*"
            }
        }
    }
}

Composite aggregation returns results within 1 min and the terms aggregation can take up to 5 min.
What I have tried so far:

*

*Adding new field user_group_permissions and adding to the above 4 fields "copy_to": "user_group_permissions"

*Adding to the above 4 fields and to the field "user_group_permissions" the next property: "eager_global_ordinals": true

*Increased the refresh_interval up to 200s

** I reindexed for the first 2 suggestions [took something like 6 hours]
All of the above did help a little with the retrieval time but still: composite aggregation takes up to 20s and terms aggregation takes up to 3 min.
[The best results were on the fields user_group_permissions which has been created in the first suggestion, with eager_global_ordinals = true and refresh_interval = 120s].
Please, if someone has any idea how to improve the retrieval times I will be grateful.

A: First of all, if you only need the first 10 results, you don't need to use the composite aggregation, which is meant to be used only if you need to paginate over all results. Simply use the terms aggregation with default size 10, that'll do the job.
Second, what you're doing with the terms aggregation is not a prefix filtering, but infix filtering, which is completely different in terms of performance. While it's easy to search for prefixes, searching for infixes requires the equivalent of a "full table scan" because each and every term must be visited.
A first optimization I would suggest is that in your second query you should do your regex in the query part (bool/should with one regex query per field), so as to reduce the document set on which the terms aggregations need to run. That might help a bit.
A second optimization is to leverage the wildcard field type which is a specialized field type made specially for grep-like wildcard and regexp queries.
Another possible optimization is to lowercase all your permissions, so that you only need to search for .*s.* instead of the uppercase variant.
Depending on your comments, I'll add more optimizations as the discussion goes on.


text:
Q: QT ODBC driver .mdb ms-access inserts not working above 1000 rows (windows) I have tested many times my code on Windows.
(I need to use ms-access to upgrade an old app)
Trying to insert rows in a query using transaction or not, bindvalues or not, inserts doesn't go beyond 1061 rows.
I have tested with this code:
this->db_ = QSqlDatabase::addDatabase("QODBC");

QString archivo_elegido = QString(ruta_inicial_ + "cods.mdb");

cout << "archivo: " << archivo_elegido.toStdString() << endl;

this->db_.setDatabaseName(QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=%1;").arg(QDir::toNativeSeparators(archivo_elegido)));

if(!this->db_.open("",""))
{
cout << this->db_.lastError().text().toStdString() << endl;
}

int i = 0;
this->query = QSqlQuery(this->db_);

for(i=0; i< 20000;i++)
{
QString q;
q.append("INSERT INTO claves ");
q.append("(claveacceso) " );
q.append( "VALUES (:claveacceso) ");
this->query.prepare(q);
this->query.bindValue(":claveacceso", QString::number(i));
this->query.exec(); // No errors here.
cout << endl << " " << i;
}

this->db_.close();

A: QString q;
q.append("INSERT INTO claves ");
q.append("(claveacceso) " );
q.append( "VALUES (?) ");
this->query.prepare(q);
QVariantList varLst;
for(i=0; i< 20000;i++)
{
  varLst << QVariant::fromValue(i);
}
this->query.addBindValue(varLst);
this->query.execBatch();

A: I had an error.
I was testing, with GNOME MDB Viewer 0.7.1, based on http://mdbtools.sourceforge.net/.
The mdb viewer was showing me only the fist 1000 rows, even when I apply a query.


text:
Q: Load page in customizer preview on panel click? I'm trying to extend customizer with some functionality but documentation is lacking for cases that are non-control related.
E.g. I'd like to load some url in preview after clicking the panel.
My two issues are:

*

*I can't attach events to panels and fields because regular click and change don't work because panels seem to be loaded not immediately.

*How would one then send a custom message to preview section?

A: I've documented how to do this in my post Navigating to a URL in the Customizer Preview when a Section is Expanded, though naturally you'd just use panels instead of sections.
This should get you what you want:
(function ( api ) {
    api.panel( 'my_panel_id', function( panel ) {
        panel.expanded.bind( function( isExpanded ) {
            if ( isExpanded ) {
                api.previewer.previewUrl.set( panelPreviewUrl );
            }
        } );
    } );
} ( wp.customize ) );

You'd replace the panelPreviewUrl variable with whatever you want to navigate the preview to. And then you'd replace 'my_panel_id' with whatever the ID is for your panel.


text:
Q: Force Proximity Search into multiple word wordform? I use Proximity to good use with Sphinx e.g. Twain NEAR/1 Mark will return
Mark Twain
and
Twain, Mark
But say I had a word form like:
Weekday > Week Day
How could I set any given search to use Proximity NEAR/3 (or NEAR/X) so it would find
Week Day
and
Day of Week
I get in this case there are other ways to skin the cat but in general, looking for a way that the multiple word map doe not get pushed as 'Word1 Word2' i.e. 'Week Day' because otherwise I get docs such as
'I worked for one entire day before realizing it was going to take a
full week'

A: There's no easy way out of the box. You can perhaps make a change in your app so it does changes each 'word' to "word"~N in your search query or even better do that only for the same wordforms that Sphinx deals with. Here's an example:
mysql> select *, weight() from idx_min where match('weekday');
+------+-------------------------------------------------------------------------------+------+----------+
| id   | doc                                                                           | a    | weight() |
+------+-------------------------------------------------------------------------------+------+----------+
|    1 | Weekday                                                                       |    1 |     2319 |
|    2 | day of week                                                                   |    2 |     1319 |
|    3 | I worked for one entire day before realizing it was going to take a full week |    3 |     1319 |
+------+-------------------------------------------------------------------------------+------+----------+
3 rows in set (0.00 sec)

mysql> select *, weight() from idx_min where match('"weekday"');
+------+---------+------+----------+
| id   | doc     | a    | weight() |
+------+---------+------+----------+
|    1 | Weekday |    1 |     2319 |
+------+---------+------+----------+
1 row in set (0.00 sec)

mysql> select *, weight() from idx_min where match('"weekday"~2');
+------+-------------+------+----------+
| id   | doc         | a    | weight() |
+------+-------------+------+----------+
|    1 | Weekday     |    1 |     2319 |
|    2 | day of week |    2 |     1319 |
+------+-------------+------+----------+
2 rows in set (0.00 sec)

mysql> select *, weight() from idx_min where match('"entire"~2 "day"~2');
+------+-------------------------------------------------------------------------------+------+----------+
| id   | doc                                                                           | a    | weight() |
+------+-------------------------------------------------------------------------------+------+----------+
|    3 | I worked for one entire day before realizing it was going to take a full week |    3 |     1500 |
+------+-------------------------------------------------------------------------------+------+----------+
1 row in set (0.00 sec)

mysql> select *, weight() from idx_min where match('weekday full week');
+------+-------------------------------------------------------------------------------+------+----------+
| id   | doc                                                                           | a    | weight() |
+------+-------------------------------------------------------------------------------+------+----------+
|    3 | I worked for one entire day before realizing it was going to take a full week |    3 |     2439 |
+------+-------------------------------------------------------------------------------+------+----------+
1 row in set (0.01 sec)

mysql> select *, weight() from idx_min where match('"weekday"~2 full week');
Empty set (0.00 sec)

The last one would be the best way to go, but you would have to:
1) parse your query. E.g. like this:
mysql> call keywords('weekday full week', 'idx_min');
+------+-----------+------------+
| qpos | tokenized | normalized |
+------+-----------+------------+
| 1    | weekday   | week       |
| 2    | weekday   | day        |
| 3    | full      | full       |
| 4    | week      | week       |
+------+-----------+------------+
4 rows in set (0.00 sec)

and if you see that for the same tokenized word you get 2 different normalized words that can be a signal for your app to wrap the tokenized word into "word"~N.
2) run the query. In this case "weekday"~2 full week


text:
Q: i want to transmit data by byte unit and i think it's metter about endianness i want to transmit data by bit unit so i was access data with char* variable. here is my code.
int main()
{
    //initiate int variable and casting with char*
    int a = 65;
    cout << a << endl;
    char* p = reinterpret_cast<char*>(&a);
    cout << "------------------" << endl;

    //check char* p is pointing &a
    cout << &a << endl;
    printf("0x%x\n", p);
    cout << "------------------" << endl;

    //access int variable with byte unit
    cout << (int)*(p + 0) << endl;
    cout << (int)*(p + 1) << endl;
    cout << (int)*(p + 2) << endl;
    cout << (int)*(p + 3) << endl;
    cout << "------------------" << endl;

    //initiate int variable and assemble with char* access in way 1
    int* b = new int(0);
    *b = *(p + 0) << 24;
    *b += *(p + 1) << 16;
    *b += *(p + 2) << 8;
    *b += *(p + 3);

    cout << *b << endl;
    cout << "------------------" << endl;

    //initiate int variable and assemble with char* access in way 2
    *b = *(p + 0);
    *b += *(p + 1) << 8;
    *b += *(p + 2) << 16;
    *b += *(p + 3) << 24;

    cout << *b << endl;

    return 0;
}

and output like this.
65         -> variable a is 65
------------------
0x61ff04
0x61ff04   -> char* p is pointing right
------------------
65
0
0
0          -> access with byte unit
------------------
1090519040 -> way 1
------------------
65         -> way 2

when i access data by byte unit that first address pointing data shows '65' so i think this system is big endian.
so i thought if i want to transmit 'a' data to variable 'b', then *(p+0) data should be go to first like way 1, but the result isn't right. *(p+0) go at last - way 2, show right value.
in easy way to think, i think i was transmit data in direct memory point to point like this
variable a    =>    variable b
[0x000000]    =>    [0x100000]
[0x000001]    =>    [0x100001]
[0x000002]    =>    [0x100002]
    ...       =>       ...

i don't know why this happen. is anyone can explain about this?
============================================================================
problem was solved. the system was not big endian. i was mistake it.

A:
when i access data by byte unit that first address pointing data shows '65' so i think this system is big endian.

No, it means it is little endian. The least significant byte is in the lowest address and has the value 65.
With respect to 'transmitting' data between pointers of the same type by copying plain-old-data byte by byte, unless you are going between systems then endianness doesn't matter. It only matters in the interpretation, and ( *(p + 0) << 24 ) | ( *(p + 1) << 16 ) | ( *(p + 2) << 8 ) | *(p + 3) is the big endian interpretation, so gives you the wrong result. You already know that *p is 65*p is 65, so even if you forget which way big or little means, *(p + 0) << 24 will be wrong.
If you do want to transmit between systems byte-by-byte, there are the posix functions hton*X*() and ntoh*X*() which convert different integral types from host to network or from network to host byte order.


text:
Q: how can I use the formtastic with out wrapper_html? or change it. I using it has a <li> tag wrapper the <input> tag always.I don't want it..

A: In my opinion, using Formtastic only makes sense if you're happy with the code it generates.
Otherwise use other form builders, or the built-in helpers, or fix your CSS to fit Formtastic code.