text:
Q: Pegar o valor do input na mesma página com PHP td bem?
Tenho um script em PHP que converte o CEP em Coordenada e gostaria que ele convertesse automaticamente de acordo com o valor de um input.
<input type="text" value="" id="cep" >
<input type="text" value="" id="latitude">
<input type="text" value="" id="longitude">
<?php
    $cep = '01311-100';
    $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$cep.'&sensor=false');
    $output= json_decode($geocode);
    $lat = $output->results[0]->geometry->location->lat;
    $long = $output->results[0]->geometry->location->lng;
    echo $lat;
    echo $long;
    ?>

Nesse acima ele transforma o cep do $cep em coordenada, mas queria que ao inserir o cep no input ele já convertesse e colocasse a latitude e longitude nos inputs correspondentes.
Esses valores serão inseridos em uma tabela mysql.
Obrigado!

A: Fazendo requisição ajax pra obter a latitude e longitude do CEP dinamicamente:

$('#cep').keyup(function() { // Dispara a função quando um caracter é digitado
  if(this.value.length > 7) { // Checa se o campo cep tem mais de 7 caracteres

    // Requisição ajax.
    var request = $.ajax({
      url: "https://maps.google.com/maps/api/geocode/json?address=21331009",
      method: "GET",
      dataType: 'json'
    });

    // Executa caso tenha sucesso na requisição.
    request.done(function( response ) {
      let location = response.results[0].geometry.location; // Obtém os valores de latitude e longitude

      // Muda adiciona os valores nos campos correspondentes
      $('#latitude').val(location.lat);
      $('#longitude').val(location.lng);
    });

    // Executa caso a requisição falhe.
    request.fail(function() {
      alert('Erro');
    });
  } else { // Limpa latitude e longitude caso o cep esteja incompleto
    $('#latitude').val('');
    $('#longitude').val('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" id="cep" maxlength="8" placeholder="Digite o CEP aqui...">
<input type="text" value="" id="latitude" readonly>
<input type="text" value="" id="longitude" readonly>


text:
Q: Java EAR project containing multiple JARS I was assigned to work with ten year old legacy Java project. The code base is huge and it's my first encounter with big enterprise project.
I'm confused about the project structure, as there are dozens of something.jar called directories inside src/application.ear directory, each of these jar folders containing it's own ant build and configuration. Yet the final build will be single ear. Is the rationale for building jars from different subsystems to ship them to possibly integrated system? Is this some common pattern to name the folders by the jar names?

A:
Is the rationale for building jars from different subsystems to ship them to possibly integrated system?

Yes,

EAR (Enterprise ARchive) is a file format used by Java EE for packaging one or more modules into a single archive so that the deployment of the various modules onto an application server happens simultaneously and coherently.

In the J2EE world, an entreprise application can be composed of web modules, ejb modules, etc.
So (and this is me guessing), the directories called something.jar can be submodules of the enterprise application o library modules required by the application (EAR)...

Is this some common pattern to name the folders by the jar names?

I don't really. I never had seen before. But I understand the purpose of such layout. The purpose is to encapsulate the files (build.xml -- ant tasks) that build some artefact called something.jar ("required by the EAR app, perhaps?"). So using this layout, a developer can easily identify which build file (build.xml) constructs what artefact. Also, using this layout, a developer can define a master build script that coordinates the order and execution of the other build scripts (EAR submodules).
So, in other words, you're watching a "pseudo" Maven framework, using ANT as implementation...
May be is time to start migrating this old application to the maven model!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the norm of the Banach space projective tensor product of finite-dimensional C*-algebras a C*-norm? Let $A$ and $B$ be two finite-dimensional C*-algebras.
Let $\gamma$ denote the projective Banach space tensor product norm on the algebraic tensor product $A\odot B$, so $\gamma(t)=\inf\{\sum_{i}\|a_i\|\|b_i\|:t=\sum_i a_i\otimes b_i\}$. Then $\gamma(ts)\leq\gamma(t)\gamma(s)$ and $\gamma(t^*)=\gamma(t)$, but does $\gamma$ also satisfy $\gamma(t^*t)=\gamma(t)^2$?
I know that $\gamma$ should be equivalent to the C*-algebra norm on $A\odot B$, since all norms on finite-dimensional spaces are equivalent, but I would like to have equality, since this would imply that the embedding of finite-dimensional C*-algebras with subunital completely positive maps in the category of Banach spaces with contractions and with the projective tensor product as a monoidal product is a strong monoidal functor.

A: I think there are various reasons from abstract tensor norm theory why this is impossible, but I'll try to give a concrete example. First, a $C^*$-norm on an algebra is uniquely determined; therefore, if $A=\ell_\infty(2)=\mathbf C^2$ with the max-norm, then the tensor norm on $A\otimes A$ is the injective tensor norm $\otimes_\varepsilon$, identifying $A\otimes A$ isometrically with $\mathbf{C}^4$ in the max-norm. (If $A=C(K)$, then $A\otimes_\varepsilon A = C(K\times K)$.) So we have to argue that $\otimes_\gamma$ is not $\otimes _\varepsilon$ in this example.
For this let us compare the duals; $(\ell_\infty(2)\otimes_\gamma  \ell_\infty(2))^* = L(\ell_\infty(2), \ell_1(2)) =: X$ and $(\ell_\infty(2)\otimes_\varepsilon  \ell_\infty(2))^* = (\ell_\infty(2; \ell_\infty(2))^* = \ell_1(2; \ell_1(2)) := Y$. Specifically, consider the element of the dual represented by $(\alpha,\beta)\mapsto \alpha (1 , 1) + \beta (1,-1)$. The norm of this element in $Y$ is $\|(1,1)\|_1 +  \|(1,-1)\|_1 = 4$, but the norm in $X$ is $\max_{|\alpha|,\beta|\le 1}  \|\alpha(1,1)+\beta(1,-1)\|_1= \max_{\alpha,\beta} (|\alpha+\beta|+|\alpha-\beta|)<4$.
So the norms are isometrically different.
PS: I read Yemon's comment, which practically says the same as mine, only after having typed this$\dots$.


text:
Q: Is there a posibillity to import own data into google analytics? I want to compare own data with data generated by google analytics. For example I want to see the number of my twitter followers compared with my page visitors per day.
Is there a way to do something like this?

A: As far as I'm aware, it is not possible to import your own data into Google Analytics. You can however export data from Google Analytics and compare it with your own data in Open Office, Excel or another graphing solution.
Google Analytics - Data Export API - Java (v2) - http://analytics.blogspot.com/2009/08/analytics-data-in-excel-through-our-api.html
Google Analytics Blog - Analytics Data In Excel Through Our API - http://code.google.com/apis/analytics/docs/gdata/2.0/gdataJava.html
Google Analytics - How to export an Analytics Report - http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=57161
SEOmoz - How to Export Google Analytics Data to Excel via the API - http://www.seomoz.org/blog/how-to-export-google-analytics-data-to-excel-via-the-api

A: Check out http://megalytic.com.  You can download both Google Analytics and Twitter into the same Excel workbook.  Handles Facebook, Omniture, and others as well.

A: You could write a script which runs daily on a server and connects to Twitter to measure the number of followers and then uploads the number of followers to Google Analytics. You could also report an event to Google Analytics when you get a new follower or when a follower unfollows you.
There are several options to upload data into Google Analytics:
1. Use a library which implements the ga.js script server-side
When you use Google Analytics in the way described by Google, you include a script on your website. This script sends data from the visitors browser to the Google Analytics server.
This script has been reverse engineered and implemented in server-side libraries. Now you can send the same data from the server to the Google Analytics server. You can use PHP-GA for PHP or pyga for Python.
2. Use the Google Analytics measurement protocol
The Google Analytics measurement protocol is a new API to send data to Google Analytics. You can send data by sending POST requests to the API.

A: For a high-level overview, you could use SWIX - I haven't tried it, but it allows you to make dashboards with input from a bunch of pre-generated sources, including Twitter, Facebook & GA. I suspect that you could build something similar with YouCalc as well, but it should work out of the box with SWIX.

A: If you are willing to use Google Spreadsheets (which I can recommend) You can use a simple script to import your Analytics data automatically.
Here is a complete rundown of how to set it up: http://spreadsheetpro.net/how-to-import-google-analytics-data-into-google-spreadsheets-in-3-simple-steps/

A: You can use the Measurement Protocol to import your own data in near real-time. It doesn't support loading data more than 4 hours old though (see the Queue Time parameter). So you would need to run updates regularly.

A: Google Analytics supports many different Data Import use cases, which can be carried out both through the API and through Web Interface. You particular use case might not be supported currently, but perhaps you still could garner incites through some combination of the Measurement Protocol and User Data Import.


text:
Q: Union find algorithm in Kruskals algorithm How does these two functions work ?
The time complexity of the function find is O(log n) assuming that the length
of each chain is O(log n). In this case, the functions same and unite also work in
O(log n) time. The function unite makes sure that the length of each chain is
O(log n) by connecting the smaller set to the larger set.
Can someone explain how with an example ?
int find(intx) {
while(x != k[x]) x = k[x];
returnx;
}

bool same(inta,intb) {
returnfind(a) == find(b);
}

void unite(inta,intb) {
a = find(a);
b = find(b);
if(s[a] < s[b]) swap(a,b);
s[a] += s[b];
k[b] = a;
}

A: You get O(log n) complexity vs. O(n) because you're always connecting the smaller set to the larger set (vs. the larger to the smaller) in the unite() function. If one set is equal to or smaller than another, the biggest the smaller set can be is the size of the larger (worst case), but will often be smaller. For example, if there are 20 elements total, the two sizes could be 1 and 19, 2 and 18, all the down to 10 and 10. The net is that when you unite two clusters, it will, at most, double in size, which means it adds, at most one level to its depth. Hence, going up the tree will take at most log2N steps b/c that's the max depth.


text:
Q: How to create a generic return type for an abstract class override method I have an abstract class that gets implemented by Java and by Android.  This class has a method that needs to return a generic Cursor so that the implementations can return their respective cursors.
My abstract class:
public abstract class DatabaseAdapter {

protected abstract com.domain.database.Cursor<?> executeQuery(String command);

}

The cursor type:
public final class Cursor<T> {

private T value = null;

public void setValue(T value) {
    this.value = value;
}

public T getValue() {
    return value;
}
    }

As stated earlier, I want the implementing method to return either a Java cursor or and Android cursor depending upon the situation.  I can create the abstract classes just fine but when I try to implement, I get a compile error.  I am apparently not understanding polymorphism very well here.
The implementing method
public Cursor executeQuery(String query){
Cursor cursor = db.rawQuery(query, selectionArgs);
return cursor;
}

where Cursor is android.database.Cursor

A: I guess you can remove com.domain.database.Cursor, but I may be wrong.
My solution is to make DatabaseAdapter generic, not Cursor.
/**
 * @param C the type of the Cursor this adapter returns
 */
public abstract class DatabaseAdapter<C> {
    protected abstract C executeQuery(String command);
}

Then you implement like this:
public class AndroidDatabaseAdapter extends DatabaseAdapter<android.database.Cursor> {
    public Cursor executeQuery(String query){
        Cursor cursor = db.rawQuery(query, selectionArgs);
        return cursor;
    }
}


text:
Q: Is there a way to morph a Laravel Eloquent model? I have a Detail (represents order details) model that I'd like to morph to either a sales order detail or a purchase order detail. So I create a table that has a 'type' column, which would have a value of 'sale' or 'purchase'.
My question is, is there a way in Laravel that I could morph the Detail model to Sale and Purchase, so that, for example, if I call App\Sale::all() it would fetch App\Detail::all()->where('type','sale') ?

A: Set the database tables:
You can set up your database tables in this structure :
purchases
    id - integer
    price - string

sales
    id - integer
    price - integer

details
    id - integer
    description - string
    detailable_id - integer
    detailable_type - string

Set your models:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Detail extends Model
{

    // Get all of the owning detailable models.
    public function detailable()
    {
        return $this->morphTo();
    }
}

class Sale extends Model
{

    // Get all of the sales member's order details.
    public function details()
    {
        return $this->morphMany('App\Detail', 'detailable');
    }
}

class Purchase extends Model
{

    // Get all of the purchase's order details.
    public function details()
    {
        return $this->morphMany('App\Detail', 'detailable');
    }
}

Retrieve data :
And then you can retrieve your sales like this :
$sales = App\Sale::find(1);

foreach ($sales->details as $order_detail) {
    //
}

Same thing with purchases :
$purchases = App\Purchase::find(1);

foreach ($purchases->details as $order_detail) {
    //
}

More about polymorphic relations : http://laravel.com/docs/5.1/eloquent-relationships#polymorphic-relations

A: Although I haven't found an "official" way to morph a single class to another. I developed the following way that could be a solution.
First, define two models Sale and Purchase that extends Detail, and use the trait that will define later.

    class Sale extends Detail {
        use SaleTrait;
    }

Then, use GlobalScope to add constraints to query builder. Here are the steps:

*

*Define a trait for Sale and Purchase model,

    trait SaleTrait {
        public static function bootSaleTrait()
        {
            static::addGlobalScope(new ActiveEventsScope);
        }
    }

*Then define the scope. NOTE: here instead of implementing ScopeInterface, I extends Sofa\GlobalScope which handles remove() method for me, so I only need to define apply() in the scope.

    class SaleScope extends GlobalScope
    {
        public function apply(Builder $builder, Model $model)
        {
            $builder->where('type', 'sale');
        }
    }

*Now I could use App\Sale::all() and App\Purchase::all() to only retrieve what I want.


text:
Q: asp.net mvc - UI for nested data I am writing a information system for a neighborhood charitable organization, as the server side wil be Asp.net MVC.
Beyond that there is no special requirement of the client UI design technolgy or Appearance,  it's my choice, including integrating third-party libraries/tools/technolgies.
At income and updating mode,  the user chooses a family, then puts its data: number of family members, income support organization, etc.
Then for each family member, he puts the information containing various personal details and reason for support.
For each reason for support, will be introduced various details including the amount required, tracking and more.
To sum up, The data is nested one inside the other: family => family member => reason to support => different information.
There are a more smaller number of nesting information.
I am looking for recomendations for a simple and fast building UI way.
I should point out that because I am doing the project on a voluntary basis, outside working hours ,I find it difficult to lern a new a technology that requires lengthy study and practice.
Thanks in advance.

A: You can use accordion for main family details.
On click accordion item, bind family member details.
On click family member bind reason to support in below other div
All above listing should be load on click,should not be load at first time.


text:
Q: Reading or writing multiple files using vhdl textio I have successfully written a vhdl code to read and write a file. Basically I read a file, process the data in the file and write the results to another file.
Now I want to extend my program to reading multiple testcases. For example the data will be available in different files named 1.txt, 2.txt, and so on till 100.txt.
I want to use a loop to read the data from the files one by one and write the output to different files. Can any one help?
type i1 is file of character;
file f1 : i1 open READ_MODE is "1.txt";

this is the type of code i have used for reading the file. How to extend it for array of files?

A: My blog here http://parallelpoints.com/node/66/ shows how to open files from within a function and read the data.
You can pass filenames as string type to a function and use text files:
file file_variable : text;

and...
file_open(file_variable, filename, read_mode);

to open it.
Beware, if you are reading binary files, different simulators behave in different ways.  Modelsim will do what you (probably) expect.  I've had GHDL fall over when an EOF character is read.  And Xilinx's simulator expects a special header on the file!
It's most portable to stick to pure text, even if you have to pre-process it.

A: I can't try this at home, so this may not work - have you tried to move your code into a procedure, with the file's name as a parameter? Then you would be able to wrap it in a simple for loop, and it won't try to do it all in parallel like it would if you have the filename as a generic in a generate loop.

A: procedure read_sample_file
   (
      file_name : in string;
      ...
   ) is
      file msgFile : text;
      ...
   begin
      file_open( msgFile, file_name, READ_MODE );


text:
Q: Json object in Camel exchange header not correctly converting to string So I'm trying to split a json array with some metadata and append the metadata to each object in the array:
{
  "@version":"1",
  "metadata":{"key1":"value1","key2":"value2"},
  "messages":[{"msg":{...}},{"msg":{...}}, ... ]
}

to
{
  "type":"msg",
  "data":{
    "@version":"1",
    "metadata":{"key1":"value1","key2":"value2"},
    "msg":{...}
  }
}

I have the following Camel route which almost works:
from("direct:kafkaMsg")
    .routeId("rKafkaMsg")
    .log(DEBUG, "JSON: ${body}")
    .setHeader("@version").jsonpath("$.@version")
    .setHeader("metadata").jsonpathWriteAsString("$.metadata") // not writing as string
    .split().jsonpathWriteAsString("$.messages..msg")
        .setHeader("msgId", jsonpath("$.msgNo"))
        .setHeader("kafka.KEY", simple("${header.msgId}"))
        .setBody(simple("{\"type\":\"msg\","
            + "\"data\":{\"@version\":\"${header.@version}\",\"metadata\":${header.metadata},"
            + "\"msg\":${body}}}"))
        .log(DEBUG, "body: ${body}")
        .log(INFO, "msgPush: writing msg to kafka - msgId: ${header.msgId}")
        .setProperty(Exchange.CHARSET_NAME, constant("UTF-8"))
        .to("kafka:sometopic?partitioner=" + DefaultPartitioner.class.getName())
    .end();

But the Json I actually get like this is:
{
  "type":"msg",
  "data":{
    "@version":"1",
    "metadata":{key1="value1",key2="value2"},  // wrong. This looks like mapToString
    "msg":{...}
  }
}

When I had .split().jsonpath("$.messages..msg") before, the 'msg' object was also wrongly formatted in the output but jsonpathWriteAsString() helped in this case. I also tried jsonpath("$.metadata", String.class) but it did not help.
Does anybody know how to fix this? Thanks.

A: I solved this using a workaround involving a Processor:
.split().jsonpath("$.messages..msg")
    .setHeader("msgId", jsonpath("$.msgNo"))
    .setHeader("kafka.KEY", simple("${header.msgId}"))
    // Processor instead of setBody()
    .process(exchange -> {
        JsonObject data = new JsonObject();
        data.put("@version", exchange.getIn().getHeader("@version"));
        data.put("metadata", exchange.getIn().getHeader("metadata"));
        data.put("msg", exchange.getIn().getBody());
        JsonObject body = new JsonObject();
        body.put("type", "msg");
        body.put("data", data);
        exchange.getOut().setBody(body.toJson());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());
    })

I prefer this solution anyway because I don't have to write part of the json string myself.


text:
Q: How to load type-2 JDBC driver by registerDriver( ) method? I am trying to load Type-2(Native API) driver by registerDriver(); method. But it says OracleDataSource cannot be converted to Driver.
 import java.sql.DriverManager;
    import java.sql.SQLException;

    import java.util.Enumeration;
    public class Driver2_Load2
    {
        public static void main(String[] args) throws SQLException
        {
            oracle.jdbc.pool.OracleDataSource d = new oracle.jdbc.pool.OracleDataSource();
            DriverManager.registerDriver(d);

            Enumeration e = DriverManager.getDrivers();
            if(e.hasMoreElements())
            {
                System.out.println(e.nextElement());
            }
        }
}

Then I tried type casting :-
oracle.jdbc.pool.OracleDataSource d = new oracle.jdbc.pool.OracleDataSource();
DriverManager.registerDriver((Driver) d);

But it throws an Exception, java.lang.ClassCastException: oracle.jdbc.pool.OracleDataSource cannot be cast to java.sql.Driver
To run:-
set classpath=;D:\ORACLE-11g\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar;
javac Driver2_Load2.java
java Driver2_Load2

A: Loading the type 2 driver is not different than loading the type 4 driver because the actual driver class is always the same. The type 2 driver also needs a complete Oracle client installed (in contrast to the type 4 driver, which only needs the .jar file)
With any modern Java and driver version there is no need to call registerDriver() or class.forName(). All you need to do is to provide a connection URL using the oci protocol rather than the thin protocol.
As documented in the manual an OCI connection is established using the driver protocol oci: jdbc:oracle:oci:...
So to create an OCI connection, you need to specify that in the URL:
DriverManager.getConnection("jdbc:oracle:oci:@//localhost:1521/orcl", "hr", "hr");

But you have to have the Oracle client including all needed DLLs installed and reachable for your JVM, but there is no need to call registerDriver() (or Class.forName())

Regarding your code: oracle.jdbc.pool.OracleDataSource is - as the class name indicates - an implementation of javax.sql.DataSource it's not a javax.sql.Driver.
registerDriver() expects the class name of a java.sql.Driver, not of a DataSource.
The Oracle driver class is oracle.jdbc.OracleDriver.

Unrelated, but: why to do you think you need the OCI driver in the first place? Oracle recommends to use the thin driver, unless you have very specific requirements, e.g. you need "Transparent Application Failover" in a RAC environment.

A: See https://docs.oracle.com/cd/F49540_01/DOC/java.815/a64685/basic1.htm, the syntax is:
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());


text:
Q: Different Results for int and long long So, I was doing a question that asked us to divide an array into two parts such that the difference between the sum of elements of both of the parts shall be minimum.
Say A = [3 2 7 4 1]. So, minimum difference is generated when [2 3 4] and [7 1] are the two parts, i.e. difference = (2+3+4)-(7+1) = 1.
My approach was pretty naive, which basically computed all different subsets of the given array, and calculate the absolute difference with its complementary array, and report the minimum of these values.
When I used int my program it gave the correct answers for all but two test cases. In these test cases, the inputs were exceeding the limits of int. So, I changed it to long long, but this gave very weird results. It even started giving wrong results for the previously correct results.
CORRECT OUTPUT GIVING CODE (using int):
#include <bits/stdc++.h>

typedef long long ll;

using namespace std;

int min_diff = INT_MAX;

void subsetGen(vector <int> &curr,vector <int> &v, int n, int index, int sum)
{
    if (!curr.empty())
    {
        int sum_1 = accumulate(curr.begin(), curr.end(), 0);
        int diff = abs(2*sum_1 - sum);
        min_diff = (diff<min_diff) ? diff : min_diff;

    }
    for (int i = index; i < v.size(); i++)
    {
        curr.push_back(v[i]);

        subsetGen (curr, v, n, i+1, sum);

        curr.pop_back(); // Backtracking
    }
    return;
}

int main()
{
    int n, sum = 0;
    cin >> n;
    vector <int> v (n, 0);
    for (int i=0; i<n; i++)
    {
        cin >> v[i];
        sum += v[i];
    }
    vector <int> curr;
    subsetGen(curr,v,n,0,sum);
    cout << min_diff;
    return 0;
}

INCORRECT OUTPUT GIVING CODE (using long long):
#include <bits/stdc++.h>

typedef long long ll;

using namespace std;

ll min_diff = LLONG_MAX;

void subsetGen(vector <ll> &curr,vector <ll> &v, int n, int index, ll sum)
{
    if (!curr.empty())
    {
        ll sum_1 = accumulate(curr.begin(), curr.end(), 0);
        ll diff = abs(2*sum_1 - sum);
        min_diff = (diff<min_diff) ? diff : min_diff;

    }
    for (int i = index; i < v.size(); i++)
    {
        curr.push_back(v[i]);

        subsetGen (curr, v, n, i+1, sum);

        curr.pop_back(); // Backtracking
    }
    return;
}

int main()
{
    int n;
    ll sum = 0;
    cin >> n;
    vector <ll> v (n, 0);
    for (int i=0; i<n; i++)
    {
        cin >> v[i];
        sum += v[i];
    }
    vector <ll> curr;
    subsetGen(curr,v,n,0,sum);
    cout << min_diff;
    return 0;
}

This was the Input I was checking for:
20
452747515 202201476 845758891 733204504 327861300 368456549 64252070 494676885 21095634 611030397 913689714 849191653 173901982 954566440 40404105 228316310 210730656 631709598 847867437 85805975

The correct answer is: 4881 (which the program using int gave)
But using long long is giving me: 4762526359 (which is the wrong answer).
I tested these code in online compilers to see if this was a problem with only my system, but encountered the same problem.


text:
Q: Find the length of a diagonal of a rectangular room of length 5m width 3m and height 2.5m using Pythagorean theorem answer according to book is 6.34m
I couldn't figure which numbers are a^2 or b^2 or c^2 as i'm given 3 numbers

A: A picture can be worth a thousand words:

Apply the Pythagorean theorem twice.

A: What you are looking for is the length of the 'solid diagonal'.
First we need to find the length of the base diagonal. That can be done easily using Pythagorean theorem. $\ \sqrt{5^2 + 3^2} = 6 $.
Now this diagonal is a leg of the bigger right triangle whose hypotenuse is the required solid diagonal. You can see this from @amd's picture.
So apply Pythagorean theorem again.
$\ \sqrt{6^2 + (2.5)^2} = \sqrt{37.25} $.
You can work that out with a calculator.
In general for a cuboid with dimensions a, b and c(order doesn't matter), the solid diagonal is:
$\ \sqrt{a^2 + b^2 + c^2} $


text:
Q: How to use multiple CSV files in mapreduce First, I will explain what I am trying to do. First, I am putting input file (first CSV file) into mapreduce job and other CSV file will be put inside mapper class. But here is the thing. The code in mapper class does not work properly, like this right bottom code. I want to combine two CSV files to use several columns in each CSV file.
For example, 1 file has BibNum (user account), checkoutdatetime (book checkoutdatetime), and itemtype (book itemtype), and 2 CSV file has BibNum (user account), Title (book Title), Itemtype and so on. I want to find out which book will be likely borrowed in coming month. I would be really appreciated if you know the way can combine two CSV file and enlighten me with any helps. If you have any doubts for my code, just let me know, I will try to clarify it.
 Path p = new Path("hdfs://0.0.0.0:8020/user/training/Inventory_Sample");
       FileSystem fs = FileSystem.get(conf);

       BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(p)));

        try {

            String BibNum = "Test";
            //System.out.print("test");
            while(br.readLine() != null){
                //System.out.print("test");
                if(!br.readLine().startsWith("BibNumber")) {
                    String subject[] = br.readLine().split(",");
                    BibNum = subject[0];
                }
            }

.
import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class StubMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

    private Text outkey = new Text();
    //private MinMaxCountTuple outTuple = new MinMaxCountTuple();

    //String csvFile = "hdfs://user/training/Inventory_Sample";
    @Override
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

       Configuration conf = context.getConfiguration();
       //conf.addResource("/etc/hadoop/conf/core-site.xml");
       //conf.addResource("/etc/hadoop/conf/hdfs-site.xml");
       Path p = new Path("hdfs://0.0.0.0:8020/user/training/Inventory_Sample");
       FileSystem fs = FileSystem.get(conf);

       BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(p)));

        try {

            String BibNum = "Test";
            //System.out.print("test");
            while(br.readLine() != null){
                //System.out.print("test");
                if(!br.readLine().startsWith("BibNumber")) {
                    String subject[] = br.readLine().split(",");
                    BibNum = subject[0];
                }
            }

            if(value.toString().startsWith("BibNumber"))
            {
                return;
            }

            String data[] = value.toString().split(",");

            String BookType = data[2];
            String DateTime = data[5];

            SimpleDateFormat frmt = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

            Date creationDate = frmt.parse(DateTime);
            frmt.applyPattern("dd-MM-yyyy");
            String dateTime = frmt.format(creationDate);

            //outkey.set(BookType + " " + dateTime);
            outkey.set(BibNum + " " + BookType + " " + dateTime);

            //outUserId.set(userId);
            context.write(outkey, new IntWritable(1));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            br.close();
        }

    }
}

A: You are reading CSV file in the mapper code.
If you are using the path to open a file in the mapper, I guess you are using Distributed Cache, then only file would be shipped with the jar to each node where the map reduce should run.
There is a way to combine, but not in the mapper.
You can try the below approach :-
1) Write 2 separate mapper for two different file.
2) Send only those fields required from mapper to reducer.
3) Combine the results in the reducer ( as you want to join on some specific key ).
 You can check out Multi Input Format examples for more.


text:
Q: Reading a csv file with a list of elements into pandas dataframe I have a CSV file in the following format:
index      A      B      C
ind1    [1,2,3][3,4,5][6,7,8]
ind2    [1,4,3,4,8][9,1,2,1,4][3,7,3,5,9]
ind3    [2,8][1,8][1,5]

where each cell (say A,ind1)has a list [1,2,3].
When I import this into a dataframe:
df=pd.read_csv('filename.csv')

I get a dataframe in the same format as the csv, however, the list in individual cell is imported as a string.
Say I index the first element of ind1 column A
df.iloc[0]['A'] gives me '[' instead of 1
basically it is reading [1,2,3] as one long string instead of reading it as a list.
How do I convert the values in all the cells into list?

A: Interesting question. If you will use pandas i would use literal_eval to encode at first the list.
import pandas as pd
 from ast import literal_eval
 df = pd.read_csv("filename.csv")

Than you can use pandas applymap to apply the literal_eval function to every cell.
df[['A', 'B', 'C']] = df[['A', 'B', 'C']].applymap(literal_eval)

Now, you have extracted the list and you can react with them like a normal list.
e.g. this will give you from the first list the first element:
df.iloc[0]['A'][0]

I hope that will help you


text:
Q: Transformation of boundary integral Given a Diffeomorphisem $\Phi$, consider the boundary integral
$ \int_{\partial\Phi(\Omega)}f\cdot\nu ~dS$,
where $\nu$ is the outer unit normal vector on $\Phi(\Omega)$. I now want to do a change of variables for this integarl to get
$ \int_{\partial\Phi(\Omega)}f\cdot\nu ~dS=  \int_{\partial\Omega}[f\circ\Phi]\cdot[\nu\circ\Phi]\left|\operatorname{det}D\Phi\right|dS$.
My Problem now is to understand the right hand site of this equation. Since $\nu\circ\Phi$ is not necessary a outer unit normal vector on $\Omega$ I am not sure if this transformation can be done in this way.


text:
Q: How do I reorder a points and corresponding labels in ggplot2 scatterplot by the numeric variable in R? I am trying to reorder the points by the numeric variable (bc) on the y-axis in the ggplot2 chart by ascending order. My x-axis is a unique identifier (uid) for each point, however, I want the corresponding label of the point to be a different variable (name). However, the wrong labels get attached when I use the "name" variable to each point. I want the correct ones to show up, of course.
lopct <- ggplot(lo_pct, aes(x = uid, y = bc)) +
  geom_point(aes(x = reorder(lo_pct$uid, lo_pct$bc), y = lo_pct$bc),
             size=2, color = "#A3A500") +
  geom_errorbar(aes(ymin = lo_pct$lci, ymax = lo_pct$uci),
                width=0.00, show_guide = F, size = 1, color = "#A3A500") +
  geom_hline(yintercept = 0, linetype="solid",
             color = "#6b5e4f", size=1) +
  scale_x_discrete(labels=lo_pct$name) +
  labs(y = "Effect size (Proportion)",
       x = "",
       title = "") +
  coord_flip()

I simply wrote the text for each of them, because I couldn't make anything work. However, now I want to add a tooltip with shiny R - and I'm encountering the same problem. And there I cannot specify the labels for each point.

A: Looks like if I add  scale_x_discrete(limits= ""), it works.
The tooltip still won't work. For that, you just have to have unique value labels.


text:
Q: Create reactive selectInput - flexdashboard with Shiny I'm trying to make a reactive selectInput using Shiny in a flexdashboard document.

*

*My first selectInput selects the type of Zone in a Marine Park.
selectInput("Zone", label = "Marine Park Zoning:",
          choices = c("All", levels(EoTR$MarineParkZone)), selected = "All")

*Then I use this input to create a reactive data frame with only the Zones selected in step 1.
zone.choices = reactive({
  if (input$Zone=="All"){
  select(EoTR, ReefName, MarineParkZone, MarineParkMgmtSection)
  }else{
  select(EoTR, ReefName, MarineParkZone, MarineParkMgmtSection)%>%
  filter(MarineParkZone==input$Zone)}
})

*Then I try to use this reactive data frame to define my choices for the next selectInput
reactive({
selectInput("Reef", label = "Priority Reef:",
        choices = zone.choices()$ReefName, selected = "Arlington Reef (16-064)")
})

When I run the document my second input displays a bunch of code instead of the select menu and therefore all the processes based from that selector fail.
Below is some code that will reproduce the problem
---
title: "Untitled"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---
```{r}
library(flexdashboard)
library(dplyr)

EoTR = data.frame(ReefName=c("Reef1", "Reef2", "Reef3", "Reef4"),
              MarineParkZone=c("Fished", "Fished", "Un-Fished", "Un-Fished"))

selectInput("Zone", label = "Marine Park Zoning:",
          choices = c("All", levels(EoTR$MarineParkZone)), selected = "All")

zone.choices = reactive({
  if (input$Zone=="All"){
  select(EoTR, ReefName, MarineParkZone)
  }else{
  select(EoTR, ReefName, MarineParkZone)%>%
  filter(MarineParkZone==input$Zone)}
})

reactive({
selectInput("Reef", label = "Priority Reef:",
        choices = zone.choices()$ReefName, selected = "Reef1")
})
```

I know it's probably something silly with how I'm defining my reactive input but I'd really appreciate any help on this.
Cheers,
Sam

A: Here is the solution for you:
---
title: "Untitled"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---
```{r}
library(flexdashboard)
library(dplyr)

EoTR = data.frame(ReefName=c("Reef1", "Reef2", "Reef3", "Reef4"),
              MarineParkZone=c("Fished", "Fished", "Un-Fished", "Un-Fished"))

selectInput("Zone", label = "Marine Park Zoning:",
          choices = c("All", levels(EoTR$MarineParkZone)), selected = "All")

zone.choices = reactive({
  if (input$Zone=="All"){
  EoTR
  }else{
  EoTR %>%
  filter(MarineParkZone==input$Zone)}
})

renderUI({selectInput("Reef", label = "Priority Reef:",
        choices = zone.choices()$ReefName, selected = "Reef1")})

```

The problem was with your selectInput("Reef"...), you have set it to be reactive (which is inccorect) --> you should rather render it as UI object (renderUI).


text:
Q: Setting up a global PTR record for entire server Digital Ocean droplet running CentOS 7 with Plesk Panel installed.
Trying to improve the email deliverability and overall state of the mail server.
Want to set up a PTR record and apply this to the DNS template so that it can be applied to all domains hosted on the server.

Not entirely sure what I should be using to set up this record.

*

*The droplet (server IP) is provided by Digital Ocean.

*We do not use Digital Ocean's DNS for the domains hosted however.

*We use custom nameservers that we host on another server, the root domain and GLUE records are registered via Namecheap. (Example: ns1.example.com, ns2.example.com).

*The server's hostname is a sub-domain on the same domain as our custom nameservers. (Example: vps-01.example.com).
If I need to contact a provider to ask about the correct details to be using for the PTR record, who is it that I need to contact? Or can I source the information myself based on our set up?
Please note: This is not a question about Plesk but specifically to do with the format and set up/provision of PTR DNS record.

A: PTR records for reverse lookups don't go in your domain's DNS zone. Instead, they must go into the reverse zone that IP is delegated to. In case of a single DO machine without its own netblock, that will be DOs DNS server. They should provide some kind of interface to do this.


text:
Q: import from SharedModule FormModule to module that exported via SharedModule Angular 2 I have some AutocompleteModule that exported with SharedModule to whole App. In SharedModule I have exported FormsModule to whole App.
But when I tried to use ngModel in AutocompleteModule I got an error about ngModel. When I imported FormsModule to AutocompelteModule also It works fine.
But I have FormsModule exported in SharedModule.  So the reason question. Can I import SharedModule to AutocompleteModule to receive access to FormsModule? (But I saw in doc that it is bad idea to do that cycle).
So question is: should I import FormsModule to AutocompelteModule aso or some better practice exists?
Thanks!

A: AutocompleteModule needs it's own FormsModule import. You may think that importing the SharedModule into the AutocompleteModule would do the trick, but it won't as you will get a circular dependency, causing it to fail.
Best option is to just directly import the FormsModule
@NgModule({
  imports: [ FormsModule ]
})
class AutocompleteModule {}

In SharedModule I have exported FormsModule to whole App

It doesn't work like that. Access to components, pipes, and directives don't get inherited. They need to be imported into the module that uses them, one way or another.


text:
Q: Sending Json raw content from ASP .Net Core controller I want to send raw Json content in a string on ASP .Net Core controller output.
If I try to do it by returning the string itself double quotes in its content will be escaped and the client will not recognize it as a Json content but as a string. Eg. :
public async Task<ActionResult<MyClass>> Get()
{
    try
    {
        // here we build an object from a service with a complex dataset
        MyClass myObject = ...;  // business code here
        // serializing the object
        JsonSerializerOptions options = new()
        {
            WriteIndented = true,
            ReferenceHandler = ReferenceHandler.IgnoreCycles
        };

        string jsonDataset = JsonSerializer.Serialize<MyClass>(myObject , options);
        // or we could do simply for testing something like: jsonDataset = "{\"Id\"=10, \"Label\"=\"HelloWorld!\"}";
        // then we send it to the client
        return Ok(jsonDataset);
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}

I cannot deserialize the json, it is too complex with object lists referencing other objects.
I cannot use NewtonSoft library, it is a no-go for my project's client. So no anonymous class for deserialization here :[|]
Is there a way to output the string "jsonObject" as an application/json content BUT WITHOUT double-quote escaping ?
Thanks for any help!

A: You can use the Content methods to return the string and specify the content type:
return Content(
  jsonDataset,
  "application/json");


text:
Q: The set of prime ideals containing any non-zero proper ideal in a commutative Noetherian ring is finite, by consideration of the topology on $Spec(R)$ In the notes by J.P. May on 'Associated Prime Ideals', for $R$ a commutative Noetherian ring and $M$ a non-zero finitely generated
$R$-module, I do not understand the first statement in the proof of the following

Theorem 0.10. $\mathrm{Ass}(M)$ is a finite subset of $\mathrm{Supp}(M)$, and the minimal elements
of $\mathrm{Ass}(M)$ and $\mathrm{Supp}(M)$ coincide.
Proof. The set of prime ideals containing any non-zero proper ideal in
a commutative Noetherian ring is finite, by consideration of the
topology on Spec(R). But we have a different proof here: the
finiteness of $\mathrm{Ass}(M)$ follows inductively from the previous two
propositions...

I am not sure what 'The set of prime ideals containing any non-zero proper ideal in a commutative Noetherian ring' is referring to and how it can be finite since this is for instance the case if the Noetherian ring $R$ has Krull dimension zero (see $V(I)$ consists of a finite set of points if and only $k[x_1,\ldots,x_n]/I$ has Krull dimension zero). For instance let $R = k[x_1, .., x_n]$ and $I$ an ideal, then $V(I)$ is the set of prime ideals containing $I$ and $V(I)$ is not necessarily finite; I must be misunderstanding something.
Ref: J.P. May's notes on 'Associated Prime Ideals' http://www.math.uchicago.edu/~may/MISC/AssoPrimes.pdf


text:
Q: How to handle class variable without $this? I'm making a WordPress plugin with OOP concept and I'm facing some wired issue.
First I have a main-plugin.php file where I have a class like this
include_once plugin_dir_path( __FILE__ ) . 'something.php';

class something {
    //some var
    public $a;
    private function __construct() { {
        //all of my wordpress hook calls are here
    }

    public function foo() {
        $this->a = 55; // this is working fine and not giving any error
    }
}

Now I have another php file which holds another class which I included in the main-plugin.php file
let's say the new file is something.php
and here I have
class some {
    //some variables
    public $b, $c;

    // now this this class when I'm doming
    public function bar() {
        $this->b =1; // this is giving me error saying this is not an object.
    }
}

Now I have no idea why $this is not working inside the else class. Also As these variables are not static variables, I really can't do self::$b. So, I was hoping if anyone else can tell me a way to access non static variables inside the class without using $this.

A: I think, you must have instance of AICP_ADMIN in https://github.com/isaumya/adsense-invalid-click-protector/blob/master/adsense-invalid-click-protector.php#L91 instead of string. So try something like
$aicpAdmin = new AICP_ADMIN;
add_action( 'admin_enqueue_scripts', array( $aicpAdmin, 'admin_scripts' ) );

A: $this is only available inside functions within the class. If you want to initialize variables, use a construct function:
public class test
{
     public $a;
     public function __construct()
     {
         $this->a = new db();
     }
}

When you initialize class test with $test = new test(), $test->a will be an instance of db.


text:
Q: Grouped bar chart with 3 variables (1 on y axis, 1 on x axis, 1 grouped) in r I'm new to this site and relatively new to R. I need to make a grouped barchart and my issue is that I need my y axis to be the count of observations of a specific variable/column. I have several hundred observations and I need to graph the number of participants who have ever been dependent on alcohol (y-axis) by race and gender.
I did this:
AlcDep_byRG_Table <- table(baseline_Alc_Race_Gender$ALCDEP_3.[baseline_Alc_Race_Gender$ALCDEP_3. >= 3],
                  baseline_Alc_Race_Gender$PRACE[baseline_Alc_Race_Gender$ALCDEP_3. >= 3],
                  baseline_Alc_Race_Gender$PGENDER[baseline_Alc_Race_Gender$ALCDEP_3. >= 3])

m <- colSums(AlcDep_byRD_Table[,,2]) # rows, columns, slice; 2 = second slice, 1, male
f <- colSums(AlcDep_byRD_Table[,,3])
barplot(c(m,f), main = "Alcohol Dependence by Race and Gender", beside = TRUE, xaxt = "n")

BUT, I don't know how to make it a grouped/clustered bar chart
I tried using ifelse but then didn't know how to subset it like the above.
Thank you so much for your help!
edit: I tried ggplot
ggplot(baseline_Alc_Race_Gender, aes(x=PRACE, y=Alc_Dep, fill = PGENDER)) +
geom_bar(stat='identity')

but the graph has lots of horizontal lines in each bar - anyone know what the mistake could be? Thank you!

A: (edited)
# create a dataframe like yours
PART_ID<-c(1001,1002,1003,1004,1005)
Alc_Dep<-c(1, 0,1,1,1)
PRACE<-c(1,2,1,3,1)
PGENDER<-c(1,2,2,2,1)
baseline_Alc_Race_Gender <- data.frame(PART_ID,PGENDER,PRACE,Alc_Dep)
baseline_Alc_Race_Gender
# solve the factor issue
baseline_Alc_Race_Gender$PGENDER<-
factor(baseline_Alc_Race_Gender$PGENDER)
baseline_Alc_Race_Gender$PRACE<-factor(baseline_Alc_Race_Gender$PRACE)
baseline_Alc_Race_Gender$Alc_Dep<-factor(baseline_Alc_Race_Gender$Alc_Dep)
# plot it
# do not specify a y!
ggplot(baseline_Alc_Race_Gender, aes(x=PRACE, fill=PGENDER)) +
   geom_bar(position=position_dodge())

Sarah,
It would help immensely if you could share a sample of your data.  But I'll make something up that may be your case.  Three columns race, gender, and a yes or no to alcohol dependence.  This should work no matter how many cases you have.  It may require you to uncomment the install ggplot2 command
d <- data.frame(column1=rep(c("race1","race2","race3"), each=4),
                column2=rep(c("male", "female"), 6),
                column3=rep(c("yes", "no"), 6))
d
# install.packages("ggplot2") you may need this
require(ggplot2)
ggplot(d, aes(x=column1, fill=column2)) +
    geom_bar(position=position_dodge())


text:
Q: Puppeteer - Map real mobile device behavior in headless (true | false) mode I want to emulate a custom device ( real mobile device dimensions) with a puppeteer, and I expect same browser behavior in real mobile device and puppeteer.
I tried
const _op = {
             args: [
                 '--no-sandbox', `--window-size=980,1788`
             ],
             headless: false,
             timeout: 60000,
             ignoreHTTPSErrors: true,
             defaultViewport: {
                 height: 1788,
                 width: 980,
                 isMobile: true,
                 hasTouch: true,
                 isLandscape: false,
                 deviceScaleFactor: 3
             }

         }

Problem
Coordinated (x,y) mismatched in real mobile device and puppeteer, like if it plot (200,300) it shows the different positions in the real mobile device and in puppeteer chromium browser .
Is these's way to map real mobile device dimensions in puppeteer, or any suggestions, if I'm missing something ?

A: To emulate a device on which to load the page you can use page.emulate(iPhone) for emulating iphone as in the example:
const puppeteer = require('puppeteer');
const iPhone = puppeteer.devices['iPhone 6'];

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.emulate(iPhone);
  await page.goto('https://www.google.com');
  // other actions...
  await browser.close();
})();

Maybe this can help you: https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#puppeteerdevices

A: The puppeteer deviceDescriptors use an object from preset value, you can pass in an object with custom values directly in page.emulate()
page.emulate({
  "name": "Moto G4",
  "userAgent": "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
  "viewport": {
    "width": 640,
    "height": 360,
    "deviceScaleFactor": 3,
    "isMobile": true,
    "hasTouch": true,
    "isLandscape": false
  }
})


text:
Q: Finding lower bound for $\alpha(G) + \omega(G)$ I'm wondering to find a lower bound for $\alpha(G) + \omega(G)$.
In my tries, I couldn't find a graph without inequation: $\alpha(g).\omega(G) \geq |V(G)|$
Thus I think one possible bound is $\alpha(G) + \omega(G) \geq 2\sqrt n$, but I have no proof for this bound.


text:
Q:  library isn't found in the GCC version (4.2.1) in Mavericks I  have a problem with GCC. I want to update it to a new version, from the 4.2.1, to program with parallel programming. However, in this version there is no library . How can I download an updated version?
The error that the terminal give me is:
omp_hello.c:11:10: fatal error: 'omp.h' file not found
#include <omp.h>
         ^
1 error generated.

A: I got this message when I tried to reinstall GCC via Homebrew.

GCC has been built with multilib support. Notably, OpenMP may not work:
    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60670
If you need OpenMP support you may want to
    brew reinstall gcc --without-multilib

So, if you have Homebrew installed, you could try (on the terminal):
brew reinstall gcc --without-multilib

This process may take a while !

A: According to this thread on apple's forums, try using gcc-4.9-bin.tar .
First install the gcc-4.9  and type "xcode-select --install" on your terminal.
Then, use "/usr/local/bin/gcc " as compiler.

A: *

*download gcc-4.9-bin.tar.gz download  or newer from
http://hpc.sourceforge.net/:
http://prdownloads.sourceforge.net/hpc/gcc-4.9-bin.tar.gz

*cd to your downloads folder and un-gzip
the archive gunzip gcc-4.9-bin.tar.gz (Google Chrome would do that
automatically)

*in the same folder run sudo tar -xvf gcc-4.9-bin.tar -C / - this will place new executable to /usr/local/bin

*add the following to ~/.bash_profile: export PATH=/usr/local/bin:$PATH

*open new terminal and run which gcc. This should point to /usr/local/bin/gcc

A: I solve it just adding aliases to .bash_profile
# Aliases in order to use brew gcc
alias gcc='gcc-5'
alias cc='gcc-5'
alias g++='g++-5'
alias c++='c++-5'


text:
Q: Matplotlib plotting is slow I am relatively new to python / matplotlib and have to plot huge numpy arrays (more than 6 mio entries). The problem is that the 6 plots I have take more than 3 GB of RAM and take very long to load.
I researched a bit and found out that I can speed matplotlib up by not loading the axes and title every time.
So now the code looks like this but it's still quite slow.
Should I use another module instead of matplotlib?
How could I speed up the process?
Thanks a lot in advance
    for key, typus in self.sensorObjects.items():
        fig, ax = plt.subplots()
        ax.set_title(key)
        ax.set_xlabel('t (ms)')
        ax.set_ylabel(self.sensorObjects[key][0].unit)
        for sensor in typus:
            data = sensor.physical_data
            ax.plot(data)
        fig.canvas.update()


text:
Q: Rails 3 after_save for tracking history of updates The reason for this post is to get feedback as to whether there's a "Rails Way" of doing what I'm attempting. The way I'm doing it seems a bit clunky and prone to human error.
I have multiple tables which I want to store history of including the time and date a record is updated. Who updates it is not important.
At the moment, I have put together the following [not yet tested, some syntax is probably wrong], but it seems like other people would have this need and that there would be a better way of doing it, whether there was a way of implementing this at the database level instead or some other inbuilt method/callback I'm not aware of.
The model CreateDdiPlanHistorical was generated including updated_at:datetime on top of the other fields seen below in the create_history method, my understanding is that should automatically populate on any records in the historicals table being added or modified.
(validations and associations stripped out for clarity)
class CallDdiPlan < ActiveRecord::Base
  attr_accessible :active, :ddi_count, :plan_name, :price

  after_save :create_history

  private

    def create_history
      CallDdiPlanHistorical.create({:active => this.active, :ddi_count => this.ddi_count, :plan_name => this.plan_name, :price => this.price, :call_ddi_plan_id => this.id})
    end

end

A: You could do some sort of roll-your-own solution, but if you really want to make the boss happy, use the audited gem:
https://github.com/collectiveidea/audited


text: Q: How to let Linux terminal close automatically at the end of a program? I am using Qt creator to compile and test my C++ code. After the program ends, I have to press the Enter key to close the terminal. It becomes annoying when there are too many terminals on the screen. How do I program it to close automatically upon finishing?


text:
Q: How do I dynamically load fonts from a web server? I need to dynamically load custom parametric fonts for a project. The fonts are coming from a web server I wrote, which takes input parameters via url and sends back an OTF file via Express. I've been trying to write the client side, but I've been having a lot of trouble.
For background, the web server routes anything from localhost:1999/font/ to makeFont(). It draws the font parameters from the url, so localhost:1999/font/43-64-24-63 returns a font with parameter values [43,64,24,63]. There are 16 parameters in reality, and the web server will eventually be hosted at a real URL, but neither of those seem important at the moment. The server generates the font and saves the file locally, then sends it back via Express's sendFile(). It's currently saving as an OTF, but I can save it as another format if need be.
I started with these tutorials:

*

*https://awik.io/dynamically-load-apply-fonts-javascript/

*https://usefulangle.com/post/74/javascript-dynamic-font-loading
and worked through a couple of other issues (FontFace and its ilk need to be ambiently declared, etc.). I now run into one of the following issues:
If I try to load a font via var junction_font = new FontFace('Junction Regular', 'url(fonts/junction-regular.woff)');, I get the following error:
Failed to decode downloaded font: http://localhost:1234/fonts/junction-regular.woff \n OTS parsing error: invalid version tag
To clarify, I downloaded an actual copy of Junction Regular's .woff and saved it in a /fonts folder in the same directory as my index.html and index.ts files.
Meanwhile, if I try to load a file directly via a real URL (I used one from a Google Fonts link), I get this error:
var junction_font = new FontFace('Junction Regular', 'https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');
Failed to load font: SyntaxError: The source provided ('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap') could not be parsed as a value list.
I also tried it on the latin WOFF2 download link at https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap, and no dice.
Searching around for these errors turns up a lot about CSS, which is exactly what I'm trying to avoid using (since I need to load fonts dynamically).
Please let me know how to go about this, either through local files or a proper download URL. I can download each file via Axios first, but would rather avoid it if possible.
Thanks so much!

A: Your first error (loading fonts from your server) seems to suggest that the fonts are not being served with the correct mime type. The extension on the end of the file name is not necessarily used to determine the type correctly.
How you go about fixing this depends on your server setup, but if you're using Express, you'll probably want to use static to serve your fonts.
Something like:
// PATH_TO_FONTS should be relative to the directory that your node process is running on

app.use('/fonts', express.static(PATH_TO_FONTS))

The second error you're getting looks like a formatting error. You need to wrap your fonts in a url() string. Like so:
var junction_font = new FontFace(
  'Junction Regular',
  'url("https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap")'
)


text:
Q: Split any number of numpy array rows into columns in a Pandas Dataframe I have a Pandas dataframe that contains two type of columns, the ones that contain numpy arrays and the ones that contain floats.
E.g.:
      arr1   f1
[0.3, 1.3]  3.5

I need to split the values of the arrays into rows.
If I only have these two columns, I can easily split the array like this:
df = pd.DataFrame([[x, j] for i, j in zip(a['arr1'], a['f1']) for x in list(i)], columns=['arr1', 'df1])

And the result looks like this:
arr1   f1
0.3   3.5
1.3   3.5

However, I can have any number of array and float columns, where the arrays in the same row always have the same length, i.e.: I can match all the elements of both arrays ((a1, b1), (a2, b2), ..., (a_n, b_n)).
      arr1   f1        arr2  f2
[0.3, 1.3]  3.5 [14.8, 1.2] 1.6

After splitting the arrays, the result should look like this:
arr1   f1  arr2  f2
 0.3  3.5  14.8 1.6
 1.3  3.5  1.2  1.6

It is easy to know what kind of data a column has, so that I can use zip accordingly, but anyway I can't figure out how to make it work for any number of columns.

A: Solutions if order of columns is important - list comprehensions with DataFrame.explode:
dfs = [df[list(x)].explode(x[0]) for x in zip(df.columns[::2], df.columns[1::2])]

df = pd.concat(dfs, axis=1).reset_index(drop=True)
print (df)
  arr1   f1  arr2   f2
0  0.3  3.5  14.8  1.6
1  1.3  3.5   1.2  1.6

And your solution:
dfs = [pd.DataFrame([[a, j] for i, j in zip(df[x[0]],
                                            df[x[1]]) for a in i], columns=x)
                    for x in zip(df.columns[::2], df.columns[1::2])]

df = pd.concat(dfs, axis=1)
print (df)
   arr1   f1  arr2   f2
0   0.3  3.5  14.8  1.6
1   1.3  3.5   1.2  1.6

A: Let us try unnesting
df = unnesting(df, ['arr1','arr2'] , axis=1)

def unnesting(df, explode, axis):
    if axis==1:
        idx = df.index.repeat(df[explode[0]].str.len())
        df1 = pd.concat([
            pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
        df1.index = idx

        return df1.join(df.drop(explode, 1), how='left')
    else :
        df1 = pd.concat([
                         pd.DataFrame(df[x].tolist(), index=df.index).add_prefix(x) for x in explode], axis=1)
        return df1.join(df.drop(explode, 1), how='left')


text:
Q: Regex lookahead. Find word without .min. in string I'm trying to replace a link in a html file with regex and nodejs. I want to replace links without a .min.js extension.
For example, it should match "common.js" but not "common.min.js"
Here's what I've tried:
let htmlOutput = html.replace(/common\.(?!min)*js/g, common.name);

I think this negative lookahead should work but it doesn't match anything. Any help would be appreciated.

A: The (?!min)*js part is corrupt: you should not quantify zero-width assertions like lookaheads (they do not consume text so quantifiers after them are treated either as user errors or are ignored). Since js does not start with min this lookahead even without a quantifier is redundant.
If you want to match a string with a whole word common, then having any chars and ending with .js but not .min.js you need
/\bcommon\b(?!.*\.min\.js$).*\.js$/

See the regex demo.
Details:

*

*\b - word boundary

*common - a substring

*\b - word boundary

*(?!.*\.min\.js$) - immediately to the right, there should not be any 0 or more chars followed with .min.js at the end of the string

*.* - any 0 or more chars

*\.js - a .js substring

*$ - end of string.

A: Here, we likely can find a simple expression to pass any char except new lines and ., after the word common, followed by .js:
common([^\.]+)?\.js

Demo
RegEx Circuit
jex.im visualizes regular expressions:

A: The end regex I'm using is /\bcommon[^min]+js\b/g
This will find the word common with any amount of chracters afterword except if those characters contain the word minand ending in js allowing me to replace scripts on my html page like:
script src="~/dist/common.js"
OR
script src="~/dist/common.9cf5748e0e7fc2928a07.js"
Thanks to Wiktor Stribiżew for helping me.


text:
Q: Normal Distribution Problem The time taken for a computer to connect to a server is normally distributed with a mean value given by 3.3 seconds and
a standard deviation of 0.66 seconds.
(a) A computer is said to have a fast connection time if it connects in less than 2.5 seconds. What percentage of computers might one expect to fall into this category?
(b) In a sample comprising 155 computers, how many would be expected to have connection times of over 4 seconds?
(c) What is the connection time for the slowest 5% of the computers?
That's the problem I have to complete. Can anyone explain/show me how to do it?
Thanks :)

A: You first need to normalize your values, if a computer connects in 2.5 seconds that is 3.3-2.5=0.8 seconds less than the mean. This is 0.8/0.66=1.212 standard deviations less than the mean. You now need to know the area of a standard normal distribution to the left of -1.212 standard deviations.
The function that gives the area of a part of the normal distribution is commonly called the Q function, so you need Q(-1.212). You can ask Wolfram Alpha to calculate this for you, it gives Q(-1.212)=0.112756. So about 11.3% of connections will be "fast". You can use similar reasoning for part B, and part C is the same thing, but backwards.
Note that the Q function Wolfram Alpha uses is actually the inverse of the one defined in the Wikipedia article. You would notice something funny going on because you would get an answer of 88.7%, whereas the average connection is "slow", so that answer wouldn't make sense.

A: For part (b) , first of all , you can let X be the random variable of the time taken for a computer to connect to a server . Then , find out the probability of the connection time over 4 seconds , which is P(X>4) .

P(X>4)=P(Z>(4-3.3)/0.66)=P(Z>1.06)=0.5-0.3554=0.1446

Then by using Binomal Distribution , let Y be the random variable of the the computers have connection time over 4 seconds .Y~Bin(155 , 0.1446)
since E(Y) = np , where E(Y) is the expected value of Y .
so the expected value in the situation is : 155(0.1446) = 22.413
Therefore , there are 22 computers have connection time over 4 seconds .
Hope it is useful information for you to solve it .


text:
Q: Images are not showing from state in react native i have saved images names in state but when i try to show them its giving the error 'Invalid call require('./assets/'+this.state.img1)' ( but when i put the image name directly in source its start working. Like :
i have also alert the state its having the same image name.
  render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img1)}
      />
       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img2)}
      />
    </TouchableOpacity>
  )
}

A: According to the documentation : In order for this to work, the image name in require has to be known statically.
// GOOD
<Image source={require('./my-icon.png')} />;

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;

// GOOD
var icon = this.props.active
  ? require('./my-icon-active.png')
  : require('./my-icon-inactive.png');
<Image source={icon} />;

What you can do is building a mapping/object :
const myImages = {
  img1: require('/path/to/img1'),
  img2: require('/path/to/img2'),
};

render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={myImages[this.state.img1]}
      />
       <Image
        style={styles.stretch}
        source={myImages[this.state.img2]}
      />
    </TouchableOpacity>
  )
}

For this to work, this.state.img1 and this.state.img2 must be a key in the object myImages.


text:
Q: My wordpress site only shows home page, all other pages Not Found Yesterday i upload my Wordpress website on free webhost 000webhost.com through filezilla al files are successfully uploaded, database connected successfully but when i open my website www.velocitycars.site40.net it shows only homepage when i open any post or another page it goes to local host or not showing any thing it shows ( This webpage is not available) but it completely works on localhost.
plz help me
i am student this is my project
im thankful to u

A: Your server configuration must be missing. Check if .htaccess file is there, and whether your hosting service provider supports use of them.
As a general rule of thumb, you can't hope to have perfect functionality from a "free" service provider.


text:
Q: The mdf data file wont shrink even if there is free space available One of my databases had 450 GB of size for the data mdf file. I Dropped the unecassary tables to reclaim some space in the database and to my surprise even if there was around 150 GB of freespace, the data file won't shrink below the Files initial size which has grown to 450 GB. What could be the simplest solution/ workaround for this ?

A: If your database is in FULL Recovery mode you can switch to SIMPLE mode then do a shrink files to reclaim space.
Normally it's due to the logs not being able to successfully shrink rather than data file.
However ensure you leave enough space for growth as the resizing will cause a lot of extra work.
I wouldn't recommend shrinking for no reason as there are plenty of posts out there indicating why you shouldn't as it can lead to fragmentation.
Check books online for the DBCC SHRINKDATABASE statement as well.


text:
Q: How to stretch iFrame height to all screen sizes I am creating a responsive website. I am having a main iFrame for customisable content and a sideBar which will display news from our company.
I am wanting the website to work on all laptop, PC/MAC and tablet screen sizes. Most of the elements stretch and are responsive including the navBar, header and footer but not the iFrame heights.
I have tried to use (vh) for the height but does not seem to work.
HTML and CSS attached:

body { /* General Body Properties */
    font-family: Trebuchet MS, Georgia, Helvetica, sans-serif;
    margin: 0;
    overflow: hidden;
}

* { /* Key element to aligning <divs> (DO NOT REMOVE) */
    box-sizing: border-box;
}

.header { /* Header properties featuring myEd and school emblems */
    padding: 30px;
    text-align: center; /* Aligns links in the navBar */
    background-image: url(/Home/Welcome/Img/backgroundHeader-4K.jpg);
    background-size: cover;
    background-repeat: no-repeat;
}

.myEd-reverse {
    width: 240px;
    height: 70px;
    float: left;
    margin-left: -60px;
    margin-top: -40px;
}

.navBar { /* Sticky navBar, either relative or fixed, depending on the scroll position of the site */
    overflow: hidden;
    background-color: #333;
    position: sticky;
    position: -webkit-sticky;
    top: 0;
}

.navBar a { /* Style the navBar links */
    float: left;
    display: block;
    color: #fff;
    text-align: center;
    padding: 8px 16px;
    text-decoration: none;
}

.navBar a.right { /* Float Quick Links, Help and Log-out navBar directory items to the right of the navBar */
    float: right;
}

.navBar a:hover { /* Change color on hover */
    background-color: #ddd;
    color: #000;
}

.navBar a.active { /* Active Link */
    background-color: #666;
    color: #fff;
}

.row { /* Alignment between sideBar and main */
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}

.sideBar { /* sideBar alignment properties */
    -ms-flex: 20%;
    flex: 20%;
    background-color: #a7a7a7;
    padding: 0px;
    height: 5000px; /* As standard to work on all screen resolutions, overflow hides excess */
}

.profilePanel { /* Panel properties */
    background-color: #585858;
    width: 100%;
    padding: 0px;
}

#newsmyEd {
    width: 100%;
    height: 67.6vh;
}

.main { /* Main Column */
    -ms-flex: 80%;
    flex: 80%;
    background-color: #a7a7a7;
    padding: 0px;
    height: 5000px; /* As standard to work on all screen resolutions, overflow hides excess */
}

.frameMain { /* Frame Properties */
    position: relative;
    left: 0;
    width: 100%;
    height: 83vh;
}

.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background-color: #333;
}

@media screen and (max-width: 700px) { /* Responsive Layout - If screen px is less than 700px, make sideBar and main stack on top of each other */
    .row {
        flex-direction: column;
    }
}

@media screen and (max-width: 400px) { /* Responsive Layout - If screen px is less than 400px, make navBar links stack vertically on top of each other */
    .navBar a {
        float: none;
        width: 100%;
    }
}
<!DOCTYPE HTML>

<title>Welcome | myEd</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/Home/Welcome/Style/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="shortcut icon" href="/Home/Welcome/Img/faviconmyEd-16x16.png">

I am only beginning in the field of HTML and CSS. How would I get the iFrame to adjust the iFrame height on all screen resolutions.
Thanks for your help.
Tom

A: Not super sure if it is what you are trying to achieve, however I have just changed
the height value of #newsmyEd to 100% and overflow-y: scroll; to your .sideBar  I hope it will help:

body { /* General Body Properties */
    font-family: Trebuchet MS, Georgia, Helvetica, sans-serif;
    margin: 0;
    overflow: hidden;
}

* { /* Key element to aligning <divs> (DO NOT REMOVE) */
    box-sizing: border-box;
}

.header { /* Header properties featuring myEd and school emblems */
    padding: 30px;
    text-align: center; /* Aligns links in the navBar */
    background-image: url(/Home/Welcome/Img/backgroundHeader-4K.jpg);
    background-size: cover;
    background-repeat: no-repeat;
}

.myEd-reverse {
    width: 240px;
    height: 70px;
    float: left;
    margin-left: -60px;
    margin-top: -40px;
}

.navBar { /* Sticky navBar, either relative or fixed, depending on the scroll position of the site */
    overflow: hidden;
    background-color: #333;
    position: sticky;
    position: -webkit-sticky;
    top: 0;
}

.navBar a { /* Style the navBar links */
    float: left;
    display: block;
    color: #fff;
    text-align: center;
    padding: 8px 16px;
    text-decoration: none;
}

.navBar a.right { /* Float Quick Links, Help and Log-out navBar directory items to the right of the navBar */
    float: right;
}

.navBar a:hover { /* Change color on hover */
    background-color: #ddd;
    color: #000;
}

.navBar a.active { /* Active Link */
    background-color: #666;
    color: #fff;
}

.row { /* Alignment between sideBar and main */
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}

.sideBar { /* sideBar alignment properties */
    -ms-flex: 20%;
    flex: 20%;
    background-color: #a7a7a7;
    padding: 0px;
    height: 5000px; /* As standard to work on all screen resolutions, overflow hides excess */
    overflow-y: scroll;
}

.profilePanel { /* Panel properties */
    background-color: #585858;
    width: 100%;
    padding: 0px;
}

#newsmyEd {
    width: 100%;
    height: 100%;
}

.main { /* Main Column */
    -ms-flex: 80%;
    flex: 80%;
    background-color: #a7a7a7;
    padding: 0px;
    height: 5000px; /* As standard to work on all screen resolutions, overflow hides excess */
    overflow-y: scroll;
}

.frameMain { /* Frame Properties */
    position: relative;
    left: 0;
    width: 100%;
    min-height: 6000px;
}

.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background-color: #333;
}

@media screen and (max-width: 700px) { /* Responsive Layout - If screen px is less than 700px, make sideBar and main stack on top of each other */
    .row {
        flex-direction: column;
    }
}

@media screen and (max-width: 400px) { /* Responsive Layout - If screen px is less than 400px, make navBar links stack vertically on top of each other */
    .navBar a {
        float: none;
        width: 100%;
    }
}
<!DOCTYPE HTML>

<title>Welcome | myEd</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/Home/Welcome/Style/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="shortcut icon" href="/Home/Welcome/Img/faviconmyEd-16x16.png">


text:
Q: Как привести объект к массиву (js/typescript) После парсинга получаю такой объект с помощью JSON.stringify
[
  {
    "$": {
      "key": "v1",
      "value": "VS1"
    }
  },
  {
    "$": {
      "key": "v2",
      "value": "VS2"
    }
  }
]

Нужно привести его к интерфейсу V[]
export interface V {
    key: string;
    value: string;
}

Как это можно исключить "$": сделать?
В результате должно получится
[
  {
    "key": "v1",
    "value": "VS1"
  },
  {
    "key": "v2",
    "value": "VS2"
  }
]

A: В данном случае, нужно получить новый массив, в котором каждому элементу соответствует элемент из старого.
Для такой операции нужно использовать метод .map
.map(el => el.$)

console.log(
  [{
      "$": {
        "key": "v1",
        "value": "VS1"
      }
    },
    {
      "$": {
        "key": "v2",
        "value": "VS2"
      }
    }
  ].map(el => el.$)
)


text:
Q: How to read a topic model trained in command line into a Java class? So I've a trained model that was created through command line with MALLET. I want to, somehow, import this trained model into a Java class. I looked through MALLET's API documentation and came across their ParallelTopicModel class but couldn't find a suitable way to import the model as a ParallelTopicModel which is what I want to do.
I know that it's possible to train a model using the MALLET Java API inside the Java class itself but I do not want to do this.
Is this possible?

A: If that trained model generated both the data model and the data instances you can do this. The ParallelTopicModel will use the data model and the Pipe that it used to train the model will be used to create an InstanceList, which you will need for the TopicInferencer.
String testingText = "my test";
ParallelTopicModel model = ParallelTopicModel.read(new File("data_model_path"));
InstanceList instances = InstanceList.load(new File("data_instances_path"));

// Create a new instance with the testing text
InstanceList testing = new InstanceList(instances.getPipe());
testing.addThruPipe(new Instance(testing_text, null, "Test Instance", null));

// Create the inferencer
TopicInferencer inferencer = model.getInferencer();


text:
Q: Why jQuery load() doesn't work? Why the following jQuery code doesn't work? I put a div element in the body already. Thanks!
$(document).ready(function(){
  $("div").load("http://www.pagetutor.com/index.html");
});

A: Without having more info:
You can't load remote domain content unless it's json content.
This is a browser restriction.


text:
Q: Can't parse xml properly with BeautifulSoup I'm trying to scrape this page: https://www.france24.com/en/europe/rss
My code:
from urllib.request import urlopen
from bs4 import BeautifulSoup

xml = urlopen("https://www.france24.com/en/europe/rss")
data = xml.read()
text = data.decode('utf-8')
bs = BeautifulSoup(text, "lxml")
items = bs.find("rss").find("channel").find_all("item")
for n, item in enumerate(items):
    print(f"\n{n+1} - {item.find('title').get_text()}")
    print(item.find("pubDate"))
    print(item.find("description").get_text().replace("\n", ""))
    print(item.find("link").get_text())

The structure I'm interested in:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
    <channel>
        <lastBuildDate>Fri, 23 Apr 2021 06:08:56 GMT</lastBuildDate>
        <item>
            <category>Europe</category>
            <title>French fishermen seek to block British shipments in Brexit protest</title>
            <link>https://www.france24.com/en/europe/20210423-french-fishermen-seek-to-block-british-shipments-in-brexit-protest</link>
            <description>
French trawlermen angered by the slow issuance of licenses to fish inside British waters after Brexit on Thursday blocked lorries carrying UK-landed fish as they arrived in Boulogne-sur-Mer, Europe's largest seafood processing centre.
</description>
            <media:thumbnail url="https://s.france24.com/media/display/70e354e8-a3e7-11eb-a6eb-005056bf87d6/w:1024/p:16x9/Brexit%20fishermen%20protest.jpg" />
            <enclosure url="https://s.france24.com/media/display/70e354e8-a3e7-11eb-a6eb-005056bf87d6/w:1024/p:16x9/Brexit%20fishermen%20protest.jpg" type="image/jpeg" length="0" />
            <guid isPermaLink="false">cadc08aa-a3e7-11eb-91c0-005056bff4a8</guid>
            <pubDate>Fri, 23 Apr 2021 03:55:46 GMT</pubDate>
            <source url="https://s.france24.com/media/display/70e354e8-a3e7-11eb-a6eb-005056bf87d6/w:1024/p:16x9/Brexit%20fishermen%20protest.jpg">© Denis Charlet, AFP</source>
            <dc:creator>NEWS WIRES</dc:creator>
        </item>

The output:
1 - French fishermen seek to block British shipments in Brexit protest
None
French trawlermen angered by the slow issuance of licenses to fish inside British waters after Brexit on Thursday blocked lorries carrying UK-landed fish as they arrived in Boulogne-sur-Mer, Europe's largest seafood processing centre.

(...)

As you can see the pubDate and the link were not printed.
Here's the result of print(bs) to see how BS parsed the xml (formatted):
<?xml version="1.0" encoding="UTF-8"?>
<html>
    <body>
        <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">
            <channel>
                <lastbuilddate>Fri, 23 Apr 2021 06:08:56 GMT</lastbuilddate>
                <item>
                    <category>Europe</category>
                    <title>French fishermen seek to block British shipments in Brexit protest</title>
                    <link />
                    https://www.france24.com/en/europe/20210423-french-fishermen-seek-to-block-british-shipments-in-brexit-protest
                    <description>
French trawlermen angered by the slow issuance of licenses to fish inside British waters after Brexit on Thursday blocked lorries carrying UK-landed fish as they arrived in Boulogne-sur-Mer, Europe's largest seafood processing centre.
</description>
                    <media:thumbnail url="https://s.france24.com/media/display/70e354e8-a3e7-11eb-a6eb-005056bf87d6/w:1024/p:16x9/Brexit%20fishermen%20protest.jpg"></media:thumbnail>
                    <enclosure length="0" type="image/jpeg" url="https://s.france24.com/media/display/70e354e8-a3e7-11eb-a6eb-005056bf87d6/w:1024/p:16x9/Brexit%20fishermen%20protest.jpg"></enclosure>
                    <guid ispermalink="false">cadc08aa-a3e7-11eb-91c0-005056bff4a8</guid>
                    <pubdate>Fri, 23 Apr 2021 03:55:46 GMT</pubdate>
                    <source url="https://s.france24.com/media/display/70e354e8-a3e7-11eb-a6eb-005056bf87d6/w:1024/p:16x9/Brexit%20fishermen%20protest.jpg">© Denis Charlet, AFP</source>
                    <dc:creator>NEWS WIRES</dc:creator>
                </item>

Note pubdate and link /.
I fail to see what the problem is. Any opinions as to why it is being parsed incorrectly?

A: For the pubDate :
In the Xml that is parsed with BS, the balise pubDate become pubdate or in your code you are looking for pubDate
Maybe you can try this.

A: Try the xml parser:
bs = BeautifulSoup(text, "xml")

Here's the output I get for the first item:
1 - Without licenses to fish in British waters, French trawlermen block deliveries of UK-landed fish
<pubDate>Fri, 23 Apr 2021 03:55:46 GMT</pubDate>
French trawlermen angered by the slow issuance of licenses to fish inside British waters after Brexit on Thursday blocked lorries carrying UK-landed fish as they arrived in Boulogne-sur-Mer, Europe's largest seafood processing centre.
https://www.france24.com/en/europe/20210423-french-fishermen-seek-to-block-british-shipments-in-brexit-protest


text:
Q: Spring Data JPA Inheritance is not working This is my person class.
@Entity
@Table(name = "Person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "PersonID")
    private Long personID;
    @Column(name = "Name")
    @Convert(converter = NameConverter.class)
    private Name name;
    @Column(name = "Geburtsdatum")
    private LocalDate geburtsdatum;
    @Column(name = "Strasse")
    private String strasse;
    @Column(name = "Hausnummer")
    private String hausnummer;
    @Column(name = "PLZ")
    private String plz;
    @Column(name = "Ort")
    private String ort;
    @Column(name = "EMail")
    private String email;
    @Column(name = "Telefonnummer")
    private String telefonnummer;

    protected Person() {}

    public Person(Name name, LocalDate geburtsdatum, String strasse, String hausnummer, String plz, String ort, String email, String telefonnummer) {
        this.name = name;
        this.geburtsdatum = geburtsdatum;
        this.strasse = strasse;
        this.hausnummer = hausnummer;
        this.plz = plz;
        this.ort = ort;
        this.email = email;
        this.telefonnummer = telefonnummer;
    }

    @Override
    public String toString() {
        return String.format("PersonID: %d\nName: %s\nGeburtsdatum: %s\nE-Mail: %s\nTelefonnummer: %s\nAdresse: %s %s, %s %s\n",personID,name.getFullName(),geburtsdatum,email,telefonnummer,strasse,hausnummer,plz,ort);
    }

    /* Getter & Setters */
}

This is my Mitglied class which should be based of the person.
@Entity
@Table(name = "Mitglied")
public class Mitglied extends Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "MitgliedID")
    private Long mitgliedID;
    @Column(name = "ZPS")
    private String zps;
    @Column(name = "ZPSNummer")
    private String zpsNummer;
    @Column(name = "Eintrittsdatum")
    private LocalDate eintrittsDatum;
    @Column(name = "Austrittsdatum")
    private LocalDate austrittsDatum;
    @Column(name = "DWZ")
    private String dwz;
    @Column(name = "Elo")
    private String elo;
    @Column(name = "FIDETitel")
    private String fideTitel;

    protected Mitglied() {}

    public Mitglied(Name name, LocalDate geburtsdatum, String strasse, String hausnummer, String plz, String ort, String email, String telefonnummer, String zps, LocalDate eintrittsDatum, LocalDate austrittsDatum, String dwz, String elo, String fideTitel) {
        super(name, geburtsdatum, strasse, hausnummer, plz, ort, email, telefonnummer);
        this.zps = zps;
        this.eintrittsDatum = eintrittsDatum;
        this.austrittsDatum = austrittsDatum;
        this.dwz = dwz;
        this.elo = elo;
        this.fideTitel = fideTitel;
    }

    /* Getter & Setters */

}

I'm having the problem that if the Mitglied inherits from the Person than i got 2 unique IDs...
My guess would be to fix my problem i could change the Person class so it would not be a table anymore, but i don't really know how i would make my Mitglied Table have a column for each value.

A: There shouldn't be multiple @Id columns in the entity hierarchy. It's only logical because essentially they describe the same object, although with some differences.
If your intention was to have mitgliedID value autogenerated one solution would be to use Hibernate's @Generated/@ValueGenerationType annotations (https://docs.jboss.org/hibernate/orm/6.0/topical/html_single/generated/GeneratedValues.html#generated-values-guide).
Also, check out this question for other ways to achieve the same result: Hibernate JPA Sequence (non-Id)


text:
Q: Pos_hint ans size_hint do not seem to work in my kv file and I do not know why So, I've been trying some Kivy, and I've introduced just a button in my kv file associated with the following python code:
#importing library
import kivy
kivy.require('1.11.1') #version

#importing functionality
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty

class FloatLayout(Widget):
    username = ObjectProperty(None)
    password = ObjectProperty(None)
    """idle code here, does nothing"""

class howyoudoin(App):
    def build(self):
        return FloatLayout()

if __name__ == '__main__':
    howyoudoin().run()

And here is my kv file:
<Button>:
    font_size:27
    size_hint: 1.0, 1.0
    background_color: 0.1, 0.5, 0.6, 1

<FloatLayout>:
    Button:
        pos_hint:{"top":1.0}
        id: btn
        text: "button"

Somehow, the size_hint ans pos_hint commands just won't work for me. This returns my button, but ignoring the pos_hint and size_hint commands.
The button does not represent the desired position and size
All other attributes do work: when I change font_size in the code, the font_size changes in the run as well. I can't figure out why :(

A: You are redefining an existing class (FloatLayout), and by doing so you are making it a simple Widget as opposed to a Layout. Since your FloayLayout is not a Layout, it does not respect size_hint and pos_hint. Redefining an existing class is generally a bad idea. If you want to extend FloatLayout, try something like this:
#importing library
import kivy

kivy.require('1.11.1') #version

#importing functionality
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty

class MyFloatLayout(FloatLayout):
    username = ObjectProperty(None)
    password = ObjectProperty(None)
    """idle code here, does nothing"""

class howyoudoin(App):
    def build(self):
        return MyFloatLayout()

if __name__ == '__main__':
    howyoudoin().run()

kv file:
<Button>:
    font_size:27
    size_hint: 1.0, 1.0
    background_color: 0.1, 0.5, 0.6, 1

<MyFloatLayout>:
    Button:
        pos_hint:{"top":1.0}
        id: btn
        text: "button"

In the above code MyFloatLayout extends FloatLayout, so the size_hint and pos_hint of the Button will now be honored.


text:
Q: System halts for a fraction of second after every 2-3 seconds I'm using Windows 7 on my HP ProBook 4250s. The problem I face is that my system halts for a fraction of second after every 2-3 seconds. These jerks are not letting me concentrate or work properly. This happens even when I'm just typing in notepad while no other application is running. I tried to install every driver from HP's website and there's no item in device manager marked with yellow icon.
Following are my system specs:
Machine: HP ProBook 4250s
OS: Windows 7 professional
RAM: 2GB
Processor: Intel Core i3 2.27GHz
Following is my HijackThis Log:
**Logfile of HijackThis v1.99.1**

Scan saved at 9:34:03 PM, on 11/13/2012
Platform: Unknown Windows (WinNT 6.01.3504)
MSIE: Internet Explorer v9.00 (9.00.8112.16450)

**Running processes:**

C:\Windows\system32\taskhost.exe
C:\Windows\System32\rundll32.exe
C:\Windows\system32\Dwm.exe
C:\Windows\Explorer.EXE
C:\Windows\System32\igfxtray.exe
C:\Windows\System32\hkcmd.exe
C:\Windows\System32\igfxpers.exe
C:\Program Files\Synaptics\SynTP\SynTPEnh.exe
C:\Program Files\PowerISO\PWRISOVM.EXE
C:\Program Files\AVAST Software\Avast\AvastUI.exe
C:\Program Files\Free Download Manager\fdm.exe
C:\Windows\system32\wuauclt.exe
C:\Program Files\Windows Media Player\wmplayer.exe
C:\Program Files\Microsoft Office\Office12\WINWORD.EXE
C:\HijackThis\HijackThis.exe

R1 - HKCU\Software\Microsoft\Internet Explorer\Main,Search Page = http://go.microsoft.com/fwlink/?LinkId=54896
R0 - HKCU\Software\Microsoft\Internet Explorer\Main,Start Page = http://bing.com/
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Default_Page_URL = http://go.microsoft.com/fwlink/?LinkId=69157
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Default_Search_URL = http://go.microsoft.com/fwlink/?LinkId=54896
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Search Page = http://go.microsoft.com/fwlink/?LinkId=54896
R0 - HKLM\Software\Microsoft\Internet Explorer\Main,Start Page = http://go.microsoft.com/fwlink/?LinkId=69157
R0 - HKLM\Software\Microsoft\Internet Explorer\Search,SearchAssistant =
R0 - HKLM\Software\Microsoft\Internet Explorer\Search,CustomizeSearch =
R0 - HKCU\Software\Microsoft\Internet Explorer\Toolbar,LinksFolderName =
R3 - URLSearchHook: (no name) - {7473b6bd-4691-4744-a82b-7854eb3d70b6} - (no file)
O2 - BHO: Adobe PDF Reader Link Helper - {06849E9F-C8D7-4D59-B87D-784B7D6BE0B3} - C:\Program Files\Common Files\Adobe\Acrobat\ActiveX\AcroIEHelper.dll
O2 - BHO: Babylon toolbar helper - {2EECD738-5844-4a99-B4B6-146BF802613B} - (no file)
O2 - BHO: MrFroggy - {856E12B5-22D7-4E22-9ACA-EA9A008DD65B} - C:\Program Files\Minibar\Froggy.dll
O2 - BHO: avast! WebRep - {8E5E2654-AD2D-48bf-AC2D-D17F00898D06} - C:\Program Files\AVAST Software\Avast\aswWebRepIE.dll
O2 - BHO: Windows Live ID Sign-in Helper - {9030D464-4C02-4ABF-8ECC-5164760863C6} - C:\Program Files\Common Files\Microsoft Shared\Windows Live\WindowsLiveLogin.dll
O2 - BHO: Minibar BHO - {AA74D58F-ACD0-450D-A85E-6C04B171C044} - C:\Program Files\Minibar\Kango.dll
O2 - BHO: Free Download Manager - {CC59E0F9-7E43-44FA-9FAA-8377850BF205} - C:\Program Files\Free Download Manager\iefdm2.dll
O2 - BHO: HP Network Check Helper - {E76FD755-C1BA-4DCB-9F13-99BD91223ADE} - C:\Program Files\Hewlett-Packard\HP Support Framework\Resources\HPNetworkCheck\HPNetworkCheckPlugin.dll
O3 - Toolbar: (no name) - {98889811-442D-49dd-99D7-DC866BE87DBC} - (no file)
O3 - Toolbar: avast! WebRep - {8E5E2654-AD2D-48bf-AC2D-D17F00898D06} - C:\Program Files\AVAST Software\Avast\aswWebRepIE.dll
O4 - HKLM\..\Run: [IgfxTray] C:\Windows\system32\igfxtray.exe
O4 - HKLM\..\Run: [HotKeysCmds] C:\Windows\system32\hkcmd.exe
O4 - HKLM\..\Run: [Persistence] C:\Windows\system32\igfxpers.exe
O4 - HKLM\..\Run: [SynTPEnh] %ProgramFiles%\Synaptics\SynTP\SynTPEnh.exe
O4 - HKLM\..\Run: [PWRISOVM.EXE] C:\Program Files\PowerISO\PWRISOVM.EXE -startup
O4 - HKLM\..\Run: [AdobeAAMUpdater-1.0] "C:\Program Files\Common Files\Adobe\OOBE\PDApp\UWA\UpdaterStartupUtility.exe"
O4 - HKLM\..\Run: [AdobeCS6ServiceManager] "C:\Program Files\Common Files\Adobe\CS6ServiceManager\CS6ServiceManager.exe" -launchedbylogin
O4 - HKLM\..\Run: [SwitchBoard] C:\Program Files\Common Files\Adobe\SwitchBoard\SwitchBoard.exe
O4 - HKLM\..\Run: [ROC_roc_ssl_v12] "C:\Program Files\AVG Secure Search\ROC_roc_ssl_v12.exe" / /PROMPT /CMPID=roc_ssl_v12
O4 - HKLM\..\Run: [avast] "C:\Program Files\AVAST Software\Avast\avastUI.exe" /nogui
O4 - HKLM\..\Run: [Wordinn English to Urdu Dictionary] "C:\Program Files\Wordinn\Urdu Dictionary\bin\Lugat.exe" -h
O4 - HKLM\..\Run: [Adobe Reader Speed Launcher] "C:\Program Files\Adobe\Reader 8.0\Reader\Reader_sl.exe"
O4 - HKCU\..\Run: [Comparator Fast] "C:\Program Files\Interdesigner Software\Comparator Fast\ComparatorFast.exe"  /STARTUP
O4 - HKCU\..\Run: [Free Download Manager] "C:\Program Files\Free Download Manager\fdm.exe" -autorun
O8 - Extra context menu item: Download all with Free Download Manager - file://C:\Program Files\Free Download Manager\dlall.htm
O8 - Extra context menu item: Download selected with Free Download Manager - file://C:\Program Files\Free Download Manager\dlselected.htm
O8 - Extra context menu item: Download video with Free Download Manager - file://C:\Program Files\Free Download Manager\dlfvideo.htm
O8 - Extra context menu item: Download with Free Download Manager - file://C:\Program Files\Free Download Manager\dllink.htm
O8 - Extra context menu item: E&xport to Microsoft Excel - res://C:\PROGRA~1\MICROS~2\Office12\EXCEL.EXE/3000
O9 - Extra button: @C:\Program Files\Hewlett-Packard\HP Support Framework\Resources\HPNetworkCheck\HPNetworkCheckPlugin.dll,-103 - {25510184-5A38-4A99-B273-DCA8EEF6CD08} - C:\Program Files\Hewlett-Packard\HP Support Framework\Resources\HPNetworkCheck\NCLauncherFromIE.exe
O9 - Extra 'Tools' menuitem: @C:\Program Files\Hewlett-Packard\HP Support Framework\Resources\HPNetworkCheck\HPNetworkCheckPlugin.dll,-102 - {25510184-5A38-4A99-B273-DCA8EEF6CD08} - C:\Program Files\Hewlett-Packard\HP Support Framework\Resources\HPNetworkCheck\NCLauncherFromIE.exe
O9 - Extra button: Research - {92780B25-18CC-41C8-B9BE-3C9C571A8263} - C:\PROGRA~1\MICROS~2\Office12\REFIEBAR.DLL
O9 - Extra button: Change your facebook look - {AAA38851-3CFF-475F-B5E0-720D3645E4A5} - C:\Program Files\Minibar\MinibarButton.dll
O10 - Unknown file in Winsock LSP: c:\windows\system32\nlaapi.dll
O10 - Unknown file in Winsock LSP: c:\windows\system32\napinsp.dll
O10 - Unknown file in Winsock LSP: c:\program files\common files\microsoft shared\windows live\wlidnsp.dll
O10 - Unknown file in Winsock LSP: c:\program files\common files\microsoft shared\windows live\wlidnsp.dll
O11 - Options group: [ACCELERATED_GRAPHICS] Accelerated graphics
O11 - Options group: [INTERNATIONAL] International
O13 - Gopher Prefix:
O17 - HKLM\System\CCS\Services\Tcpip\..\{920289D7-5F75-4181-9A37-5627EAA163E3}: NameServer = 8.8.8.8,8.8.4.4
O17 - HKLM\System\CCS\Services\Tcpip\..\{AE83ED2F-EF14-4066-ACE2-C4ED07A68EAA}: NameServer = 9.9.9.9,8.8.8.8
O18 - Protocol: ms-help - {314111C7-A502-11D2-BBCA-00C04F8EC294} - C:\Program Files\Common Files\Microsoft Shared\Help\hxds.dll
O18 - Protocol: skype4com - {FFC8B962-9B40-4DFF-9458-1830C7DD7F5D} - C:\PROGRA~1\COMMON~1\Skype\SKYPE4~1.DLL
O18 - Protocol: wlpg - {E43EF6CD-A37A-4A9B-9E6F-83F89B8E6324} - C:\Program Files\Windows Live\Photo Gallery\AlbumDownloadProtocolHandler.dll
O18 - Filter hijack: text/xml - {807563E5-5146-11D5-A672-00B0D022E945} - C:\PROGRA~1\COMMON~1\MICROS~1\OFFICE12\MSOXMLMF.DLL
O20 - AppInit_DLLs: c:\progra~2\browse~1\23787~1.43\{16cdf~1\browse~1.dll c:\progra~2\browse~1\22630~1.40\{16cdf~1\browse~1.dll
O20 - Winlogon Notify: igfxcui - C:\Windows\SYSTEM32\igfxdev.dll
O23 - Service: avast! Antivirus - AVAST Software - C:\Program Files\AVAST Software\Avast\AvastSvc.exe
O23 - Service: Google Software Updater (gusvc) - Google - C:\Program Files\Google\Common\Google Updater\GoogleUpdaterService.exe
O23 - Service: HP Support Assistant Service - Hewlett-Packard Company - C:\Program Files\Hewlett-Packard\HP Support Framework\hpsa_service.exe
O23 - Service: HP Quick Synchronization Service (HPDrvMntSvc.exe) - Hewlett-Packard Company - C:\Program Files\Hewlett-Packard\Shared\HPDrvMntSvc.exe
O23 - Service: HP Software Framework Service (hpqwmiex) - Hewlett-Packard Company - C:\Program Files\Hewlett-Packard\Shared\hpqWmiEx.exe
O23 - Service: HP Service (hpsrv) - Hewlett-Packard Company - C:\Windows\system32\Hpservice.exe
O23 - Service: Intel(R) Management and Security Application Local Management Service (LMS) - Intel Corporation - C:\Program Files\Intel\Intel(R) Management Engine Components\LMS\LMS.exe
O23 - Service: Mozilla Maintenance Service (MozillaMaintenance) - Mozilla Foundation - C:\Program Files\Mozilla Maintenance Service\maintenanceservice.exe
O23 - Service: @%SystemRoot%\system32\qwave.dll,-1 (QWAVE) - Unknown owner - %windir%\system32\svchost.exe (file missing)
O23 - Service: @%SystemRoot%\system32\seclogon.dll,-7001 (seclogon) - Unknown owner - %windir%\system32\svchost.exe (file missing)
O23 - Service: Skype Updater (SkypeUpdate) - Skype Technologies - C:\Program Files\Skype\Updater\Updater.exe
O23 - Service: Adobe SwitchBoard (SwitchBoard) - Adobe Systems Incorporated - C:\Program Files\Common Files\Adobe\SwitchBoard\SwitchBoard.exe
O23 - Service: Intel(R) Management & Security Application User Notification Service (UNS) - Intel Corporation - C:\Program Files\Intel\Intel(R) Management Engine Components\UNS\UNS.exe
O23 - Service: @%PROGRAMFILES%\Windows Media Player\wmpnetwk.exe,-101 (WMPNetworkSvc) - Unknown owner - %PROGRAMFILES%\Windows Media Player\wmpnetwk.exe (file missing)