text:
Q: How to (massively) reduce the number of SQL queries in Rails app? In my Rails app I have users which can have many invoices which in turn can have many payments.
Now in the dashboard view I want to summarize all the payments a user has ever received, ordered either by year, quarter, or month. The payments are also subdivided into gross, net, and tax.
user.rb:
class User < ActiveRecord::Base

  has_many  :invoices
  has_many  :payments

  def years
    (first_year..current_year).to_a.reverse
  end

  def year_ranges
    years.map { |y| Date.new(y,1,1)..Date.new(y,-1,-1) }
  end

  def quarter_ranges
    ...
  end

  def month_ranges
    ...
  end

  def revenue_between(range, kind)
    payments_with_invoice ||= payments.includes(:invoice => :items).all
    payments_with_invoice.select { |x| range.cover? x.date }.sum(&:"#{kind}_amount")
  end

end

invoice.rb:
class Invoice < ActiveRecord::Base

  belongs_to :user
  has_many :items
  has_many :payments

  def total
    items.sum(&:total)
  end

  def subtotal
    items.sum(&:subtotal)
  end

  def total_tax
    items.sum(&:total_tax)
  end

end

payment.rb:
class Payment < ActiveRecord::Base

  belongs_to :user
  belongs_to :invoice

  def percent_of_invoice_total
    (100 / (invoice.total / amount.to_d)).abs.round(2)
  end

  def net_amount
    invoice.subtotal * percent_of_invoice_total / 100
  end

  def taxable_amount
    invoice.total_tax * percent_of_invoice_total / 100
  end

  def gross_amount
    invoice.total * percent_of_invoice_total / 100
  end

end

dashboards_controller:
class DashboardsController < ApplicationController

  def index
    if %w[year quarter month].include?(params[:by])
      range = params[:by]
    else
      range = "year"
    end
    @ranges = @user.send("#{range}_ranges")
  end

end

index.html.erb:
<% @ranges.each do |range| %>

  <%= render :partial => 'range', :object => range %>

<% end %>

_range.html.erb:
<%= @user.revenue_between(range, :gross) %>
<%= @user.revenue_between(range, :taxable) %>
<%= @user.revenue_between(range, :net) %>

Now the problem is that this approach works but produces an awful lot of SQL queries as well. In a typical dashboard view I get 100+ SQL queries. Before adding .includes(:invoice) there were even more queries.
I assume one of the major problems is that each invoice's subtotal, total_tax and total aren't stored anywhere in the database but instead calculated with every request.
Can anybody tell me how to speed up things here? I am not too familiar with SQL and the inner workings of ActiveRecord, so that's probably the problem here.
Thanks for any help.

A: Whenever revenue_between is called, it fetches the payments in the given time range and the associated invoices and items from the db. Since the time ranges have lot of overlap (month, quarter, year), same records are being fetched over and over again.
I think it is better to fetch all the payments of the user once, then filter and summarize them in Ruby.
To implement, change the revenue_between method as follows:
def revenue_between(range, kind)
   #store the all the payments as instance variable to avoid duplicate queries
   @payments_with_invoice ||= payments.includes(:invoice => :items).all
   @payments_with_invoice.select{|x| range.cover? x.created_at}.sum(&:"#{kind}_amount")
end

This would eager load all the payments along with associated invoices and items.
Also change the invoice summation methods so that it uses the eager loaded items
class Invoice < ActiveRecord::Base

   def total
     items.map(&:total).sum
   end

   def subtotal
     items.map(&:subtotal).sum
   end

   def total_tax
     items.map(&:total_tax).sum
   end

end

A: Apart from the memoizing strategy proposed by @tihom, I suggest you have a look at the Bullet gem, that as they say in the description, it will help you kill N+1 queries and unused eager loading.

A: Most of your data do not need to be real time. You can have a service calculating the stats and storing them wherever you want (Redis, cache...). Then refresh them every 10 minutes or upon user's request.
In the first place, render your page without stats and load them with ajax.


text:
Q: Vue Js running code when Modal has been oepend I have a link that has an ID, and I am trying to load data in to my form once the bootstrap is open (because the id can be different than the one when the page loads) How can I only run my method, once the modal has been opened?
I want to run the setData method every time the modal is oepened via a link
<template>

            <button type="button" class="close" data-dismiss="modal">×</button>

Edit Job

My html file has the called component which is opened via a link:
id}' onclick='getID({$job->id})' data-toggle='modal' data-target='#editJob'>

                <edit-job :id="id"></edit-job>

Set data is in my edit-job component:
Vue.component('edit-job', require('./pages/jobs/edit-job.vue'));

A: To perform my task, I didn't need to check if the modal opened. On the initial page load my prop Id is set to null. So I created a watcher for when my ID changes to run my method:
    watch: {
        id: function(newid){
            this.setData()
        }
    },

I will  leave this answer open if any one wants to add to the discussion of better ways etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove $v,Tv,...,T^{n-1}v$ is a base of V $V$ is a linear space of dimension $n$ over $F$.
$T: V \to V$ is a linear transformation, s.t. $T^n$ = 0 and $T^{n-1}\ne 0$
Prove that there is $v$ from $V$ s.t. $\{v,Tv,...,T^{n-1}v\}$ is a base of $V$.
I tried to conclude things about the kernel, and to work with a base of $V$, but got stuck.
Any help appreciated.

A: As $T^{n-1}\ne 0$ there exists $v\in V$ such that $T^{n-1}v\ne 0$. Then, $$\lambda_1v+\lambda_2Tv+\cdots+\lambda_nT^{n-1}v=0$$ $$\Rightarrow T\left(\lambda_1v+\lambda_2Tv+\cdots+\lambda_nT^{n-1}v\right)=T(0)$$
$$\Rightarrow \lambda_1Tv+\lambda_2T^2v+\cdots+\lambda_n\underbrace{T^{n}v}_{=0}=0$$ Taking repeatedly $T$ in both sides you'll finally get $$\lambda_1=0\Rightarrow \lambda_2=0\Rightarrow \cdots \Rightarrow \lambda_n=0.$$
So, $B=\{v,Tv,...,T^{n-1}v\}$ is linearly independent and $|B|=\dim V=n,$ so $B$ is basis of $V.$

A: Suppose the set is linearly dependent.  Then
$$a_0v+a_1Tv+a_2T^2v+...+a_{n-1}T^{n-1}v=0$$
for non-trivial set of $a_i$.  First suppose $a_0 \neq 0$. Then you can rewrite the terms as
$$v=a'_1Tv+a'_2T^2v+...+a'_{n-1}T^{n-1}v$$
Now, apply $T^{n-1}$ to both sides of the equation.  The right side is zero, while the left side is non-zero.
Similarly, if $a_0=0$ but $a_1 \neq 0$ then you can write
$$Tv=a'_2Tv^2+a'_3T^3v+...+a'_{n-1}T^{n-1}v$$
Apply $T^{n-2}$ to the equation, and you get same result as above.  Continuing this process shows that all of the $a_i$ have to be zero, reaching a contradiction.  Finally, since the number of elements in the set equals the dimension, it is a basis for $V$.


text:
Q: Use case of BeanNameAware I can't figure out any use case of BeanNameAware interface except for logging the name of bean itself.
I did my research but I could not find a single person who wrote something other than just printing the bean name after the bean has been initialized. Does it have any real use case?

A: BeanNameAware can be used where we have an multiple classes subclassing a abstract class and would like to know the name of those particular bean in order to use their functionality, do something if bean name follows certain pattern, manipulate them, etc. Let's take an example and understand it:
abstract class Parent implements BeanNameAware {

    String beanName;

    void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    abstract void doFilter();

}

@Component
class Child1 extends Parent {
    @Override
    void doFilter() {
        // some impl
    }
}

@Component
class Child2 extends Parent {
    @Override
    void doFilter() {
        // some impl
    }
}

And we have a service method that takes instance of all Parent class and invokes abstract void doFilter() method implementation:
@Service
class SomeService{

    @Autowired
    Parent[] childs; // injecting all Child*

    void doSomethingWithChilds() {
        for(Parent child: childs) {
            child.doFilter(); // invoking their doFilter() impl
            String currentChildName = child.beanName;
            // We now know the name of current child* bean
            // We can use it for manipulating the child* instance
            // This is useful because each child instance will have a different bean name

            if(currentChildName.equals("child2")) {
                // do something special with child2
            }

        }
    }
}


text:
Q: Convert problem to linear programming task I have function $\max \{ |x-1| + 2|y-1| | x,y \in R, x+y \leq 2 \}$. Can this problem be converted to LP? I think it cant because of the abs. value in criterial function, but Im not sure.
If it can, how to convert it? I think that restrictive conditions are already in correct form so I only have to convert criterial function to some form without abs. if its possible.. Thanks for advice!

A: Yes, it can be converted into LP. Use the following hint
Hint: $|z|$ can be replaced by $z^{+}+z^{-}$ along with the conditions $z^{+}\geq 0, z^{-}\geq 0$.


text:
Q: Using LocalStorage for html table I have been working on an HTML app in order to keep track of dungeons that I have done in world of warcraft weekly by ticking the boxes next to the dungeon names.
I have created the table and the functions for marking the boxes on click as done and they can also be toggled off if needed.
The problem I'm facing is that I don't know how to use LocalStorage in order to keep that information when the page refreshes or closes.

$(document).ready(function() {
    $(".sjitem").click(function() {
      if ($(this).hasClass("done")) {
        $(this).removeClass("done");
      } else {
        $(this).addClass("done");
      }
      localStorage.setItem("sjitem", "done");
    });
  }

);

  Home
  <title>BFA Tracker</title>

      Dungeons
      Weekly
Tracker

      Freehold

      Shrine of
the Storm

      Tol Dagor

      Waycrest
Manor

      Atal'Dazar

      The
MOTHERLODE!!!

      Temple of
Sethraliss

      The
Underrot

      King's
Rest

      Siege of
Boralus


text:
Q: How can I change the size of rgl plots in Shiny RMarkdown? I'm creating a Shiny document using RMarkdown and am including reactive plots from rgl. I cannot, however, change the viewport size of the rendered plots. That is, I cannot change the height and width of the space in which the plots render. How might I make the rendered plots bigger than their default?
EDIT: Alternating fig.width in the knitr options does not change the width of Shiny render functions, it seems.
Below is the document I have so far.
---
title: "Untitled"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(rgl)
library(dplyr)
source("https://raw.githubusercontent.com/trestletech/rgl/master/vignettes/setup.R")
```

```{r, rgl = TRUE, echo = FALSE}
inputPanel(
  sliderInput("b1", label = withMathJax("\\(\\beta_1\\)"), min = -.4, max = .4, value = .4, step = .025),
  sliderInput("b2", label = withMathJax("\\(\\beta_2\\)"), min = -.4, max = .4, value = .4, step = .025),
  sliderInput("b3", label = withMathJax("\\(\\beta_3\\)"), min = -.2, max = .2, value = .2, step = .025)
)

r <- reactive({
  set.seed(12479)
  nobs <- 200
  x <- rnorm(nobs)
  z <- rnorm(nobs)
  r2 <- input$b1^2 + input$b2^2 + input$b3^2
  y <- input$b1 * x + input$b2 * z + input$b3 * x*z + rnorm(nobs, sd = sqrt(1 - r2))
  d <- data.frame(x, z, y)

  fit_int <-   lm(y ~ x*z, data = d)
  fit_noint <- lm(y ~ x+z, data = d)

  scale <- seq(-3, 3, length.out = 30)

  dp <- expand.grid(x = scale, z = scale, KEEP.OUT.ATTRS = FALSE)

  dp_int <- dp %>%
    mutate(., y = predict(fit_int, .)) %>%
    filter(-3 <= y, y <= 3)

  dp_noint <- dp %>%
    mutate(., y = predict(fit_noint, .)) %>%
    filter(-3 <= y, y <= 3)

  return(list(
    d = d,
    fit_int = fit_int,
    fit_noint = fit_noint,
    dp_int = dp_int,
    dp_noint = dp_noint))
})

renderRglwidget({
  try(rgl.close())
  layout3d(matrix(c(1,1,2,3), byrow = TRUE, ncol = 2), sharedMouse = TRUE)

  with(r()$d, plot3d(x, z, y, xlim = c(-3, 3), ylim = c(-3, 3), zlim = c(-3, 3), main = "scatter"))

  next3d()
  with(r()$d, plot3d(x, z, y, xlim = c(-3, 3), ylim = c(-3, 3), zlim = c(-3, 3), main = "with int"))
  with(r()$dp_int, points3d(
    x, z, y, col = rgb(1,0,0), alpha = .25))

  next3d()
  with(r()$d, plot3d(x, z, y, xlim = c(-3, 3), ylim = c(-3, 3), zlim = c(-3, 3), main = "without int"))
  with(r()$dp_noint, points3d(
    x, z, y, col = rgb(0,.5,0), alpha = .25))

  rglwidget(width = 1400)
})
```

A: Add this function to your code:
myRenderRglwidget <- function(expr, env = parent.frame(), quoted = FALSE, outputArgs = list()) {
  if (!quoted) { expr <- substitute(expr) } # force quoted

  markRenderFunction(rglwidgetOutput,
                     shinyRenderWidget(expr, rglwidgetOutput, env, quoted = TRUE),
                     outputArgs = outputArgs)
}

Then instead of calling renderRglwidget, call myRenderRglwidget, and
add an extra argument at the end, outputArgs = list(width = 1400), i.e.
the last few lines of your code chunk should be
  with(r()$dp_noint, points3d(
    x, z, y, col = rgb(0,.5,0), alpha = .25))

  rglwidget()
}, outputArgs = list(width = 1400))

This modification will eventually make it into rgl, and you won't need to use myRenderRglwidget, you'll just be able to use renderRglwidget with the extra argument.


text:
Q: How much legacy Objective-C code can Hyperloop work with? Hyperloop looks like an exciting way forward for Appcelerator. I've read the very basic Hyperloop docs and watched the intro video. In the intro video I can see that simple Swift or Objective-C files can be used,
I'm interested to find out how much of an exisiting Swift/Objective-C codebase could be dropped into a Hyperloop project?
Could we for example, take an entire project written in Swift/Objective-C and work on it using Hyperloop?
Does anyone have any hands on experience?
Cheers!

A: You can potentially use a lot of the code but you can't (today) easily drop in a full xcodeproject without a bit of work.
If you look at the example iOS project that comes alongside Hyperloop (http://labs.appcelerator.com/project/55f74a9f421c44837717716b/Hyperloop-Module) you can see some drop in examples of both swift and objective-c code.

A: I recommend looking at the examples at Loop Modules since they provide a lot of how-to for using Swift-Objective C in Hyperloop. From my own experience, you can't drop and drag a current X-Code project, every piece that is integrated into Hyperloop works as a module (they call it framework, but for me it is a module) which needs to be adapted to be used inside Titanium.
My personal experience, with enough tinkering (or knowledge) you can integrate any native Swift-Objective C component you want. I even went as far as compiling source C and integrating that in Hyperloop and calling the functions in that with C as well.
Currently I'm using Javascript, Swift, Objective-C and C in the same project and it works great so far :)
Also the latest documentation from Appcelerator is here
Another good news is Hyperloop is now available to the free Indie program at Appcelerator.


text:
Q: Issue with Eloquent Relationships in Laravel 4.2 I have an issue using Eloquent ORM in Laravel 4.2
I have 2 tables, banks and bank_accounts
In banks i have the ID of the bank and in the bank_accounts table i have bank_id and it's foreign key pointing to banks table.
I have been struggling with this for hours and looking in the Laravel Documentation without any luck.
I have two models:
BankAccounts Model:
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

    class Cuentas extends Eloquent
    {
      protected $table      = 'icar_cuentas';
      protected $primaryKey = 'id';
      public    $timestamps = FALSE;

      public function Banco()
      {
        return $this->belongsTo('Bancos','id_banco');
      }
    }

Banks Model:
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Bancos extends Eloquent
{
  protected $table      = 'icar_bancos';
  protected $primaryKey = 'id';
  public    $timestamps = FALSE;

  public function cuentasRelacionadas()
  {
    return $this->hasMany('Cuentas');
  }
}

What i need is to list the accounts added by the user and show the name of its related bank but didn't figured out how to do it.
So far i have in the Controller:
public function showCuentas()
  {
    $results = Cuentas::all();

    return View::make('content.bancos.list_bancos', array('bancos' => $results));
  }

And the View:

            @foreach($bancos as $banco)
                          @if($banco->activo == 'si')
                             {{-- */$estado = 'Activo';/* --}}
                          @endif
                          @if($banco->activo == 'no')
                             {{-- */$estado = 'Inactivo';/* --}}
                          @endif

                id)) }}"> | id)) }}" onclick="return confirma('Realmente deseas eliminar la cuenta {{ $banco->cuenta }}');">
                {{ $banco->banco->first()->banco }}
                {{ $banco->cuenta }}
                {{ $banco->tipo }}
                {{ $estado }}

              @endforeach

But it always shows the name of the First Bank in the table instead of the related one.
Appreciate any help

A: You shouldn't use lazy loading, because, for each Cuenta you will have another query in your database. Use eager loading instead:
$results = Cuentas::with('banco')->get();

Then you go:
foreach($bancos as $banco) { //--> I think you should replace with cuentas, but it's up to you
    ....
    {{ $banco->banco->banco }} // also, terrible. Use banco.name instead. Give proper name to easily understand your code
    ....
}

A: well, the doc say for the method Model::belongsTo (laravel 4.2)
belongsTo( string $related, string $foreignKey = null, string $otherKey = null, string $relation = null)

i see the second argument you pass to your function Cuentas::belongsTo()  is 'id_cuentos'
But in class Bancos the primary key attribute say the name of the primary key is 'id'.
protected $primaryKey = 'id';

isn't there something wrong about it ?

A: The public function Banco() is a belongsTo relation and will return a Bancos object - not a collection of them. So when you call ->fist() on that object it's not the Collection::fist() function - it is Bancos::first(). That is the reason why you allways get the first entry from Bancos model.
In your foreach loop $banco is a Cuentas object. And $banco->banco is the related Bancos object that you need. So if you have an attribute $banco in your Bancos object - all you need to call in your template is
{{ $banco->banco->banco }}

As others mentioned in their answers, you should either rename Banco() to banco() or call {{ $banco->Banco->banco }}.
As a side note: Your naming style is very confusing. Why do you call a Cuentas collection $bancos?
I would rename some things:

*

*function Banco() => function banco()

*array('bancos' => $results) => array('cuentas' => $results)

*@foreach($bancos as $banco) => @foreach($cuentas as $cuenta)

*{{ $banco->banco->banco }} => {{ $cuenta->banco->banco }}
Additionally (if possible) i would rename the attribute Bancos::banco to Bancos::name so you can call {{ $cuenta->banco->name }} without confusing the reviewers.

A: I'm pretty sure things are case sensitive and you are using Banco in the model and banco in the view.


text:
Q: Flutter/Dart - Trying to iterate over a map of values // Syntax help needed I'm a self-learning beginner at coding, failing at a self-set task. The aim of the task is ultimately to figure out the syntax...but I spent hours now. So...help pls! Warning: I thoroughly confused myself...so don't expect beauty in my attempt.
I want to use iterate over this map:
const marginsCard = [
  {
    'ID': 0,
    'margins': [
      {'marginLeft': 0},
      {'marginRight': 5},
      {'marginBottom': 0},
      {'marginTop': 20},
    ],
  },
  {
    'ID': 1,
    'margins': [
      {'marginLeft': 5},
      {'marginRight': 0},
      {'marginBottom': 0},
      {'marginTop': 20,},
    ],
  },
  {
    'ID': 2,
    'margins': [
      {'marginLeft': 5},
      {'marginRight': 0},
      {'marginBottom': 0},
      {'marginTop': 20,},
    ],
  },
];

The goals are to

*

*iterate over 'ID'

*hand over the values for the margins to  a constructor method that

*hand back a Card with the specified margins

*put those Cards in a list.

The function calling the constructor function in its current state:
buildCardElementList(){

  cardElementsList = [
  ...(marginsCard[int.parse('ID')] as List<Map<String,Object>>).map((cardElement){
    return buildCardElement(cardElement['marginLeft'], cardElement['marginRight'], cardElement['marginBottom'], cardElement['marginTop']);
  }).toList()];
  return cardElementsList;
}

There is so much try and eror in this, I'm sure there are multiple issues. Can someone help me out with clean syntax so I can start to understand what I'm doing again?
Thanks!
EDIT // P.S.: I'm leaving out the receiving/constructing function; it's not the issue.

A: Enjoy ;)
void main() {
  final cards = marginsCard.map(_buildCard).toList();
  print(cards);
}

Card _buildCard(Map<String, Object> cardElement) {
  return Card(
    marginLeft: resolveMargin(cardElement, 'marginLeft'),
    marginRight: resolveMargin(cardElement, 'marginRight'),
    marginBottom: resolveMargin(cardElement, 'marginBottom'),
    marginTop: resolveMargin(cardElement, 'marginTop'),
  );
}

num resolveMargin(Map<String, Object> cardElement, String marginName) {
  final marginElements = cardElement['margins'] as List<Map<String, Object>>;
  return marginElements.firstWhere((marginElement) => marginElement.containsKey(marginName))[marginName] as num;
}

class Card {
  final num marginLeft, marginRight, marginBottom, marginTop;
  Card({required this.marginLeft, required this.marginRight, required this.marginBottom, required this.marginTop});

  @override
  String toString() => "marginLeft: $marginLeft; marginRight: $marginRight; marginBottom: $marginBottom; marginTop: $marginTop";
}

const marginsCard = [
  {
    'ID': 0,
    'margins': [
      {'marginLeft': 0},
      {'marginRight': 5},
      {'marginBottom': 0},
      {'marginTop': 20},
    ],
  },
  {
    'ID': 1,
    'margins': [
      {'marginLeft': 5},
      {'marginRight': 0},
      {'marginBottom': 0},
      {'marginTop': 20,},
    ],
  },
  {
    'ID': 2,
    'margins': [
      {'marginLeft': 5},
      {'marginRight': 0},
      {'marginBottom': 0},
      {'marginTop': 20,},
    ],
  },
];


text:
Q: Normalization - removing transitive dependency I am creating a rules engine which will be executed in code, but I have a problem defining a properly normalized database structure for it:

*

*There are templates from which rules can be derived

*Each template will define a set of fields that can be used by a rule

*Each rule will define a set of conditions that can be tested against the fields

So for example I may have a template 'Bicycle' that would have fields 'Wheel Size' and 'Number of gears'.
I could then create a number of rules against that template such as:

*

*'Childrens bike': Wheel Size = 14"

*'Mountain bike': Wheel Size = 26" and Number of Gears = 27

*'City bike': Wheel Size = 26" and Number of Gears = 3

This is a simplified version of the database design I have so far:

And the associated SQL:
CREATE TABLE RuleTemplate(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Name NVARCHAR(100) NOT NULL
)

CREATE TABLE Field(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    RuleTemplateId INT NOT NULL FOREIGN KEY REFERENCES RuleTemplate(Id),
    Name NVARCHAR(100) NOT NULL
)

CREATE TABLE [Rule](
    Id INT IDENTITY(1,1) PRIMARY KEY,
    RuleTemplateId INT NOT NULL FOREIGN KEY REFERENCES RuleTemplate(Id),
    Name NVARCHAR(100) NOT NULL
)

CREATE TABLE Condition(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    RuleId INT NOT NULL FOREIGN KEY REFERENCES [Rule](Id),
    FieldId INT NOT NULL FOREIGN KEY REFERENCES Field(Id),
    ComparisonValue NVARCHAR (100) NOT NULL
)

This design is vulnerable to anomalies as a rule can contain conditions which refer to fields from a different template than the rule.
Can anyone suggest a table design which will overcome this weakness?

A: I think that same Field can participate in several templates so Field and RuleTemplate is actually M:M.
Next, you can't enforce rules like 'Condition should refer only to Fields that belong to Rule's template' in a declarative way, and keep this schema normalized. But you can control rules like this using triggers. If you see a lot of weird questions like this, usually it means that probably we can choose better base entities for a subject area.
It doesn't mean that this schema can't be used. No, it is normalized and good enough to be used in application. But data integrity should be checked on application side. It is natural way to deal with scheme like this. GUI should never show wrong columns in rule designer.

Concerning another set of entities. Logically every rule is an expression. Expression is a tree-like structure. Unfortunately relational schema is not a good fit for information like this. You'll meet a lot of difficulties further on the way, for example, type of ComparisionValue column should be different for different fields. Solution can be XML which store expression. It is better option for expressions, type-safe and way more flexible.

A: Don't you simply want to have the structure
Templates -> Fields -> Rules -> conditions
This will ensure that rules are associated with the correct fields and the correct fields are associated with the template


text:
Q: Hola alguien sabe porque el primer printf si se introduce un valor superior a 20, sale el siguiente printf pero despues se acaba el codigo de repente Este codigo es la entrada a un cajero para sacar dinero
el primer printf pide la cantidad de dinero que se quiere sacar, el segundo el dinero que habia en el banco y el tercero el dinero que queda una vez has sacado dinero
los else if se utilizan para deteerminar la cantidad de billetes que se van a dar

Muchas gracias!!


text:
Q: a question on time, distance and speed and logic In a race of length d meters, A beats B by x meters and C by y meters. By what distance does B beat C in the same race?
A. (y-x)d/d-y meters
B. (y-x)d/d-x meters
C. d(d-y)/d-x meters
D. (y-x) meters

A: Hint
Just draw a straight line and put A, B and C locations (B being at $x$ behind A and C being at $y$ behind A).
I am sure that you can take from here.

A: Actually, I believe the previous posters are not correct because they assume that each of the racers is moving at the same speed. I will assume that each of the racers is instead moving at his own constant speed.
Let a, b, and c be the speeds of the racers. Then we have these equations using $d = rt$:
$$
at = d
\\ bt = d - x
\\ ct = d - y
$$
If you think about it, the distance between racers B and C once B has finished the race is the difference between the total race distance and the distance C traveled in the time it took B to finish the race:
$$d - c\left(\frac{d}{b}\right)$$
Now, we have to make it look like one of the answer choices. First, subtract the two fractions. Then solve equations 2 and 3 for b and c, respectively, because none of the answer choices involve speeds. Substitute them into the fraction:
$$\frac{(d - x)d - (d - y)d}{bt}$$
Finally, substitute equation 2 in for bt, simplify a bit and you have one of the answer choices.


text:
Q: How can I repeat the whole code until the user quits? How can I loop the "Would you like to buy something else?" its at the bottom most of the code, after answering Yes then it will go back again from choosing from the available categories.
I'll place the switch again after knowing how can i loop this
#include <iostream>
using namespace std;

char acoustic, electric, drums, piano, music, equip, Yes, No;

int pay1, pay2, pay3, pay4, pay5;
std::string answer;

int main()
{
cout << "Welcome to the Music Shop" << endl <<endl;

cout << "Categories                    Products                Price"<<endl;
cout << "[a] Acoustic Guitar      Fender Acoustic Guitar     P6,900.00"<< endl;
cout << "                         Hartwood Acoustic Guitar   P6,300.00" << endl;

cout << "[b] Electric Guitar      Gibson Electric Guitar     P8,500.00" << endl;
cout << "                         Ibanez Electric Guitar     P25,000.00" << endl;

cout << "[c] Drums                Pearl Drum Kits            P27,000.00" << endl;
cout << "                         Roland Electronic Drums    P24,000.00" << endl;

cout << "[d] Piano                Casio Digital Piano        P19,000.00" << endl;
cout << "                         Roland Piano               P120,000.00" << endl;

cout << "[e] Music Equipments     Guitar String              P113.00" << endl;
cout << "                         Headphones                 P1,600.00" << endl;
cout << "                         Amplifier                  P2,800.00" << endl;
cout << "                         Digital Mixer              P4,750.00" << endl;
cout << "                         Vocal Microphone           P860.00" << endl;
cout << "                         Guitar Tuner               P537.00" << endl;
cout << "                         Guitar Pick                P360.00" << endl<<endl;

cout << "Choose from the available categories: ";
cin >> music;

switch (music)
{
    case 'a':

    cout<< "Acoustic Guitar" << endl;
    cout<< "1. Fender Acoustic Guitar   - P6,900.00" << endl;
    cout<< "2. Hartwood Acoustic Guitar - P6,300.00" << endl <<endl;
    cout<<"Choose from the available Acoustic Guitars:";
    cin>>acoustic;

    if (acoustic == '1'){
        cout<<"Enter your payment:";
        cin>>pay1;
        if (pay1==6900){
            cout<<"You have succesfully purchased Fender Acoustic Guitar"<<endl;
        }
            else if (pay1>6900){
                pay1 -= 6900;
                cout<<"Your change is:"<<pay1<<endl;
            }
                else if (pay1<6900){
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (acoustic == '2'){
        cout<<"Enter your payment:";
        cin>>pay1;
        if (pay1==6300){
            cout<<"You have succesfully purchased Fender Acoustic Guitar"<<endl;
        }
            else if (pay1>6300){
                pay1 -= 6300;
                cout<<"Your change is:"<<pay1<<endl;
            }
                else if (pay1<6300)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else {
        cout<<"Invalid"<<endl;
    }

    break;

    case 'b':

    cout<< "Electric Guitar" << endl;
    cout<< "1. Gibson Electric Guitar   -P8,500.00" << endl;
    cout<< "2. Ibanez Electric Guitar   -P25,000.00" << endl <<endl;
    cout<<"Choose from the available Electric Guitars:";
    cin>>electric;

        if (electric=='1'){
        cout<<"Enter your payment:";
        cin>>pay2;
        if (pay2==8500){
            cout<<"You have succesfully purchased Fender Acoustic Guitar"<<endl;
        }
            else if (pay2>8500){
                pay2 -= 8500;
                cout<<"Your change is:"<<pay2<<endl;
            }
                else if(pay2<8500)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (electric=='2'){
        cout<<"Enter your payment:";
        cin>>pay2;
        if (pay2==25000)
        {
            cout<<"You have succesfully purchased Fender Acoustic Guitar"<<endl;
        }
            else if (pay2>25000){
                pay2 -= 25000;
                cout<<"Your change is:"<<pay2<<endl;
            }
                else if (pay2<25000)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else {
        cout<<"Invalid";
    }
        break;

    case 'c':

    cout<< "Drums" << endl;
    cout<< "1. Pearl Drum Kits          -P27,000.00" << endl;
    cout<< "2. Roland Electronic Drums  -P24,000.00" << endl <<endl;
    cout<<"Choose from the available Drums:";
    cin>>drums;

        if (drums=='1'){
        cout<<"Enter your payment:";
        cin>>pay3;
        if (pay3==27000){
            cout<<"You have succesfully purchased Pearl Drum Kits"<<endl;
        }
            else if (pay3>27000){
                pay3 -= 27000;
                cout<<"Your change is:"<<pay3<<endl;
            }
                else if(pay3<27000)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (drums=='2'){
        cout<<"Enter your payment:";
        cin>>pay3;
        if (pay3==24000)
        {
            cout<<"You have succesfully purchased Rolans Electronic Drums"<<endl;
        }
            else if (pay3>24000){
                pay3 -= 24000;
                cout<<"Your change is:"<<pay3<<endl;
            }
                else if (pay3<25000)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else {
        cout<<"Invalid";
    }
     break;

     case 'd':

    cout<< "Piano" << endl;
    cout<< "1. Casio Digital Piano      -P19,000.00" << endl;
    cout<< "2. Roland Piano             -P120,000.00" << endl <<endl;
    cout<<"Choose from the available Piano:";
    cin>>piano;

        if (piano=='1'){
        cout<<"Enter your payment:";
        cin>>pay4;
        if (pay4==19000){
            cout<<"You have succesfully purchased Casio Digital Piano"<<endl;
        }
            else if (pay4>19000){
                pay4 -= 19000;
                cout<<"Your change is:"<<pay4<<endl;
            }
                else if(pay4<19000)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (piano=='2'){
        cout<<"Enter your payment:";
        cin>>pay4;
        if (pay4==120000){
            cout<<"You have succesfully purchased Roland Piano"<<endl;
        }
            else if (pay4>120000){
                pay4 -= 120000;
                cout<<"Your change is:"<<pay4<<endl;
            }
                else if(pay4<120000)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else {
        cout<<"Invalid";
    }
     break;

     case 'e':

    cout<< "Music Equipments" << endl;
    cout << "1. Guitar String            -P113.00" << endl;
    cout << "2. Headphones               -P1,600.00" << endl;
    cout << "3. Amplifier                -P2,800.00" << endl;
    cout << "4. Digital Mixer            -P4,750.00" << endl;
    cout << "5. Vocal Microphone         -P860.00" << endl;
    cout << "6. Guitar Tuner             -P537.00" << endl;
    cout << "7. Guitar Pick              -P360.00" << endl <<endl;

    cout<<"Choose from the available Music Equipments:";
    cin>>equip;

        if (equip=='1'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==113){
            cout<<"You have succesfully purchased Guitar String"<<endl;
        }
            else if (pay5>113){
                pay5 -= 113;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<113)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='2'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==1600){
            cout<<"You have succesfully purchased Headphones"<<endl;
        }
            else if (pay5>1600){
                pay5 -= 1600;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<1600)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='2'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==1600){
            cout<<"You have succesfully purchased Headphones"<<endl;
        }
            else if (pay5>1600){
                pay5 -= 1600;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<1600)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='3'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==2800){
            cout<<"You have succesfully purchased Amplifier"<<endl;
        }
            else if (pay5>2800){
                pay5 -= 2800;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<2800)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='4'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==4750){
            cout<<"You have succesfully purchased Digital Mixer"<<endl;
        }
            else if (pay5>4750){
                pay5 -= 4750;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<4750)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='5'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==860){
            cout<<"You have succesfully purchased Vocal Microphone"<<endl;
        }
            else if (pay5>860){
                pay5 -= 860;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<860)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='6'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==537){
            cout<<"You have succesfully purchased Guitar Tuner"<<endl;
        }
            else if (pay5>537){
                pay5 -= 537;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<537)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else if (equip=='7'){
        cout<<"Enter your payment:";
        cin>>pay5;
        if (pay5==360){
            cout<<"You have succesfully purchased Guitar Pick"<<endl;
        }
            else if (pay5>360){
                pay5 -= 360;
                cout<<"Your change is:"<<pay5<<endl;
            }
                else if(pay5<360)
                {
                    cout<<"You do not have enough money"<<endl;
                }
    }
    else {
        cout<<"Invalid";
    }
}

 cout<<"\nWould you like to buy something else?"<<endl;
 cout<<"Yes or No?"<<endl;
 cin>>answer;

 if (answer == "Yes"){
 cout<<"Choose from the available categories"<<endl;
 cout<<"[a] Acoustic Guitar"<<endl;
 cout<<"[b] Electric Guitar"<<endl;
 cout<<"[c] Drums"<<endl;
 cout<<"[d] Piano"<<endl;
 cout<<"[e] Music Equipments"<<endl;
 cin >> music;

 switch(music){
 }
}
else if (answer == "No"){
        cout<<"Thank you for visiting our shop come again";
}
}

Need the loop so i can just keep buying everytime i choose Yes

A: In any case, you will need a loop.
There are several options, and it is rather a matter of taste which one to chose...
bool isContinue = true;
while(isContinue)
{
    // ...
    std::string input;
    // get input, convert to upper case for case-insensitive comparison
    isContinue = input == "YES";
}

Almost the same, but skipping very first (unnecessary comparison):
bool isContinue = false; // initial value is irrelevant, will be overwritten anyway
do
{
    // ...
    isContinue = input == "YES";
}
while(isContinue);

or an seemingly endless loop:
for(;;)
{
    // ...
    if(input != "YES")
        break;
}

The last variant is especially useful if you need to decide right in the middle of the loop body if you need to stop:
for(;;)
{
    // some initial work
    if(doWeNeedToStop)
        break;
    // some work to be done if we did NOT stop
}

Yet interesting: where to place the loop? Well, around all the stuff you want to repeat, so:
int main()
{
    // stuff you want to do only once at programme start,
    // e. g. welcome message
    for(;;)
    {
        // stuff you want to repeat
    }
    // stuff you want to do only once before programme ends,
    // e. g. printing a good-bye message

    return 0;
}

A: In a very awful, but very fast way, you can use a label and a goto statement; here's a doc.
If you want to be cleaner, you might implement a do-while loop that checks the answer; like this:
do {
    // do your stuff
} while (answer == "Yes");

std::cout << "Thank you for visiting our shop come again";


text:
Q: Using 'externals' in Webpack gives error "failed to resolve module specifier" I'm testing a library that is exported as a module (by Webpack) with something like
// myLib.js
const a = 1;
export { a as myVal };

My script for the page is
// index.js
import { myVal } from 'my-lib'

console.log (myVal)

In webpack.config.js I have externals: { myLib: 'myLib' }. In my index.html, I would have
...
  <script type="module" src="https://unpkg.com/myLib"></script>
  <script type="module" src="index.js"></script>
...

This leads to run time error of Uncaught TypeError: Failed to resolve module specifier "myLib". Relative references must start with either "/", "./", or "../".
This is because despite the library has been loaded onto the page, it is not referenced by the name myLib.
What's the proper way to set up Webpack so that when I import 'myLib' in index.js, it knows I mean import from 'http://unpkg.com/myLib'?

A: One workaround is to import the whole module and the make it a global variable, like so in index.html
...
  <script type="module">
    import * as myLib from 'https://unpkg.com/myLib'
    window.myLib = myLib
  </script>
  <script type="module" src="index.js"></script>
...

Another solution seems to be to generate modules as outputs
externals: { myLib: 'https://unpkg.com/myLib' }
experiments: { outputModule: true },

This gives you .mjs files. You'll see the first line in the output file with something like
import * as __WEBPACK_EXTERNAL_MODULE_https_unpkg_com_myLib_9592ca0f__ from "https://unpkg.com/myL";

This allows you to continue to use import { myVal } from 'myLib' in your code, while the compiled file substitutes myLib for the URL.
Note: This externals setting will generate an error if you do not output as modules. The generated file will have the line module.exports = https://unpkg.com/myLib, which is invalid JS syntax. If you put `` around the URL, syntax becomes valid, but what should be your module is just a string, i.e. module.export has a string value.
Note: This approach doesn't work well with HttpWebpackPlugin yet, as the injected script tags does not add type="module" for your module output files. You'll need to do this manually by specifying scriptLoading: 'module' (v5.5.0)
Results from webpack 5.72.1


text:
Q: readimagefile() not working as expected (C++) I'm trying to create sprites from a picture and when I use readimagefile() it just displays a black window. I tried the same code on an other file with different x and y and it was working fine. I checked, and the files are in the correct directories and the x and y sized match. Here are the codes
int gd = DETECT;
int gm;

initwindow(1000, 600, "Window", 20, 20, 0, 1);
readimagefile("load.jpg", 0, 0, 8, 8);
getch();

^This one is working
int gd = DETECT;
int gm;

initwindow(1000, 600, "Window", 20, 20, 0, 1);
readimagefile("sprites.jpg", 0, 0, 200, 100);
getch();

^This one isn't
(graphics, conio, stdlib, stdio are included)
What could be the problem here?

A: Update: seems like it just didn't like the .jpg format, even though i have imagemagick. Just use bmp.

A: I Found the problem, it's the bit depth color
it seems readimagefile() function can only read images with 24-bit depth
so you have to convert your image to that specific bit depth.


text:
Q: DHCP server & MAC address I have database, where are MAC addresses stored and base on that database I assigned the static IP address to them. Is there a way to automatically assign the IP address to users, who don't have MAC in my database ?
Kind Regards

A: Consider using isc-dhcp-server to do all of your IP address allocations. It can assign a specific IP address based on MAC, while at the same time assigning IP addresses from a separate reserved pool when the MAC address is not one that it knows about.


text:
Q: How should I use the word next in this sentence? English ain't my first language, so I'm getting confused on how I should use the word "next" in this sentence.
Which one is correct?
"Should I resign next from the Student Organisation?"
or
"Should I resign from the Student Organisation next?"
Thank you for your answers

A: I would say to use the second phrase:
"Should I resign from the Student Organization next?"
This phrase gives a more logical impression that you are using a series of steps to achieve something and this is the next step.

A: The word ain't is no longer in common use by people with basic education. It might be in use regionally, but the people using it know it is not 'proper' English. It's an affect or slang and used with humour or in relaxed circumstances. I might use it in the same company where I would feel comfortable using a swear word.  If you were joking, please excuse me. I completely understood what you meant.
"Should I resign from the Student Organisation next?" is fine, but I think I would say, "Next, should I resign from the Student Organisation?" It make the question more clear or concise -- we know exactly what you mean to say.


text:
Q: Is it possible to make a new method on a standard nodeJS object such as "fs" using C++/napi etc? I'm interested in making my first native C/C++ addon for nodeJS.
Conceptually it's a filesystem method that acts on a path or a file descriptor and is closely related to fs.stat() and friends.
From reading the documentation and looking at N-API examples I can't see whether it's possible or definitely impossible to create a new method.
Does anybody know if this can be done or if I have to just make it standalone?

A: I think the only way to do this is to "wrap" the object you want to extend.
Basically make a new module "fs2" that passes through all the standard calls to "fs" that is required by your new module, but also add your new calls, or replace the calls you wish to augment, with your N-API calls.
Code using your module would then only need to use
let fs = require("fs2");

instead of
let fs = require("fs");

I'm not sure if there are several ways to wrap a nodeJS module to achieve this, or if there is one clearly best way. I'm sure there are other SO questions covering all that.


text:
Q: How to call HTML formated text submitted in database as formatted on screen I am using Tinymce text editor to insert formatted data into database. However, when I call the data back to display on screen, it comes with html tags.

testing if its working fine

However it should have been displayed as "testing if its working fine". Any php string function to display it as it was submitted in database. (Strip_tags shows the plain text, and not a formatted text as it was submitted. Also,you may suggest any better text editor.
Following is the php call to extract data from database to display the result on screen
<textarea rows="7" class="form-control">'.$msg_rows['msg_message'].'</textarea>


text:
Q: Moving Asp.Net WebAPI into a Separate Site from Asp.Net MVC site for AngularJS App We have a Asp.Net MVC 5.0 project which uses AngularJS for front end. The project has WebAPI Controller in the same project and it is deployed to same website. The application is built with Individual User Account project template and uses Asp.Net Identity and Claims. There is file upload module where users upload some 100MB+ files that goes through webapi and ng-file-upload plugin. Due to increase in user base we wanted to quickly improve the upload speed by separating API alone into a separate site in a new server and scale it when needed. Since API controller is currently under ASP.Net MVC solution which uses OWIN cookie authentication the API is authorized by the cookie authentication middleware.
What is the quick way to get the API into a separate site? I beleive we need to implement OAUTH token based on the MVC site and make the new API site to consume the token by enabling CORS. If we do this we are not sure if we need to remove cookie based authentication and re-implement authentication using the new token based authentication. Are there any other approach we can take here by still using cookie based authentication for the Asp.Net MVC site and separating api into a new site?
Note- We also plan to build Mobile app using this API so we believe we have to separate the webapi into a separate site and bring OAuth token based authorization.
Thanks in advance!
Regards,
Bala

A: If your mvc site is going to be only client side code only without any major back-end c#. This requires no security as your data comes from API which is what needs to be secured. If you dont want to seperate the two in different domains. Angular will need to read the user information being sent from the server which is why HTTPs only encrypted cookie will not work. If they are going to be different server and domain, plus you need multiple consumers of the API, you should move to oAuth and bearer token based login with refreh tokens and the whole thing. This way you can scale the api into multiple load balancers and still use the bearer token and this would be stateless. That being said you can still achieve this with cookie by storing the token in cookie that way, angular can parse and use the values and the api can validate the signature of the token and use the values. With them having to be on the same domain so they can share the cookie. This can be done without using cookie and simply using LocalStorage as well.


text:
Q: How to replace dataframe values by other dataframe values, keeping values that are equal to both in R? I have two dataframes, toy1 and toy2. I would like to create a new dataframe, replacing the different values that are in toy2 in toy1 and keeping the same values (0) that are in toy1. Taking into account that there are different numbers of columns and rows.
So in this example below, i want a result that is a dataframe of 208 columns and 2 rows.
toy1:
structure(list(revenue = 0, risk = 0, target_amount = 0, company_years = 0,
approved_commitee = 0, score = 0, reason_Capital_giro = 0,
reason_Compra_equip = 0, reason_Compra_estoque = 0, reason_Cons_div = 0,
reason_Expansao = 0, reason_Outros = 0, reason_working_capital = 0,
serasa_0 = 0, serasa_1 = 0, serasa_1.5 = 0, serasa_1.8 = 0,
serasa_2 = 0, serasa_2.6 = 0, serasa_3 = 0, serasa_3.1 = 0,
serasa_3.2 = 0, serasa_3.3 = 0, serasa_3.4 = 0, serasa_3.6 = 0,
serasa_3.8 = 0, serasa_4 = 0, serasa_4.2 = 0, serasa_4.4 = 0,
serasa_4.6 = 0, serasa_5 = 0, pontualidade_0.75neg = 0, pontualidade_0 = 0,
pontualidade_0.25 = 0, pontualidade_0.75 = 0, pontualidade_2.25 = 0,
pontualidade_2.5 = 0, pontualidade_2.75 = 0, pontualidade_3 = 0,
pontualidade_3.25 = 0, pontualidade_3.5 = 0, pontualidade_3.75 = 0,
pontualidade_4 = 0, pontualidade_4.25 = 0, pontualidade_4.5 = 0,
pontualidade_4.75 = 0, pontualidade_5 = 0, qualidade_divida_0 = 0,
qualidade_divida_1 = 0, qualidade_divida_1.4 = 0, qualidade_divida_1.6 = 0,
qualidade_divida_2 = 0, qualidade_divida_2.2 = 0, qualidade_divida_2.8 = 0,
qualidade_divida_3.4 = 0, qualidade_divida_3.5 = 0, qualidade_divida_3.7 = 0,
qualidade_divida_3.8 = 0, qualidade_divida_4 = 0, qualidade_divida_4.2 = 0,
qualidade_divida_4.5 = 0, qualidade_divida_4.6 = 0, qualidade_divida_4.8 = 0,
qualidade_divida_5 = 0, bancabilidade_0 = 0, bancabilidade_0.1 = 0,
bancabilidade_0.2 = 0, bancabilidade_0.5 = 0, bancabilidade_0.6 = 0,
bancabilidade_0.7 = 0, bancabilidade_0.8 = 0, bancabilidade_1 = 0,
bancabilidade_1.2 = 0, bancabilidade_1.3 = 0, bancabilidade_1.4 = 0,
bancabilidade_1.5 = 0, bancabilidade_1.6 = 0, bancabilidade_1.7 = 0,
bancabilidade_1.8 = 0, bancabilidade_2 = 0, bancabilidade_2.1 = 0,
bancabilidade_2.2 = 0, bancabilidade_2.3 = 0, bancabilidade_2.4 = 0,
bancabilidade_2.5 = 0, bancabilidade_2.6 = 0, bancabilidade_2.7 = 0,
bancabilidade_2.8 = 0, bancabilidade_3 = 0, bancabilidade_3.1 = 0,
bancabilidade_3.2 = 0, bancabilidade_3.3 = 0, bancabilidade_3.4 = 0,
bancabilidade_3.5 = 0, bancabilidade_3.6 = 0, bancabilidade_3.8 = 0,
bancabilidade_3.9 = 0, bancabilidade_4 = 0, bancabilidade_4.1 = 0,
bancabilidade_4.2 = 0, bancabilidade_4.4 = 0, bancabilidade_4.5 = 0,
bancabilidade_4.6 = 0, bancabilidade_4.7 = 0, bancabilidade_4.8 = 0,
bancabilidade_5 = 0, alavancagem_0 = 0, alavancagem_0.2 = 0,
alavancagem_1 = 0, alavancagem_1.6 = 0, alavancagem_2 = 0,
alavancagem_2.4 = 0, alavancagem_2.5 = 0, alavancagem_3 = 0,
alavancagem_3.4 = 0, alavancagem_4 = 0, alavancagem_5 = 0,
porte_0 = 0, porte_1 = 0, porte_1.4 = 0, porte_2 = 0, porte_2.4 = 0,
porte_2.8 = 0, porte_3 = 0, porte_3.2 = 0, porte_3.6 = 0,
porte_4 = 0, porte_4.4 = 0, porte_4.6 = 0, porte_4.8 = 0,
porte_5 = 0, receita_recorrencias_0.6 = 0, receita_recorrencias_0.8 = 0,
receita_recorrencias_1 = 0, receita_recorrencias_1.4 = 0,
receita_recorrencias_2 = 0, receita_recorrencias_2.4 = 0,
receita_recorrencias_2.6 = 0, receita_recorrencias_3 = 0,
receita_recorrencias_3.2 = 0, receita_recorrencias_3.4 = 0,
receita_recorrencias_3.8 = 0, receita_recorrencias_4 = 0,
receita_recorrencias_4.4 = 0, receita_recorrencias_5 = 0,
respaldo_patrimonio_0 = 0, respaldo_patrimonio_0.4 = 0, respaldo_patrimonio_0.5 = 0,
respaldo_patrimonio_0.7 = 0, respaldo_patrimonio_0.75 = 0,
respaldo_patrimonio_0.8 = 0, respaldo_patrimonio_1 = 0, respaldo_patrimonio_1.2 = 0,
respaldo_patrimonio_1.3 = 0, respaldo_patrimonio_1.4 = 0,
respaldo_patrimonio_1.5 = 0, respaldo_patrimonio_1.7 = 0,
respaldo_patrimonio_1.9 = 0, respaldo_patrimonio_2.2 = 0,
respaldo_patrimonio_2.3 = 0, respaldo_patrimonio_2.6 = 0,
respaldo_patrimonio_3 = 0, respaldo_patrimonio_3.2 = 0, respaldo_patrimonio_3.5 = 0,
respaldo_patrimonio_3.6 = 0, respaldo_patrimonio_4 = 0, respaldo_patrimonio_4.4 = 0,
respaldo_patrimonio_5 = 0, reputacional_1 = 0, reputacional_2 = 0,
reputacional_2.5 = 0, reputacional_3 = 0, reputacional_3.5 = 0,
reputacional_3.65 = 0, reputacional_4 = 0, reputacional_5 = 0,
impacto_covid_1 = 0, impacto_covid_1.5 = 0, impacto_covid_2 = 0,
impacto_covid_2.5 = 0, impacto_covid_3 = 0, impacto_covid_3.5 = 0,
impacto_covid_3.65 = 0, impacto_covid_4 = 0, impacto_covid_5 = 0,
business_sector_Comercio = 0, business_sector_Industria = 0,
business_sector_Servicos = 0, state_AC = 0, state_AM = 0,
state_BA = 0, state_CE = 0, state_DF = 0, state_GO = 0, state_MG = 0,
state_MS = 0, state_MT = 0, state_PA = 0, state_PB = 0, state_PE = 0,
state_PR = 0, state_RJ = 0, state_RS = 0, state_SC = 0, state_SP = 0,
state_TO = 0, decision_motor_approved = 0, decision_motor_denied = 0), row.names = 1L, class = "data.frame")

toy2
 structure(list(revenue = c(4397487.34, 198019.75), risk = c(12137650.06,
469506.24), target_amount = c(150000, 1e+05), company_years = c(18,
9), approved_commitee = structure(c(2L, 2L), .Label = c("NO",
"YES"), class = "factor"), score = c(134, 128), reason_Compra_equip = c(1,
1), serasa_1.8 = c(1, 1), pontualidade_0.25 = c(1, 1), qualidade_divida_1 = c(1,
1), bancabilidade_0.2 = c(1, 1), alavancagem_1.6 = c(1L, 1L),
    porte_4.6 = c(1, 1), receita_recorrencias_3 = c(1, 1), respaldo_patrimonio_0.5 = c(1,
    1), reputacional_5 = c(1, 1), impacto_covid_3 = c(1, 1),
    business_sector_Comercio = c(1, 1), state_GO = c(1, 1)), row.names = c(10L,
12L), class = "data.frame")

A: Check this :
a <- which(names(toy1) %in% names(toy2))
toy1[2,] <- 0
toy1[a] <- toy2

toy1 has only 1 row while toy2 has two. So I added an extra 0 row in toy1.

A: Because there is a cbind.data.frame method, you could cbind the portion of toy1 that has non-matching column names to all of toy2. R does recycling of needed rows in this situation. Admittedly the column order might not be the same. It could be restored to the original ordering if needed.
toy1.2 <-cbind(toy1[ ! names(toy1) %in% names(toy2) ], toy2 )
toy1.2
#---------------------------

  reason_Capital_giro reason_Compra_estoque reason_Cons_div reason_Expansao reason_Outros reason_working_capital
1                   0                     0               0               0             0                      0
2                   0                     0               0               0             0                      0
  serasa_0 serasa_1 serasa_1.5 serasa_2 serasa_2.6 serasa_3 serasa_3.1 serasa_3.2 serasa_3.3 serasa_3.4 serasa_3.6
1        0        0          0        0          0        0          0          0          0          0          0
2        0        0          0        0          0        0          0          0          0          0          0
#snipped a bunch of rows, leaving the new data from toy2

    revenue       risk target_amount company_years approved_commitee score reason_Compra_equip serasa_1.8
1 4397487.3 12137650.1        150000            18               YES   134                   1          1
2  198019.8   469506.2        100000             9               YES   128                   1          1
  pontualidade_0.25 qualidade_divida_1 bancabilidade_0.2 alavancagem_1.6 porte_4.6 receita_recorrencias_3
1                 1                  1                 1               1         1                      1
2                 1                  1                 1               1         1                      1
  respaldo_patrimonio_0.5 reputacional_5 impacto_covid_3 business_sector_Comercio state_GO
1                       1              1               1                        1        1
2                       1              1               1                        1        1


text:
Q: LC_LOAD_DYLINKER and custom linker on IOS While looking through the list of LC_ commands supported by Mach-O files I noticed the LC_LOAD_DYLINKER command, which specifies which dynamic linker to use.
On IOS, this seems to always point to the same location, the standard DYLD on the device.
I was curious whether a custom linker is supported on IOS using this command, and if so are they any guidelines for creating one? Has anyone done this before?

A: There is no other public dynamic linker on iOS, and probably no other private dynamic linker either. Mac OS X only has dyld. Most people wouldn't benefit from making a new dynamic linker, especially considering that:

*

*loading applications is a critical task;

*loading applications is complex;

*the dynamic linker must be able to load libraries without the help of any shared library, including libSystem.so, which exposes the C standard library and the POSIX API;

*Apple's dyld works just fine.

Linux is in a similar situation, with ELF executables having an interp section that specifies the path to the expected dynamic linker (if any). While this would allow you to create your dynamic linker if you felt like it, in practice, most modern x86 systems only have two: one for 32-bit applications, and one for 64-bit applications (which are really just two builds of the same program). Since libc has to be loaded from a dynamic linker, libc projects tend to include one; but the task is fundamental enough that there aren't a lot of them around. I'm only aware of libc's ld and musl's ld-musl.


text:
Q: How to make Angular parent FormGroup invalid until all nested FormGroups are valid I have a FormGroup containing nested FormGroups. I want to put a validator on the BasicInfo child FormGroup (on FirstName control) using the code below. However, I want to disable the submit button if the entire parent form group is invalid. If any of the children are invalid, it should be invalid until all children are valid. But this is not happening on initial load. It only happens if I touch any of the child input elements.
stackblitz link
user-registration.component.ts (parent component). First name should be required
 .....
  this.userForm = this.fb.group({
  basicInfo: this.fb.group({
    firstName: [],
    lastName: [],
    email: [],
    age: []
  }),
  .....

basic-info.component.ts
  //setting required firstName
  ngAfterViewInit(){
    this.form.get('firstName').setValidators(Validators.required)
    this.form.updateValueAndValidity()
  }

basic-info.component.html

Parent form always returns true on initial load. The submit button should be disabled if the firstName is blank.

A: this.form.controls["firstName"].addValidators([Validators.required]);


text:
Q: How to use sqlite VACUUM in android I have an android app which involves login to the app and it performs many CRUD operations. When user logins first time, it logs him/her quickly if there is any data available for that user that will be downloaded.
But later on when re-login again, theprocess is very slow, sometimes it takes around 20 to 30mins. So, I read about using VACUUM to avoid free space created when the record is deleted.
I am bit confused when and how to use VACUUM, is it while opening the database that is when user login ? or some other time.
Any suggestions on this would be helpful.
Thanks

A: From: https://sqlite.org/lang_vacuum.html

Running VACUUM ensures that each table and index is largely stored
  contiguously  within the database file

About many CRUD operations: the db file usually becomes fragmented, especially
when these operations involve say deleting large amount of data.
With Java code it's fairly simple:
db.execSQL("VACUUM");

although the process can take a while and it is not possible to monitor its progress.
Of course you don't need to execute this statement every time you run the app, but periodically.
Or you may let the user execute this process, if he/she experiences delays on loading the data, or even logging in, after you make clear that such an operation, just like any reconstructing operation is not 100% safe, so propose first a backup.


text:
Q: allowable filenames for source files Which characters may appear in filenames that are included (\include)?
Are hyphens and underscores okay? Is there a dependence on the underlying filesystem or encoding of the LaTeX source that does the including? Are only ASCII characters allowed?

A: The filename syntax is one of the few explicitly system-dependent parts of TeX. web2c based TeX systems allow most characters allowed by the filesystem. (For example spaces are allowed if you surround the entire path with " quotes).
Note that LaTeX for example does not assume that the extension (to a base name) is formed by appending . with the extension. Some systems did not allow such names and the file usually known as article.cls might be article in a directory cls or [cls]article or any of various other syntactic possibilities. The file textsys.cfg is read at format-making time and by default automatically determines these:
 This file contains the site specific definitions of the four macros\\
 |\@currdir|, |\input@path|, |\filename@parse| and |\@TeXversion|.

But may be defined locally to be anything appropriate to the system.
Note that special characters may need special handling in order to be passed to the file name reader. For example the character ~ is allowed but LaTeX typically gives this a definition that expands to \nobreakspace{} which isn't the intended interpretation in a file name. \string~ works though. See this question for instructions on how to deal with spaces in filenames. Similar issues relate to non ascii characters. If using classic TeX (rather than xetex/luatex) 8bit characters will be given active definitions designed for typesetting rather than using as filename strings. Also the file system may be using utf8 or may be using a local code page and LaTeX probably doesn't really know which (the underlying file IO of the web2c system presumably knows but TeX macros can't access that) so again you may have to use the input "verbatim" using \string or some equivalent quoting method in order to pass bytes directly to the underlying filename reader. It all depends...


text:
Q: What is the difference between CROSS JOIN and CROSS JOIN TABLE In the following code :
SELECT ... FROM ... CROSS JOIN TABLE ... WHERE ...;

What does CROSS JOIN TABLE mean ?
I searched on the net, but all I can find is about CROSS JOIN only.
I suppose CROSS JOIN TABLE acts on a table, meaning a table like that :
CREATE OR REPLACE ... AS TABLE OF ...;

Here is the full query :
SELECT prog.id_oct_prog_tran_a_participati, prog.code_ressource, prog.instant_depart, prog.commentaire, prog.en_hors_economie_de_comb, discr.delai, discr.valeur_point, MOD(delai, 60) AS H24
          FROM req_prog prog
            CROSS JOIN TABLE(POINTS_DISCRETS(pIdChronique=>id_chr_substitution)) discr
          WHERE horizon <= 'J1'
            AND delai > 0
          ORDER BY id_oct_prog_tran_a_participati, instant_depart, horizon, delai

POINTS_DISCRETS is a function that returns an element of type TYPE_TAB_POINT. And TYPE_TAB_POINT is a type that the DBA created as following :
create or replace TYPE "TYPE_TAB_POINT" AS TABLE OF TYPE_POINT;

Where TYPE_POINT is a type created as following :
create or replace TYPE "TYPE_POINT" AS OBJECT
(
ID_CHRONIQUE NUMBER,
HORIZON      VARCHAR2(2),
NUM_POINT    NUMBER(4),
DELAI        NUMBER(5),
VALEUR_POINT FLOAT
);

So, as you see here, CROSS JOIN TABLE acts on a table but not a table as we usually mean in a database, more a table like an array.
Is it the case ? And, if yes, how can it be considered like a real table ?

A: You're parsing the statement incorrectly, which is confusing you I think. CROSS JOIN TABLE isn't one fragment; it's aCROSS JOIN (but could be any join type) between your real table req_prog and, separately, TABLE(...) to tell the query to treat the return value of the function call as a table.
TABLE(...) is the table collection expression:

The table_collection_expression lets you inform Oracle that the value of collection_expression should be treated as a table for purposes of query and DML operations. The collection_expression can be a subquery, a column, a function, or a collection constructor.

Here POINTS_DISCRETS is the collection constructor - returning TYPE_TAB_POINT, which is a collection, most of which you already figured out.
In this case your collection is a table of objects, and treating it as a table allows you both to join and to refer to the attributes of the object that forms each 'row' as if it were a column. The TABLE() is aliased as discr, so you are able to refer to discr.delai - where delai is one of the attributes of the TYPE_POINT type. If you were using an inner or outer join, rather than a cross join, you would use the same construction in the join condition, e.g. ON discr.x = prog.x. Once you apply the table collection expression you just treat it as a table in the rest of the statement.


text:
Q: React : I want to update state when user select 3rd option I am trying to update the state value , For example if user select 3rd option from select then I want to update a state value . I tried but state value is not changing could someone please help me how to solve this problem . Thanks
Code
class Calendar extends Component {
    constructor(){
        super();
        this.state={
            isCustomer:false
        }
    }
render(){
return(
  <select>
   <option value="1">1</option>
   <option value="2">1</option>
   <option value="3" onChange={this.setState({isCustomer:true})}>1</option>
  </select>
)}

export default Calendar

A: You can achieve it by using the onChange event within select (and not option). You can then check if the value selected is the third one.
Working example:

class Calendar extends React.Component {
    state = {
        isCustomer: false
    }

    onChange = ev => {
      this.setState(
        {isCustomer:ev.target.value === "3"},
        () => { console.log(this.state.isCustomer)
      })
    }

    render(){
      return(

          <select onChange={this.onChange}>
           <option value="1">1</option>
           <option value="2">54</option>
           <option value="3">Customer</option>
          </select>
          {this.state.isCustomer && <input defaultValue="Hi customer :)"></input>}

      )
   }
}

ReactDOM.render(<Calendar/>, document.getElementById('root'))

A: You are calling function directly on change it will lead to infinite state what you can do is :
class Calendar extends Component {
constructor(){
        super();
        this.state={
            isCustomer:false
        }
    }
   handleChange = (e) => {
     console.log(e.target.value)
      if(e.target.value==="3"){
       this.setState({isCustomer:true})
      }
   }

render(){
  console.log(this.state);
return(
  <select  onChange={this.handleChange}>
   <option value="1">1</option>
   <option value="2">1</option>
   <option value="3" >1</option>
  </select>
)
}
}

export default Calendar

Code demo : https://stackblitz.com/edit/react-dxheff

A: You need to use the onChange event on the select tag not the option tag.
Then apply some additional logic to your event-handler to check if the desired option was selected.
Here is the working sandbox: https://codesandbox.io/s/peaceful-sound-v0stt
import React, { Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class Calendar extends Component {
  constructor() {
    super();
    this.state = {
      isCustomer: false
    };
  }

  handleOnChange = e => {
    if (e.target.value == 3) {
      this.setState({ isCustomer: true });
    }
  };

  render() {
    console.log(this.state.isCustomer);
    return (

        <select onChange={this.handleOnChange}>
          <option value="1">1</option>
          <option value="2">1</option>
          <option value="3">1</option>
        </select>
        {this.state.isCustomer ? <input placeholder="name" /> : ""}

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Calendar />, rootElement);

For your specific issue with the alert(). Just trigger the alert in the call-back function like this:
  onChangeHandler = e => {
    if (e.target.value == 3) {
      this.setState(
        {
          isCustomer: true
        },
        () => alert("It is working")
      );
    }
  };

A: First you cant embed event on option , so you've to bind onChange event on the select ragn
Second thing you have to pass a function inside your event not direct instructions ..
I dont know exactly what you want to achieve but may be the above snippet will help , it sets the isCustomer state only at  option value 3

class Calendar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isCustomer: false
    }
  }

  selectChange = (evt) => {

      let val = evt.target.value;

      this.setState({
        isCustomer: val === "3"
      }, () => {
        document.getElementById("state").innerHTML ="state is :" + JSON.stringify(this.state);
      })
  }

  render() {
    return (
      <select onChange ={ (e) => this.selectChange(e) }  >
      <option value = "1" > 1 < /option>
      <option value = "2" > 2 < /option>
      <option value = "3"
       > 3 < /option>
      </select>
    )
  }
}

ReactDOM.render( < Calendar / > , document.getElementById("calendar"));


text:
Q: Overloading C++ Insertion Operator (<<) for a class I'm trying to write a class that overloads the insertion operator but in my header file I get the error.
Overloaded 'operator<<' must be a binary operator (has 3 parameters)

Here is my code:
.h file
ostream & operator<<(ostream & os, Domino dom);

.cpp file
ostream & operator<< (ostream & os, Domino dom) {
    return os << dom.toString();
}

I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?

A: You probably put your operator<< inside a class declaration.  That means it takes an extra hidden parameter (the this parameter).  You need to put it outside of any class declaration.

A: The insertion operator (<<) can be used as a member function or a friend function.
operator << used as a member function
ostream& operator<<(ostream& os);

This function should be invoked as :
dom << cout;

In general if you are using the operator as a member function, the left hand side of the operator should be an object. Then this object is implicitly passed as an argument to the member function. But the invocation confuses the user and it does not look nice.
operator << used as a friend function
friend ostream& operator<<(ostream& os, const Domino& obj);

This function should be invoked as :
cout << dom;

In this case the object dom is explicitly passed as a reference. This invocation is more traditional and user can easily understand the meaning of the code.

A: /*insertion and extraction overloading*/
#include<iostream>
using namespace std;
class complex
{
   int real,imag;

public:
    complex()
    {
      real=0;imag=0;
    }
    complex(int real,int imag)
    {
        this->real=real;
        this->imag=imag;
    }
    void setreal(int real)
    {
        this->real=real;
    }
    int getreal()
    {
       return real;
    }
    void setimag(int imag)
    {
        this->imag=imag;
    }
    int getimag()
    {
       return imag;
    }
    void display()
     {
      cout<<real<<"+"<<imag<<"i"<<endl;
     }

};//end of complex class

 istream & operator >>(istream & in,complex &c)
     {
         int temp;
         in>>temp;
         c.setreal(temp);
         in>>temp;
         c.setimag(temp);
         return in;
     }
 ostream &operator <<(ostream &out,complex &c)
 {
     out<<c.getreal()<<c.getimag()<<endl;
     return out;
 }

int main()
{
  complex c1;
  cin>>c1;
 // c1.display();

  cout<<c1;
  //c1.display();
  return 0;
}


text:
Q: remove duplicates from ng-repeat

        <input type="checkbox" name={{name}} id="{{$index}}" ng-model="user.checkpermission.checked[$index]" ng-change="ChangedPermission(user)">
        {{name}}

    Please select a checkbox

user.role is an array of objects. In each of those objects,  I have an array called permissions.I get repeating values for name after collectively iterating through permissions array of every object as one array may have just 'show' and other might have 'Show', 'Delete'.
How do I display only unique values for name and get rid of the duplicates here?


text:
Q: Viewcontroller's navigation bar is added below navigation controller's navigation bar inside tab bar controller I have a Tab Bar Controller that has a navigationcontroller with a view controller attached.
For some unknown reason the navigation bar of the view controller does not look like it always does. Instead the view controller's navigation bar is added below the navigation controller's.
When I look at the view controllers embedded in the first navigation controller before the Tab Bar Controller is shown, it works as expected.
This it what it should look like

And this

Now when I segue to the Tab Bar Controller which has a new navigation controller with a view controller embedded it looks like this:

I don't want an additional navigation bar below the one provided by the navigation controller.
I want the title and the item of the view controller merged with the navigation controller.
So the final result should display a row with the back button, the title and the bar button item(Search Image)
What am I missing?
I've also tried adding the navigation items programmatically but nothing seemed to work.
Project on github
My Code
    //
//  SideViewController.swift
//  Sample
//
//  Created by  on 08.02.20.
//  Copyright © 2020 . All rights reserved.
//

import UIKit

class SideViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Search"

    }
    @objc func action(){

    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

A: There is two ways that I found you can resolve this either by presenting tab bar controller modally or hiding navigation bar of a tab bar controller when view loads.
First solution can be achieved like this:

*

*Open Main.storyboard.

*Select last segue in this storyboard(one that navigates to Side storyboard).

*Make sure that you have Attribute Inspector selected. Now change Kind attribute to Present Modally and Presentation attribute to Full Screen.

And second solution can be achieved like this:

*

*Create new file by selecting File > New > File > Cocoa Touch Class and press Next.

*Change Subclass of: to UITabBarController and name your class to whatever make sense to you.

*Then inside of viewDidLoad() paste this navigationController?.navigationBar.isHidden = true in order to hide current navigation bar.

*Assign your class to TabViewController in the Side storyboard by selecting TabViewController and changing Class attribute to your class name in Identity Inspector. It should autocomplete when you entering your class name. Press Enter to make sure that you confirm the changes.

Remember to make just one of this two solutions. Which one would it be is up to your needs.


text:
Q: Design pattern to consume API that supports pagination I want to get some results back from a REST API that supports pagination. The way the API works is you make the initial request and get back the following.

*

*List of objects

*Total Count

*Number Remaining

*Result Identifier

To get the remaining object I need to make another request passing in the results identifier and rinse and repeat.
What I am having trouble with is writing a method that does this "elegantly". I would like to have a single method where I pass in the initial query and it makes as many API calls as necessary to get back all objects and just adds them together as a single list which is returned from the method.
Are there any good design patterns to follow in this type of scenario? Do I need to use recursion for the method to call itself or is there a simpler approach? I see lots of posts on how to design an API to properly paginate but have not found anything that describes how to properly consume an API that supports pagination.


text:
Q: What regex to use to take only first occurrence of number in string? I have table with comments like this
'Payment amount: 11000,50 from 144232'

'Payment amount: 13 450,20 from 144232'

Sometimes white spaces occurs in number, because people typing this manually. I need to get first numbers like 11000,50 and 13 450,20 from example.
I'm trying to use
regexp_replace('Payment amount: 11000,20 from 144232','([a-zA-Z:\s])','','g') and get result '11000,20144232', but I need only '11000,00'
How can I improve regex or what function I need to use to get this numbers?

A: To get the first number in the string with a comma and 2 digits after it, and spaces can occur between the digits due to typing:
^[a-zA-Z:\s]*(\d[\s\d]*,\s*\d\s*\d)

Explanation

*

*^ Start of string

*[a-zA-Z:\s]* Match 0+ times any of the listed chars in the character class

*( Capture group 1 (this will contain the value)

*

*\d Match a digit

*\d[\s\d]* Match 0+ times a whitespace char or digit

*,\s*\d\s*\d Match a comma and 2 digits with optional whitespace chars (Add \M if there can be no more word character following)

*) Close group 1

Regex demo | Postgresql demo

A broader match could be to match 0+ times any char except a digit \D* instead of using [a-zA-Z:\s]*
Regex demo

A: This works for your examples, with or without decimals:
^[a-zA-Z:\s]+([\d\s]*(,\d{1,2})?)

https://regex101.com/r/1JEe3F/1

A: I would do it like this:
SELECT (regexp_match(
           'Payment amount: 11000,00 from 144232',
           '[[:digit:]][[:digit:] ]*(?:,[[:digit:]]+)')
       )[1];

 regexp_match
--------------
 11000,00
(1 row)

A: Somewhat simpler but less strict, ([+\-]?\d[\d ,\.]+).*
SELECT (regexp_matches('Payment amount: 11,000.00 from 144232', '([+\-]?\d[\d ,\.]+).*'))[1];

Result: 11,000.00


text:
Q: How to get transparent navigation bar in root viewcontroller using UIappearance In my app's delegate, I specify a transparent tool bar with (as suggested in an answer to question 18969248):-
The code is:
UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
navigationBarAppearance.backgroundColor = [UIColor clearColor];
[navigationBarAppearance setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
navigationBarAppearance.shadowImage = [[UIImage alloc] init];
navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];

This works for all view controllers pushed on to the navigation controller's stack, but not for the root view controller (which is loaded from a NIB).
How can I get transparency in the root view controller's navigation bar?

A: Maybe you should load your RootViewController programmatically through your AppDelegate this way, if you're using storyboard :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"yourStoryboard"
                                                             bundle: nil];
    YourCustomRootViewController *customRootVC = (YourCustomRootViewController*) [mainStoryboard instantiateViewControllerWithIdentifier:@"firstAddProductViewController"];

    // If you're not using storyboard, simply instantiate it this way
    YourCustomRootViewController *customRootVC = [[YourCustomRootViewController alloc] initWithNibName:@"yourNib" bundle:nil];

    /* In here, you want to add the code relative to the navigation bar of your rootVC */
    [self.window setRootViewController:customRootVC];

}


text:
Q: XSLT2.0: solution to take all nodes in one tag if parent is same Hi I want to write xslt 2.0 solution for following example.
I want to take all the child elements inside one character untill the node is other character itself
Input xml
<para>
<character>
 <formatting>format</formatting>
</character>
<character>
 <formatting>format1</formatting
<formatting>format2</formatting
</character>
this is a text node
<character>
 <formatting>format3</formatting>
</character>
<character>
 <formatting>format7</formatting>
<formatting>format8</formatting>
</character>
</para>

Expected output
<para>
<character>

    <formatting>format</formatting>
    <formatting>format1</formatting>
    <formatting>format2</formatting>

</character>
this is a text node
<character>
<formatting>format3</formatting>
 <formatting>format7</formatting
<formatting>format8</formatting
</character>
</para>

A: You should be able to use xsl:for-each-group and group adjacent based on the name.
Example...
XML Input
<para>
    <character>
        <formatting>format</formatting>
    </character>
    <character>
        <formatting>format1</formatting>
        <formatting>format2</formatting>
    </character>
    this is a text node
    <character>
        <formatting>format3</formatting>
    </character>
    <character>
        <formatting>format7</formatting>
        <formatting>format8</formatting>
    </character>
</para>

XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="para">
        <xsl:copy>
            <xsl:for-each-group select="node()" group-adjacent="name()">
                <xsl:choose>
                    <xsl:when test="current-group()[1][self::character]">
                        <character>
                            <xsl:apply-templates select="current-group()/node()"/>
                        </character>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="current-group()"/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

XML Output
<para>
   <character>
      <formatting>format</formatting>
      <formatting>format1</formatting>
      <formatting>format2</formatting>
   </character>
    this is a text node
    <character>
      <formatting>format3</formatting>
      <formatting>format7</formatting>
      <formatting>format8</formatting>
   </character>
</para>


text:
Q: UIButton with resizable Image Ok guys,
i know i am doing something wrong, but i cannot figure that out. here is the code that will
put the resizable image for the normal button state.
self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)];
    [self.loginButton setImage:image forState:UIControlStateNormal];
    [self addSubview:self.loginButton];

Here is the image

either the image asset is wrong or the code.
the image is of 21 px width.
the cap inset of 10 & 10 on left right leaves 1Px to resize.
does any one spot what i am doing wrong.
thanks all for stopping by
Arun

A: you should do it this way:
self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)];
[self.loginButton setBackgroundImage:image forState:UIControlStateNormal];
[self.view addSubview:self.loginButton];

This way you are setting the background image property of the button. The background image is already attached to the button view, so no need to addSubview.

A: try
self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]; //assuming the height is 44
    [self.loginButton setImage:image forState:UIControlStateNormal];
    [self addSubview:self.loginButton];


text:
Q: Very Simple AngularJS Dropdown displaying a list of values with multiselect checkboxes Very Simple AngularJS Dropdown displaying a list of values with multiselect checkboxes
I would like to make a dropdown with a list of values, where one can multiselect among these values with a checkbox on each value in the dropdown list. I want to be able to react to the event when one checks or unchecks the checkbox for one of the values I display in dropdown.
I would like the solution to be as simple as possible, so if it can be made without some custom directive, or third party library. I would prefer that.
So basically I just want to display a totally plain AngularJS drop down, with a check box for each value in the dropdown list.
Something like just adding a checkbox to it and make it able to perform multiselect. The dropdown should also be scrollable.
https://docs.angularjs.org/api/ng/directive/select
I have found some more complex solutions to give you an idea about what I want:
enter code herehttps://codepen.io/elmahdim/pen/hlmri
enter code herehttps://jsfiddle.net/michaeldeongreen/22et6sao/9/
But I find these solutions too complex and would like something really simple if possible.


text:
Q: Access 2007 form with SQL Server 2008 backend working with images I have a situation where I'm using MS Access 2007 for forms, queries and reports, and SQL Server 2008 as the back-end holding data.
The idea is that the database will be on a server and connected to clients (Access forms) via a LAN.
Now I need to store images to the database through the Access form and display them also on a form, other clients should be able to view these pictures on their forms.
I've tried making a varbinary(MAX) field in SQL Server with different form controls in access but it was too complicated for the user to choose the image file and it didn't display the picture on the form as well .

A: I would highly advise against storing images as columns in your database.  Store them on a network machine and then save the folder address.  Give each of your images that you save a unique name.  In your instance, have the names be descrptive of what the actual images are (since it sounds like the system is designed for internal users only).  Large public sites like Facebook or Twitter store image names as long random strings to prevent unauthorized users from snooping.  Ever time you save an image on your local drive, insert its name into your database.  You'll now have a link between your database (which stores the images' metadata) and the actual images themselves.
More info in this thread


text:
Q: BASH - Filename with space passed to sFTP not resolving peroperly I'm trying to pass a filename with spaces to a script that will download the passed filename from an sFTP server. I'm having an issue with the script recognizing that, after resolving, is one filename instead of two words.
export tloc=/path/to/target
export usr=username
export svr=host.name.com
export pwd=pass1234
export sloc=/path/to/source
export file="test file_12345.zip"

#-- Perform download of file specified using passed paramters.
sshpass -p $pwd sftp -o StrictHostKeyChecking=no $usr@$svr:$sloc/"$file" $tloc

I understand that when the script executes, it will resolve the words contained in the quotes as one word and then remove the quotes. What am I missing here?  In other languages, I've been able to nest quotes or use some other syntax to have the end result appear as below.
sshpass -p pass1234 sftp -o StrictHostKeyChecking=no usernamehost.name.com:/path/to/source/"test file_12345.zip" /path/to/target

Any help would be most appreciated.

A: That's due to a misfeature (bug?) of sftp.  The filename you pass on the command line is effectively provided to the sftp's interactive "get" command as-is, but the get command splits on whitespace and uses the part after the space as the destination, ignoring your $tloc command line argument.
You need an extra level of quoting to get it to do what you want:
sshpass -p $pwd sftp -o StrictHostKeyChecking=no $usr@$svr:$sloc/"\"$file\"" $tloc


text:
Q: Running parallel_tests for Ruby-Capybara not working Running a simple login automation test using Capybara. No database is used.
I am trying to use parallel_test gem to invoke multiple test sessions at the same time (chrome browser) using the following command
parallel_rspec -n 2
two browsers are invoked but only the first one is launched with the correct URL and the second one is simply blank. Also, the login and password values are concatenated twice (data collision) in the first browser input fields.
Framework - Non-rails. Ruby with capybara
config/database.yml

test: &TEST
  adapter: postgresql
  host: localhost
  database: test_db<%= ENV['TEST_ENV_NUMBER'] %>
  encoding: utf8
  username: postgres
  password: postgres

spec_file - 1
describe '' do
 it '' do
  ENV['TEST_ENV_NUMBER'] = ''
 end
end

spec_file - 2
describe '' do
 it '' do
  ENV['TEST_ENV_NUMBER'] = '2'
 end
end

both spec files are in the same folder
There is very little guidance for nonrails setup. Any help would be much appreciated.


text:
Q: How to join with exactly one match on a separate table in mysql? I'm having a problem with mysql that you might be able to help. I have 2 tables with the following structure, and a couple of sample rows
TABLE 1
-------
LISTID     NAME        10_OTHER_COLUMNS
---------------------------------------
1          List1
2          List2
3          List3

TABLE 2
-------
LISTID      LISTTYPE(ENUM, 4 options)
------------------------------------------------
1           type1
1           type2
2           type3
3           type1
3           type2
3           type3

The relation is one to many from TABLE 1 to TABLE 2. I want to do a select on TABLE 1 where the rows are return ONLY, and ONLY IF they have exactly one match on TABLE 2. Explaining better, a list may have more than one type, if I simply do a:
SELECT t1.*
FROM table_1 t1
LEFT JOIN table_2 t2 USING (listid)
WHERE t2.listtype = 'type3'

It returns List2 and List3. I want to remove List3 from the results and only have List2. Any ideas?

A: Ok, I THINK I got it...  You are asking for ex: "type3", an English description to clarify would be...
Give me a list of all Tables (ie: ListID) that AT MOST have ONLY the one code I'm looking for and nothing else, not associated with any other "types".
select
      t1.*
   from
      ( select
              t2.ListID,
              count(*) as TotalTypesForTable,
              sum( if( t2.type = 'type3', 1, 0 )) as TypeWanted
           from
              Table2 t2
           group by
              t2.ListID ) PreQuery

      JOIN Table1 t1
         on PreQuery.ListID = t1.ListID
   where
          PreQuery.TypeWanted = 1
      AND PreQuery.TotalTypesForTable = 1

FEEDBACK OPTION...
Per your comment about a couple million records, I would adjust it this way which may also be faster overall too.
select
      t1.*
   from
      Table2 t2Required

         LEFT JOIN Table2 as t2Extra
            on t2Required.ListID = t2Extra.ListID
           AND NOT t2Extra.type = 'type3'

         JOIN Table1 t1
            on t2Required.ListID = t1.ListID
   where
          t2Required.type = 'type3'
      and t2Extra.ListID IS NULL

I'd like to also know the performance difference on the second one.  This second approach actually works based on an INTENTIONAL expected "don't find me", but doesn't require a sub-select.  By joining table2 to itself on same ID, but an "any other" type than the one we're looking for, the ONLY one we want is the entry where WE DONT find in the t2Extra instance.  THEN, get the table name from t1...


text:
Q: IIS SMTP Service Routing Outbound Mail Regarding the SMTP service that is including in Microsoft's Internet Information Services (IIS) 6.0.
I have it in my mind that the built-in SMTP service is not capable of routing outbound messages, except to spcific domains that have to be manually specified. However, I've just had a conversation with someone that has challenged my understanding. I've looked at various articles on the web and they are only confusing me more.
So, can anyone categorically state whether or not the IIS SMTP service can be used as a general purpose relay for outbound mail? For example, can I set up a web site that uses it to send outbound mail and the SMTP service will go out and look up the MX records for the recipient and route the email?

A: Yes, the SMTP service in IIS is capable of full end-to-end delivery. In order for it to function this way, the following requirements must be met:

*

*The server needs to be on a routable IP address (ie not an IP address in one of the reserved private ranges)

*The DNS settings on the server need to be configured properly so it can resolve MX records of the recipient domains properly

*You need to clear out the "smart host" setting. Find this by right-clicking on the SMTP server in the IIS Admin console, select Properties, select the "Delivery" tab, click the "Advanced" button, and you will see the space for entering a smart host.

A: Yes, the IIS SMTP can be used as normal SMTP server.
If you're experiencing problems, try to look for IP restrictions for Relaying on the SMTP server in the "Connections" window of the SMTP configuration. You could also check if a firewall is blocking TCP port 25 traffic from that server.


text:
Q: Input File esta enviando um blob object cortado para o banco de dados em JavaScript puro Eu não sou muito bom em frontend então eu estou usando apenas javascript puro para fazer com que minha aplicação envie dados para o banco de dados (mysql). Porem quando eu vou enviar um object do tipo blob ele vem com erro.
`
    const file = document.querySelector('input[type=file]').files[0];
    file.arrayBuffer().then((arrayBuffer) => {
    const blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);})

Eu estou fazendo a conversão do input em um blob, porem quando vou olhar no banco de dados
interior do blob no db
e no meu console, ele esta mostrando as informações corretas
imagem do console