Optimizing .gs search & replace script?

Question: Hoping someone could just point out my probably obvious mistakes.
Code searches a Data page & copies matched info to a Results page. This is fine & works quickly.
What happens is when I add an overwrite section to the script. It overwrites matched entries as "Done" on the data page, so if the Data page gets added to, the previous entries won't match again.
I have 2 variants I've tried that work but are quite slow...as in you can sit & watch each match change to "Done" once every few seconds.
Appreciate any insight.
Here's the code:
function cellMatch() {
  // Sheet Import
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName("Raw_Data"); // Data
  var sheet2 = ss.getSheetByName("Pallet_Data");// Result
  var sheet3 = ss.getSheetByName("Close");// Search
  // Data Import
  var lr = sheet1.getLastRow();
  var data = sheet1.getRange(2,1,lr-1,2).getValues();
  var lc = sheet2.getLastColumn()+1;
  var key = sheet3.getRange("A2").getValue();
  var matched = [["Pallet "+lc+" ("+key+")"]];

  //Start
  for (var i=0; i<lr-1; i++) {
    if (data[i][1] == key) {
      var temp = [];
      temp.push(data[i][0]);
      matched.push(temp);

// Slow Overwrite-----------------------------------
/*
if(i>0){
  var temp1 = sheet1.getRange(i,2).getValue();
  var temp2 = sheet1.getRange(i+1,2).getValue();
  var temp3 = sheet1.getRange(i+2,2).getValue();
    // Testing1
    if(temp1 == key ){
      sheet1.getRange(i,2).setValue("Done");
    }
    if (i== lr-2){
      if (temp2 == key){
          sheet1.getRange(i+1,2).setValue("Done");
       }
      if (temp3 == key){
         sheet1.getRange(i+2,2).setValue("Done");
       }
    }
}
*/
  }

  // Shorter code but even slower overwrite----------------
/*
  for(var i=1; i<=lr; i++){
    var temp1 = sheet1.getRange(i,2).getValue();
    if(temp1 == key){
      sheet1.getRange(i,2).setValue("Done");
     }
   }
*/

// Location Update ---------------------------------
    var A7 = sheet3.getRange("A7");
    A7.setValue(matched);

// Data Write -----------------------------------------
  var result = sheet2.getRange(1,lc,matched.length);
  result.setValues(matched);

}

Link to the Test Sheet
Answer: Solution:
The script runs slow because there are API calls in for loops. Best practice is to manipulate only the array inside the loop and do the API calls before and after the loop.
In your code it would look like this:
function cellMatch() {
  // Sheet Import
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName("Raw_Data"); // Data
  var sheet2 = ss.getSheetByName("Pallet_Data");// Result
  var sheet3 = ss.getSheetByName("Close");// Search
  // Data Import
  var lr = sheet1.getLastRow();
  var datarange = sheet1.getRange(2,1,lr-1,2);
  var data = datarange.getValues();
  var lc = sheet2.getLastColumn()+1;
  var key = sheet3.getRange("A2").getValue();
  var matched = [["Pallet "+lc+" ("+key+")"]];

  //Start
  for (var i=0; i<lr-1; i++) {
    if (data[i][1] == key) {
      var temp = [];
      temp.push(data[i][0]);
      matched.push(temp);
      data[i][1] = "Done";
    }

// Location Update ---------------------------------
    var A7 = sheet3.getRange("A7");
    A7.setValue(matched);

// Data Write -----------------------------------------
  datarange.setValues(data);
  var result = sheet2.getRange(1,lc,matched.length);
  result.setValues(matched);
}

Note that the for loop does not have any getValue()/setValue() methods.
This has the same effect on your sample sheet, only way faster.
Comment: Thanks for that!! If you don't mind, why won't just ```data[i][1] = "Done"``` work without the ```datarange.setValues(data)```?  I had tried something similar before, thinking it would write on each loop. It makes in context how you implemented it.
Comment: ````data```` is only an internal array in the script, copied when ````getValues()```` was used earlier. You still need to use ````setValues(data)```` to apply it to the sheet.

Optimizing .gs search & replace script?


Load scripts in the head AND bottom of the page?

Question: I need to load head.js in my head and application.js at the bottom of my page. The following seems to stop all my scripts being loaded! Is there a syntax error? Im confused as I used the documentation from here:
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}

  js-header:
    header: true
    js:
      /ui/head.js: {preprocess: false, minified: false, weight: '-100'}

  js-footer:
    js:
      /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

UPDATE - It appears to me that header: true is used to move either all or none of the scripts to the head. Can someone confirm if this is right?
If this is the case, how can I load scripts in both the head and the bottom of the page?
Answer: You have to add additional libraries: https://ffwagency.com/blog/managing-css-and-javascript-files-drupal-8-libraries
So in my theme.info.yaml
libraries:
  - THEME-NAME/global
  - THEME-NAME/custom

In my theme.libraries.yaml file:
global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}
  js:
    /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

custom:
  version: 1.x
  header: true
  js:
    /ui/head.js: {}


Inverse image of dominating component

Question: Let $f:X\rightarrow Y$ be a surjective proper morphism of varieties, with $Y$ irreducible. The fibers of $f$ are irreducible (not necessarily of same dimension). Let $U$ be an irreducible, dense, open subset of $Y$, such that $f^{-1}(U)$ is isomorphic to $U$.
Then $f^{-1}(U)$ is an irreducible open set of $X$. Is $\overline{f^{-1}(U)}$ an irreducible component of $X$. It is clearly an irreducible closed set of $X$. Why is it maximal?
If $g:Y\rightarrow Z$ is again a proper surjective morphism with $Z$ irreducible. When can we say that $\overline{f^{-1}(U)}$ is the only component of $X$ dominating $Z$?
Answer: Note for the following that making a statement about $h=g\circ f$ doesn't really differ from making a statement about $f$, because $h$ is also surjective and proper with an irreducible target, and that's all we know about $f$. The following also answers the question about $f$.
As per request in the comment, we will prove the following statement: Let $f\colon X\to Y$ be a proper surjective morphism of varieties with $Y$ irreducible. Then, there is only one irreducible compoent of $X$ dominating $Y$ if and only if there is a nonempty open subset $U\subseteq Y$ such that $f^{-1}(U)$ is irreducible.
Assume first there is an $U$ with this property and let $W\subseteq X$ be any irreducible component of $X$ dominating $Y$. Since $f(W)=Y$, we know that $W\cap f^{-1}(U)$ is nonempty and open in $W$. It follows that
$$\overline{f^{-1}(U)}\supseteq\overline{W\cap f^{-1}(U)}=W,$$
the equality holding because $W$ is irreducible.
By maximality of $W$ on the other hand, $W=\overline{f^{-1}(U)}$, so there is only one component of $X$ dominating $Y$ and it is equal to $\overline{f^{-1}(U)}$.
For the converse, assume that there is only one component of $X$ which dominates $Y$, call it $W$. Then, $f(W)=Y$. Let $H\subseteq X$ be the union of all other irreducible components of $X$, it is a closed subset of $X$ and $f(H)$ is a proper, closed subset of $Y$. Set $U:= Y\setminus f(H)$, this is a nonempty open subset of $Y$. Furthermore, $f^{-1}(U)$ is a nonempty open subset of $W$ by construction, hence $W=\overline{f^{-1}(U)}$. Since $W$ is irreducible, so is $f^{-1}(U)$.
Comment: No, we assumed $f(W)=Y$, so in particular there is some $x\in W$ with $f(x)\in U$, in particular $x\in f^{-1}(U)\cap W$.
Comment: I don't understand the end. It doesn't seem to be complete?
Comment: @user349424: Yes odd, I don't know how that happened..
Comment: we have proper surjective maps $f:X\rightarrow Y$ and $g:Y\rightarrow Z$ where $Y$ and $Z$ are irreducible and $f^{-1}(U)\simeq U$, where $U\subset Y$ open. If I want only one component $ X$ to dominate $Z$ then do you mean we should have some open subset of $Z$ such that the preimage in $X$ is irreducible? Can you please indicate a proof of this?

Inverse image of dominating component


Maui How to show cursor as pointer on Windows?

Question: In a Maui app on Windows, I would like the cursor to look like a pointer while hovering over a Label with TapGestureRecognizer or a Button. Is that possible and if so, how?
All I have found so far is some alternative way of feedback through background color.
<PointerGestureRecognizer PointerEntered="OnPointerEntered"
                          PointerExited="OnPointerExited" />

and C#:
private void OnPointerEntered(object? sender, PointerEventArgs e)
{
    (((Label)sender!)!).BackgroundColor = Colors.LightCyan;
}

private void OnPointerExited(object? sender, PointerEventArgs e)
{
    (((Label)sender!)!).BackgroundColor = Colors.White;
}

Comment: A quick [web search](https://duckduckgo.com/?q=maui+windows+cursor&ia=web) yielded this: https://vladislavantonyuk.github.io/articles/Setting-a-cursor-for-.NET-MAUI-VisualElement/
Comment: I have not looked closely at code, but probably you have EITHER not correctly added **static class CursorExtensions** that defines `SetCustomCursor`, and adds it to `VisualElement`, OR have mixed up **cross-platform** `VisualElement` with a **platform-specific** class, which must be inside folder `Platforms/PlatformNameHere` or inside `#if PlatformNameHere`. To test the first case, see if intellisense can find `CursorExtensions.SetCustomCursor(.., ..)`, or complains it does not exist.
Comment: @Julian It looks pretty cool. But VisualElement does not have a method SetCustomCursor(..) (used in his class CursorBehavior), so it does not work.
Answer: The sample code does work on my side. When debugging the code, click the SetCustomCursor() in CursorExtensions.cs and then go to its definition (enter F12), it directs to the CursorExtensions.cs in Platforms/Android. So you may need add that implementation in your Maui project.
Also, notice that the namespace format is little difference compared to that you create a new class. You can download the sample project and then copy necessary file to your Maui Project. The only thing you need to do is changing the namespace MauiCursor; to your own proejct namespace namespace yourownproject;


reading widememo valus in oracle toad

Question: I have the following query
SELECT A.COLUMN_NAME AS COLUMN_NAME_1_ON_2,
       UC.CONSTRAINT_NAME AS NAME_1_CONSTRAINTS_2_,
       UC.SEARCH_CONDITION AS CONDITION
  --,UC2.TABLE_NAME AS REFERENCE_TABLE
  FROM USER_CONSTRAINTS UC
       JOIN ALL_CONS_COLUMNS A ON A.CONSTRAINT_NAME = UC.CONSTRAINT_NAME
       LEFT JOIN USER_CONSTRAINTS UC2
          ON UC.R_CONSTRAINT_NAME = UC2.CONSTRAINT_NAME

This query SEARCH_CONDITION condition of the constraint but it is coming as wide memo and not being being read by my code. Earlier In toad 11.5 I used the  SEARCH_CONDITION_VC which gave the proper result, but now when I run this column it gives the following error

[Error] Execution (2: 2): ORA-00904: "UC2"."SEARCH_CONDITION_VC": invalid identifier

How do I get use the result of the search condition in oracle toad 13.4?
Answer: It isn't about TOAD version, but database version.
I presume you're connected to a database whose version is lower than 12c because - in those versions, there's no SEARCH_CONDITION_VC column.
See the difference:
SQL> select banner from v$version where rownum = 1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 188.8.131.52.0 - Production

SQL> desc user_constraints;
 Name                                                  Null?    Type
 ----------------------------------------------------- -------- ------------------------------------
 OWNER                                                          VARCHAR2(128)
 CONSTRAINT_NAME                                       NOT NULL VARCHAR2(128)
 CONSTRAINT_TYPE                                                VARCHAR2(1)
 TABLE_NAME                                            NOT NULL VARCHAR2(128)
 SEARCH_CONDITION                                               LONG
 SEARCH_CONDITION_VC                                            VARCHAR2(4000)    --> here it is
 R_OWNER                                                        VARCHAR2(128)
 R_CONSTRAINT_NAME                                              VARCHAR2(128)
 DELETE_RULE                                                    VARCHAR2(9)
 STATUS                                                         VARCHAR2(8)
 DEFERRABLE                                                     VARCHAR2(14)
 DEFERRED                                                       VARCHAR2(9)
 VALIDATED                                                      VARCHAR2(13)
 GENERATED                                                      VARCHAR2(14)
 BAD                                                            VARCHAR2(3)
 RELY                                                           VARCHAR2(4)
 LAST_CHANGE                                                    DATE
 INDEX_OWNER                                                    VARCHAR2(128)
 INDEX_NAME                                                     VARCHAR2(128)
 INVALID                                                        VARCHAR2(7)
 VIEW_RELATED                                                   VARCHAR2(14)
 ORIGIN_CON_ID                                                  NUMBER

SQL>

SQL> select banner from v$version where rownum = 1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 22.214.171.124.0 - 64bit Production

SQL> desc user_constraints;
 Name                                                  Null?    Type
 ----------------------------------------------------- -------- ----------------------------------
 OWNER                                                          VARCHAR2(30)
 CONSTRAINT_NAME                                       NOT NULL VARCHAR2(30)
 CONSTRAINT_TYPE                                                VARCHAR2(1)
 TABLE_NAME                                            NOT NULL VARCHAR2(30)
 SEARCH_CONDITION                                               LONG            --> no SEARCH_CONDITION_VC column
 R_OWNER                                                        VARCHAR2(30)
 R_CONSTRAINT_NAME                                              VARCHAR2(30)
 DELETE_RULE                                                    VARCHAR2(9)
 STATUS                                                         VARCHAR2(8)
 DEFERRABLE                                                     VARCHAR2(14)
 DEFERRED                                                       VARCHAR2(9)
 VALIDATED                                                      VARCHAR2(13)
 GENERATED                                                      VARCHAR2(14)
 BAD                                                            VARCHAR2(3)
 RELY                                                           VARCHAR2(4)
 LAST_CHANGE                                                    DATE
 INDEX_OWNER                                                    VARCHAR2(30)
 INDEX_NAME                                                     VARCHAR2(30)
 INVALID                                                        VARCHAR2(7)
 VIEW_RELATED                                                   VARCHAR2(14)

SQL>

What to do, then? Create a function which will return a string out of the "original" search_condition. Something like this:
SQL> CREATE OR REPLACE FUNCTION f_long (par_con_name IN VARCHAR2)
  2     RETURN VARCHAR2
  3  IS
  4     l_col  LONG;
  5  BEGIN
  6     SELECT search_condition
  7       INTO l_col
  8       FROM user_constraints
  9      WHERE constraint_name = par_con_name;
 10
 11     RETURN SUBSTR (l_col, 1, 4000);
 12  END;
 13  /

Function created.

SQL> SELECT f_long ('SYS_C0085257') FROM DUAL;

F_LONG('SYS_C0085257')
--------------------------------------------------------------------------
"OIB" IS NOT NULL

SQL>

Comment: It is also possible to work this around without new DB objects [with `XMLTABLE`](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=ce106ae166e34205ec3c0f2a0cbeb64b) and `dbms_xmlgen.getxmltype('select table_name, constraint_name, search_condition from USER_CONSTRAINTS)`. But performance will be slow, it is better use another subquery and restrict it to `SEARCH_CONDITION is not null`.

reading widememo valus in oracle toad


Convergence from Gamma to Normal Distribution

Question: I came across this problem:
Problem
If I have $X_1, X_2, ..., X_n$ $n$ iid random variables which pdf is
$$
f_X(x) = \begin{cases} \dfrac{x^{\mu-1} e^{-x}}{\Gamma{(\mu)}} &0<x<\infty, \\0&\text{elsewhere}\end{cases}
$$
namely a $\text{Gamma}(\alpha=\mu, \beta=1)$ distribution. Let $n\bar{X}_n= X_1+X_2+\cdots+X_n$. I need to prove that $$T_n\stackrel{\text{dist}}{\stackrel{n\to\infty}{\longrightarrow}}N(0,{1}/{\mu})$$ where
$$T_n= \frac{\sqrt{n}(\bar{X}_n-\mu)}{\bar{X}_n}$$
My Solution:
I thought of a possible solution in two steps:

First, we need to find the pdf of $\bar{X}_n$ and then of $T_n$.
Then we take the limit of it and if we get a Normal distribution then, we solved the question.

\begin{align*}
F_T(t) &=  P(T \le t)
\\&
= P(\frac{\sqrt{n}(\bar{X}_n-\mu)}{\bar{X}_n} \le t)
\\&
= P(\frac{(\bar{X}_n-\mu)}{\bar{X}} \le \frac{t}{\sqrt{n}})
\\&
= P(1- \frac{\mu}{\bar{X}_n} \le \frac{t}{\sqrt{n}})
\\&
= P(\frac{\mu}{\bar{X}_n} \ge 1- \frac{t}{\sqrt{n}})
\\&
= P(\frac{\bar{X}_n}{\mu} \le \frac{\sqrt{n}}{\sqrt{n}-t})
\\&
= P(\bar{X}_n \le \frac{\mu\sqrt{n}}{\sqrt{n}-t})
\end{align*}
Now, I should do the integration $\int_0^\frac{\mu\sqrt{n}}{\sqrt{n}-t}$ of the pdf of $\bar{X}_n$. But it is not the same distribution as $X_i$. It is something else. This is where I stuck in my solution.
To clarify: My goal is to prove $T_n\stackrel{\text{d}}{\longrightarrow}Normal$, not finding the distribution of $\bar{X}_n$.
Any help will be appreciated!
Comment: @Xi'an Is it $Ga(\mu,n)$?
Comment: @Xi'an Can you clarify, please? How to check if it applies or not?
Comment: @Xi'an I came to the conclusion that to integral is not solvable, or it won't help me do the next step. CLT is close to what I have, but not the same. The problem is the $\bar{X}$ in the dominator.
Comment: @Xi'an Sorry, but I still can't see how Slutsky's theorem would help. The theorem assumes one variable to converge to a constant. In my case, both nominator and dominator should converge to a variable.
Comment: @Xi'an That's what I meant in my previous comment. Both of them should converge to a variable. Not a variable and a constant, as stated by Slutsky's theorem.
Answer: This problem is a direct application of Slutsky's theorem:

If $X_n$ converges in distribution to a random element $X$
  and if $Y_n$ converges in probability to a constant $c$, then $X_n/Y_n$ converges in distribution to $X/c$.

In your setting, the theorem numerator "$X_n$" is replaced with $\sqrt{n}(\bar{X}_n-\mu)$, since, by virtue of the Central Limit Theorem,
$$\sqrt{n}(\bar{X}_n-\mu)\stackrel{\text{dist}}{\stackrel{n\to\infty}{\longrightarrow}}\mathcal{N}(0,\text{var}(X_i))$$ and here $\text{var}(X_i)=\mu$, hence $$\sqrt{n}(\bar{X}_n-\mu)\stackrel{\text{dist}}{\stackrel{n\to\infty}{\longrightarrow}}\mathcal{N}(0,\mu)\,.$$ And the theorem denominator "$Y_n$" is replaced with $\bar{X}_n$ which converges in probability to its expectation $\mu$ by the weak law of large numbers. Hence,
$$\dfrac{\sqrt{n}(\bar{X}_n-\mu)}{\bar{X}_n}\stackrel{\text{dist}}{\stackrel{n\to\infty}{\longrightarrow}}\mathcal{N}(0/\mu,\mu/\mu^2)
$$i.e.
$$\dfrac{\sqrt{n}(\bar{X}_n-\mu)}{\bar{X}_n}\stackrel{\text{dist}}{\stackrel{n\to\infty}{\longrightarrow}}\mathcal{N}(0,1/\mu)$$
Q.E.D.
Comment: Thanks for the answer. I though $\bar{X}$ will converge to a variable. I was Wrong. Thanks again!


Calling Models from Config Files

Question: I am writing a ruby scheduler - namely rufus-scheduler and there are commands i need to write in the initializers section inside the config folder to perform a task every 1 minute or so. I am trying to access a method from a module within this. So my code would look like
scheduler.every("1m") do
  puts("HELLO #{Time.now}")
  ModelName.methodname("WHAT ARE YOU DOING")
end

This somehow doesn't perform the necessary operation in the model. Also im not sure if this is the right way to do things - such as call a model inside a config file. Is there a better place to put this code in the Model? Or is calling a Model within config files perfectly good practice. I looked over the internet to see the usage of different types of files in ruby but couldn't find a proper material. Any help or guidance appreciated.
Answer: If you want to access models from stand-alone tasks the best way is to use the rails runner wrapper. For example, you'd call your script as:
rails runner call_model.rb

This loads in the Rails environment and then executes your script, eliminating the need to do that yourself. Models on their own will not work since they are lacking the context of Rails.
If that's not sufficient, you may need to load the Rails environment more directly by including config/environment.rb into your rufus-scheduler configuration.
Answer: It sounds like you actually want a real scheduled action of some sort. config files are for configuration, not for actual working code of that sort.
There are tons of ways to run scheduled tasks in rails.
google "rails daemons" or "rails scheduled tasks" to start you off.
Here's a good list of scheduled-task best practices using cron:
A cron job for rails: best practices?

Calling Models from Config Files


How to efficently use Drupal as a laboratory notebook and information management system?

Question: I am a chemo-informatics researcher looking to find user experiences and feedback on methods to keep laboratory notebooks on a computer and/or online using Drupal ( e.g. plugins to use, taxonomies).
Comment: Do you want something similar to Google Notes?
Comment: some links : http://linnovate.github.com/openidealapp/ , http://www.scivee.tv/node/21244
Comment: There's no reason to use a CMS as a notebook. Evernote. Microsoft OneNote. Google Docs. There are so many good options built for this task already.
Comment: Actually there are. A CMS can be deployed on web and scale up to your needs. Plus you own the data (vs Google).
Answer: How do you want to organize your information?  I would use a content type such as 'notebook_entry' with a taxonomy 'subjects' and/or 'projects' that allows free tagging of terms.
notebook_entry should use the body field for the bulk of your content.  You can add additional text/image/file fields for storing related information that can be displayed with the content.
I recommend using views to display your notebook entries.  You can create an argument in your page view with the taxonomy term or terms you've defined for the notebook_entry content type.  This will make the page only display entries related to that term.  You'll have to create a menu block filtered by the taxonomy to access your content.  It will list each of the taxonomy terms as links to your page view that displays your notebook_entries.  Create a list of terms and use the global text field to make a link to the path of your page view including the arguments.
Comment: Why would you want a local installation in the first place? The point of having a web-based solution is not having to install something locally. In case of Evernote, what you have locally is a standalone application, which is something completely different to provide better Usability/Offline capabilities. Synchronizing data like this between multiple installlations (I assume others would then also have local installations, not just you) is quite a complex problem space (Dealing with multiple edits, conflicts, etc.)
Comment: Thanks for your answer Arosboro. I would also want to create a system that is working like Evernote, being able to sync two drupal installations between my local computer and my online hosting. Do you have heard of a plugin to do that ?
Comment: If you want to work locally, consider writing notes as emails with an offline email app, then sending them to a predefined email address when you have Internet access. You can use the Mailhandler module to poll that email box, pick up the notes, map your email contents to desired fields, and create the Drupal nodes.
Comment: @Roland i totally understand your need :) try http://drupal.org/project/deploy


floats with overflow hidden and min-width in firefox

Question: I am working on a simple responsive layout, where I have a list containing of an small floated left image and information about image on side . On full width, I want to display info on same row as image. On small width I need the text to appear under image. I am using min-width in info container along with overflow hidden, so it does not wrap. This works in chrome but not in firefox. Is there any workaround? Thank you.
code

css
.wrapper {width:100%}
.image {height:50px;width:50px;margin:10px;border:1px solid;float:left}
.info {min-width:200px;overflow:hidden}
.clear {clear:both}

fiddle
http://jsfiddle.net/b4ffoayh/
Solution: what works for me - I added float left to .info as well and put 70%width on .info. This way firefox seems to cooperate.
Answer: You need to use media queries. Here's a fast example based off of your fiddle:
http://jsfiddle.net/austinthedeveloper/b4ffoayh/1/
@media (max-width: 600px) {
    .image {
        display: block;
        float: none;
    }
}

Shrink the html window to see it working.
I also added the clear on the lists to fix the floating issues. Overflow:hidden is not necessary unless you're really wanting it for some reason.
Comment: I do not want to use mediaqueries. Think of wrapper as only a part of full width. So I need to do this based on width of wrapper.
Answer: Both elements within the list-item need to be floating. Then the .info needs to take up remaining space next to the image, which can be achieved by using the calc() function.
This is what I added to make it work:
.info {float:left;width:calc(100% - 100px);}
li:after {content:" ";display:block;clear:left;}

Comment: hi, I think I need a solution for css2 as well:)


Como adicionar efeito Shadow em um Framelayout?

Question: Eu gostaria de adicionar um efeito shadow que resulta-se em um ressalto da tela, igual este abaixo:
Imagem do google:

Código
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/gray">

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView_header_book"
            android:layout_width= "match_parent"
            android:layout_height="84dp"
            android:layout_marginBottom="410dp"
            android:scaleType="fitXY"
            android:src="@drawable/header_book"/>

        <TextView
            android:id="@+id/custom_view_loja"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_horizontal|center_vertical"
            android:maxLines="1"
            android:textColor="@color/white"
            android:textSize="@dimen/overlay_loja"
            android:textStyle="bold"
            android:shadowColor="@color/black"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="2"/>

        <TextView
            android:id="@+id/custom_view_shopping"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:gravity="center_horizontal|center_vertical"
            android:shadowColor="@color/black"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="2"
            android:maxLines="1"
            android:textColor="@color/white"
            android:textSize="@dimen/overlay_shopping" />

        <TextView
            android:id="@+id/custom_view_competencia"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="71dp"
            android:gravity="center_horizontal|center_vertical"
            android:maxLines="1"
            android:textColor="@color/white"
            android:textSize="@dimen/overlay_competencia"
            android:shadowColor="@color/black"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="2"/>
    </FrameLayout>

    <LinearLayout
        android:id="@+id/custom_view_information_container"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/custom_view_book_horizontal"
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:orientation="horizontal" >

            <LinearLayout
                android:id="@+id/custom_view_book_text_data"
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:orientation="vertical">

                <FrameLayout
                    android:layout_width="245dp"
                    android:layout_height="60dp"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_marginTop="88dp"
                    android:background="@color/white">

                    <ImageView
                        android:id="@+id/imageView_aluguel_shopping"
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:layout_gravity="left"
                        android:layout_marginLeft="15dp"
                        android:layout_marginTop="6dp"
                        android:src="@drawable/aluguel_shopping" />

                    <TextView
                        android:id="@+id/textView_aluguel_icon_title"
                        android:layout_width="wrap_content"
                        android:layout_height="14dp"
                        android:layout_gravity="left"
                        android:layout_marginLeft="75dp"
                        android:layout_marginTop="17dp"
                        android:gravity="left"
                        android:text="Aluguel"
                        android:textColor="@color/black"
                        android:textSize="@dimen/overlay_aluguel_icon"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/custom_view_valor_aluguel"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_gravity="left"
                        android:layout_marginLeft="73dp"
                        android:layout_marginTop="30dp"
                        android:gravity="left"
                        android:maxLines="1"
                        android:textColor="@color/green_aliansce"
                        android:textSize="@dimen/overlay_valorAluguel" />

                    <ImageView
                        android:id="@+id/imageView_aluguel_mensal_icon"
                        android:layout_width="10dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginBottom="6dp"
                        android:layout_marginLeft="32dp"
                        android:src="@android:drawable/presence_online" />

                    <TextView
                        android:id="@+id/textView_aluguel_mensal_icon_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="18.5dp"
                        android:layout_marginRight="60dp"
                        android:gravity="right"
                        android:text="Mensal"
                        android:textColor="@color/black"
                        android:textSize="8dp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/custom_view_valor_aluguelMensal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="28dp"
                        android:layout_marginRight="55dp"
                        android:gravity="right"
                        android:maxLines="1"
                        android:textColor="@color/black"
                        android:textSize="7dp" />

                    <ImageView
                        android:id="@+id/imageView_valor_anual_icon"
                        android:layout_width="10dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginBottom="6dp"
                        android:layout_marginLeft="85dp"
                        android:src="@android:drawable/presence_invisible" />

                    <TextView
                        android:id="@+id/textView_aluguel_anual_icon_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="18.5dp"
                        android:layout_marginRight="13dp"
                        android:gravity="right"
                        android:text="Anual"
                        android:textColor="@color/black"
                        android:textSize="8dp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/custom_view_valor_aluguelAnual"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="28dp"
                        android:layout_marginRight="6dp"
                        android:gravity="right"
                        android:maxLines="1"
                        android:textColor="@color/black"
                        android:textSize="7dp" />
                </FrameLayout>

                <FrameLayout
                    android:layout_width="245dp"
                    android:layout_height="60dp"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_marginTop="4dp"
                    android:background="@color/white">

                    <ImageView
                        android:id="@+id/imageView_venda_shopping"
                        android:layout_width="40dp"
                        android:layout_height="50dp"
                        android:layout_gravity="left"
                        android:layout_marginLeft="20dp"
                        android:layout_marginTop="6dp"
                        android:src="@drawable/venda_shopping" />

                    <TextView
                        android:id="@+id/textView_vendas_icon_title"
                        android:layout_width="wrap_content"
                        android:layout_height="14dp"
                        android:layout_gravity="left"
                        android:layout_marginTop="17dp"
                        android:layout_marginLeft="75dp"
                        android:gravity="left"
                        android:text="Venda"
                        android:textColor="@color/black"
                        android:textSize="@dimen/overlay_venda_icon"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/custom_view_valor_venda"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_gravity="left"
                        android:layout_marginTop="30dp"
                        android:layout_marginLeft="70dp"
                        android:gravity="left"
                        android:maxLines="1"
                        android:textColor="@color/green_aliansce"
                        android:textSize="@dimen/overlay_valorVenda"
                        android:textStyle="bold" />

                    <ImageView
                        android:id="@+id/imageView_venda_mensal_icon"
                        android:layout_width="10dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginBottom="6dp"
                        android:layout_marginLeft="32dp"
                        android:src="@android:drawable/presence_online" />

                    <TextView
                        android:id="@+id/textView_venda_mensal_icon_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="18.5dp"
                        android:layout_marginRight="60dp"
                        android:gravity="right"
                        android:text="Mensal"
                        android:textColor="@color/black"
                        android:textSize="8dp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/custom_view_valor_vendaMensal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="28dp"
                        android:layout_marginRight="55dp"
                        android:gravity="right"
                        android:maxLines="1"
                        android:textColor="@color/black"
                        android:textSize="8sp" />

                    <ImageView
                        android:id="@+id/imageView_venda_anual_icon"
                        android:layout_width="10dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginBottom="6dp"
                        android:layout_marginLeft="85dp"
                        android:src="@android:drawable/presence_invisible" />

                    <TextView
                        android:id="@+id/textView_venda_anual_icon_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="18.5dp"
                        android:layout_marginRight="13dp"
                        android:gravity="right"
                        android:text="Anual"
                        android:textColor="@color/black"
                        android:textSize="8dp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/custom_view_valor_vendaAnual"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="28dp"
                        android:layout_marginRight="6dp"
                        android:gravity="right"
                        android:maxLines="1"
                        android:textColor="@color/black"
                        android:textSize="8sp" />

                </FrameLayout>

                <FrameLayout
                    android:layout_width="245dp"
                    android:layout_height="35dp"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_marginTop="4dp"
                    android:background="@color/white">

                    <ImageView
                        android:id="@+id/imageView_custo_ocupacao_shopping"
                        android:layout_width="40dp"
                        android:layout_height="30dp"
                        android:layout_gravity="left"
                        android:layout_marginTop="3dp"
                        android:layout_marginLeft="20dp"
                        android:src="@drawable/ocupacao_shopping" />

                    <TextView
                        android:id="@+id/textView_custo_ocupacao_icon_title1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginTop="5dp"
                        android:layout_marginLeft="75dp"
                        android:gravity="left"
                        android:text="Custo"
                        android:textColor="@color/black"
                        android:textSize="@dimen/overlay_venda_icon"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/textView_custo_ocupacao_icon_title2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginTop="14dp"
                        android:layout_marginLeft="75dp"
                        android:gravity="left"
                        android:text="Ocupação"
                        android:textColor="@color/black"
                        android:textSize="@dimen/overlay_venda_icon"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/badge_custoOcupacao_valor"

            android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_gravity="left"
                    android:layout_marginTop="30dp"
                    android:layout_marginLeft="85dp"
                    android:gravity="left"
                    android:maxLines="1"
                    android:textSize="11sp"
                    android:textStyle="bold" />

            </FrameLayout>

        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Comment: Thiago, evite usar formatação de citação perto de código sem ser necessário, pois o código vai precisar de 8 espaços para ficar destacado.
Answer: Você pode adicionar elevação ao seu FrameLayout. Veja:
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:elevation="4dp"
    android:translationZ="4dp">

Obs.: O elevation está disponível a partir da v21 Android.
 PS.: mais tarde volto aqui e completo essa resposta
Comment: Você precisa colocar um padding no layout externo ao FrameLayout e adicionar neste mesmo layout um android:clipToPadding="false"
Comment: já tentei utilizar este dois comandos no Framelayout e até já tentei aumentar os valores deles, mas não acontece nada. O que será?


Interpretation of Simple Uniform Marginal Density Example from Mathematical Statistics by Rice

Question: I am stuck trying to visualize Example B from Mathematical Statistics and Data Analysis 3rd ed by Rice. The examples revolve around the concept of independence of Random Variables which is defined in the following way:

I included Example A from which Example B is derived:

A couple of things going on here:

He says "rotate the square by $90^{\circ}$" so first off that has to be a typo because that will just give me another square. So we shall assume $45^{\circ}$ to get the desired diamond.

He first says "you can see that the marginal density of $X$ is nonegative for $\frac{-1}{2} \leq x \leq \frac{1}{2}$, but is not uniform. Why is it nonnegative? Is it because when we integrate over the bounds of integration our marginal density will be positive? More importantly, why is this marginal not considered uniform anymore? The bounds of integration may have changed, but the joint density is still defined as $f_{XY}(x,y) = 1$.

In trying to illustrate the concept of independence he took the result $f_{X}(0.9) > 0$ and $f_{Y}(0.9)>0$. Now using my scattered trig knowledge the bounds of integration would've changed to $\frac{-1}{\sqrt{2}} \leq x \leq \frac{1}{\sqrt{2}}$ and same for $y$. Which would mean $f_{X}(0.9) = 0$ and same for $Y$. I get what he may have been trying to insinuate, if he had chosen $f_{X}(0.65)$ and $f_{Y}(0.65)$ he would've gotten the desired result I believe.

Maybe because of my inability to sketch this out properly or put it into some graphing software I'm not seeing what is occurring, but I don't think that would help too much here. I asked a lot of questions here so if one was of most importance it would be #2 and why is the marginal density not a uniform density anymore?
Answer: The answer is very simple....the error you found is not the only one in the text.
Rotating the square of 45° you get a diamond with the same area $A=1$

Where, obviously,
a) $y=-\frac{\sqrt{2}}{2}-x$
b) $y=\frac{\sqrt{2}}{2}+x$
c) $y=-\frac{\sqrt{2}}{2}+x$
d) $y=\frac{\sqrt{2}}{2}-x$
Then the joint density is the following
$$f_{XY}(x,y)=\mathbb{1}_{(-\frac{\sqrt{2}}{2};0)}(x)\mathbb{1}_{(-\frac{\sqrt{2}}{2}-x;\frac{\sqrt{2}}{2}+x)}(y)+\mathbb{1}_{[0;\frac{\sqrt{2}}{2})}(x)\mathbb{1}_{(x-\frac{\sqrt{2}}{2};\frac{\sqrt{2}}{2}-x)}(y)$$
to derive the marginal X it is enough to integrate in Y (with the joint density expressed as I did the integral extremes are written in the joint density)
Thus
$$ f_X(x) =
\begin{cases}
2x+\sqrt{2},  & \text{if $ -\frac{\sqrt{2}}{2}<x<0 $ } \\
\sqrt{2}-2x, & \text{if $0 \leq x<\frac{\sqrt{2}}{2}$ } \\
0, & \text{elsewhere }
\end{cases}$$
so X density is non negative for $ -\frac{\sqrt{2}}{2}<x<\frac{\sqrt{2}}{2}$ but it is not uniform....it's a triangle!
Comment: @dc3rd : a uniform density is of the form $f=\frac{1}{b-a}$. In example 1. if you integrate the joint density in dy you obtain $f_X(x)=1$; Uniform (constant) in its domain. In example 2. the density is a triangle...not a constant. Integrating on the whole triangle of course you have to obtain 1 otherwise it is not a denisty. It is not necessary to integrate but it is enough to calculate the triangle area: it's 1
Comment: @dc3rd : please do not laugh! I used paintbrush
Comment: @dc3rd : just FYK: a density with a triangular shape is called "triangular density"
Comment: So shape wise I see it's a triangle, but what about the shape prevents it from being considered uniform? Is it because if we integrate over the whole area of the triangle we won't get $1$? i.e: $\int_{-\frac{\sqrt{2}}{2}}^{\frac{\sqrt{2}}{2}}f_{X}(x) \neq 1$?
Comment: So it's because the density is not a constant term why it is not considered a uniform density then. Great to know. Thanks for the assistance. What did you use for the graphic by the way?
Comment: Better than what I could do....at least you were able to draw it correctly.


Is Tikhonov regularization the same as Ridge Regression?

Question: Tikhonov regularization and ridge regression are terms often used as if they were identical. Is it possible to specify exactly what the difference is?
Comment: Hi @JungyeonKim Including your comment here: https://mdav.ece.gatech.edu/ece-6254-spring2017/notes/11-regression-regularization.pdf
In the context of regression, Tikhonov regularization has a
special name: ridge regression, which is essentially exactly what we have been talking about, but in the special case where we are penalizing all coefficients in equally except for the offset.
Comment: @JungyeonKim What you wrote is OK but not exact. Ridge regression is a specific case of Tikhonov regularization with the added twist of conversion into a correlation matrix, which has the advantage of allowing comparisons between models of the magnitude of the smoothing coefficient, but is not a necessary step. Moreover, there are, in the notes you linked to, additional assumptions made that are not necessary concerning variance, in fact, they are neither unique nor always desirable. A ridge  target can be a minimum error of any desired model parameter, not just minimum fit error.
Answer: Tikhonov regularizarization is a larger set than ridge regression. Here is my attempt to spell out exactly how they differ.
Suppose that for a known matrix $A$ and vector $b$, we wish to find a vector $\mathbf{x}$ such that
:
$A\mathbf{x}=\mathbf{b}$.
The standard approach is ordinary least squares linear regression. However, if no $x$ satisfies the equation or more than one $x$ does—that is the solution is not unique—the problem is said to be ill-posed. Ordinary least squares seeks to minimize the sum of squared residuals, which can be compactly written as:
$\|A\mathbf{x}-\mathbf{b}\|^2 $
where $\left \| \cdot \right \|$ is the Euclidean norm. In matrix notation the solution, denoted by $\hat{x}$, is given by:
$\hat{x} = (A^{T}A)^{-1}A^{T}\mathbf{b}$
Tikhonov regularization minimizes
$\|A\mathbf{x}-\mathbf{b}\|^2+ \|\Gamma \mathbf{x}\|^2$
for some suitably chosen Tikhonov matrix, $\Gamma $. An explicit matrix form solution, denoted by $\hat{x}$, is given by:
$\hat{x} = (A^{T}A+ \Gamma^{T} \Gamma )^{-1}A^{T}{b}$
The effect of regularization may be varied via the scale of matrix $\Gamma$.  For $\Gamma = 0$ this reduces to the unregularized least squares solution provided that (ATA)−1 exists.
Typically for ridge regression, two departures from Tikhonov regularization are described. First, the Tikhonov matrix is replaced by a multiple of the identity matrix
$\Gamma= \alpha I $,
giving preference to solutions with smaller norm, i.e., the $L_2$ norm. Then  $\Gamma^{T} \Gamma$ becomes $\alpha^2 I$ leading to
$\hat{x} = (A^{T}A+ \alpha^2 I )^{-1}A^{T}{b}$
Finally, for ridge regression, it is typically assumed that $A$ variables are scaled so that $X^{T}X$ has the form of a correlation matrix. and $X^{T}b$ is the correlation vector between the $x$ variables and $b$, leading to
$\hat{x} = (X^{T}X+ \alpha^2 I )^{-1}X^{T}{b}$
Note in this form the Lagrange multiplier $\alpha^2$ is usually replaced by $k$, $\lambda$, or some other symbol but retains the property $\lambda\geq0$
In formulating this answer, I acknowledge borrowing liberally from Wikipedia and from Ridge estimation of transfer function weights
Comment: (+1) For completeness, it is worth mentioning that in practical application the regularized system would typically be written in the form
$\begin{bmatrix}A\\ \alpha \Gamma\\ \end{bmatrix}x\approx\begin{bmatrix}b\\0\\ \end{bmatrix}\implies \hat{A}x\approx \hat{b}$, which can then be solved as a standard linear least squares problem (e.g. via QR/SVD on $\hat{A}$, without explicitly forming the normal equations).
Comment: Good point. I'll add it in later.
Comment: Are smoothing splines and similar basis expansion methods a subset of Tikhonov regularization?
Comment: @Sycorax I do not expect so. For example, a B-spline would set derivatives at zero at endpoints, and match derivatives and magnitudes of spline to data in between endpoints. Tikhonov regularization will minimize whatever parameter error you tell it to by changing slope of fit. So, different things.
Comment: Also, Tychonov regularization has a formulation in arbitrary dimensions for (separable?) Hilbert spaces
Answer: Carl has given a thorough answer that nicely explains the mathematical differences between Tikhonov regularization vs. ridge regression. Inspired by the historical discussion here, I thought it might be useful to add a short example demonstrating how the more general Tikhonov framework can be useful.
First a brief note on context. Ridge regression arose in statistics, and while regularization is now widespread in statistics & machine learning, Tikhonov's approach was originally motivated by inverse problems arising in model-based data assimilation (particularly in geophysics). The simplified example below is in this category (more complex versions are used for paleoclimate reconstructions).

Imagine we want to reconstruct temperatures $u[x,t=0]$ in the past, based on present-day measurements $u[x,t=T]$. In our simplified model we will assume that temperature evolves according to the heat equation
$$ u_t = u_{xx} $$
in 1D with periodic boundary conditions
$$ u[x+L,t] = u[x,t] $$
A simple (explicit) finite difference approach leads to the discrete model
$$ \frac{\Delta\mathbf{u}}{\Delta{t}} = \frac{\mathbf{Lu}}{\Delta{x^2}} \implies \mathbf{u}_{t+1} = \mathbf{Au}_t $$
Mathematically, the evolution matrix $\mathbf{A}$ is invertible, so we have
$$\mathbf{u}_t = \mathbf{A^{-1}u}_{t+1} $$
However numerically, difficulties will arise if the time interval $T$ is too long.
Tikhonov regularization can solve this problem by solving
\begin{align} \mathbf{Au}_t &\approx \mathbf{u}_{t+1} \\
        \omega\mathbf{Lu}_t &\approx \mathbf{0}
\end{align}
which adds a small penalty $\omega^2\ll{1}$ on roughness $u_{xx}$.
Below is a comparison of the results:

We can see that the original temperature $u_0$ has a smooth profile, which is smoothed still further by diffusion to give $u_\mathsf{fwd}$. Direct inversion fails to recover $u_0$, and the solution $u_\mathsf{inv}$ shows strong "checkerboarding" artifacts. However the Tikhonov solution $u_\mathsf{reg}$ is able to recover $u_0$ with quite good accuracy.
Note that in this example, ridge regression would always push our solution towards an "ice age" (i.e. uniform zero temperatures). Tikhonov regression allows us a more flexible physically-based prior constraint: Here our penalty essentially says the reconstruction $\mathbf{u}$ should be only slowly evolving, i.e. $u_t\approx{0}$.

Matlab code for the example is below (can be run online here).
<code>% Tikhonov Regularization Example: Inverse Heat Equation
n=15; t=2e1; w=1e-2; % grid size, # time steps, regularization
L=toeplitz(sparse([-2,1,zeros(1,n-3),1]/2)); % laplacian (periodic BCs)
A=(speye(n)+L)^t; % forward operator (diffusion)
x=(0:n-1)'; u0=sin(2*pi*x/n); % initial condition (periodic & smooth)
ufwd=A*u0; % forward model
uinv=A\ufwd; % inverse model
ureg=[A;w*L]\[ufwd;zeros(n,1)]; % regularized inverse
plot(x,u0,'k.-',x,ufwd,'k:',x,uinv,'r.:',x,ureg,'ro');
set(legend('u_0','u_{fwd}','u_{inv}','u_{reg}'),'box','off');
</code>
Comment: @Carl this is certainly true. We could even use it *here*, by switching variables to $v=Lu$! (In general, any Tikhonov problem with an invertible Tikhonov matrix can be converted to ridge regression.)
Comment: All compliments warmly received. It is worthwhile mentioning, even if slightly off topic, that both Tikhonov regularization and [ridge regression](https://www.google.com/patents/CA2784219A1?cl=en) can be used for targeting physical regression targets. (+1)


Imagem saindo fora da div no topo e no rodapé

Question: Como faço para criar um div com bordas e posicionar  uma imagem com um valor de desconto acima dessa div saindo fora dela e logo abaixo centralizado um botão no meio da div como a imagem em anexo;
Comment: oque vc ja tem de codigo pronto ou tentou fazer ?
Comment: @ViniciusShiguemori ainda não tenho nada preciso apenas de um exemplo cru mesmo que segue essa lógica!
Comment: imaginei, bem cara aqui o objetivo é te ajudar com problemas no código ou conceito/conhecimento não dar a resposta pronta, afinal isso seria errado para o seu aprendizado, seria bom vc dar uma estudada nas classes do bootstrap na sua documentação https://getbootstrap.com/docs/3.3/getting-started/ ou um site que eu utilizei muito https://www.w3schools.com/bootstrap/default.asp, antes de publicar perguntas assim de uma ollhada https://pt.meta.stackoverflow.com/questions/1084/como-devemos-formatar-perguntas-e-respostas?cb=1
Comment: @ViniciusShiguemori então eu já criei vários site no mercado usando bootstrap já li toda a documentação do bootstrap o problema não é este é que estou com dúvidas em como fazer o mencionado acima, conheço as políticas do fórum.
Answer: Da uma olhada no código, acho que é isso que vc queria... Mas não é só para vc copiar e colar. Tenta dar uma estudada no código para ver como as coisas funcionam etc. Eu mesmo só fiz isso pq acho que uma forma para eu mesmo aprender as coisas, tenha esse maindset tb []´s

html, body {
    width: 100%;
    height: 100%;
    display: flex;
    margin: 0;
    padding: 0;
    background-color: black;
}
.container {
    margin: auto;
    background-color: black;
    border: 1px solid snow;
    height: 200px;
    width: 150px;
    display: flex;
    position: relative;
    justify-content: center;
}
.produto {
    height: 100px;
    width: 100px;
    background-color: red;
    margin: auto;
    background: url(https://www.placecage.com/c/100/100) no-repeat center;
}
.valor{
    position: absolute;
    top: -20px;
    left: -20px;
    background-color: red;
    padding: 0.5em;
    color: #fff;
}
.comprar{
    position: absolute;
    bottom: -20px;
    background-color: red;
    padding: 0.5em;
    color: #fff;
}

$000,00

comprar

Comment: Obrigado @hugocsl


How to pass bundle into fragment using getSupportFragmentManager?

Question: I have an activity which receives a bundle from another activity. The bundle is a simple url string. The receiving activity launches a fragment using getSupportFragmentManager as shown below, and this works as expected.
I would like to pass the url string on to the fragment, but cannot find a way to do this. All the examples I have seen use different patterns to launch the fragment. Any suggestions appreciated!
See my comment as to why this is not exactly a duplicate of another question.
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;

public class GalleryActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_gallery);

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setBackgroundDrawable(
                    new ColorDrawable(Color.parseColor("#273134")));

            //Get the URL string from the calling activity

            String url = super.getIntent().getExtras().getString("urlString");

            Toast.makeText(this, "URL String is: " + url, Toast.LENGTH_LONG).show();

/*
Here is a new bundle. How do we get this passed to the new fragment?
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
*/

            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.content, RecyclerViewFragment.newInstance())
                    .commit();
        }
    }

Comment: Possible duplicate of [How to pass Bundle from Fragment to Fragment](https://stackoverflow.com/questions/17063378/how-to-pass-bundle-from-fragment-to-fragment)
Comment: Not exactly - see my comment on the accepted answer. The problem was caused by the line ".add(R.id.content, RecyclerViewFragment.newInstance())" inside getSupportFragmentManager - this is sort of a shortcut which tripped me up.
Answer: you can set the bundle in the fragment using the setArguments on fragment instance. you can find more info in the docs.
for your example:
Fragment fragment = RecyclerViewFragment.newInstance();

Bundle bundle = new Bundle();
bundle.putString("url", url);

fragment.setArguments(bundle);

getSupportFragmentManager()
        .beginTransaction()
        .add(R.id.content, fragment)
        .commit();

and in your onCreate or onCreateView in the fragment use:
String url =  getArguments().getString("url")

Answered question in the stackoverflow: setArguments - getArguments
Comment: Thanks! I was getting tripped up by using the shortcut ".add(R.id.content, RecyclerViewFragment.newInstance())" in getSupportFragmentManager, instead of in the fragment declaration as you suggested.


Erro: Referência de objeto não definida para uma instância de um objeto

Question: Estou tentando resgatar os dados de uma tela com um Id específico, para posteriormente gravar em outra tela, porém um erro ocorre dizendo:

"Referência de objeto não definida para uma instância de um objeto."

[HttpGet]
public ActionResult Registro(int id)
{
        var model = new CombustivelViewModelRegistro();
        try
        {
            var rep = new AtribuirVeiculoRepsitorio();
            AtribuirVeiculo av = rep.ObterPorId(id);
            model.Veiculo = av.Veiculo.Matricula;
            model.Funcionario = av.Funcionario.Nome;
        }
        catch(Exception e)
        {
            ViewBag.Mensagem = e.Message;
        }
    return View(model);
}

[HttpPost]
public ActionResult Registro(CombustivelViewModelRegistro model)
{
    if (ModelState.IsValid)
    {
        var c = new Combustivel();
        try
        {
            c.DataAbastecimento = model.DataAbastecimento;
            c.DataCadastro = DateTime.Now;
            c.Kilomtragem = Convert.ToDouble(model.Kilometragem);
            c.Quantidade = model.Quantidade;
            c.IdCombustivel = model.IdCombustivel;
            c.Veiculo.Matricula = model.Veiculo;
            c.Funcionario.Nome = model.Funcionario;

            var service = new CombustivelRepositorio();
            service.Inserir(c);

            return RedirectToAction("Index");
        }
        catch (Exception e)
        {
            ViewBag.Mensagem = e.Message;
        }
    }
    return View();
}

Comment: Em qual linha acontece? Provavelmente essas chamadas ao seu repositório que busca um valor pode estar retornando um null, e você esta tentando atribuir um valor a uma propriedade.
Comment: Forneça mais detalhes na sua pergunta, pois uma pergunta com o título parecido já foi respondida e dada como encerrada
Comment: O seu Veiculo esta null e você tenta atribuir um valor a Matricula dele.
Comment: sera que devo inicializar c.Veiculo = new Veiculo();
                c.Funcionario = new Funcionario();
Comment: @MAXFXavier Você ainda está recebendo o erro "Referência de objeto não definida para uma instância de um objeto"?
Answer: Depois desta linha
var c = new Combustivel();

Você precisa instanciar uma Veiculo no objeto c
c.Veiculo = new Veiculo();

Você também pode alterar o construtor de Combustivel para sempre que uma instância for criada, criar também uma instância de Veiculo.
public class Combustivel
{
    public Combustivel()
    {
        this.Veiculo = new Veiculo();
    }

    // Propriedades da classe
}


finding the limits of integration. joint probability

Question: <code>A candy company distributes boxes of chocolates
with a mixture of creams, toffees, and cordials.
Suppose that the weight of each box is 1 kilogram, but
the individual weights of the creams, toffees, and cordials
vary from box to box. For a randomly selected
box, let X and Y represent the weights of the creams
and the toffees, respectively, and suppose that the joint
density function of these variables is
f(x, y) =

24xy, 0 ≤ x ≤ 1, 0 ≤ y ≤ 1, x+ y ≤ 1,
0, elsewhere.
(a) Find the probability that in a given box the cordials
account for more than 1/2 of the weight.
</code>
In letter a, it means x+y < 1/2, now how can we find the limits of the double integral? proper approach to solve this problem? thanks
PS: there would be no problem if the limits can be easily deciphered. but for this one its asking P(X + Y < 1/2)
Comment: Draw a sketch of the plane with coordinate axes $x$ and $y$, and indicate on it the region where $f(x,y) > 0$. (Hint: it is a triangle).  The point $(X,Y)$ always lies inside this region.  Draw on the same sketch the region where $X+Y < 1/2$.  (Hint: it is the region below a straight line). Now you have to find the probability that the point $(X,Y)$ lies in the region defined by $X+Y<1/2$ and you know that $(X,Y)$ _must_ lie in the triangle sketched before. Do you necessarily **have** to integrate to find the answer or do you think a guess might suffice?
Comment: Sorry, I misread the pdf as being nonzero for $x+y<1/2$. While the first part of my suggestion still holds (see David Mitra's answer to get details of how to do what I merely suggested), you _do_ need to set up an integral to get the probability, and again, David has explained in detail how to do so.
Answer: The first thing you have to do is sketch the region of interest
$$
X+Y<\textstyle{1\over 2}, \quad X,Y\ge 0
$$
This will be be the region of all points in  in quadrant 1 whose coordinates $(x,y)$ satisfy: $$y<-x+\textstyle{1\over 2}:$$

The region is shown in pink above (note the density is 0 above the dashed line). If we call this region $A$, the integral is
$$
\int\kern-5pt\int_A f(x,y) dA.
$$
To set up the double integral as an iterated integral, you may think of the region as being generated by the vertical lines $\color{darkgreen}{\ell_x}$ as $x$ ranges from $x=0$ to $x=1/2$.
You first fix $x$ and "integrate along $\ell_x$" in the vertical direction. Then you integrate the $\ell_x$ integrals from $x=0$ to $x=1/2$.
So, fix $x$ and consider $\ell_x$.  The  limits of the  inner integral are from the bottom of $\ell_x$ to the top.  The bottom of $\ell_x$ is $y=0$ and the top is $y=-x+{1\over 2}$.
Note the inner integral will be with respect to $y$.
So the inner integral is
$$
\int_0^{-x+{1\over 2}} xy \,dy
$$
Now set up the outer integral.  As mentioned, we integrate the above expression from $x=0$ to $x=1/2$:
$$
\int_0^{1/2}\int_0^{-x+{1\over 2}} xy\, \,dy\,dx.
$$

Alternatively, you can think of the region as being generated by horizontal lines $\color{maroon}{\ell_y}$ that range from $y=0$ to $y=1/2$.
Here, you'd integrate along a horizontal line first, from its left endpoint, 0, to its right endpoint $-y+{1\over2}$. Then, integrate with respect to $y$ from $y=0$ to $y=1/2$:
$$
\int_0^{1/2}\int_0^{-y+{1\over 2}} xy\, \,dx\,dy.
$$
Comment: why is that the outer integral is using constnts as limits unlike the inner integral which uses some variables. cant get the logic behind on why not follow the way the 1st integral was set up
Comment: @blackandyello The inner integral in the first double integral above  integrates over the line $\ell_x$ from its bottom to its top. The bottom of the line $\ell_x$ always at $y=0$.  The top depends where $\ell_x$ is exactly: the top is at $y=-x+1/2$ since it touches the line $x+y=1/2$.  The outer integral will always have constants as its limits. They range from the leftmost of the $\ell_x$ lines, $x=0$, to the right most, $x=1/2$.
Comment: @blackandyello The second double integral  is just another way of  setting it up. Note the $dx$ and $dy$ are interchanged; in the second double integral, we're integrating with respect to $x$ first (instead of wrt $y$ first as in the first double integral).   For some problems,  one way may be easier than the other. Here, it doesn't really matter.


ANTLR Parser Null Pointer Exception

Question: I am trying to put actions into C function grammar but getting error.
For example:
expressionStatement returns [String value]
    :   expression? ';' {$value = (($expression.value != null)?$expression.value:"") + ";";}
    ;

Please review the above rule and let me know if I am doing right to return the expression value. Please note that the rule has condition (?).
The grammar is correctly run with antlr to generate java files and java files also compiled correctly but when I run it with code to parse then it gives null pointer exception.
Please reply me soon how can I write the actions correctly in this case?
Answer: If expression expression does not match then $expression == null so $expression.value is a NullPointerExceptions.
Try:
expressionStatement returns [String value]
:   expression? ';' {
                     if($expression != null){
                       if($expression.value != null){
                         $value = $expression.value
                       }else{
                         $value = "";
                       }
                       $value  += ";";
                     }
                    }
;

ANTLR Parser Null Pointer Exception


How to split strings with regex without first and last special character

Question: I'm having trouble using regex.
So basically I have this kind of string :
string = '<bash><exit><bash-trap><terminology>'

What I would like to have in the end is a list of all separate words :
['bash', 'exit', 'bash-trap', 'terminology']
What I've done so far :
substitution = re.sub(r'[^A-Za-z0-9-]+', ' ', string)
then
re.split(r'[^A-Za-z0-9-])',substitution)
Which gives me the following result :
['', 'bash', 'exit', 'bash-trap', 'terminology', '']
Thanks !
Comment: `print(re.findall(r"\<(.*?)\>", string))` ?
Comment: Your regex isn't that bad. You can simply call `substitution.split()` after your first `re.sub`.
Comment: Or add a [`strip`](https://www.journaldev.com/23625/python-trim-string-rstrip-lstrip-strip#:~:text=strip()%3A%20returns%20a%20new,string%20with%20trailing%20whitespace%20removed.&text=lstrip()%3A%20returns%20a%20new,left%E2%80%9D%20side%20of%20the%20string.) before the `split`.
Answer: Use pattern \<(.*?)\>
Ex:
import re

string = '<bash><exit><bash-trap><terminology>'
print(re.findall(r"\<(.*?)\>", string))
# --> ['bash', 'exit', 'bash-trap', 'terminology']

Answer: All you want is a list of words inside angle brackets. So, you can use re.findall directly on the input string.
re.findall(r'<(.*?)>', string)

Code:
import re

string = '<bash><exit><bash-trap><terminology>'
print(re.findall(r'<(.*?)>', string))
# ['bash', 'exit', 'bash-trap', 'terminology']


How Can I Retrieve SIP Credentials via the HTTP GET method using MOD_XML_CURL

Question: I've got an installation of FusionPBX with a FreeSWITCH and PostgreSQL backend.  I've been reading online in various places that it's possible to use mod_xml_curl to retrieve SIP credentials stored in a MySQL database instead of the static XML files that FreeSWITCH uses.
I am interested, however, in how I can retrieve SIP credentials from the PostgreSQL database that FusionPBX uses using an HTTP GET request.  I am currently studying up the fs_curl contribution made by Raymond Chandler (intralanman) but I am a novice developer trying to learn the ropes so any assistance would be very much appreciated.
Answer: To get started, make changes in xml_curl.conf
<binding name="directory">
      <param name="gateway-url" value="http://<directoryserverip>/directory" method="GET" bindings="directory"/>
 </binding>
Create a web server (directory) that can handle your web request /directory.
You should be able to see all the request headers.
create a function to return a dynamic directory xml for that user as mentioned here https://freeswitch.org/confluence/display/FREESWITCH/mod_xml_curl
Note: you know the user name from request header. so make a connection to get the actual password for that user in your DB and substitute in xml and return it as response
Freeswitch will allow the registration if requested password and the one you sent in directory xml matches else it send forbidden.
Comment: I had to search to the end of the internet to find this.


should I write header to all my html page?

Question: I'm new to web design. I wonder that should I have to write header for every page on my website? for example I have index.html, contact.html, about.html. should I copy header to all page ?
Comment: Yes. However, if you don't want to do that for every file you would generally use a server-side language like PHP to put your header in a file then include it on other files so you wouldn't have to keep writing it.
Comment: Yes, you should. it's pretty common practice.
Answer: Yes, each page must contain a header. Because they're separated.
To be honest, these kind of questions (like yours) shouldn't be asked here. You should try to read some HTML books to get you started.


Calculate P(A ∪ B) if it is given that P(A) = 1/3 and P(B | Ac) = 1/4.

Question: "Calculate P(A ∪ B) if it is given that P(A) = 1/3 and P(B | Ac) = 1/4."
The textbook solution is 1/2 although I can't seem to get there. Here's what I have so far...
P(Ac) = 2/3
P(A) = (2/3)c = 1/3
P(B | Ac) = P(B ∩ Ac) / P(Ac)
¼ = P(B ∩ Ac) / 2/3
P(B ∩ Ac) = 1/6
P(B ∩ Ac) = P(B) + P(Ac) – P(B ∪ Ac)
1/6 = P(B) + (2/3) – P(B ∪ Ac)?
Thanks!
Comment: What does Ac mean?
Comment: @saulspatz: I think it must mean $A^c$.
Comment: This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: You're almost there.  $A$ and $B\cap A^c$ are disjoint and their union is $A\cup B$ (draw a Venn diagram if you need to convince yourself).
So $P(A\cup B)=P(A)+P(B\cap A^c)=\frac13+\frac16 = \frac12$.


difference of two random variables: symmetric distribution if only location parameter is different?

Question: In Box and Tiao (1973) page# 156, authors write that if the distributions of two random variables are identical except location, then the distribution of the differences would certainly be symmetric. In other words, if two random variables are identical except in their mean, then the difference of the two random variables would be symmetric.
But authors have not provided any proof for this claim. Maybe because it is supposed to be obvious. But I am not able to understand why this statement is true? It will be helpful if someone can show a proof for this claim or an intuitive explanation
Answer: If a random variable $T$ has a distribution symmetric about zero, then $ T\stackrel{D}{=} -T $, meaning that $T$ and $-T$ has the same distribution.  If $T$ has a distribution symmetric about some value $\mu$, then $T-\mu$ is symmetric about zero, so that $ T-\mu \stackrel{D}{=} -(T-\mu) = -T+\mu $.
Let $X_1, Y_1$ be two independent random variables, identical in distribution. Then define $X=X_1-\theta, Y=Y_1$. Then $X$ and $Y$ will be "identical except location" (in distribution) (I take this to be the authors meaning). Then $D_1 = X_1-Y_1$ is symmetric about zero: $D_1 = X_1-Y_1\stackrel{D}{=} Y_1-X_1=-(X_1-Y_1)=-D_1$.
Let $D=X-Y$. To show that $D$ has a symmetric distribution (about some center $\mu$), so: $ X-Y= X_1-\theta -Y_1=(X_1-Y_1)-\theta=D_1-\theta \stackrel{D}{=} -D_1-\theta = -(D+\theta)-\theta$ and by adding $\theta$ on both sides we finally get $ D+\theta \stackrel{D}{=} -D-\theta $ concluding the proof.
Note that we dont even need the independence of $X_1$ and $Y_1$. It is enough to assume that $X_1, Y_1$ are excahgeable, that is: $(X_1,Y_1)\stackrel{D}{=} (Y_1, X_1)$, and everything goes through.
Answer: Suppose $Y$ and $Y^\prime$ are the random variables in question, where there is a number $\mu$ for which $Z=Y^\prime-\mu$ and $Y$ are identically distributed. (That's what "identical except location" means.)  The question concerns the random variable $$X=Y^\prime-Y = \mu + Z - Y.$$
The underlying idea is that when $Z$ and $Y$ can be swapped without changing their joint distribution (they are "exchangeable"), then
$$2\mu - X = \mu + Y - Z$$
obviously has the same distribution as $X,$ because it arises through exchanging $Y$ and $Z.$ (It is likely the authors implicitly assumed--or even previously stated--that $Y$ and $Y^\prime$ are independent, which easily implies the exchangeability of $Z$ and $Y.$)
The equivalence in distribution of $X$ and $2\mu-X$ is the very definition of symmetric.


Entity queue JSONAPI pagination & How to add JSON API in views?

Question: I'm using below modules
https://www.drupal.org/project/entityqueue & JSON API
Through entity queue. I have added 5 Articles.
Now I would like to apply pagination on that.
We are accessing via
http://domain.com/jsonapi/my-5-articles?include=items
I tried to add include=items&items[paging]=1. but seems not working
I need to add limit & offset
If we do same in
http://domain.com/jsonapi/node/article?page[limit]=1
then we are getting
"links": {
"self": "http://domain.com/jsonapi/node/article?page%5Blimit%5D=1",
"next": "http://domain.com/jsonapi/node/article?page%5Boffset%5D=1&page%5Blimit%5D=1",
"last": "http://domain.com/jsonapi/node/article?page%5Boffset%5D=31&page%5Blimit%5D=1"
},

We are not able to get same in entityqueue.
How to add JSON API in views?
Answer: Is sounds like you're assuming functionality that may-or-may-not be there.
Assuming /jsonapi/my-5-articles is an alias for /jsonapi/entity_subqueue/$MY_QUEUE_MACHINE_NAME?include=items, items[paging] isn't a query param for pagination, only page is (with [] options for specifying page size & offsets).
It sounds like what you want, in terms of the JSON API spec, is a paginated compound document (i.e. the included property that has all your queue nodes for the items relationship). Per the JSON API spec:

A server MAY choose to limit the number of resources returned in a response to a subset ("page") of the whole set available.
A server MAY provide links to traverse a paginated data set ("pagination links").
Pagination links MUST appear in the links object that corresponds to a collection. To paginate the primary data, supply pagination links in the top-level links object. To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

It's optional for the JSON API module to supply pagination links. If it does supply them, it will be in the links document property for the resource you're requesting.
Since you're wanting pagination for included resources, the spec says:

To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

I'm assuming "corresponding links object" is different from "top-level links" and they're referring to links property for objects within the included array.
From a quick look over the JSON API docs/code it doesn't appear to support this functionality. That may or may not be the case, you'll need to see if it does. You should check the project's issue queue.
The specs' flexibility on this scenario means the authors may not have put the functionality in there. If that's the case, you'll need to figure out a workaround or implement your own solution here.


Is a different CV arrangement the same as a validation set?

Question: I have a smallish dataset ~ 1500 rows X 500 columns.  I've been using a standard 5 fold CV setup where row 1 = CV set1, row2 = CV set2, ... row 6 = CV set1,etc.
I'm at the point where I'm trying to do some feature reduction work/parameter optimization and concerned about over-fitting by using the same CV setup to find parameters and then get error measures.
My question is this:  if I create a separate CV indexing setup where row 1 = CV set 5, row 2 = CV set 3,..., row6 = CV set 1, etc. does this function similarly to having a separate validation set or do I need to explicitly have a 50/25/25 train/validation/test setup?
Comment: You could use bootstrap for the error rate estimation.
Answer: It is best to treat CV as a method for estimating the generalization performance of a method for modeling the data (rather than of the model) and if your method includes feature selection then you need to perform the feature selection step independently in each fold of the cross-validation; otherwise you will end up with an optimistically biased performance estimate.
Re-partitioning the dataset to get a different cross-validation estimate (which seems to be what you are suggesting) will end up with a biased performance estimate as the test data in each fold of the performance evaluation CV will have been used to optimize the model by minimizing the feature selection CV estimate.
The simple rule is that the test data for performance estimation cannot have been used in any way (no matter how indirectly) in tuning any aspect of the model.  I find nested cross-validation is a good approach for most problems.


Processing jobs in a Windows Service

Question: I've created a Windows Service in C# using HangFire looks like:
using System;
using System.Configuration;
using System.ServiceProcess;
using Hangfire;
using Hangfire.SqlServer;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        private BackgroundJobServer _server;

        public Service1()
        {
            InitializeComponent();

            GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string");
        }

        protected override void OnStart(string[] args)
        {
            _server = new BackgroundJobServer();
        }

        protected override void OnStop()
        {
            _server.Dispose();
        }
    }
}

I'm using VS 2017 on Windows 10.
After compiling and service installed successfully but not started!
When I try to start manually it gives the famous Error 1053: The service did not respond to the start or control request in a timely fashion.
I found an answer in stackoverflow.com regarding grant permission to NT AUTHORITY\SYSTEM. It does not solve my problem
Please help. Thanks.
Comment: (If "the SQL sever" runs on the same machine, you did tell the SCM that your service depends on it?)
Answer: for Debugging use this pattern:
1.Add this method into WindowsService1 class:
 public void OnDebug()
 {
    OnStart(null);
 }

2.In Program.cs file change the content to something like it:
static class Program
{
    ///
    /// The main entry point for the application.
    ///
    static void Main()
    {
      #if DEBUG
        var Service = new WindowsService1();
        Service.OnDebug();
      #else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new WindowsService1()
        };
        ServiceBase.Run(ServicesToRun);
      #endif
    }
}

By this way you can run your code in User Session and check possible problems (Non User-Specific Problems).
** Don't put all of your codes on OnStart method. The state of a service will turns to Started whenever OnStart ends.
** Use a thread to do you works instead:
    System.Threading.Thread MainThread { get; set; } = null;
    protected override void OnStart(string[] args)
    {
        MainThread = new System.Threading.Thread(new System.Threading.ThreadStart(new Action(()=>{
            // Put your codes here ...
        })));
        MainThread.Start();
    }

    protected override void OnStop()
    {
        MainThread?.Abort();
    }

Most of the times your error is because of this problem.

Processing jobs in a Windows Service


Blazor Adding HttpClientHandler to add Jwt to HTTP Header on requests

Question: I am using the Visual Studio 2019 and .Net Core 3.0.0-preview-7 with the standard Blazor Client, Server and Shared templates.
In the application our server side WebApi application will always require a JWT token to be present in the header for authorization.
From looking at the following
Make HTTP requests using IHttpClientFactory in ASP.NET Core
I created the following handler;
public class JwtTokenHeaderHandler : DelegatingHandler
{
    private readonly ILocalStorageService _localStorage;

    public JwtTokenHeaderHandler(ILocalStorageService localStorage)
    {
        _localStorage = localStorage;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (!request.Headers.Contains("bearer"))
        {
            var savedToken = await _localStorage.GetItemAsync<string>("authToken");

            if (!string.IsNullOrWhiteSpace(savedToken))
            {
                request.Headers.Add("bearer", savedToken);
            }
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

Where I use Blazored.LocalStorage to get the saved token from localstorage and add it to the header.
Now, at this point I am not sure what to do as if I add the following to the Blazor.Client Startup.cs;
services.AddTransient<JwtTokenHeaderHandler>();
services.AddHttpClient("JwtTokenHandler")
    .AddHttpMessageHandler<JwtTokenHeaderHandler>();

I get the error message;

'IServiceCollection' does not contain a definition for 'AddHttpClient'
  and no accessible extension method 'AddHttpClient' accepting a first
  argument of type 'IServiceCollection' could be found (are you missing
  a using directive or an assembly reference?)

Can anyone direct me to what I am doing wrong here?
Comment: @HenkHolterman I said this is in the `Blazor.Client` project? I want to add the JWT to the header of all calls I make to the server side controls.
Comment: The Hosted model/template is Blazor client-side. Plus a 'normal' Web Api project.
Comment: @Matthew Flynn, you'd better call your app client-side Blazor.
Comment: @HenkHolterman ok, so on the 'normal' webapi I have `[Authorize]` attributes on the controllers, authorisation is standard 'bearer' jwt in the message header. this is working ok, Now on the blazor client side app when it makes a call to get some data etc to the WebApi I just want to intercept the Post, Get etc and add the Jwt stored in localstorage to the header of the request
Comment: I think this url will help you https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1
Answer: I found a really good tutorial and sample demonstrating this (complete with roles/policy based claims):
https://chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/
Here is an extract below, setting the default request headers on the default http client (through DI). All calls to your web api will then include the bearer token:
public class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorage;

    public ApiAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)
    {
        _httpClient = httpClient;
        _localStorage = localStorage;
    }
    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var savedToken = await _localStorage.GetItemAsync<string>("authToken");

        if (string.IsNullOrWhiteSpace(savedToken))
        {
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
        }

        // **************    Set JWT header       ****************
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", savedToken);
        // *******************************************************

        return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(savedToken), "jwt")));
    }
    // ...
}

Answer: @Matthew Flynn, currently you can't use IHttpClientFactory on client-side Blazor.
And you don't have to derive from HttpMessageHandler (DelegatingHandler). It has already been done by Blazor. The following  is n extension class to extend the functionality of the HttpClient service to enable the ability to add the Jwt token to the header of the request message...
ServiceExtensions.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Security.Claims;
    using System.Text;
    using System.Text.Json.Serialization;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Components;
    using Microsoft.Extensions.DependencyInjection;

 public static class ServiceExtensions
    {
     public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string url, AuthenticationHeaderValue authorization)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = authorization;

                var response = await httpClient.SendAsync(request);
                var responseBytes = await response.Content.ReadAsByteArrayAsync();
                return JsonSerializer.Parse<T>(responseBytes, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
            }
}

The following show how to call an endpoint on your Web Api, passing the Jwt token which is read from the localStorage. (incidentally, none of these versions is secured with data protection)
Index.razor
@page "/"

@inject ILocalStorageService localStorage
@inject HttpClient Http

Hello, world!

    Welcome to your new app.

// Razor content to display emloyees come here.....

@code {
Employee[] employees;

    protected override async Task OnInitAsync()
    {
        var token = await localStorage.GetTokenAsync();
        employees = await Http.GetJsonAsync<Employee[]>(
            "api/employees",
            new AuthenticationHeaderValue("Bearer", token));
    }
}

Hope this works... If not, and you can't solve thr errors, come here and tell the community about it...
Comment: I agree it looks like Blazor restrict this as it adds it own HttpClient defaults to work with webassembly (I did have a gitu issue link but cant find it). I suppose extension methods are the best work around for now, I was just hoping I could avoid intercept each call without having to do this. :(
Comment: Not many know this, but the HttpClient service on client-side Blazor is not the actual or real HttpClient we've known for years. It is actually  an implementation of the JavaScript Fetch Api...
Comment: Follow up on this, can I abstract the token from localstorage within the extension method? I was trying to make a HttpClient wrapper to reduce the code on the component side that does add the authorization header and token value all in one "PostJsonAsync()" call
Answer: The following adds X-CSRF-TOKEN header to http requests:
public class CustomHttpMessageHandler : DelegatingHandler
{
    private readonly IJSRuntime _js;
    public CustomHttpMessageHandler(IJSRuntime js)
    {
        _js = js;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var afrt = await _js.InvokeAsync<string>("getCookie", ".AFRT");
        request.Headers.Add("X-CSRF-TOKEN", afrt);
        return await base.SendAsync(request, cancellationToken);
    }
}

In Program.cs configure like below:
builder.Services.AddScoped<CustomHttpMessageHandler>();
builder.Services.AddHttpClient("ApiClient", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddHttpMessageHandler<CustomHttpMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("ApiClient"));

You need to install Microsoft.Extensions.Http package to your blazor webassembly client.
Comment: This should be the accepted answer, at least now on .NET 6 (I haven't tested previous versions).
Comment: Will this also intercept requests made from a third party javascript library?
Answer: You need the NuGet package Microsoft.Extensions.Http which contains the AddHttpClient method. Install it with the following command: Install-Package Microsoft.Extensions.Http -Version 3.0.0-preview7.19362.4
As it seems, this NuGet package is automatically provided in server-side blazor but has to be installed seperately in client-side blazor.
Comment: Correct. It's a big(gish) package and the wasm runtime has to be trimmed as much as possible.
Comment: @HenkHolterman from the links I found it looks like this is not compatible yet with wasm, as the blazor clientside sets up its own httpclient, overriding this seems to break it. Installing this to the client project and then running it currently causing a runtime exception.
Comment: @MatthewFlynn - look at the exact name, Blazor has its own HttpClient package.


Como eu faço para que cada linha da minha matriz armazene uma substring?

Question: Suponhamos que o usuário digitasse: Eu sou muito lindo
Cada linha da Matriz armazenaria uma substring ficando assim:

Eu
sou
muito
lindo
Comment: Uma possibilidade é você definir um array de ponteiros para char e alocar memória dinamicamente pra armazenar cada string e apontar por cada elemento do array. Pesquise pela função strtok (https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtok.html).
Answer:
1) Defina a quantidade de palavras que você deseja ler para a matriz.
2) Crie um char** e use malloc passando como o parâmetro o tamanho de intptr_t * número de palavras que você deseja ler
3) Crie um char[N] onde N é o número de letras máximo de letras em uma única palavra
4) Crie um laço para a leitura dos valores em cada iteração (Número das palavras que você quer ler), armazene a palavra na variável do passo 3
5) Realize um malloc na variável do passo 2 para cada palavra, indexando-a na variável de iteração do loop. Neste malloc você irá usar o tamanho da palavra lida (strlen) + 1 (NUL Byte)
6) Utilize a função strcpy para passar o buffer lido (variável do passo 3) para a matriz (variável do passo 2)

Não se esqueça depois de utilizar o free() para liberar memória.


Prove a particular set is a ring with unity

Question: I have to show that $(\mathbb{Z}[G],+,.)$ is a unitary ring, where $$\mathbb Z[G]=\{\sum_{g \in G} a_g.g| a_g \in \mathbb Z, a_g \neq 0, \text{only for finite g in G}\}$$ with $G$ group and $(\sum a_g.g)+(\sum b_g.g)=\sum (a_g+b_g).g$;$(\sum a_g.g).(\sum b_g.g)=\sum(\sum_{g_1 g_2=g}a_{g_1}b_{g_2}).g$.
I am confused about how $\mathbb Z[G]$ is defined. If $a_g \in \mathbb Z$ and $g \in G$, does it make any sense to do the operation $a_g.g$? I mean, is $a_g.g$ in $\mathbb Z$ or in $G$?. I would appreciate if someone could describe me this ring and to tell how it is called in case it has a particular name. Thanks in advance.
Answer: $\Bbb Z[G]$, or sometimes just $\Bbb ZG$, is called the group ring (of $G$ over $\Bbb Z$). One can think of the ring as the free $\Bbb Z$-module generated by $G$:
$$\Bbb Z[G]=\bigoplus_{g\in G}\Bbb Zg.$$
Then one can equipe $\Bbb Z[G]$ with the multiplication as mentioned in the question.
Recall that one can think of elements of $\Bbb Z[G]$ as a collection $\{a_g:g\in G\}$, where $a_g$ are integers and only finitely many of $n_g$'s are non-zero. This element corresponds to $\sum a_g\cdot g$ in the question. In particular, $a_g\cdot g$ is an element of $\Bbb Zg$.
Let $e$ be the unit of $G$, then the unit of $\Bbb Z[G]$ is the element $1\cdot e\in \Bbb Z e$.