text:
Q: Additional custom dimensions for products in Woocommerce I have a products with the following size parameters:

*

*Length (Woocomerce standard)

*Width (Woocomerce standard)

*Height (Woocomerce standard)

*Diameter

*Thickness

*Circuit
In the product edit page I have only Length, Width, Height (Woocomerce standard)
I would like to add my other sizes parameters
How can I add this extra sizes properly?
Is there any filter for this?

A: There is multiple ways…
1) Using Product attributes: (without any coding need):

*

*You should create 3 new product attributes (one for each other missing dimension).

*You should set each of them in each product with the correct options (displayed on products option) and values.

Advantage: Those other dimention attributes will be displayed on product pages.
Disadvantages:

*

*Each attribute Needs to be set for each product and each value is going to be a term of this product attribute.

*There are no specific existing WC_Product methods to get those custom product attributes like the default dimension ones. So is going to be more complicated to get them outside the product page.

2) Using custom setting fields:
// Add custom fields to product shipping tab
add_action( 'woocommerce_product_options_dimensions', 'add_product_options_other_dimensions');
function add_product_options_other_dimensions(){
    global $product_object;

    $product_id = method_exists( $product_object, 'get_id' ) ? $product_object->get_id() : $product_object->id;

    echo '

'; // New option group

    woocommerce_wp_text_input( array(
        'id'          => '_diameter',
        'label'       => __( 'Diameter', 'woocommerce' ),
        'desc_tip'    => 'true',
        'description' => __( 'Diameter description help.', 'woocommerce' )
    ) );

    woocommerce_wp_text_input( array(
        'id'          => '_thickness',
        'label'       => __( 'Thickness', 'woocommerce' ),
        'desc_tip'    => 'true',
        'description' => __( 'Thickness description help.', 'woocommerce' )
    ) );

    woocommerce_wp_text_input( array(
        'id'          => '_circuit',
        'label'       => __( 'Circuit', 'woocommerce' ),
        'desc_tip'    => 'true',
        'description' => __( 'Circuit description help.', 'woocommerce' )
    ) );

}

// Save the custom fields values as meta data
add_action( 'woocommerce_process_product_meta', 'save_product_options_other_dimensions' );
function save_product_options_other_dimensions( $post_id ){

    if( isset( $_POST['_diameter'] ) )
        update_post_meta( $post_id, '_diameter', esc_attr( $_POST['_diameter'] ) );

    if( isset( $_POST['_thickness'] ) )
        update_post_meta( $post_id, '_thickness', esc_attr( $_POST['_thickness'] ) );

    if( isset( $_POST['_circuit'] ) )
        update_post_meta( $post_id, '_circuit', esc_attr( $_POST['_circuit'] ) );

}

// Add custom fields to product variation settings
add_action( 'woocommerce_product_after_variable_attributes','add_variation_options_other_dimensions', 10, 3 );
function add_variation_options_other_dimensions( $loop, $variation_data, $variation ){

    $variation_diameter = get_post_meta($variation->ID,"_diameter", true );
    if( ! $variation_diameter ) $variation_diameter = "";

    $variation_thickness = get_post_meta($variation->ID,"_thickness", true );
    if( ! $variation_thickness ) $variation_thickness = "";

    $variation_circuit = get_post_meta($variation->ID,"_circuit", true );
    if( ! $variation_circuit ) $variation_circuit = "";

    echo '
';

    woocommerce_wp_text_input( array(
        'id'          => '_diameter' . '_' . $loop,
        'label'       => __( 'Diameter', 'woocommerce' ),
        'desc_tip'    => 'true',
        'description' => __( 'Diameter description help.', 'woocommerce' ),
        'value'       => $variation_diameter
    ) );

    woocommerce_wp_text_input( array(
        'id'          => '_thickness' . '_' . $loop,
        'label'       => __( 'Thickness', 'woocommerce' ),
        'desc_tip'    => 'true',
        'description' => __( 'Thickness description help.', 'woocommerce' ),
        'value'       => $variation_thickness
    ) );

    woocommerce_wp_text_input( array(
        'id'          => '_circuit' . '_' . $loop,
        'label'       => __( 'Circuit', 'woocommerce' ),
        'desc_tip'    => 'true',
        'description' => __( 'Circuit description help.', 'woocommerce' ),
        'value'       => $variation_circuit
    ) );

    echo '
';
}

// Save product variation custom fields values
add_action( 'woocommerce_save_product_variation','save_variation_options_other_dimensions', 10 ,2 );
function save_variation_options_other_dimensions( $variation_id, $loop ){

    $built_lenght = $_POST["_diameter_$loop"];
    if( isset($built_lenght) )
        update_post_meta( $variation_id, '_built_lenght', esc_attr($built_lenght) );

    $built_width = $_POST["_thickness_$loop"];
    if( isset($built_width) )
        update_post_meta( $variation_id, '_built_width', esc_attr($built_width) );

    $built_height = $_POST["_circuit_$loop"];
    if( isset($built_height) )
        update_post_meta( $variation_id, '_built_height', esc_attr($built_height) );
}

This code goes on function.php file of your active child theme (or theme).
You will get that for products:

And that for product variations (in variable products "variations settings):

Now to display and get those values, you will have to override the woocommerce template via your theme as explained in this documentation.
The file to copy and override via your theme is: single-product/product-attributes.php template.
You will have to add some code to it to display your custom additional dimension labels and values just after the displayed default dimentions.
To output the correct values you will use get_post_meta() function.
For example to display the diameter value you will use:
<?php echo get_post_meta( $product->get_id(), '_diameter', true ); ?>

A: You can use custom_fields or product attributes for this.


text:
Q: Show existence of limit Let $f:\mathbb{R}\rightarrow \mathbb{R}$ be a continuous periodical function with period $T>0$.
Show that:
$$\lim_{a\rightarrow\infty}\int_0^Tf(ax)dx$$
exists and calculate this limit.

A: Substituting $u = ax$, we obtain (for $a > 0$)
$$\int_0^T f(ax)\,dx = \frac{1}{a} \int_0^{aT} f(u)\,du.\tag{1}$$
If $a$ is an integer, then, since
$$\int_{kT}^{(k+1)T} f(u)\,du = \int_0^T f(x)\,dx$$
by the periodicity, $(1)$ becomes
$$\int_0^T f(ax)\,dx = \int_0^T f(x)\,dx.$$
So if the limit
$$\lim_{a\to\infty} \int_0^T f(ax)\,dx$$
exists at all, it must be $\int_0^T f(x)\,dx$. To see that the limit in fact exists, note that
$$\int_0^{aT} f(u)\,du = \int_0^{\lfloor a\rfloor T} f(u)\,du + \int_{\lfloor a\rfloor T}^{aT} f(u)\,du.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prediction.io - pio train fails with OutOfMemoryError We are getting the following error after running "pio train". It works about 20 minutes and fails on Stage 26.
[ERROR] [Executor] Exception in task 0.0 in stage 1.0 (TID 3)
[ERROR] [SparkUncaughtExceptionHandler] Uncaught exception in thread Thread[Executor task launch worker-0,5,main]
[ERROR] [SparkUncaughtExceptionHandler] Uncaught exception in thread Thread[Executor task launch worker-4,5,main]
[WARN] [TaskSetManager] Lost task 2.0 in stage 1.0 (TID 5, localhost): java.lang.OutOfMemoryError: Java heap space
  at com.esotericsoftware.kryo.io.Output.<init>(Output.java:35)
  at org.apache.spark.serializer.KryoSerializer.newKryoOutput(KryoSerializer.scala:80)
  at org.apache.spark.serializer.KryoSerializerInstance.output$lzycompute(KryoSerializer.scala:289)
  at org.apache.spark.serializer.KryoSerializerInstance.output(KryoSerializer.scala:289)
  at org.apache.spark.serializer.KryoSerializerInstance.serialize(KryoSerializer.scala:293)
  at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:239)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)

Our server has about 30gb memory, but about  10gb is taken by hbase+elasticsearch.
We are trying to process about 20 millions of records created by Universal Recommender.
I've tried the following command to increase executor/driver memory, but it didn't help:
pio train -- --driver-memory 6g --executor-memory 8g

What options could we try to fix the issue? Is it possible to process that amount of events on server with that amount of memory?

A: Vertical scaling can take you only so far but you could try increasing the memory available if it's AWS by stopping and restarting with a larger instance.
CF looks at a lot of data, Since Spark gets it's speed by doing in-memory calculations (by default) you will need enough memory to hold all of your data spread over all Spark workers and in your case you have only 1.
Another thing that comes to mind is that this is a Kryo error so you might try increasing the Kryo buffer size a little, which is configured in engine.json
Also there is a Google Group for community support here: https://groups.google.com/forum/#!forum/actionml-user


text:
Q: Exception in thread "main" java.lang.AbstractMethodError: ch.qos.logback.classic.Logger.isTraceEnabled()Z I'm newbie to hibernate.I have searched all the links.But i couldn't find the answer.I was trying to execute the hibernate annotation example i got the error called
Exception in thread "main" java.lang.AbstractMethodError: ch.qos.logback.classic.Logger.isTraceEnabled()Z
Please refer the following details.
Here is my POJO class
package com.vaannila.course;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="COURSES")
public class Course implements Serializable
{
private long courseId;
private String courseName;
public Course()
{
}
public Course(String courseName)
{
this.courseName = courseName;
}
@Id
@GeneratedValue
@Column(name="COURSE_ID" ,updatable = false, nullable = false)
public long getCourseId()
{
return this.courseId;
}
public void setCourseId(long courseId)
{
this.courseId = courseId;
}
@Column(name="COURSE_NAME", nullable=false)
public String getCourseName()
{
return this.courseName;
}
public void setCourseName(String courseName)
{
this.courseName = courseName;
}
}

Here is my configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="connection.password">root</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.vaannila.course.Course" />
    </session-factory>
</hibernate-configuration>

here is my util class is
package com.vaannila.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}

Here is my test class
package com.vaannila.course;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaannila.util.HibernateUtil;

public class Main {
public static void main(String[] args)
{
    Main obj = new Main();
    Long courseId1 = obj.saveCourse("Physics");

}
public Long saveCourse(String courseName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long courseId = null;
try
{
transaction = session.beginTransaction();
Course course = new Course();
course.setCourseName(courseName);
courseId = (Long) session.save(course);
transaction.commit();
}
catch (HibernateException e)
{
transaction.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
return courseId;
}
}

Jars in class path are
1.hibernate-commons-annotations.jar
2.hibernate-annotations.jar
3.ejb3-persistence.jar
4.hibernate3.jar
5.dom4j-1.6.1.jar
6.logback-classic-0.8.jar
7.logback-classic-0.3.jar
8.logback-core-0.9.6.jar
9.slf4j-api-1.5.8.jar
10.jta-1.1.jar
11.dom4j-1.6.1.jar
12.antlr-2.7.6.jar
13.commons-collections-3.1.jar
14.cglib-2.2.jar
15.asm-1.5.3.jar
16.mysql-connector-java-5.0.4.jar
And the stack trace is
Exception in thread "main" java.lang.AbstractMethodError: ch.qos.logback.classic.Logger.isTraceEnabled()Z
    at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:116)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:111)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2119)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2115)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1339)
    at com.lara.Manager.main(Manager.java:20)


text:
Q: Regex Multi Line Named Group I have an online form that customers fill out and submit that generates a purchase order. That data is also send to a monitored inbox, that I am using with power automate in business central to parse out the data, and enter it into our ERP.
An example of how I am parsing that data out:
Email Body:
Street Address: 95 N 200 E
City: BOUNTIFUL
State / Province: UT
Postal / Zip Code: 84010-4848
The regex pattern I have been using is:
Street Address: (?<streetaddress>.+|)
City: (?<city>.+|)
State \/ Province: (?<state>.+|)
Postal \/ Zip Code: (?<zip>.+)

It works. Later in the body of the email I have:
* S12 (Amount: 730.00 USD, Special Quantity: 1546)
* IRONWORKS DRing (Amount: 1,599.00 USD, Special Quantity: 1)
* IRONWORKS LRing (Amount: 399.00 USD, Special Quantity: 1)
* IRONWORKS SRing (Amount: 1,199.00 USD, Special Quantity: 1) **
My regex for this however doesn't work and I cannot understand why.
\* S12 \(Amount: 730.00 USD, Special Quantity: (?<S12Quantity>\d+|)
\* IRONWORKS DRing \(Amount: 1,599.00 USD, Special Quantity: (?<DQuantity>\d+|)
\* IRONWORKS LRing \(Amount: 399.00 USD, Special Quantity: (?<LQuantity>\d+|)
\* IRONWORKS SRing \(Amount: 1,199.00 USD, Special Quantity: (?<SQuantity>\d+|)

I'm just trying to pull the quantity for each item, but also need to later find a way to do the same thing with the revenue amount.

A: At the end of your capture group you have an open parentheses.
from:
(?<S12Quantity>\d+|)

to:
(?<S12Quantity>\d+)\)

You'll need to account for the capture group closing ) and the literal ) at the end of the string.
I've tested this with the fix and it works on Rubular for me:
\* S12 \(Amount: 730.00 USD, Special Quantity: (?<S12Quantity>\d+)\)
\* IRONWORKS DRing \(Amount: 1,599.00 USD, Special Quantity: (?<DQuantity>\d+)\)
\* IRONWORKS LRing \(Amount: 399.00 USD, Special Quantity: (?<LQuantity>\d+)\)
\* IRONWORKS SRing \(Amount: 1,199.00 USD, Special Quantity: (?<SQuantity>\d+)\)

A: Each line ends with ), and this character pattern is missing in the pattern.
Also, periods must be escaped since . matches any character.
Besides, (\d+|) is a convoluted way of saying (\d*) - zero or more digits.
Use
\* S12 \(Amount: 730\.00 USD, Special Quantity: (?<S12Quantity>\d+)\)
\* IRONWORKS DRing \(Amount: 1,599\.00 USD, Special Quantity: (?<DQuantity>\d*)\)
\* IRONWORKS LRing \(Amount: 399\.00 USD, Special Quantity: (?<LQuantity>\d*)\)
\* IRONWORKS SRing \(Amount: 1,199\.00 USD, Special Quantity: (?<SQuantity>\d*)

See proof


text:
Q: Preinititalize a map in C++ I need a class to have a const std::map from string to pointer to a function. How can I initialize this map without adding elements like this:
string func1(string a){
    return a;
}

string func2(string x){
    return "This is a random string";
}

//In class declaration:
   const map<string,string(*)(string)> a;

//Where should this go? Any other, probably better method to initialize this map?
    a["GET"] = &func1;
    a["SET"] = &func2;

EDIT:
I am doing this on pre-C++11

A: A typical way I used to do this pre-C++11 was to create a function that returns the map and initialise my const variable using that function.
#include <algorithm>
#include <iostream>
#include <map>
#include <string>

typedef std::map<std::string, std::string(*)(std::string)> MyMap;

std::string forward(std::string s) { return s; }
std::string backward(std::string s) { std::reverse(s.begin(), s.end()); return s; }

MyMap Init()
{
    MyMap map;
    map["forward"] = &forward;
    map["backward"] = &backward;
    return map;
}

const MyMap Map = Init(); // <--- initialise map via function

int main()
{
    for (MyMap::const_iterator iter = Map.begin(); iter != Map.end(); iter++)
        std::cout << (*iter->second)(iter->first) << "\n";
    return 0;
}

Live example


text:
Q: include in php not working  <?php
    include("/Crypt/RSA.php");
    $rsa = new Crypt_RSA();
     $token=base64_decode("iKmHdK3ChRBPAU/I/wTKld4up91TMrcWjkE+VGggVryRzvhKC6l+sZ3F+j+qyW8rxg01/uu2E3z6aVirwmQ0ig==");
     $private=base64_decode("MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAyUFH4OJOUOKh38raMxiQhmtuNSMxcznSdt9fWiJZOYpnv1rbu3h/heNCIOxOHSrlMz8FAKAW6rd9ddXNcm4myQIDAQABAkEApGbPcMVtdGWuFkJ/PH40kZnwzTeSja4OX0zZd6fXe0hBZZjA1nREuLGh2x7OXkpArytgQ35W2NHCxeldniTmgQIhAO7SB0Mhb/HLst4ty6HT2kZoAC/N2UdsBtQFdC8sNNxXAiEA17t4cVsx5EYYFifDSUwawz5pJSfrQYk1C0H1atL9Id8CIQDOtJL8k7BkxD5o95JM2yUN02518eGiY+n1EVNikQyfuQIgdph88fQsTU2rWCKr3NOVstfQfbigP/rpyjKMdBlhRwkCIE/x13OF2JUHlA5DqxCVh3LHMDDowr7SkQ2QVkqfBcAb");
    $rsa->loadKey($privateKey);
    echo $rsa->decrypt($cipher);
?>

i kept my include_path as .:/usr/local/lib/php
i am getting errors like this:

Warning: include(/Crypt/RSA.php) [function.include]: failed to open stream: No such file or directory in /home/futureti/public_html/reg2.php on line 2
Warning: include() [function.include]: Failed opening '/Crypt/RSA.php' for inclusion (include_path='.:/usr/local/lib/php') in /home/futureti/public_html/reg2.php on line 2
Fatal error: Class 'Crypt_RSA' not found in /home/futureti/public_html/reg2.php on line 3

A: Try this:
include('../Crypt/RSA.php');

Your current leading / is creating an absolute link, so going right back to your root directory.
../ means one folder up.

A: Try using the document root variable:
$doc_root = $_SERVER['DOCUMENT_ROOT'];
include($doc_root . "/Crypt/RSA.php");


text:
Q: What's an example of a space that needs the Hahn-Banach Theorem? The Hahn-Banach theorem is rightly seen as one of the Big Theorems in functional analysis.  Indeed, it can be said to be where functional analysis really starts.  But as it's one of those "there exists ..." theorems that doesn't give you any information as to how to find it; indeed, it's quite usual when teaching it to introduce the separable case first (which is reasonably constructive) before going on to the full theorem.  So it's real use is in situations where just knowing the functional exists is enough - if you can write down a functional that does the job then there's no need for the Hahn-Banach Theorem.
So my question is: what's a good example of a space where you need the Hahn-Banach theorem?
Ideally the space itself shouldn't be too difficult to express, and normed vector spaces are preferable to non-normed ones (a good non-normed vector space would still be nice to know but would be of less use pedagogically).
Edit: It seems wrong to accept one of these answers as "the" answer so I'm not going to do that.  If forced, I would say that $\ell^\infty$ is the best example: it's probably the easiest non-separable space to think about and, as I've learnt, it does need the Hahn-Banach theorem.
Incidentally, one thing that wasn't said, and which I forgot about when asking the question, was that such an example is by necessity going to be non-separable since countable Hahn-Banach is provable merely with induction.

A: I'd like to summarize the answer that has developed from Eric Shechter's book, via Mark Meckes, plus the remark from Gerald Edgar.  Since it's not really my answer, I'm making this a community answer.

*

*The Hahn-Banach theorem is really the Hahn-Banach axiom.  Like the axiom of choice, Hahn-Banach cannot be proved from ZF.  What Hahn and Banach proved is that AC implies HB.  The converse is not true:  Logicians have constructed axiom sets that contradict HB, and they have constructed reasonable axioms strictly between AC and HB.  So a version of Andrew's question is, is there a natural Banach space that requires the HB axiom?  For the question, let's take HB to say that every Banach space $X$ embeds in its second dual $X^{**}$.

*As Shechter explains, Shelah showed the relative consistency of ZF + DC + BP (dependent choice plus Baire property).  As he also explains, these axioms imply that $(\ell^\infty)^* = \ell^1$.  This is contrary to the Hahn-Banach theorem as explained in the next point.    A striking way to phrase the conclusion is that $\ell^1$ and its dual $\ell^\infty$ become reflexive Banach spaces.

*$c_0$ is the closed subspace of $\ell^\infty$ consisting of sequences that converge to 0.  The quotient $\ell^\infty/c_0$ is an eminently natural Banach space in which the norm of a sequence is $\max(\lim \sup,-\lim \inf)$.  (Another example is $c$, the subspace of convergent sequences.  In $\ell^\infty/c$, the norm is half of $\lim \sup - \lim \inf$.) The inner product between $\ell^1$ and $c_0$ is non-degenerate, so in Shelah's axiom system, $(\ell^\infty/c_0)^* = 0$.  Without the Hahn-Banach axiom, the Banach space $\ell^\infty/c_0$ need not have any non-zero bounded functionals at all.

A: There is another logical tidbit here.
Hahn-Banach (HB) is strictly weaker than Axiom of Choice (AC), meaning--under the assumption of consistence as usual--in ZF, AC implies HB but not the other way around.  Another intermediate theorem of functional analysis is the Krein-Milman theorem: "A compact convex nonempty set in a locally convex space has an extreme point"  Call it KM.  In ZF, AC implies KM but not the other way around.  And the interesting point is that, taken both together, we do get AC.  So in ZF, HB+KM implies and is implied by AC.

A: I don't fully understand what you're asking, but the one proof I know of the fact that (up to topological isomorphism) the only complete Archimedean fields are $\mathbb{C}$ and $\mathbb{R}$ uses the Hahn-Banach theorem.

A: I'm not sure exactly what you have in mind by "need the Hahn-Banach theorem".  One standard example of something pretty concrete for which Hahn-Banach in some form is needed is to show that there are linear functionals on $\ell^\infty$ which are not represented by elements of $\ell^1$.  It's a standard exercise to show that $\ell^1$ acts as the dual of sequences converging to 0; since that is a proper closed subspace of $\ell^\infty$, Hahn-Banach produces further linear functionals on $\ell^\infty$.
This is closely related to the subject of Banach limits.

A: The Gelfand-Naimark theorem says that any $C^\ast$-algebra is isomorphic to a norm closed $\ast$-subalgebra of $B(H)$ for a suitable Hilbert space $H$. In order to prove this theorem, it is imperative that our $C^\ast$-algebra have states, which uses the Hahn-Banach theorem.
One can also use the Hahn-Banach theorem instead of Tychonoff's theorem to construct $\beta X$, the Stone-Cech compactification of $X$. This is closely related to @Mark Meckes' answer.

A: If $G$ is a group, Bavard showed that the stable commutator length vanishes on $[G,G]$ if and only if $G$ admits no nontrivial "homogeneous quasimorphisms". These functions (on the space of group $1$-boundaries) are constructed using the Hahn-Banach theorem, but are usually very hard (or impossible) to write down explicitly.
Another example: let $M$ be a triangulated manifold, and suppose we orient every edge of every simplex in such a way that the orientations come from a "total order" on each triangle. We would like to assign positive "lengths" to each edge in such a way that on each triangle, the sum of the values on the "short edges" is equal to the value on the "long edge" (where "short" and "long" are defined according to the orientations). The (finite-dimensional!) Hahn-Banach theorem tells us we can do this if and only if every oriented loop in the 1-skeleton is homologically essential; i.e. "homological positivity" can be improved to "chain positivity". Of course the finite-dimensional Hahn-Banach theorem is just a psychological crutch, but versions of this construction in other categories need the "real" Hahn-Banach theorem (applied to certain spaces of de Rham currents).

A: The simplest example I know are the real numbers as vector space over the rationals.
The Hahn-Banach theorem asserts the existence of additive functionals other than standard addition,
For instance, $f$ with $f(1)=1, f(\pi)=0$.


text:
Q: Spark - MongoDb - slow dataframe.limit(2) in java when compared with the pyspark version Having a following python script:
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName('Test') \
    .config("spark.driver.extraJavaOptions", "-Xss1G") \
    .master('local[*]') \
    .getOrCreate()

dataframe = spark.read.format("com.mongodb.spark.sql.DefaultSource").option("database",
                                                                                "finance")\
    .option("collection", "finished13").option(
            "uri", "mongodb://localhost:27017/test") \
    .option("pipeline",
            "[ { '$sort': {'prop1':-1} }, {'$limit': 700}]").load()

dataframe = dataframe.limit(2)

dataframe.show()

Spark initially starts-off by sampling over the Mongodb structure therefore the load() call takes a while. Dataframe.limit(2) call is immediate (as expected) as spark is a lazy executor. At the other hand I write the very same code in Java, as seen below:
SparkSession session = SparkSession
        .builder()
        .master("local[*]")
        .appName("Java Spark SQL basic example")
        .config("spark.driver.extraJavaOptions", "-Xss1G")
        .getOrCreate();
Dataset<Row> dataset = session.read().format("com.mongodb.spark.sql.DefaultSource").option("collection", "finished13")
        .option("uri", "mongodb://localhost:27017/test").option("pipeline",
                "[ { '$sort': {'prop1':-1} }, {'$limit': 700}]").load();

dataset = dataset.limit(2);

Object rows = dataset.collect();

In the Java version, dataset.limit(2) takes approximately 9 minutes to complete. It is sampled over the same collection. Collection consists of roughly 30k documents. Each document is of the same structure and contains around 27k properties (first level, no nesting). Average document size is 1.5MB. Any idea why does Java version takes eternity to complete?

A: Just for the future folks if anyone else stumbles across the same issue - with mongo-java-driver-3.7.0, mongo-spark-connector_2.11-2.2.2 the driver works such that when adding few operations such as limit, select etc it iterates over all the columns. I have had 30k of them, therefore it took ages. My workaround was to create new collection through a native java driver where only aggregated documents were stored (with way fewer fields) and access this collection through spark API.


text:
Q: Approximate normal distribution(this is different from what I asked earlier $\log(n)$ is replaced by $\sqrt{\log{n}}$) Let $ X \sim N (0, 1)$. For $x$ large enough, the tail of the distribution of $X$ may be approximated as $$P(X > x) \sim e^{-x^2/2}/(x\sqrt{2\pi})$$
Consider a sequence of independent r.v. all having a standard normal distribution. For every $a > 0$, $n = 1, 2, \ldots$, define the event $$U_{a,n} =\left \lbrace X_n \ge a\times \sqrt{\log(n)}\right \rbrace.$$
a) Calculate $P(\limsup \, U_{a,n})$, which may depend on $a$.
b) Prove $\limsup \left(X_n/\sqrt{\log(n)} \right) = \sqrt{2} $ a.e.
for a) should i still consider B-C lemma to do it?
and anyone can give me some hint for b)?

A: a) Yes, B-C does it. Now,
\begin{align*}
\sum_{n\ge 1}\mathbf{P}(U_{a,n})&\leq\sum_{n\geq 1}\frac{\exp(-{a^2\log n}/2)}{a\sqrt{2\pi\log n}}\\
&=\sum_{n\geq 1}\frac{1}{a n^{a^2/2}\sqrt{2\pi\log n}}\\
&<\infty, \quad\text{if}\quad a> \sqrt{2}.
\end{align*}
Hence, if $a> \sqrt{2}$,
\begin{equation*}
\mathbf{P}(\limsup_{n\rightarrow\infty} U_{a,n})=\mathbf{P}(U_{a,n},\text{i.o.})=0.
\end{equation*}
Similarly, you can show (either using the usual Gaussian lower bound $\frac{x}{x^2+1}e^{\dots}\dots$ or being careful with the approximation--the latter's easier) that
\begin{equation*}
\sum_{n\ge 1}\mathbf{P}(U_{a,n})=\infty, \quad\text{if}\quad a\le \sqrt{2}.
\end{equation*}
Since the $U_{a,n}$s are independent, for $a\le\sqrt{2}$,
\begin{equation*}
\mathbf{P}(\limsup_{n\rightarrow\infty} U_{a,n})=\mathbf{P}(U_{a,n},\text{i.o.})=1.
\end{equation*}
b) From the first part of (a):
Let $a> \sqrt{2}$. Then there is some $N$ such that $n\ge N$ implies:
\begin{equation*}
\frac{X_{n}}{\sqrt{\log n}}\le a,\quad\text{a.s.},
\end{equation*}
since the $\limsup$ is $0$. Now let $n\rightarrow\infty.$
It follows that (since it holds for all $a>\sqrt{2}$)
\begin{equation*}
\limsup_{n\rightarrow\infty}\frac{X_{n}}{\sqrt{\log n}}\le \sqrt{2},\quad\text{a.s.}.
\end{equation*}
Showing $\ge$ follows from using the definition of $\limsup$ and the second part of (a).
Summary: Show that the series in step (a) converges for certain values of a and diverges otherwise. Then, use B-C to find the $\limsup$. Third, follow the definition of $\limsup$.


text:
Q: Can't get selected values of dynamically created Select List list to objects in Razor Pages I am trying to assing the selected values of Select lists to fields in a complex object list in a loop but its creating new instances of the objects with the selected value and overwriting the existing objects. Tried adding inputs for other fields but it doesnt copy complex variables and leaves them null or empty again.
I have a list of Ball objects with a string id, integer weight value and a dictionary of Color objects and boolean value(I will also use that dictionary for checkboxes). I am initializing the list and dictionary and creating Select Lists in a foreach loop with index. When I submit via Save button I expect to fill the SelectedColorId field of the current Ball object with the selected colorId but it creates a new Ball object with SelectedColorId field only and others null. I tried copying other values with input tags but still couldnt get the complex objects like availableColors dictionary.
How can I assing the selected values to existing objects field without using js or jquery?
page view
values after submitting
public class Color
{
    private string id;
    private string name;

    public Color(string id, string name)
    {
        this.Id = id; //color-black
        this.Name = name; //black
    }

    public string Id { get => id; set => id = value; }
    public string Name { get => name; set => name = value; }
}

 public class Ball
{
    private string id; //smallBall
    private Dictionary<Color, bool> availableColors;
    private string selectedColorId; //color-red
    private int weight; //1

    public Ball() { }

    public Ball(string id, Dictionary<Color, bool> availableColors, int weight)
    {
        Id = id;
        AvailableColors = availableColors;
        SelectedColorId = "";
        Weight = weight;
    }

    public string Id { get => id; set => id = value; }
    public Dictionary<Color, bool> AvailableColors { get => availableColors; set => availableColors = value; }
    public string SelectedColorId { get => selectedColorId; set => selectedColorId = value; }
    public int Weight { get => weight; set => weight = value; }
}

my .Cshtml.cs file:
[BindProperties]
public class SelectBindingTestModel : PageModel
{
    private List<Ball> balls;

    public List<Ball> Balls { get => balls; set => balls = value; }

    public IActionResult OnGet()
    {
        if (Balls == null)
        {
            Balls = new List<Ball>();
            Balls.Add(new Ball("smallBall", new Dictionary<Color, bool>() {
                { new Color("color-black", "black"), true },
                { new Color("color-red", "red"), true },
                { new Color("color-white", "white"), true },
                { new Color("color-blue", "blue"), true }} , 1));

            Balls.Add(new Ball("mediumBall", new Dictionary<Color, bool>() {
                { new Color("color-blue", "blue"), true },
                { new Color("color-yellow", "yellow"), true },
                { new Color("color-khaki", "khaki"), true }}, 2));

            Balls.Add(new Ball("largeBall", new Dictionary<Color, bool>() {
                { new Color("color-brown", "brown"), true },
                { new Color("color-red", "red"), true },
                { new Color("color-green", "green"), true },
                { new Color("color-pink", "pink"), true }} , 3));
        }
        return Page();
    }

    public IActionResult OnPostConfirm()
    {
        return Page();
    }
}

and .Cshtml file:

Test page for binding Select items

<form method="post">

    @{
        int i = 0;
    }
    @foreach (Ball ball in @Model.Balls)
    {

            @ball.Id
            <select class="form-control form-control-sm" asp-for="Balls[i].SelectedColorId" asp-items="@new SelectList(ball.AvailableColors.Keys.ToList(), nameof(Color.Id), nameof(Color.Name))" href="#">
                <option value="" disabled>Select Color</option>
            </select>

        i++;
    }

        <button type="submit" class="btn btn-primary" asp-page-handler="Confirm" id="Confirm">Save</button>

A: Update:

my expectation is to assing it to smallBall which already has values
in its other fields

For other fields, such as the Id and weight property, you can use a hidden field to store the value in the Form.
Code like this:
@foreach (Ball ball in @Model.Balls)
{

        @ball.Id

        <input type="hidden" name='Balls[@i].Id' value="@Model.Balls[i].Id" >

        <select class="form-control form-control-sm" asp-for="Balls[i].SelectedColorId"
            asp-items="@new SelectList(ball.AvailableColors.Keys.ToList(), nameof(Color.Id).ToString(), nameof(Color.Name))" href="#">
            <option value="" disabled>Select Color</option>
        </select>

    i++;
}

But to the availableColors dictionary, I suggest you could create a data repository to store them, then, in the post method, you can query the data repository and according to the Ball Id to get the availableColors dictionary. Instead of transfer them via form.
The result like this:


text:
Q: Sql pivot - but dont sum the values I have a table schema that looks like this
CREATE TABLE [dbo].[Discounts](
      [Id] [int] NOT NULL,
      [ProductId] [varchar(50)] NOT NULL,
      [LowerBoundDays] [int] NOT NULL,
      [UpperBoundDays] [int] NOT NULL,
      [Discount] [decimal](18, 4) NOT NULL,

And some data like this
        lower       upper discount(%)
product1  0         10          0
product1  10        30          1
product1  30        60          2
product1  60        90          3
product1  90        120         4
product2  0         10          0
product2  10        30          1
product2  30        60          2
product2  60        90          3
product2  90        120         4

How can I do a pivot query to get 2 rows that look like this:
            0-10    10-30   30-60   60-90   90-120
product1    0       1       2       3       4
product2    0       1       2       3       4

A: Since you are using SQL Server, there are several ways that you can convert the rows of data into columns.
You can use an aggregate function with a CASE expression to get the result:
select productid,
  max(case when lower = 0 and upper = 10 then discount end) [0-10],
  max(case when lower = 10 and upper = 30 then discount end) [10-30],
  max(case when lower = 30 and upper = 60 then discount end) [30-60],
  max(case when lower = 60 and upper = 90 then discount end) [60-90],
  max(case when lower = 90 and upper = 120 then discount end) [90-120]
from CorporateSpread
group by productid;

See SQL Fiddle with Demo.
If you are using SQL Server 2005+, then you can use the PIVOT function:
select productid, [0-10], [10-30], [30-60], [60-90],[90-120]
from
(
  select productid,
    discount,
    cast(lower as varchar(10)) + '-' + cast(upper as varchar(10)) rng
  from CorporateSpread
) d
pivot
(
  max(discount)
  for rng in ([0-10], [10-30], [30-60], [60-90],[90-120])
) piv;

See SQL Fiddle with Demo.
The above two version work great if you have a known number of values, but if you have an unknown number of ranges, then you will need to to use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(cast(lower as varchar(10)) + '-' + cast(upper as varchar(10)))
                    from CorporateSpread
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT productid, ' + @cols + '
            from
            (
                select productid,
                  discount,
                  cast(lower as varchar(10)) + ''-'' + cast(upper as varchar(10)) rng
                from CorporateSpread
            ) x
            pivot
            (
                max(discount)
                for rng in (' + @cols + ')
            ) p '

execute sp_executesql @query;

See SQL Fiddle with Demo. All versions will give a result:
| PRODUCTID | 0-10 | 10-30 | 30-60 | 60-90 | 90-120 |
-----------------------------------------------------
|  product1 |    0 |     1 |     2 |     3 |      4 |
|  product2 |    0 |     1 |     2 |     3 |      4 |


text:
Q: How to understand "The collection of all sets satisfying a given property may not be a set" I'm a beginner in set-theory, and I got to read:
"The collection of all sets satisfying a given property may not together form a set"
I would like to ask, could this statement be translated as follows (in general):
"The collection of all sets satisfying a given property may not together form a set that also satisfies the given property"
Or is the added qualification not needed ? --- meaning that the collection may form "something" that does not follow from the Axioms of Set Theory ?

A: Its actually stronger than that. The collection of all sets that satisfy a certain property may form what is known as a proper class. A proper class is a collection of sets which is to big to be a set itself. Which means ZF can prove that it does not exist. (ZF can prove that no set exists such that this set contains all sets which satisfy the aforementioned property)
For example, if we apply this to the property, x=x, then the collection of all sets which satisfy this property, is just the proper class containing all sets. ZFC can prove that a set containing all sets cannot exist, because sets are not allowed to contain themselves in ZFC, due to the axiom of foundations.
This is slightly informal, but every time you have the collection of all sets satisfying $\varphi(x)$, is not a set itself, this will happen because you can show that the "number" of sets which satisfy that property is the same size as the total "number" of sets.
(calling it a number is very very much problematic, but I think its a useful way to think about it)

A: The added modification makes the statement weaker. Let $P$ denote the given property. The original statement asserts that the collection of all sets satisfying $P$ is not a set at all. Whereas your modification asserts that the collection of all sets satisfying $P$ either fails to be a set (as in the original statement) or is a set, albeit one failing to satisfy $P$.
Note that the original version implies your modified version. However, by Russel's paradox the original version is true. Therefore, the possibility that you have added - that the collection of sets satisfying $P$ is a set failing to satisfy $P$ - is unnecessary.

Remark: In set theory, a collection that is not a set is called a proper class. Therefore, another way to rephrase the original statement is
"The collection of all sets satisfying a given property may be a proper class."


text:
Q: How to shim npm package dependency in browserify? So I have a React project, in which I'm actually deploying with react-lite as the footprint is much smaller. I'd like to use react-nouislider, but in it's package.json, I've found this:
"peerDependencies": {
    "react": "^0.14.0"
}

What this means is that whenever I require react-nouislider, it pulls in React instead of react-lite. How do I shim dependencies of an npm package from my top-level package.json?
This is how I'm shimming react-lite in:
"browser": {
    "react": "react-lite"
}

And I tried this, but it didn't work:
"browserify-shim":{
    "react-nouislider": {
        "depends": "react-lite"
    }
}

How is it possible to shim a dependency of a package itself?

A: Browserify Shim's tagline is:

Makes CommonJS incompatible files browserifyable.

Your issue here is that react-lite is already CommonJS compatible. For any CommonJS compatible file, Browserify will automatically add its dependencies and peerDependencies as appropriate, before Browserify Shim gets involved.
I suggest you change the peerDependencies entry in the react-nouislider package to the appropriate version of react-lite and remove your Browserify Shim config above as it's no longer needed. When you do this, be sure to run any tests in the react-nouislider package to make sure it still works with react-lite instead of React. A good way of doing this is forking react-nouislider to your own repo, making the change there, and pulling from that repo in your package.json.


text: Q: Como testar WebServices php em Android com biblioteca Retrofit Tenho um aplicativo Android no Android Studio e estou usando a biblioteca retrofit para conectar com um servidor php. Quero saber como eu faço para testar esse app em um celular real com o servidor rodando no meu notebook. No caso, qual a estrutura que eu tenho que montar para realizar o teste?


text:
Q: Z transform of a polynomial signal $$x(k)=\begin{cases} k^n \qquad k\ge 0 \\ 0 \ \  \qquad k<0 \end{cases}$$
I have this formula to calculate the Z transform:
$$\mathscr{Z} \{x(k) \}=\Big(-z \ \frac{d}{dz}\Big)^n \Big[ \frac{z}{z-1} \Big]$$

I have considered this particular case: $$x(k)=\begin{cases} k^2 \qquad k\ge 0 \\ 0 \ \  \qquad k<0 \end{cases}$$

$$f(z)=\frac{z}{z-1}$$
$$f'(z)=\frac{-1}{(z-1)^2}$$
$$-z f'(z)=\frac{z}{(z-1)^2}$$

$$g(z)=\frac{z}{(z-1)^2}$$
$$g'(z)=\frac{(z-1)^2-2z(z-1)}{(z-1)^4}=\frac{-z-1}{(z-1)^3}$$
$$-z g'(z)=\frac{z^2+z}{(z-1)^3}$$

So $$\mathscr{Z} \{ x(t) \}=\frac{z (z+1)}{(z-1)^3}$$

But, I have tried to calculate the inverse Z transform:
$$\mathscr{Z}^{-1} \Big\{\frac{z (z+1)}{(z-1)^3} \Big\}=\mathscr{Z}^{-1} \Big\{H(z) \Big\}$$

Partial fraction decomposition of $\frac{H(z)}{z}$:

$$\frac{z+1}{(z-1)^3}=\frac{1}{(z-1)^2}+\frac{2}{(z-1)^3}$$

$$\mathscr{Z}^{-1} \Big\{\frac{z}{(z-1)^2} \Big\}=k \ u(k)$$
$$\mathscr{Z}^{-1} \Big\{\frac{2z}{(z-1)^3} \Big\}=k^2 \ u(k)$$

$$\mathscr{Z}^{-1} \Big\{H(z) \Big\}=(k+k^2) \ u(k)$$

Where is the mistake?

I know this formula to calculate the inverse Z transform:
$$\mathscr{Z^{-1}}\Big[ \frac{C_{i,j} \ z}{(z-p_i)^j}\Big]=C_{i,j} \ \frac{k^{(j-1)}}{(j-1)!} \ p_i^{k-j+1} \ u(k)$$

Is it not applicable to $\frac{z(z+1)}{(z-1)^3}$?

Thanks

A: Consider:
$$z(z+1) = z^{2} + z = (z^{2} - 2 z + 1) + 3(z-1) + 2$$
which leads to
\begin{align}
\frac{z(z+1)}{(z-1)^{3}} &= \frac{(z-1)^{2} + 3 \, (z-1) + 2}{(z-1)^{3}} \\
&= \frac{1}{z-1} + \frac{3}{(z-1)^{2}} + \frac{2}{(z-1)^{3}}.
\end{align}
Using
\begin{align}
\frac{1}{1-x} &= \sum_{k=0}^{\infty} x^{k} \\
\frac{1}{(1-x)^{2}} &= \sum_{k=0}^{\infty} (k+1) \, x^{k} \\
\frac{1}{(1-x)^{3}} &= \frac{1}{2} \, \sum_{k=0}^{\infty} (k+1)(k+2) \, x^{k}
\end{align}
provides
\begin{align}
\frac{z(z+1)}{(z-1)^{3}} &= \sum_{k=0}^{\infty} \left[ 1 - 3 \, (k+1) + 2 \, \frac{(k+1)(k+2)}{2} \right] \, z^{-k} \\
&\Doteq \left[ 1 - 3 \, (k+1) + (k^{2} + 3 k + 2) \right] \\
&\Doteq k^2.
\end{align}


text:
Q: randomly select n lines from a file with possible repetition I Have a text file with more than 1 million lines. The individual lines are not very big (about 200-270 characters each).
I am trying to randomly pick 60% of the number of lines in input, where each line can be repeated in the output. In the above example, my output would have 600,000 lines, but only 500,000 lines out of them might be unique. I also need the lines which were not picked at all, in a different output file. Any individual line should not appear in both the output files.
Each line in a input file has a record like below.

*

*Record1

*Record2

*Record3

*Record4

*Record5

*Record6

*Record7

If I am trying to pick 5 random lines in a file output1.txt, where each line can be repeated. Lets say following were the lines picked and are in output1.txt

*

*Record3

*Record5

*Record2

*Record2

*Record5

The remaining records should go to output2.txt.

*

*Record1

*Record4

*Record6

*Record7

The order of the records does not matter.
I think I can write code to do this using Java, but I was wondering I can do it quickly using some command or scripting. I tried using 'shuf' to pick the lines, but how can I then make sure that the lines which have been picked, don't appear in the second output I am trying to get.
I am working on a Linux machine. Any suggestions or comments are welcome. Thanks.

A: Here is a Perl solution.
I seem to be writing this a lot recently, but indexing a very large text file is the best way to get random access to it without reading the entire file into memory.
This program uses the tell operator to establish the offset of the current record within the source file, the seek operator to return to a specific record, and vec to keep track of which records have been selected.
Note that the do { ... } while EXPR form executes the do-block before first checking the condition, and has been chosen specifically for this purpose.
The program expects the file to be scanned for data to be specified on the command line. The output files are selected.txt for the 60% selected and unselected.txt for the remainder.
use strict;
use warnings;

my $file = shift or die "No input file specified";

open my $infh, '<', $file or die qq(Unable to open "$file" for input: $!);
my @index;
do { push @index, tell $infh } while <$infh>;

my $used = "\0" x (@index / 8 + 1);

my $outfh;

open $outfh, '>', 'selected.txt' or die $!;
my $n = 0;
while ($n++ / @index < 0.6) {
  my $rec = int rand scalar @index;
  seek $infh, $index[$rec], 0;
  print $outfh scalar <$infh>;
  vec($used, $rec, 1) = 1;
}

open $outfh, '>', 'unselected.txt' or die $!;
for my $rec (0 .. $#index) {
  next if vec($used, $rec, 1);
  seek $infh, $index[$rec], 0;
  print $outfh scalar <$infh>;
}

Edit
I hesitate to use a module to replace so little code, but here is a version using Tie::File as ikegami recommends in case anyone prefers this approach.
use strict;
use warnings;

use Tie::File;

my $file = shift or die "No input file specified";

tie my @index, 'Tie::File', $file, mode => O_RDONLY
    or die qq(Unable to open "$file" for input: $!);

my $outfh;
my @used;

open $outfh, '>', 'selected.txt' or die $!;
my $n = 0;
while ($n++ / @index < 0.6) {
  my $rec = int rand scalar @index;
  print $outfh $index[$rec], "\n";
  $used[$rec]++;
}

open $outfh, '>', 'unselected.txt' or die $!;
for my $rec (0 .. $#index) {
  print $outfh $index[$rec], "\n" unless $used[$rec];
}

A: This randomly picks one line of the N lines of the file until N/6 lines are picked. The rate of duplicates is not controlled.
To save memory, we'll keep the file position of the lines in memory instead of the lines themselves. Tie::File does that for us.
#!/usr/bin/env perl
use strict;
use warnings;

use Tie::File  qw( );

my ($input_qfn, $picked_qfn, $unpicked_qfn) = @ARGV;

tie(my @lines, 'Tie::File', $input_qfn, autochomp => 0)
   or die;

my $num_lines = @lines;
my @unpicked_indexes = 0..$num_lines-1;
my @picked_indexes;
for (1..$num_lines*.6) {
   my $rnd_idx = int(rand($num_lines));
   $unpicked_indexes[$rnd_idx] = undef;
   push @picked_indexes, $rnd_idx;
}

open(my $picked_fh, '>', $picked_qfn)
   or die $!;
print($picked_fh $lines[$_]) for @picked_indexes;

open(my $unpicked_fh, '>', $unpicked_qfn)
   or die $!;
print($unpicked_fh $lines[$_]) for grep defined, @unpicked_indexes;

A: Example ~ 10% in STDOUT twice, another 50% in STDOUT once, rest 40% in STDERR
awk 'BEGIN {srand()} !/^$/ { r = rand(); if (r <= .60) print $0; if (r <= 0.10) print $0; if (r > .60) print $0 > "/dev/stderr"; }'

Note: Redirect STDOUT to one file > file1 and STDERR to other file 2> file2 ...

A: You can do it in bash script using this code:
without repetition of lines in the output:
#!/bin/bash

lines=$(wc -l inputfile.txt | awk '{print $1}')

echo $lines

# computation of percentage of random lines we
# want to pick e.g. 60%
let percentage=$((lines*60/100))

echo $percentage

# pick the random lines
random_lines=$(sort -R inputfile.txt | head -n $percentage)

# show the random lines
echo $random_lines

with repetition of lines in the output:
#!/bin/bash

lines=$(wc -l inputfile.txt | awk '{print $1}')

echo $lines

# computation of percentage of random lines we
# want to pick e.g. 60%
let percentage=$((lines*60/100))

echo $percentage

# pick the random lines
for ((i=1; i<$percentage; i++))
do
  echo $(sort -R inputfile.txt | head -n 1)
done

A: The mathematical jargon you are looking for is as follows: You have a set of 1 million elements and you wish to pick sample elements "with replacement"; furthermore you wish to know the elements which were not picked.
universe = range(10**6)  # or whatever your elements are
numElementsToChoose = int(0.6*len(universe))

chosen = [random.choice(universe) for _ in range(numElementsToChoose)]
unchosen = set(universe) - set(chosen)

Demo:
>>> len(chosen), len(unchosen)
(600000, 548815)

(This code is inelegant because universe should be a set, but python doesn't natively support picking a random element from a set, only a sequence... ugh.)

A: If you have shuf, you probably have comm, which has the -3 option to compare two sorted files and output the lines found in only one file.


text:
Q: Only href="#", no onclick(), how do I load this in script? I'm in the process of writing a scraper for the articles on the site https://www.welt.de. I'd also like to include the comments. However, when loading the page, not all comments are loaded automatically. Instead one has to click on a link to load more comments, until at some point, all are loaded.
Eg: https://www.welt.de/finanzen/immobilien/article183878020/Bundesbank-sieht-im-Immobilienboom-ein-Stabilitaetsrisiko.html
When you scroll down, there appears a surface "MEHR KOMMENTARE ANZEIGEN" (German for 'show more comments').
This link looks like:

MEHR KOMMENTARE ANZEIGEN

<svg viewBox="0 0 15 9" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(-608.000000, -4318.000000)" fill="#787878">
<polygon transform="translate(615.205882, 4322.852941) rotate(-90.000000) translate(-615.205882, -4322.852941) " points="618.264706 4315.79412 611.205882 4322.85353 618.264706 4329.91176 619.205882 4328.97059 613.088824 4322.85353 619.205882 4316.73529">
</polygon>
</g>
</g>
</svg>

However, I do not know how to load this link in a script?
I understand that href="#" is used when a link is handled by javascript and that it is bad style, as it is only used to change the appearance of the mouse, for which there are other methods.
But where is the onClick() method? Kinda dumbfoundead here...

A: Clicking that show comments twice gives me the following urls
https://api-co.la.welt.de/api/comments?document-id=183878020&created-cursor=2018-11-15T13:52:41.714&sort=NEWEST
https://api-co.la.welt.de/api/comments?document-id=183878020&created-cursor=2018-11-15T12:23:26.896&sort=NEWEST

Which returns the comments. So just use the post id you have and keep fiddling with created-cursor until you get all the comments?
EDIT:
Removing the creator-cursor parameter should give you all the comments
https://api-co.la.welt.de/api/comments?document-id=183878020

EDIT 2:
As someone else mentioned, this might not be a good idea without first contacting the owner of the site.

A: As far as finding the click handler:
If you inspect this element, you can see it has a click event handler calling something in communityweb.js:

This is almost certainly attached with javascript somewhere else (eg, document.getElementById('something').addEventListener("click", function(){ ... } );)
If you want, you can follow through and see the code it's calling (be sure to use the 'pretty print' feature, as it's minified):

It gets complicated from there, but if you're determined enough you could step through in the debugger and see what's being called.


text:
Q: Finding out the duplicate element in an array There is an array of size n and the elements contained in the array are between 1 and n-1 such that each element occurs once and just one element occurs more than once.  We need to find this element.
Though this is a very FAQ, I still haven't found a proper answer.  Most suggestions are that I should add up all the elements in the array and then subtract from it the sum of all the indices, but this won't work if the number of elements is very large.  It will overflow.  There have also been suggestions regarding the use of XOR gate dup = dup ^ arr[i] ^ i, which are not clear to me.
I have come up with this algorithm which is an enhancement of the addition algorithm and will reduce the chances of overflow to a great extent!
for i=0 to n-1
  begin :
    diff = A[i] - i;
    sum  = sum + diff;
  end

diff contains the duplicate element, but using this method I am unable to find out the index of the duplicate element.  For that I need to traverse the array once more which is not desirable.  Can anyone come up with a better solution that does not involve the addition method or the XOR method works in O(n)?

A: There are many ways that you can think about this problem, depending on the constraints of your problem description.
If you know for a fact that exactly one element is duplicated, then there are many ways to solve this problem.  One particularly clever solution is to use the bitwise XOR operator.  XOR has the following interesting properties:

*

*XOR is associative, so (x ^ y) ^ z = x ^ (y ^ z)

*XOR is commutative: x ^ y = y ^ x

*XOR is its own inverse: x ^ y = 0 iff x = y

*XOR has zero as an identity: x ^ 0 = x

Properties (1) and (2) here mean that when taking the XOR of a group of values, it doesn't matter what order you apply the XORs to the elements.  You can reorder the elements or group them as you see fit.  Property (3) means that if you XOR the same value together multiple times, you get back zero, and property (4) means that if you XOR anything with 0 you get back your original number.  Taking all these properties together, you get an interesting result: if you take the XOR of a group of numbers, the result is the XOR of all numbers in the group that appear an odd number of times.  The reason for this is that when you XOR together numbers that appear an even number of times, you can break the XOR of those numbers up into a set of pairs.  Each pair XORs to 0 by (3), and th combined XOR of all these zeros gives back zero by (4).  Consequently, all the numbers of even multiplicity cancel out.
To use this to solve the original problem, do the following.  First, XOR together all the numbers in the list.  This gives the XOR of all numbers that appear an odd number of times, which ends up being all the numbers from 1 to (n-1) except the duplicate.  Now, XOR this value with the XOR of all the numbers from 1 to (n-1).  This then makes all numbers in the range 1 to (n-1) that were not previously canceled out cancel out, leaving behind just the duplicated value.  Moreover, this runs in O(n) time and only uses O(1) space, since the XOR of all the values fits into a single integer.
In your original post you considered an alternative approach that works by using the fact that the sum of the integers from 1 to n-1 is n(n-1)/2.  You were concerned, however, that this would lead to integer overflow and cause a problem.  On most machines you are right that this would cause an overflow, but (on most machines) this is not a problem because arithmetic is done using fixed-precision integers, commonly 32-bit integers.  When an integer overflow occurs, the resulting number is not meaningless.  Rather, it's just the value that you would get if you computed the actual result, then dropped off everything but the lowest 32 bits.  Mathematically speaking, this is known as modular arithmetic, and the operations in the computer are done modulo 232.  More generally, though, let's say that integers are stored modulo k for some fixed k.
Fortunately, many of the arithmetical laws you know and love from normal arithmetic still hold in modular arithmetic.  We just need to be more precise with our terminology.  We say that x is congruent to y modulo k (denoted x ≡k y) if x and y leave the same remainder when divided by k.  This is important when working on a physical machine, because when an integer overflow occurs on most hardware, the resulting value is congruent to the true value modulo k, where k depends on the word size.  Fortunately, the following laws hold true in modular arithmetic:
For example:

*

*If x ≡k y and w ≡k z, then x + w ≡k y + z

*If x ≡k y and w ≡k z, then xw ≡k yz.

This means that if you want to compute the duplicate value by finding the total sum of the elements of the array and subtracting out the expected total, everything will work out fine even if there is an integer overflow because standard arithmetic will still produce the same values (modulo k) in the hardware.  That said, you could also use the XOR-based approach, which doesn't need to consider overflow at all. :-)
If you are not guaranteed that exactly one element is duplicated, but you can modify the array of elements, then there is a beautiful algorithm for finding the duplicated value.  This earlier SO question describes how to accomplish this.  Intuitively, the idea is that you can try to sort the sequence using a bucket sort, where the array of elements itself is recycled to hold the space for the buckets as well.
If you are not guaranteed that exactly one element is duplicated, and you cannot modify the array of elements, then the problem is much harder.  This is a classic (and hard!) interview problem that reportedly took Don Knuth 24 hours to solve.  The trick is to reduce the problem to an instance of cycle-finding by treating the array as a function from the numbers 1-n onto 1-(n-1) and then looking for two inputs to that function.  However, the resulting algorithm, called Floyd's cycle-finding algorithm, is extremely beautiful and simple.  Interestingly, it's the same algorithm you would use to detect a cycle in a linked list in linear time and constant space.  I'd recommend looking it up, since it periodically comes up in software interviews.
For a complete description of the algorithm along with an analysis, correctness proof, and Python implementation, check out this implementation that solves the problem.
Hope this helps!

A: Adding the elements is perfectly fine you just have to take mod(%) of the intermediate aggregate when calculating the sum of the elements and the expected sum. For the mod operation you can use something like 2n. You also have to fix the value after substraction.


text:
Q: Hadoop Mapper: Class or Interface I am a bit confused about the basic Mapper structure in Hadoop.  On the web, many example implementations use Mapper as a class and thus their classes extend Mapper.  As far as I have seen, which is Hadoop 19, Mapper is an interface.  What happened?

A: In the old API, Mappers implemented an interface as you might expect.
When the big overhaul came around, they decided to change it to a fully fledged class so that it can act as the often needed Identity Mapper if used as is, or extended for your own implementations.
It's just a matter of whether you're using the old or new API for your project, you shouldn't mix - org.apache.hadoop.mapred is the old API, org.apache.hadoop.mapreduce is the new.


text:
Q: How to make a blur transparent linear layout I have a transparent layout in android, and behind the layout there is an image. how to make the linear blur ? I found examples to make the image itself blur but I don't want to make whole image blue, just only the part that is behind the linear layout.

A: Set a semitransparent Blur image to the linear layout or simplest set a color to linear layout and set it to semitransparent by defining alpha
edited solution
do this...
1.) create a blur copy of the image u have on background.
2.) clip the image by using
Bitmap croppedBmp = Bitmap.createBitmap(originalBmp, startX, startY, widthLayout , heightOfLayout);

3.) set this image in the Linear Layout using an image-view with height and width attribute as fill-parent.

A: I have pretty complex solution, so there won't be any code. So, here is idea, step by step:

*

*Let's assume that your layout have just single custom LinearLayout. No ImageView as a background.

*What we going to do, is draw background drawable of LinearLayout by our own, so it will first draw full image and then draw blurred square from the same image on top. Content of LinearLayout might be moved to desired position using paddings.

*So, create something like MyLinearLayout and put it to your layout resource. Provide required constructors.

*Override onAttachedToWindow() and onDetachedFromWindow() methods. Inside them we should load our background Bitmap and recycle it accordingly. Let's name it mBackground

*Override draw() method. Inside it we're going to first draw our mBackground.

*Then, you can use Canvas#clipRect() method to crop drawing area of Canvas to some specified rectangle. In your case, this rectangle should be the area below your content. You can figure it out using View#getPadding*() methods. Don't forget to call canvas#save() before clipping drawing area.

*Now you can draw your bitmap once again with blur (I don't know which method exactly you're using, so let's assume that you know how to do it... but you still can share it with us :) ). Cool thing is that you can just draw the same Bitmap once again in full scale - since we had called clipRect before, it will be drawn only within this area. Don't forget to call canvas#restore() after drawing background.

*Call super.draw() to draw rest of the stuff, that your LinearLayout contains.


text:
Q: Cause of file open error with _lopen because of unexpected file lock I'm maintaining a desktop application that accesses data on servers.  Multiple users can access the same files.  We have a library that opens the files for retrieval using _lopen (C library function).  We always open read only with SHARE_DENY_NONE.
To improve performance, we keep the file open until the user exits the application.  That is when the file is closed.
However, if there is no activity for over 20 minutes, we will lose the connection to the server.  In that case we start the connection and open the file again.  Supposedly there is a file close operation called when the connection is lost, but there is no proof that the file close is called.
Unfortunately, once or twice a day users get an error message that they are unable to open a file.  We think this is because the file is locked, because we can't open it in explorer either.  The only way to clear the error is to call IISRESET so that all the file handles for retrieval are cleared.  However, today we got the error message which is a generic file open error, and we were able to open the file in explorer and also clear the problem by recycling the app pool.
Because some users get the file open error as soon as they start the application before they have done anything, we think that this problem must be caused by some other user (or process) locking the file.  We are unable to replicate the error.
I have reviewed the source code to see how the file is opened.  I have reviewed Process Explorer and the file is always accessed by our software.  I have reviewed process monitor and seen that the file is opened permitting read/write operations by other users, and that the file is closed when the application closes.  We never get the error on our development servers, but only on the production servers.  The error doesn't depend on large numbers of users, because we can't replicate it using a test program that opens the file 1000 times with 1000 different users.  Also, we have seen the error with only 9 users.
I hope someone can suggest additional tests to try or additional reasons this problem might occur.


text:
Q: The type or namespace name 'IPublishedContent' could not be found in Umbraco 8 I've media picker in Umbraco 8 and I want to display image in my cshtml page.
@inherits Umbraco.Web.Mvc.UmbracoViewPage
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Leadership

                    @foreach (var childPage in Model.Children())
                    {

                                @{
                                    var leaderImage = childPage.Value<IPublishedContent>("leaderImage");
                                }

But I am getting error :

The type or namespace name 'IPublishedContent' could not be found (are
  you missing a using directive or an assembly reference?)

I don't it is issue because of Umbraco V8 or is there anything missing?
UPDATED:

A: IPublishedContent is defined in the Umbraco.Core.Models namespace.
You should have an entry
<add namespace="Umbraco.Core.Models" />

in the system.web.webPages.razor/pages/namespaces section of Views\Web.config.

A: IPublishedContent moved again, now it resides in Umbraco.Core.Models.PublishedContent:
using Umbraco.Core.Models.PublishedContent;

A: For namespace and Library
@using Umbraco.Core.Models

For Model
@model Umbraco.Core.Models

For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)


text:
Q: The verb "take" can mean "remove" or
*

*The verb "take" can mean "remove" or it can mean "move" or it can mean "accept", depending on context.

*The verb "take" can mean "remove" or it can mean "move" or it can mean "accept".
Qa) Can I say that "can" in sentence 1) relates to a particular use of the verb in question, whose context - when established - will quickly resolve the issue of interpretation?
Qb) Can I say that "can" in sentence 2) would be a general statement of possible meanings, not related to any specific context?
Note: I know the meaning of "can" is the same in 1) and 2). I'm just concerned about the two conclusions above.


text:
Q: Changing order of integration in cylindrical coordinates I'm having a problem in changing order of integration in triple integration, in cylindrical coordinates. I would be grateful for a little help.The question is:
Let D be the region bounded below by the cone $z= \sqrt{x^2 + y^2} $ and above by the parabola $z=2-x^2-y^2$. Set up the triple integrals in cylindrical coordinates that give the volume of D using the following orders of integration.
(a) $dzdrd\theta$, (b)$drdzd\theta$, (c) $d\theta dzdr$
I drew the graph, and it looks like an ice cream cone, with radius of 1. I figured out (a), which was $ 0\leq \theta  \leq 2\pi$, $0 \leq r \leq 1$, and $r \leq z \leq 2-r^2$. which would give the equation  $\int_0^{2\pi}  \int_0^1  \int_r^{2-r^2} dzrdrd\theta $ . And this was the method that our professor taught us.
But I'm not sure what to do for (b) and (c). Which way should I look at the graph? For (b), i guess the interval of integration for $\theta$ is $ 0\leq \theta  \leq 2\pi$ but I'm not sure for $z$ and $r$.....
I thought in double integral with polar coordinates, I can't change the order of $drd\theta$. Why can I do it here?

A: For (b): $\int_0^{2\pi}\int_0^1\int_z^\sqrt{2-z}rdrdzd\theta$
For (c): $\int_0^1\int_r^{2-r^2}\int_0^{2\pi}d\theta dzrdr$
You can bring $d\theta$ anywhere with other limits remaining same due to symmetry of the problem.


text:
Q: How do I register my iOS app to open certain file types? I'm struggling on this issue, sending and receiving data by email from my ios application.
It send alright, but when I have to open ( hold tap on the file) suppose to prompt me if i want to open with my application. I set the file extension on ipz.
Here is a copy of my info-plist.
Do I miss something?
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleDocument</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleTypename</key>
        <string>iPrick List Document</string>
        <key>LSHandlerRank</key>
        <string>Owner</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>com.ipricklist.iPrickList.ipz</string>
        </array>
    </dict>
</array>
<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeIconFiles</key>
        <array>
            <string>logo1</string>
        </array>
        <key>CFBundleTypeName</key>
        <string>iPrick List Document</string>
        <key>CFBundleTypeOSTypes</key>
        <array>
            <string>com.ipricklist.iPrickList</string>
        </array>
        <key>LSItemContentTypes</key>
        <array>
            <string>com.ipricklist.iPrickList.ipz</string>
        </array>
    </dict>
</array>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFiles</key>
<array>
    <string>logo1.png</string>
    <string>Default@2x.png</string>
    <string>Default.png</string>
    <string>logo2.png</string>
</array>
<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>logo1.png</string>
            <string>Default@2x.png</string>
            <string>Default.png</string>
            <string>logo2.png</string>
        </array>
        <key>UIPrerenderedIcon</key>
        <true/>
    </dict>
</dict>
<key>CFBundleIdentifier</key>
<string>com.ipricklist.iPrickList</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSMainNibFile</key>
<string>MainWindow</string>
<key>UIFileSharingEnabled</key>
<true/>
<key>UIPrerenderedIcon</key>
<true/>
<key>UTExportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.data</string>
        </array>
        <key>UTTypeDescription</key>
        <string>iPrick List Document</string>
        <key>UTTypeIdentifier</key>
        <string>com.ipricklist.iPrickList.ipz</string>
        <key>UTTypeSize320IconFile</key>
        <string>logo1</string>
        <key>UTTypeSize64IconFile</key>
        <string>logo2</string>
        <key>UTTypeTagSpecifications</key>
        <dict>
            <key>public.filename-extension</key>
            <string>ipz</string>
            <key>public.mime-type</key>
            <string>application/iPrickList</string>
        </dict>
    </dict>
</array>
</dict>
</plist>


text:
Q: Purpose of Json schema file while loading data into Big query from a csv file Can someone please help me by stating the purpose of providing the json schema file while loading a file to BQtable using bq command. what are the advantages?
Dose this file help to maintain data integrity by avoiding any column swap ?
Regards,
Sreekanth

A: Specifying a JSON schema--instead of relying on auto-detect--means that you are ensured to get the expected types for each column being loaded. If you have data that looks like this, for example:
1,'foo',true
2,'bar',false
3,'baz',true

Schema auto-detection would infer that the type of the first column is an INTEGER (a.k.a. INT64). Maybe you plan to load more data in the future, though, that looks like this:
3.14,'foo',true
1.59,'bar',false
-2.001,'baz',true

In that case, you probably want the first column to have type FLOAT (a.k.a. FLOAT64) instead. If you provide a schema when you load the first file, you can specify a type of FLOAT for that column explicitly.


text:
Q: How to configure TextWrapping for CheckBox control? I need to set TextWrapping for CheckBox like for TextBlock, but CheckBox hasn't TextWrapping property. How to configure TextWrapping for CheckBox?
<Grid>
    <ListBox>
        <TextBlock Text="{Binding LocalizedResources.CleanCity, Source={StaticResource LocalizedStrings}}" Foreground="Black" FontSize="32" FontWeight="Bold"/>
        <CheckBox x:Name="c1" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <CheckBox x:Name="c2" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <CheckBox x:Name="c3" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <CheckBox x:Name="c4" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <CheckBox x:Name="c5" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <TextBlock Text="{Binding LocalizedResources.SafeCity, Source={StaticResource LocalizedStrings}}" Foreground="Black" FontSize="32" FontWeight="Bold"/>
        <CheckBox x:Name="c6" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <TextBlock Text="{Binding LocalizedResources.ComfortableCity, Source={StaticResource LocalizedStrings}}" Foreground="Black" FontSize="32" FontWeight="Bold"/>
        <CheckBox x:Name="c7" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <CheckBox x:Name="c8" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
        <CheckBox x:Name="c9" Foreground="{StaticResource CustomApplicationTextBrush}" Background="#BFC2E2FD"/>
    </ListBox>
</Grid>

Thank you!

A: Checkbox can be declared like this as well
        <CheckBox>
            <TextBlock>
                Hi
            </TextBlock>
        </CheckBox>

Now textblock supports textwrapping :)
Edits
           <CheckBox>
            <CheckBox.Content>
            <TextBlock TextWrapping="Wrap" Width="100">
                Hi fkffk kffk f fkfkf fk kfhkf fkf kf fkfk
            </TextBlock>
            </CheckBox.Content>
          </CheckBox>

the above edit would enable checking unchecking on tapping the textblock.
to set the text from code behind
(yourcheckbox.Content as Textblock).Text="Hi world!";

A: You can always add textblock inside checkbox like this.
<CheckBox>
    <TextBlock Width="250" TextWrapping="Wrap">
               Write your text here and wrap it whenever you want..!!
    </TextBlock>
</CheckBox>

Note : This will not allow you to check/uncheck box when you click on text.

A: You can use float: left; in your css file
You can refer this JSfiddle Link (http://jsfiddle.net/davidThomas/9s8Db/10/) . this will help you for sure..!


text:
Q: If there is a program that communicates to many different IPs on port 4000, how can I restrict that to just a few IPs? I have a program that communicates with other PCs as well as a central server to handle all of it on port 4000. What I want to do is make it so that the program doesn't communicate with all those different PCs, just 1 of them and the central server.
I'm running Ubuntu 16.04. Could someone help me with this?
Thanks.

A: There are a lot of good HowTo documents and guides online; I prefer the Digital Ocean tutorials myself and recommend them highly.
How To Set Up a Firewall with UFW on Ubuntu 16.04
There are some things you need to consider before diving into any sort of generic tutorial. Make sure you understand exactly what the program you are constraining is trying to do.
Understanding how a program initiates a session between your local machine and the remote server is important. You mention 4000/tcp: is this the port the server listens on? Does the server establish another connection back to your local computer on 4000/tcp? If yes, then you need to enable 4000/tcp both inbound and outbound to your only your trusted IPs. Why are other machines trying to connect to your local machine on 4000/tcp if it is not the server?
I would dig deeper into the application documentation and make sure you understand how and why all the different machines are trying to talk to the server and your local machine, if that is intentional or not, and what consequences blocking 4000/tcp to everything but the server and one other peer can have.


text:
Q: Field of algebraic numbers over Q with p-adic value
Define $\overline{\mathbb{Q}} \subset \mathbb{C}$ to be the subset consisting of all complex numbers which are algebraic over $\mathbb{Q}$. We know that $\overline{\mathbb{Q}}$ is a countable field and that is algebraically closed.

*

*Show that there exists a sequence of finite extensions $E_{0}=Q  \subset E_{1} \subset \ldots \subset E_{n} \subset \ldots \overline{\mathbb{Q}}$, i.e. each $E_{i}/E_{i-1}$ is a finite exntesion and $\overline{\mathbb{Q}} = \cup_{n} E_{n}$.

*(Using the above) show that for any prime $p$, the $p$-adic absolute value extends to an absolute value on $\overline{\mathbb{Q}}$.

So, I proved 1 (just define $E_{i} = \mathbb{Q} (a_{1}, a_{2},\ldots, a_{i}$, where $\overline{\mathbb{Q}} = \left\{a_{1}, a_{2},\ldots\right\}$ ), but I don't know how to formalize $2$. Of course, using the fact that every nonarchimedean absolute value on a field, extends in at least one way to every finite extension, we get an extension of the p-adic valuation on each $E_{n}$, but I don't see how to end $2$. Perhaps, a continuity argument?
Thanks.

A: As you say, you get an extension of the $p$-adic valuation to each $E_n$, and every element of Q-bar is in $E_n$ for some $n$, so you have extended the $p$-adic valuation to Q-bar, haven't you?

A: Note that the extension of the $p$-adic valuation to $E_n$ is typically not unique; the possible extensions are in bijection with the number of primes in the ring of integers of $E_n$ lying over the prime $p$.
So for each $n$ there is a (non-empty!) finite set $S_n$ of extensions of the $p$-adic valuation to $E_n$.  Restricting an extension from $E_{n+1}$ to $E_n$ gives a map $S_{n+1} \to S_n$.  So you have a projective sequence of finite sets
$$ \cdots \to S_{n+1} \to S_n \to \cdots \to S_1 \to S_0$$
and you are trying to choose an element from each in a compatible fashion, i.e. you are trying to choose an element in the projective limit.  This will be possible if (and only if!) the projective limit is non-empty.
Added: As Gerry points out in (the comments to) his answer, these maps are
surjective, and so one can just successively choose an element of each $S_n$
that maps to the previous choice in $S_{n-1}$; this gives the desired extensino.
Earlier unnecessary discussion:
General fact: the projective limit of a projective sequence of non-empty finite sets is always non-empty.
Proof: A special case of a more general fact about projective limits called the Mittag--Leffler property, which is also pretty easy to prove directly (although not completely trivial if you've never thought about this kind of things before).
Added: When the maps $S_{n+1} \to S_n$ are surjective (as they are in our context), this really
is trivial; as was already noted above in this special case, just choose a point in each $S_{n+1}$ mapping to the previous choice in $S_n$!


text:
Q: Won't a potentiometer powered by a dc supply cause a short-circuit at lower end of the range? Many tutorials in the Arduino or Raspberry Pi community simulate an analog sensor with a potentiometer. The potentiometer, being a passive device, is powered from the same DC power source that supplies the microcomputer. Usually, the +5V (or +3.3V) and GND pins on the Arduino or Pi are used for this purpose.
This doesn't seem safe to me. Suppose we turn the potentiometer all the way down in this configuration. The resistance should be 0 Ohms and that should short the DC power supply. Yet, this is just what many tutorials like this one here recommend: https://www.instructables.com/id/How-to-use-Potentiometer-Arduino-Tutorial/
How come? I always include a resistor in series with the potentiometer to avoid this situation but no one else seems to think this necessary. Thanks in advance for any help.

A: A potentiometer has three terminals. The two extremes of the resistive element and the central wiper.
The resistive element always has the same resistance. So it is safe to connect those two extremes to the power supply.
That way the wiper will change the voltage continuously from the supply to ground.

A: Common use of a potentiometer involves applying a voltage across it, and then the "wiper" (the moving part) in the middle will have a "divided" voltage. It is essentially two resistors with a wire (wiper) in the middle.
This means that for any given supply voltage, there is a constant resistance across the whole potentiometer. The example on the left below has a 5V supply, and a 1kΩ potentiometer. 5V/1000Ω=5mA The wiper however will have a varying resistance.
The example on the right is what you were thinking of (Use of only the wiper and one other terminal). Observe that it does not divide the voltage.  And yes: The current will indeed exceed a safe value when the wiper goes too far.

Here is a link to the interactive simulation of the circuit above. You can drag the slider on the right to move the potentiometer's wiper. While your cursor hovers over the slider, you can see the values of "R1" and "R2", which always add up to 1k.


text:
Q: Xamarin builds failed with Xcode 8 I got the this error when rebuild Xamarin iOS after updating UI using Xcode 8:
Xamarin.iOS.Common.targets: Error: Error executing task DetectSdkLocations
I'm using Xcode Version 8.0 (8A218a)
Xamarin 6.1 build 5441,
Xamarin.iOS,
Version: 10.0.0.6 (Xamarin Studio Community),
Hash: 6c3fee4,
Branch: xcode8,
Build date: 2016-09-09 13:01:32-0400
Anyone can help?

A: I finally found the solution by Opening Preferences and choose right SDK Location (Xcode.app).

Restart Xamarin Studio to take effect.
Hope this help anyone has this issue.


text:
Q: Switching between pages does not work on a react app that is deployed on Netlify I created a react project and ran npm run build  in terminal so I could deploy it on Netlify.
If I run npx serve -s build in terminal and open the link, page works as expected.
When I deploy build on Netlify everything works fine until I try switching pages. I get an error where it says Page not found.
I haven't tried anything else after deploying the page on Netlify since I have no clue what could be the problem.


text:
Q: How to customize error pages for all 4xx and 5xx error status for Drupal 9? I know Drupal 9 offers custom error pages for 404 and 403, but how can I create error pages for other errors like 500, 503 - to be more precise, like all 4xx and 5xx errors?
I found this module - https://www.drupal.org/project/error_page installed and configured by adding this line of code:
set_error_handler(['Drupal\error_page\ErrorPageErrorHandler', 'handleError']);
set_exception_handler([
  'Drupal\error_page\ErrorPageErrorHandler',
  'handleException',
]);
// Log the UUID in the Drupal logs.
$settings['error_page']['uuid'] = TRUE;
// Your templates are located in path/to/templates, one level above the webroot.
$settings['error_page']['template_dir'] = DRUPAL_ROOT . '/../path/to/templates';

but I didn't see any changes. Can anyone help me with this module, or is there any other way that I can customize pages for all error status?


text:
Q: RESTORE HEADERONLY is terminating abnormally I am unable to restore my database. I am getting this error message:

RESTORE HEADERONLY is terminating abnormally(Microsoft SQL Server, Error: 3242

Please help with a solution. Version is 2008. Am trying to restore it on same version.

A: An earlier version of SQL Server doesn't understand a later version's backups. Note that SQL Server 2008 is a different version from SQL Server 2008 R2.
That is one possibility to why it fails.
If that isn't the case, then you have a corrupt backup, quite simply. You can try to produce a new backup (from the same or a different database) and see what happens when you try to restore that one. But the on that gives you an error message isn't healthy! The error message is evidence of that.
And remember to always include the full error message, including possible error messages from this operation found in the errorlog file.


text:
Q: Compilation problems while learning React DND I am starting to learn React Drag and Drop from http://react-dnd.github.io/react-dnd/docs-tutorial.html
But I am having problems understanding the tutorial. Next are all the files I created but at compilation I get:
 dragDropBundle.js:830 Warning: Failed prop type: The prop
  `connectDropTarget` is marked as required in `BoardSquare`, but its value is `undefined`.
   in BoardSquare (created by Board)
   in Board (created by DragDropContext(Board))
   in DragDropContext(Board)

and
dragDropBundle.js:31408 Uncaught TypeError: connectDropTarget is not a function
  at BoardSquare.render (dragDropBundle.js:31408)
  at dragDropBundle.js:16370

Can someone explain me please what is wrong? I am reading this tutorial several times and hitting the wall with it.
Here it is the content of my file entry.js from where my program starts:
import React from "react";
import ReactDOM from "react-dom";
import Square from "./Square.jsx";
import Board from "./Board.jsx";
import Knight from "./Knight.jsx";

import { observe } from "./Game.jsx";
import { canMoveKnight, moveKnight } from "./Game.jsx";

const rootEl = document.getElementById("root");

observe(knightPosition =>
  ReactDOM.render(<Board knightPosition={knightPosition} />, rootEl)
);

Here it is the content of my file Board.jsx:
import React, { Component } from "react";
import { DragDropContext } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";

import PropTypes from "prop-types";
import Square from "./Square.jsx";
import Knight from "./Knight.jsx";
import { canMoveKnight, moveKnight } from "./Game.jsx";
import { BoardSquare } from "./BoardSquare.jsx";

export class Board extends Component {
  renderPiece(x, y) {
    const [knightX, knightY] = this.props.knightPosition;
    if (x === knightX && y === knightY) {
      return <Knight />;
    }
  }

  renderSquare(i) {
    const x = i % 8;
    const y = Math.floor(i / 8);
    return (
      <div key={i} style={{ width: "12.5%", height: "12.5%" }}>
        <BoardSquare x={x} y={y}>
          {this.renderPiece(x, y)}
        </BoardSquare>
      </div>
    );
  }

  handleSquareClick(toX, toY) {
    if (canMoveKnight(toX, toY)) {
      moveKnight(toX, toY);
    }
  }

  render() {
    console.log(this.props.knightPosition);
    const squares = [];
    for (let i = 0; i < 64; i++) {
      squares.push(this.renderSquare(i));
    }

    return (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexWrap: "wrap"
        }}
      >
        {squares}
      </div>
    );
  }
}

Board.propTypes = {
  knightPosition: PropTypes.arrayOf(PropTypes.number.isRequired).isRequired
};

export default DragDropContext(HTML5Backend)(Board);

Here it is the content of my file Knight.jsx:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { ItemTypes } from "./Constants.jsx";
import { DragSource } from "react-dnd";

const knightSource = {
  beginDrag(props) {
    return {};
  }
};

function collect(connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging()
  };
}

class Knight extends Component {
  render() {
    const { connectDragSource, isDragging } = this.props;
    return connectDragSource(
      <div
        style={{
          opacity: isDragging ? 0.5 : 1,
          fontSize: 25,
          fontWeight: "bold",
          cursor: "move"
        }}
      >
        ♘
      </div>
    );
  }
}

Knight.propTypes = {
  connectDragSource: PropTypes.func.isRequired,
  isDragging: PropTypes.bool.isRequired
};

export default DragSource(ItemTypes.KNIGHT, knightSource, collect)(Knight);

Here it is the content of my file Square.jsx:
import React, { Component } from "react";
import PropTypes from "prop-types";

export default class Square extends Component {
  render() {
    const { black } = this.props;
    const fill = black ? "black" : "white";
    const stroke = black ? "white" : "black";

    return (
      <div
        style={{
          backgroundColor: fill,
          color: stroke,
          width: "100%",
          height: "100%"
        }}
      >
        {this.props.children}
      </div>
    );
  }
}

Square.propTypes = {
  black: PropTypes.bool
};

Here it is the content of my file: BoardSquare.jsx
import React, { Component } from "react";
import PropTypes from "prop-types";
import Square from "./Square.jsx";
import { canMoveKnight, moveKnight } from "./Game.jsx";
import { ItemTypes } from "./Constants.jsx";
import { DropTarget } from "react-dnd";

const squareTarget = {
  drop(props) {
    moveKnight(props.x, props.y);
  }
};

function collect(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver()
  };
}

export class BoardSquare extends Component {
  render() {
    const { x, y, connectDropTarget, isOver } = this.props;
    const black = (x + y) % 2 === 1;

    return connectDropTarget(
      <div
        style={{
          position: "relative",
          width: "100%",
          height: "100%"
        }}
      >
        <Square black={black}>{this.props.children}</Square>
        {isOver && (
          <div
            style={{
              position: "absolute",
              top: 0,
              left: 0,
              height: "100%",
              width: "100%",
              zIndex: 1,
              opacity: 0.5,
              backgroundColor: "yellow"
            }}
          />
        )}
      </div>
    );
  }
}

BoardSquare.propTypes = {
  x: PropTypes.number.isRequired,
  y: PropTypes.number.isRequired,
  connectDropTarget: PropTypes.func.isRequired,
  isOver: PropTypes.bool.isRequired
};

export default DropTarget(ItemTypes.KNIGHT, squareTarget, collect)(BoardSquare);

A: Your error is caused by this props type setting:
BoardSquare.propTypes = {
  // ...
  connectDropTarget: PropTypes.func.isRequired,
  //                               ^^^^^^^^^^^ property connectDropTarget is market as required
  // ...
};

Which marks connectDropTarget as a required prop in BoardSquare.
What should happen is that, because you wrap BoardSquare into a DropTarget, the DropTarget knows to set the value for connectDropTarget in the props of BoardSquare through the collect function.
However, what you are doing is using the barebones BoardSquare function, not the one wrapped in DropTarget.
// Board.jsx
import {BoardSquare} from './BoardSquare.jsx';
//     ^           ^ you are importing BoardSquare, not DropTarget(...)(BoardSquare)

This should be:
// Board.jsx
import BoardSquare from './BoardSquare.jsx';

So this means that, since you're not using the component wrapped in DropTarget, nothing is calling the collect function and thus nothing is setting the connectDropTarget prop.
To clean things up, you can probably remove the export of the barebones class from BoardSquare and only export the class wrapped in DropTarget:
// BoardSquare.jsx
export class BoardSquare extends Component {
// ^^^ remove this export statement


text:
Q: Git checkout master ; impossible I have a question, Ive cloned a repo from GitHub, and someone told me to switch the branch to master to apply new patch, like update kernel and after re switch to the repo branch.
But I don't know why I can't switch to master, do you know why?
I've tried some methods that I found here and there but still impossible.
EDIT: Adding pic, we see he used master branch except the 21.02 open wrt branch.

$ git checkout master
error: pathspec 'master' did not match any file(s) known to git
$ git fetch
$ git checkout master
error: pathspec 'master' did not match

A: Try a git branch -r to see what branches are available.  Odds are they didn't use "master" as a branch name, and you need to adjust your git checkout xxxx command to match the branch name they used.

A: If you need to make a contribution to the openwrt/openwrt repository, branch master:

*

*install GitHub CLI gh

*Create a Personal Access Token if you hadn't one already

*use gh auth login to authenticate yourself to GitHub
echo myToken | gh auth login --with-token

*fork and clone the original repository (if you had not already created a fork), with gh repo fork
gh repo fork openwrt/openwrt --clone --remote --renamote-name upstream

*create a local branch from the upstream repository
git switch -c myFix upstream/master
# work and add commits

*create a Pull Request from your current work from myFix branch, with gh pr create:
gh pr create --title "The bug is fixed" --body "Everything works again" -b master


text:
Q: ANDROID: access variable in paused activity Let's say we have an Android app that consists of a MainActivity, and also a bound intent service (or any other background service that continues to run while MainActivity is paused).
Lets say we have some variables belonging to MainActivity, MainAcitivity.variable1, and MainActivity.variable2.
Is it safe/normal to update these variables from the background service while MainActivity is paused?  I know that it works without errors, but it seems strange to me that it is possible to interact with a class/thread that is "asleep."  If you send multiple updates while Main is paused, do they all end up in a buffer that gets dealt with when Main is resumed?  or do the updates happen immediately?
What technical subject to these questions have to do with?
Thankyou!!

A: You shouldn't get used to this. simply because your Service will not be able to see your Activity's variable when the app is closed.
A very good solution is to cache the changes made by the Service in local storage, and use BroadcastReciever to update the Activity if it is running. In addition to that, the Activity should get data from the storage in the onResume() method and update the UI accordingly.