text:
Q: What does :or mean in Clojure destructuring? The source for faraday's scan function (https://github.com/ptaoussanis/faraday/blob/master/src/taoensso/faraday.clj#L1197) has a destructuring form that I am struggling to understand...
(source far/scan)
(defn scan
  "..."
  [client-opts table
   & [{:keys [attr-conds last-prim-kvs span-reqs return limit total-segments
              filter-expr
              segment return-cc?] :as opts
       :or   {span-reqs {:max 5}}}]]
...)

What does that :or {span-reqs {:max 5}} do?

A: :or {span-reqs {:max 5}} specifies that iff opts does not have the key :span-reqs, span-reqs will be bound to the map {:max 5}.
Note that span-reqs does not directly refer to the key :span-reqs - this would also be possible:
(defn scan
  [client-opts table
   & [{:keys [attr-conds last-prim-kvs return limit total-segments
              filter-expr
              segment return-cc?] :as opts
       foo :span-reqs
       :or {foo {:max 5}}}]])

Observe that in the :or map you can generally provide default expressions for symbols you have bound in the destructoring form.
N. B.: Be careful with putting runtime expressions in :or. As of Clojure 1.9-alpha14 they will still be evaluated regardless of whether they are needed (see http://dev.clojure.org/jira/browse/CLJ-1676).

A: To put this in context I'll wrap it in an example function:
user> (defn foo [client-opts
                 table
                 & [{:keys [attr-conds
                            last-prim-kvs
                            span-reqs
                            return
                            limit
                            total-segments
                            filter-expr
                            segment return-cc?]
                     :as opts
                     :or {span-reqs {:max 5}}}]]
        (println "client-opts")
        (clojure.pprint/pprint client-opts)
        (println "table")
        (clojure.pprint/pprint table)
        (println "opts")
        (clojure.pprint/pprint opts)
        (println "the symbol attr-conds is bound to:" attr-conds)
        (println "the symbol limit is bound to:" limit)
        (println "the symbol span-reqs is bound to:" span-reqs))
#'user/foo
user> (foo :I'm-a-client-opt
           :I'm-a-table
           {:attr-conds 1
            :span-reqs [1 2 3]
            :limit 47}
           {:attr-conds :i-will-be-ignored}
           {:limit :i-will-also-be-ignored})
client-opts
:I'm-a-client-opt
table
:I'm-a-table
opts
{:attr-conds 1, :span-reqs [1 2 3], :limit 47}
the symbol attr-conds is bound to: 1
the symbol limit is bound to: 47
the symbol span-reqs is bound to: [1 2 3]
nil

Now we see that it binds some names to parts of the first map in a list, so lets take that destructing expresion apart:
& ;; this symbol collects all the rest of the arguments into a list
[ ;; this one then does list destructuring on the list indicated by the &
 {:keys [attr-conds     ;; This block destructures the first (and only the first) entry in the vector.
         last-prim-kvs  ;; Because this is a map it will do map destructuring and
         span-reqs      ;; bind (assigns) values to symbols in this list
         return
         limit
         total-segments
         filter-expr
         segment return-cc?]
  :as opts              ;; the entire map in the first position in the list created by the & will be bound to the name opts
  :or {span-reqs {:max 5}}}] ;; if span-reqs is not in the map at all,
                             ;; then the map {:max 5} will be bound to the name
                             ;; span-reqs instead

So the keyword :or in that nested destructuring expression assigns a default value to a symbol, if the third argument to the function is a map that does not provide a value for the keyword :span-reqs. It does nothing if the keyword :span-reqs is present and contains other keys without providing a value for :max. It does not merge the default values into the map in this context, it just provides a value if it's completely missing:
here is is with the value not specified at all:
user> (foo :I'm-a-client-opt
           :I'm-a-table
           {:attr-conds 1
            ;; :span-reqs [1 2 3] ;; removed this one
            :limit 47}
           {:attr-conds :i-will-be-ignored}
           {:limit :i-will-also-be-ignored})
client-opts
:I'm-a-client-opt
table
:I'm-a-table
opts
{:attr-conds 1, :limit 47}
the symbol attr-conds is bound to: 1
the symbol limit is bound to: 47
the symbol span-reqs is bound to: {:max 5}
nil

and again with a value specified, where that value does not include a :max
user> (foo :I'm-a-client-opt
           :I'm-a-table
           {:attr-conds 1
            :span-reqs {:min -7} ;; present but contains something else
            :limit 47}
           {:attr-conds :i-will-be-ignored}
           {:limit :i-will-also-be-ignored})
client-opts
:I'm-a-client-opt
table
:I'm-a-table
opts
{:attr-conds 1, :span-reqs {:min -7}, :limit 47}
the symbol attr-conds is bound to: 1
the symbol limit is bound to: 47
the symbol span-reqs is bound to: {:min -7}
nil

A: It is the default value.  For more details please see http://clojure.org/guides/destructuring
(def my-map {:a "A" :b "B" :c 3 :d 4})
(let [{a :a, x :x, :or {x "Not found!"}, :as all} my-map]
  (println "I got" a "from" all)
  (println "Where is x?" x))
;= I got A from {:a "A" :b "B" :c 3 :d 4}
;= Where is x? Not found!

using :keys we get
(let [{:keys [a x] :or {x "Not found!"}, :as all} my-map]
  (println "I got" a "from" all)
  (println "Where is x?" x))

with the same result


text:
Q: Get result in one line loop My output:
I have CMShehbaz
CMShehbaz

Expected:
I have CMShehbaz CMShehbaz

I am trying get result in one line. I tried with end="", concat +, but did not
work. I want result in one line.
lines = []
with open('user.txt') as f:
    lines = f.readlines()

count = 0
for line in lines:
    count += 1
    print("I have {}  {}".format(line,line) )
    print(f'line {count}: {line}')

A: I'm not quite sure why you have a counter in there if all you want is a single string, but this will do that job.
user.txt
CMShehbaz1
CMShehbaz2
CMShehbaz3

python file
with open('user.txt') as f:
    foo = "I have "
    bar = " ".join(line.strip() for line in f)
    print(foo+bar)

# Or you can do

    foo = " ".join(line.strip() for line in f)
    print(f"I have {foo}")

Gives you the output:
I have CMShehbaz1 CMShehbaz2 CMShehbaz3

If you want to know how many names are in foo then you can do
    print(len(foo.split(' ')))  # this will give you 3

A: I suspect that "user.txt" is a list of usernames each on a new line.
so in your code line will look something like "USER\n"
You can strip off the "\n" character of use some of the solutions posted previously: How to read a file without newlines?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP halts output of data on apostrophe I wrote a php script that pulls some data from a database and displays it in XML format. For some reason it halts output when it gets to an apostrophe in the data. This is a SELECT statement, and a simple one at that, so I don't understand why there are any issues with apostrophes or quotation marks. I've tried using addslashes() and mysql_real_escape_string(), even though my understanding is that those are for sanitizing data being inserted into the database, and it did not help. I'm stumped. Below is the code and thanks in advance for any advice!
<? if($result = $mysqli->query("SELECT * FROM ".$tbl)){
while($row = $result->fetch_object()){ ?>
<slide>
    <id><?= $row->id ?></id>
    <title><?= $row->title ?></title>
    <chatter><?= $row->description ?></chatter>
    <image><?= $row->path ?></image>
    <link><?= $row->href ?></link>
    <active><?= $row->active ?></active>
</slide>
<? }
}else{
    echo $mysqli->error;
}

EDIT:
It turns out I have misunderstood the problem. They are not apostrophes but instead are right single quotes. If I change them to actual apostrophes the script works but I still don't understand why it doesn't simply output them though.

A: Try with str_replace("'", "\'", $field_to_be_replaced);
You can replace the ' char with a blank space if you prefer, just for testing.

A: the apostrophe (') is an invalid character for XML!
You must call $safe_string = str_replace("'","'",$string) in all your fields before
outputting the .XML file.
Check here to learn about these characters and build a more complete str_replace
EDIT:
What im using:
// save ubercart products in XML
function replace_characters_for_xml($str) {
   return str_replace(
      array("&",">","<","'",'"'),
      array("&",">","<","'","""),$str
   );
}
...
$row->title = replace_character_for_xml($row->title);
$row->href = replace_character_for_xml($row->href);
...

A: Are you sure it halts on the output of the data, and not when the data is processed? Apostrophe's have special meaning in XML, so if they are included in your XML data you have to replace them with an entity reference. There are 5 predefined entity references in XML, for less than, greater than, ampersand, apostrophe, and one for quotation mark. Alternatively, you can mark the text as CDATA so that the XML parser doesn't try to parse it.
Try making your program output the XML data to a text file instead of to wherever it is going now. Does it still halt on the apostrophe? If not, then it's definitely because of a problem parsing the data. If your program still halts on the apostrophe even when outputting the data only to a text file, there may be a problem somewhere else in the program where that data is processed. Check all the references to the variable containing the data, and see if you can find the exact line the program breaks on.


text:
Q: What does "the orthogonal basis vectors spanning the subspace perpendicular to vector $\vec{e}_1$" mean? I am reading a paper titled "A Robust Real-Coded Genetic Algorithm using Unimodal Normal
Distribution Crossover Augmented by Uniform Crossover : Effects
of Self-Adaptation of Crossover Probabilities" by Ono, Kita, and Kobayashi.  You can download the paper from CiteSeerX.
In the discussion about the UNDX operator on page 2, Ono et. al use the phrase "vectors $\vec{e}_2$, ..., $\vec{e}_{n_{param}}$ are the orthogonal basis vectors spanning the subspace perpendicular to vector $\vec{e}_1$".
I do not have the mathematical background to interpret this phrase.  I need to understand it so I can code UNDX and similar genetic crossover operators.  What does it mean, and how do I do it?
My best interpretation after consulting Wikipedia pages for concepts like basis and spanning set is that I'm supposed to build a rotation and translation of an identity matrix so that one of my points is the origin and the vector to one of the other points is one of my axes.  I do not know whether this interpretation is correct.  Trying to follow this idea lead to a bunch of 3D specific answers for building rotation matrices from two vectors, but I need a general approach that can handle any number of dimensions.
Am I even on the right track?
EDIT
I have read the Wikipedia pages on the Gram-Schmidt process.  It seems easy enough to apply Gram-Schmidt to the UNDX process in the paper, but there is also a UNDX-m process proposed in this paper by Kita, Ono, and Kobayashi.  Another paper by Deb, Joshi, and Anand also describes UNDX-m and proposes a modification to it called PCX.  Both of these processes allow for an arbitrary number of points to be used in the recombination.  Both of them use the same sort of language to describe this a set of vectors $\left\{\vec{e}^{\left(i\right)} \forall 1 \le i \le n_{param} \right\}$, and I am confused as to how I can apply the Gram-Schmidt process to a set of arbitrary points.
I will use the example of PCX since access to that paper is free.  Suppose that my number of points $\mu=10$, and I choose the ten blue parent points marked as blue diamonds in the figure below.  The red square represents the mean vector $\vec{g}$ of the ten parents.  The green arrow represents the direction vector $\vec{d}^{\left(p\right)}$.  PCX requires knowing the $\vec{e}^{\left(i\right)}$ vectors that are the "orthonormal bases that span the subspace perpendicular to $\vec{d}^{\left(p\right)}$."

How do I determine the $\vec{e}^{\left(i\right)}$ vectors described above from the vector $\vec{d}^{\left(p\right)}$ and the remaining nine parent points?  Applying Gram-Schmidt using all possible $\vec{d}^{\left(i\right)} \equiv \vec{p}^{\left(i\right)} - \vec{g}$ as the set of vectors does not seem to work...
EDIT
I think I figured out the answer to my edit.  I'm not sure why it took so long to click >_<
I had been assuming that there had to be something special about the basis calculated so that points outside of those described could not be generated.  But that is not the case; the only necessity is that this basis be able to generate vectors in the same directions as the points used.  This means that if all the points chosen happen to lie on a hyperplane, there should only be enough orthogonal vectors needed to describe the plane.
If this is true, then it does not matter which $n_{param} - 1$ of the remaining $\mu - 1$ points are chosen for the Gram-Schmidt process.  So long as the vectors do not lie along a line, they will generate a new basis vector, and in conjunction they will describe a spanning set possible of describing any and all of the points generated.
I can see why people might have found my bewilderment confusing now : )

A: Take your vector and extend it to a basis.  Then, apply Gram-Schmidt to the remaining vectors and you will get an orthonormal basis to the vector's orthogonal complement.

A: This is some very basic linear algebra.  The vectors $\vec{v}_i$ are orthogonal: this means that $\vec{e}_j^T \vec{e}_k = 0$ for all $j \ne k$.  They are a basis of the subspace orthogonal to $\vec{v_1}$: this means that every vector orthogonal to $\vec{v}_1$ can be
written in exactly one way as a linear combination $\sum_{i=2}^{n_{param}} c_i \vec{v}_i$ for some scalars $c_i$.  Thus together with $\vec{v_1}$ they are a basis of the whole vector space: every vector in the vector space can be written in exactly one way as a linear
combination $\sum_{i=1}^{n_{param}} c_i \vec{v}_i$.
It's not clear that you are "supposed to" do anything, but if you want to find such a basis the Gram-Schmidt process is often a good way to do it.


text:
Q: The type parameter G is hiding the type G public class MyGenericClass< G> {

    public <G> G genericMethod1(G g){
        System.out.println(g.toString());
        return g;

    }

    public <X> G genericMethod2(G g) {
        System.out.println(g.toString());
        return g;
    }

    public <X> X genericMethod3(G g) {
        System.out.println(g.toString());
        Integer i = new Integer(100);
        return (X) i;
    }

    public static void main(String... cmdarg) {

        MyGenericClass<Employee> gemp = new MyGenericClass<Employee>();
        Employee e1 = new Employee();
        e1.setName("My Name");

        String resultOfMethod3 = gemp.genericMethod3(e1);
        System.out.println(resultOfMethod3);

    }

}

in genericMethod1: I get the compiler warning as "The type parameter G is hiding the type G".
Question:
Which G is hidden by this G? What's the actual meaning of this?
genericMethod2 doesn't show any errors/warnings.
Question:
I thought it should not compile. why is two different types allowed in same method signature? What can be typical real time example to compare with G and X?
In genericMethod3: I'm intentionally returning an Integer object and in the main method i'm trying to assign the result to a String. As expected: I got the ClassCastException.
Question: Isn't the original purpose of having generics to avoid ClassCastExceptions? Why did the compiler allow it? Is this a bug in the design of Generics?

A: Generics can be used at class level and at method level:

*

*public class MyClass<T>: T is available for all instance members (i.e. non-static) of the class (fields, methods, inner classes...)

*public (static) <U> ReturnType myMethod(..) {...}: U is available for the method only

You're mixing them.
With public <G> G genericMethod1(G g), this <G> generic is hiding the class' one since they have the same name, so the latter isn't available in the method anymore. If you want to use the class' generic, don't specify it at the method level: public G genericMethod1(G g).
With public <X> G genericMethod2(G g), you're defining a generic <X> that isn't used: only the class' generic G is used.
With public <X> X genericMethod3(G g), you're defining a generic <X> that is used for the return value of the method. In the method body, you're casting an int to X but you can't be sure that X is a super type of int. Technically, this can be done with <X super Integer>, but I'm not sure this is actually what you're looking for.

A: public class MyGenericClass< G> {

    public <G> G genericMethod1(G g){
        System.out.println(g.toString());
        return g;

    }

You have two different <G> variables here, one on class level and one on method level. This is roughly equivalent to having a field and a local variable of the same name. The local variable would "win" in that case, just as the method level <G> would override the class-level one. Since this is a common cause of errors, IDEs warn you of this.
Method 2 doesn't redefine <G>, so it generates no warning.

A: change your genericMethod1 as follow:
public G genericMethod1(G g){
    System.out.println(g.toString());
    return g;
}


text:
Q: Integrating audio files (specifically MP3) with c++ Win32 API? I've been using the irrKlang library to play all sorts of audio files, mostly MP3s, for my applications. However those are console applications since the irrKlang engine is built that way. Now I would like to build GUIs integrated with audio and music (specifically a music player), but I haven't been able to incorporate irrKlang with it.
So is there any other music library that will allow me to integrate music files (preferably MP3s, even though I know they're extremely complicated) with Win32 API? Also, is there any way I could be able to integrate the existing irrKlang library with a GUI written in Win32 API (with no MFC)?
(I am using c++, irrKlang 1.5.0, CodeBlocks 13.12, and Windows 8)
Any help or suggestions would be appreciated. Thanks in advance.


text:
Q: Too vs Either in agreement of negative sentences
SAM: I don't like choclates.
BOB: 1) I too, don't like choclates. (Or) 2)I don't like choclates, either.

What would be the correct sentence of Bob, Sentence1 or Sentence2?
If anyone sentence of bob is wrong why is it wrong?


text:
Q: Restrict maximum entries for primary key I want to have a table where you can have a maximum number of rows (e.g. 3) for the primary key. If there are already three rows for a primary key and another row is added, another one should be removed.
Example: I have a table that looks like this:
####################################
#   PrimaryKey  |   AnotherValue   #
####################################
|    abcdef     |       123        |
|    abcdef     |       456        |
|    abcdef     |       789        |
|    xyz123     |       sdf        |
|    xyz123     |       5s6        |
|    789klm     |       w8a        |
|    789klm     |       a4d        |
____________________________________

I tried to create a TRIGGER that only allows a maximum of three entries for each PrimaryKey using the following...
 CREATE TRIGGER maxThreeEntries AFTER INSERT ON table
   BEGIN
     DELETE FROM table WHERE (
        SELECT PrimaryKey, COUNT(PrimaryKey)
        FROM table
        GROUP BY PrimaryKey
        HAVING COUNT(PrimaryKey) > 3
     );
   END;

... which does not compile.
The inner SELECT - when using it alone - works fine for my need and returns the PrimaryKey along with the number of corresponding rows.

A: Try this:
CREATE TRIGGER maxThreeEntries AFTER INSERT ON table
       BEGIN
         DELETE FROM table WHERE PrimaryKey IN (
            SELECT PrimaryKey
            FROM table
            GROUP BY PrimaryKey
            HAVING COUNT(PrimaryKey) > 3
         );
       END;

you need to compare something in your delete WHERE clause.   You probably also want to add a WHERE clause within the SELECT statement to make sure you are only finding the primary key the trigger looks for.   I am not sure how to do it in mySQL, I mostly work with SQL-Server

A: I have found following solution. There are two triggers. Before insert trigger checks if there are three rows with given primaryKey. If so, then it changes 'primaryKey' of inserted row to some specific value. This row is deleted in after insert trigger.
CREATE or replace TRIGGER maxThree BEFORE INSERT ON my_table for each row
    BEGIN
        DECLARE pkc integer;
        SET @pkc := (select count(*) from my_table where primaryKey=new.primaryKey);

        if pkc>2 then
            new.primaryKey:='aaaaaaaaaa';
        end if;
    END;

CREATE or replace TRIGGER maxThreeAI AFTER INSERT ON my_table
    BEGIN
        delete from my_table where primaryKey='aaaaaaaaaa';
    END;

This solution has one limitation. We are choosing some specific value for primaryKey. I choosed 'aaaaaaaaaa'. But if you will want to insert row with such primaryKey then this row will not be inserted.
What will happen after inserting rows to this table:
insert into my_table(primaryKey, anotherValue) values('abc', '111');  -- row inserted
insert into my_table(primaryKey, anotherValue) values('abc', '222');  -- row inserted
insert into my_table(primaryKey, anotherValue) values('abc', '333');  -- row inserted

insert into my_table(primaryKey, anotherValue) values('abc', '444');
-- this fourth row will not be inserted.
-- First trigger will change 'primaryKey' value of this row to 'aaaaaaaaaa'
-- and row ('aaaaaaaaaa', '444')  will be inserted.
-- But then second insert will call
delete from my_table where primaryKey='aaaaaaaaaa';
-- and this command will delete this fourth row.

So after these four inserts only first three rows will be in the table.
I declared variable 'pkc'. Before inserting another row I count rows witch have primaryKey the same as 'primaryKey' of this new row. This count is saved to variable pkc (select into). And then I use this variable in if statement.


text:
Q: How to set up test_helper.rb when using Minitest, Capybara, Factorybot, and Database Cleaner I've seen a lot of examples of how to set up Capybara, Database Cleaner, and Factorybot with Rspec, but none with the Minitest setup that comes out of the box with Rails.
I'm struggling with Capybara::ElementNotFound errors when I run my test suite as a whole, but all of the tests that fail pass when run in isolation.
So, this leads me to believe that I need to use database_cleaner, but I can't figure out a setup that gets the test suite passing. What should my test_helper.rb look like if I'd like to use Minitest, Capybara, Factorybot, and Database Cleaner?
Here's my current test_helper.rb:
ENV['RAILS_ENV'] ||= 'test'
Minitest::Reporters.use!
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'minitest/reporters'
require 'capybara/rails'
require 'capybara/minitest'
require 'database_cleaner'

DatabaseCleaner.strategy = :truncation

class ActiveSupport::TestCase
  include FactoryBot::Syntax::Methods
end

class ActionDispatch::IntegrationTest
  include Capybara::DSL
  include Capybara::Minitest::Assertions # Make `assert_*` methods behave like Minitest assertions

  Capybara.server = :puma
  Capybara.server_port = 3001
  Capybara.app_host = 'http://localhost:3001'

  Capybara.register_driver :selenium do |app|
    Capybara::Selenium::Driver.new(app, browser: :chrome)
  end

  Capybara.javascript_driver = :chrome

  Capybara.configure do |config|
    config.default_max_wait_time = 10 # seconds
    config.default_driver        = :selenium
  end

  def teardown
    Capybara.reset_sessions!
    Capybara.use_default_driver
    DatabaseCleaner.clean
  end
end

Gemfile:
group :test do
  gem 'capybara'
  gem 'webdrivers'
  gem 'capybara-selenium'
  gem 'capybara-email'
  gem 'faker'
  gem 'database_cleaner'
  gem 'rails-controller-testing'
  gem 'minitest'
  gem 'minitest-reporters'
  gem 'guard'
  gem 'guard-minitest'
end

The I call DatabaseCleaner.start in the setup for any test using Factorybot like this:
require 'test_helper'

class AccountTenancyTest < ActionDispatch::IntegrationTest
  setup do
    DatabaseCleaner.start
    @acme_widgets_owner         = create(:acme_widgets_owner)
    @generic_gadgets_owner      = create(:generic_gadgets_owner)
  end

  test "Account owners can't access someone else's account" do
    # test goes here
  end
end

What am I doing wrong with this setup that is causing the Capybara::ElementNotFound: errors when I run rails test if the tests are passing in isolation?

A: Since you're running Rails >= 5.1 you don't need DatabaseCleaner (Rails 5.1+ shares the DB connection between the app and the tests and uses transactions to isolate each test from others).  Remove all references to database cleaner. Then change your integration tests to System Tests which is what you should be writing for Capybara tests in Rails 5.1+. That will then automatically set up all the before and teardown blocks necessary for basic Capybara tests.
I'm guessing your email tests are failing because the url being put in the emails isn't including the port number the test is being run on. Switching to system tests may fix that, if not you can specify Capybara.always_include_port = true to ensure the port gets added into the URL from the email.


text:
Q: Запуск двух и более php-скриптов асинхронно внутри php-скрипта Уважаемые коллеги, мне хотелось бы написать один единственный скрипт, который я вставил бы в кронтаб на хостинге. А внутри его было бы что-то типа
<?php
exec(file1.php);
exec(file2.php);
....
?>

И чтобы не было ожидания при переходе от одного вызова exec к другому. Спасибо!


text:
Q: With iTunes DJ gone from iTunes 11, what's a good replacement solution? With iTunes DJ gone from iTunes 11, how can I go to replace or even enhance the lost functionality?

A: I'm still adjusting it, but here is something that might actually be better than iTunes DJ on some aspects:

*

*create a playlist with some rules approaching the way you were using iTunes DJ. Something like Rating > 3, not played in a month, live update based on least played or random or whatever you were using with iTunes DJ.

*start playing

*switch to Mini Player

*turn on Up Next View and extend it vertically. You can alternatively show previously played using the clock icon.

What I like with this is the amount of interaction you have with the songs coming up. With a few clicks and remaining in that compact view, you can delete songs, add songs in the queue from genius recommendations. You can even bring up a full iTunes window on the side for drag and drop of additional songs or quick add (via alt-click) of songs to Up Next. Might take a little while to get used to it but it has potential.


text:
Q: the program works but its incorrect and not sure where going wrong I'm trying to answer the questions shown for my homework but not sure where going wrong: These days it's common to find a criminal by finding a match of their
DNA with a computer database. Oddly DNA is a code like computer
code but the code is written in 4 'base pairs' called  (G,T,A,C).
We can store DNA on a computer by decoding it and storing it
in an array ( G=0,T=1,A=2,C=3 ) so a DNA sample can be stored in an
integer array int DNA[] = { 1,3,2,1,1,2,0,2,3,3,3 } ; except much much
longer (millions of base pairs make up a single gene). Write a function called HW2F called which takes two DNA arrays. One is called sample the
other criminal. If the sequences match then return a boolean true
( found criminal match) or  false ( not this sample).So
      public boolean HW2F( int sample[] , int criminal[ ] )
       {

        for(int i=0; i < sample.length; i++)
        {
                if(sample[i] == criminal[i])
                {
                    return true;

                }
         }
                return false;
       }

no error message as program works but doesnt retrun correct values

A: Your code needs a small tweak, Here is the complete code
public boolean HW2F(int sample[], int criminal[]) {

        for (int i = 0; i < sample.length; i++) {
            if (sample[i] != criminal[i]) {
                return false;
            }
        }
        return true;
    }


text:
Q: Dymola working directory is an UNC-path (VM) Having issues with my Dymola setup. I'm trying a simulation in a VM right now because I have a Mac and I need to wait for my requested PC to be approved. Anyhow... I'm trying to verify the VC compiler VS/Visual Compiler 2019 and I think its finding the right cl.exe but it won't write the dymosim.c file in the current directory. It complains about the working directory being a UNC-path but to be honest I'm not that familiar with setups on Windows so I can't tell if its a Windows issue or a Parallels (VM) issue.
Dymola is in C:\Program Files\Dymola 2021 or at least that's what File Explorer and Command Prompt is seeing it as which doesn't seem like a UNC-path to me.

A: The issue isn't where Dymola is located, but your current/working directory. Type cd in Dymola to see what it is.
If the current directory is \\somecomputer\something\... it's an UNC-path.
Note that Dymola might try work around this when actually compiling (but not when verifying), but it's still best to correct it.


text: Q: Increasing the stack size in C++ when using Cygwin or MinGW in Windows I am executing a c++ program with large number of recursion function calls. When executing normally it gives stack overflow on runtime. So I am trying to find a way to increase the stack size. I found two methods: first is running but the second if doesn't become true. second method is using the following command while compiling : g++ -std=c++11 -Wl --stack <stack size> file.c -o file. This command gives error that  is not a valid file. So what is the way to increase the stack size. And why are the methods I used not working? And for those asking for code, the code is irrelevant. Its just recursive quicksort with large array of 100k ints.


text:
Q: automation filter query by IsDelete field in model builder ef core 3 I want not to return entity when the flag is IsDelete=true. I've written this code for all entities:
builder.HasQueryFilter(x => !x.IsDelete)

I want to write a code for all entities in a model builder, not code like one by one in IentityTypeConfiguration.
How can I do this ?

A: This implementation requires that you have your entities to implement ISoftDeleteAware interface, so if you have your own interface just rename accordingly:
public interface ISoftDeleteAware
{
    bool IsDeleted { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    //Mapping code etc …
    var versionedEntities = modelBuilder.Model.GetEntityTypes();

    foreach (var entityType in versionedEntities)
    {
        modelBuilder.Entity(entityType.ClrType, entityBuilder =>
        {
        //Global Filters
        var lambdaExp = ApplyEntityFilterTo(entityType.ClrType);
        if (lambdaExp != null)
            entityBuilder.HasQueryFilter(lambdaExp);
        });
    }
}

protected virtual LambdaExpression ApplyEntityFilterTo(Type entityClrType)
{
    if (typeof(ISoftDeleteAware).IsAssignableFrom(entityClrType))
    {
        var parameter = Expression.Parameter(entityClrType, "entity");
        var member = Expression.Property(parameter, nameof(ISoftDeleteAware.IsDeleted));
        var body = Expression.Equal(member, Expression.Constant(false));
        return Expression.Lambda(body, parameter);
    }
    return null;
}


text:
Q: Creating Date objects in Kotlin for API level less than or equal to 16 It may sound very funny and basic, but I am struggling with creating a DateTime kind of object in Kotlin by passing the number of seconds from epoch to it.
Either the examples that I am getting are of the libraries that require API level 26, or just talk about format conversion from string of DD-MM-YYYY to some other.
I have tried "LocalDateTime", "Timestamp", "Date" so far, but Kotlin either refuses to recognise them or the doesn't agree to the function parameters, or is unable to resolve namespace conflict. Or the examples are of Java, which don't work in Kotlin or don't have equivalent in Kotlin.
With Date() I am getting error "Cannot access '': It is private in Date()"
With LocalDate, LocalDateTime, I am getting the API level error
With Timestamp I am getting error "None of the following functions can be called with the arguments supplied". I am passing Long as the parameter as mentioned in documentation. But it is expecting "Parcel" or "Date".
Could someone please help?

A: Update: In recent versions of Android tooling, API desugaring brings to older versions of Android much of the java.time functionality that is built into Android 26 and later.

tl;dr

*

*Use java.time classes.Never use Date, Calendar, or SimpleDateFormat.

*Add the ThreeTenABP library to your project.

*See How to use ThreeTenABP in Android Project.

Avoid legacy date-time classes
The legacy classes such as Date & Calendar are terrible, created by people who did not understand date-time handling. These classes were supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
The Instant class replaces the Date class, both representing a moment in UTC (an offset of zero hours-minutes-seconds).
Instant instant = Instant.now() ;  // Capture the current moment in UTC.

The Calendar class, or more precisely, its most commonly-used concrete subclass GregorianCalendar is replaced by ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).

Convert
Best to avoid the legacy date-time classes entirely. But sometimes you may need to interoperate with old code not yet updated to java.time. In that case, convert. Look to new to…/from… conversion methods added to the old classes.
Calendar calendar = GregorianCalendar.from( zdt ) ;

…and…
ZonedDateTime zdt = ( ( GregorianCalendar ) calendar ).toZonedDateTime() ;

Back-port
The java.time classes are built into Java 8 and later, and Android 26 and later.
For Java 6 & 7, use the back-port found in the ThreeTen-Backport project. Most of the java.time functionality is found there. This project is led by the same man leading the java.time project and JSR 310, Stephen Colebourne.
For Android before 26, use the adaptation of that back-port to Android, the ThreeTenABP project.

A: I use Calendar for Kotlin
val date = Calendar.getInstance()
date.timeInMillis = 5000000
txtDate.text = date.time.toString()

A: Does this work for you?
Instant.fromEpochSeconds(<number>)


text:
Q: Getting only the raw link using bs4 and requests What I'm aiming to get is only the raw link which I can then use to download the image. but I keep getting some extra characters along with the link.
from bs4 import BeautifulSoup
import requests
from bs4 import BeautifulSoup
import requests

def getPages():
    x = 0
    url = 'https://readheroacademia.net/manga/boku-no-hero-academia-chapter-137/'
    req = requests.get(url)
    webpage = req.content
    soup = BeautifulSoup(webpage, 'html.parser')
    pages = soup.findAll('div', attrs={'class': 'acp_content'})
    for p in pages:
        y = p.findAll('img')
        print(y)
getPages()

What I end up getting looks like this:
[]
and I was hoping I could get something like this:
https://2.bp.blogspot.com/-p72DilhF-_s/WRSF41vu50I/AAAAAAAAlsk/6BTxzQAzPkwteMgEHch2JFH0JKKpbKrZACHM/s16000/0137-001.png

A: If you want to get only the src, you can do:
for p in pages:
    y = [tag["src"] for tag in p.findAll("img")]
    print(y)

It gets the url out of each img tag instead of getting the whole tag.
Also, if you're using bs4 or BeautifulSoup4, use find_all instead of findAll. findAll is bs3, the older version.

A: I think it will work:
>>> from bs4 import BeautifulSoup
>>> data = """"""
>>> soap = BeautifulSoup(data,"lxml")
>>> for i in soap.find_all("img"):
        link = i.get("src")
        print(link)

A: An alternative approach is to use XPath. I suggest using lxml here since there is no XPath support within Beautiful. This is actually a very simple solution:
from lxml import html
import requests

page = requests.get('https://readheroacademia.net/manga/boku-no-hero-academia-chapter-137/')
tree = html.fromstring(page.content)
#This will create a list of img src attributes beneth the `<div id="acp_content" class="acp_content">` tag:
srcs = tree.xpath('//div[@id="acp_content"]//img/@src')


text:
Q: How can I get only +7927xxxxxxx mobile numbers from contact list? I have an app that has to show my phone contact list. But how can I get only +7927xxxxxxx mobile numbers?
private void createListView(View fragmentView) {
    contactList = (ListView) fragmentView.findViewById(R.id.list_contacts);
    contactsAdapter = getContactAdapter(contactList);

    contactList.setAdapter(contactsAdapter);
    contactList.setOnItemClickListener(new OnContactClickListener());
}


text:
Q: Union e order by juntos Bom tenho no banco de dados MYSQL a tabela chatlogs com: de,para,msg,datetime.
Onde ficam as mensagem trocadas e informações ok, partindo deste ponto gostaria de saber como faria para fazer um histórico das mensagens, exemplo:

o usuário carlos entrou na conta dele no chat de maria entao recuperaria as conversas antigas novamente em ordem por datahr utilizando o datetime

Ex:
select msg from chatlogs where de = joana and para = carlos order by datetime ... conseguiria recuperar o historico msgs dela em ordem ... porem preciso que o histórico mostre tudo em ordem minhas msg tambem ...

Ex:

joana:oi
  carlos: oie td bem?
  joana: sim e vc?
  carlos: td ok

de ordem correta + não sei como faria, havia tentado assim:
select msg from chatlogs where de = joana and para = carlos
union
select msg from chatlogs where de = carlos and para = joana
order by datetime

Explicação do que tentei fazer:
tentei pegar todas msg enviada de carlos para joana e todas msg de joana para carlos e juntei com union tudo e depois mandei receber em ordem por datahr.
Alguma sugestão?

A: Você pode ter esse resultado simplesmente alterando seu select sem a necessidade de utilizar o union.
select msg from chatlogs where (de = joana and para = carlos) or (de = carlos and para = joana) order by datetime


text:
Q: Spark on Yarn IO issues When scheduling a spark job on yarn is there a possibility to control home any executors are placed on a physical node?
I currently set the spark.executor.cores to 4.
Now when YARN places multiple executors on the same data node it is 4* #numberOfExecutorsOnSameNodethreads trying to read and possibly also swapping as HDFS and the temporary directory of spark reside on the same disks.
So this results in huge issues regarding blocked IO time. Getting SSDs is not an option for now. Are there other things I can try?

A: One quick fix is to increase spark.executor.memory as this might over-allocate memory but prevent too many executors being launched on the same data nodes.


text:
Q: react-native redux repopulate the state That's the component in question. Before the component is mounted, it successfully dispatches an action {this.props.populateGrid()}. Everything is fine, I can see the state in the logger (basically it's a nested array of random numbers). When I press the button, it should rehydrate the state with new random numbers. Yet, I get the following error: Cannot read property 'populateGrid' of undefined.
import React, { Component, PropTypes } from 'react';
import { View, StyleSheet, Button } from 'react-native';
import Grid from './Grid';
import * as globalStyles from '../styles/global';

export default class Body extends Component {

  componentWillMount() {
    this.refresh();
  }

  refresh() {
    this.props.populateGrid();
  }
  render() {
    return (
      <View style={styles.body}>
        <Grid inGrid={this.props.grid} />
        <Button
          onPress={this.refresh}
          title={'Regenerate the Grid'}
        />
      </View>
    );
  }

}

Container:
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import { listNumbers, pickNumber } from '../actions/numberActions';
import { populateRow, populateGrid } from '../actions/gridActions';
import Body from '../components/Body';

const mapStateToProps = state => ({
  numbers: state.numbers,
  grid: state.grid
});

const mapDispatchToProps = dispatch => (
  bindActionCreators({
    listNumbers,
    pickNumber,
    populateRow,
    populateGrid
  }, dispatch)
);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Body);

Action:
import { POPULATE_ROW, POPULATE_GRID } from './actionTypes';
import { randNumbers, randGrid } from '../utils/generators';

export const populateRow = (n) => {
  return {
    type: POPULATE_ROW,
    payload: randNumbers(n)
  };
};

export const populateGrid = () => {
  return {
    type: POPULATE_GRID,
    payload: randGrid()
  };
};

reducer:
import { POPULATE_ROW, POPULATE_GRID } from '../actions/actionTypes';

export default (state = [], action = {}) => {
  switch (action.type) {
    case POPULATE_ROW:
      return action.payload || [];
    case POPULATE_GRID:
      return action.payload || [];
    default:
      return state;
  }
};

Generators of numbers (it's the second function in this case)
export const randNumbers = (n) => {
  let numbers = new Array(n);
  const shuffled = [];

  // fill one array with the numbers 1-10
  numbers = numbers.fill(1).map((_, i) => i + 1);

  // shuffle by taking a random element from one array
  // and pushing it to the other array
  while (numbers.length) {
    const idx = numbers.length * Math.random() | 0; // floor trick
    shuffled.push(numbers[idx]);
    numbers.splice(idx, 1);
  }
  return shuffled;
};

export const randGrid = () => {
  const shuffled = randNumbers(6);
  const array = shuffled.map(a => {
        let r = new Array(6);
        r = [a, ...randNumbers(5)];
        return r;
    });
  return array;
};

A: I think you need to bind this to your refresh method in your onClick handler, so that this is set properly when refresh executes:
<Button
  onPress={this.refresh.bind(this)}
  title={'Regenerate the Grid'}
/>

Hope that helps!


text:
Q: how to convert linkedhashmap to inverted commas except one array value this is my linkedhashmap
LinkedHashMap<String, Object> jsonOrderedMap = new LinkedHashMap<String, Object>();
jsonOrderedMap = {MessageName=HAPPY DIWALI, MessageID =M001, ListofVehicleID =["KA 01-A-1234","KA-01-A-567"]}

I want result to be in
{"MessageName":"HAPPY DIWALI","MessageID ":"M001","ListofVehicleID ":["KA 01-A-1234","KA-01-A-567"]}

am using
Gson gson = new Gson();
String json = gson.toJson(jsonOrderedMap, LinkedHashMap.class);

to convert but am getting result as
{"MessageName":"HAPPY DIWALI","MessageID ":"M001","ListofVehicleID ":"[\"KA 01-A-1234\",\"KA-01-A-567\"]"}

with array inverted commas and slashes inside the array


text:
Q: How can i display the new result in my listView rather showing it one below the other each time i search new data?     public void displayItems(View view) {
    String s2 = editText.getText().toString();
    ArrayList<HashMap<String, String>> allItems = dbcontroller.searchdata(s2);
    ArrayList<HashMap<String, String>> a = dbcontroller.getcbrands();
    String firstCompany="",secondCompany="";
    long count = 0;
    long ean_num = Long.parseLong(s2);
    if (allItems.size() == 0) {
        allItems = dbcontroller.getpdata(s2);

        for (HashMap<String, String> map : allItems) {
            //if (map.get("EAN").equals(s2)) {
            //pselected.add(map);
            //if (map.get("EAN")..equals(s2)) {

            long ean_num_pred = Long.parseLong(map.get("EAN"));

            Log.d("coredictor", "the value is " + ean_num);
            Log.d("coredictor", "the predicted value is " + ean_num_pred);
            count = count + 1;
            if (count == 1) {
                firstCompany = map.get("COMPANY");
                selected.add(map);
            }
            if (count == 2) {
                secondCompany = map.get("COMPANY");
            }
        }
        long belowRange = ean_num - 50;
        long aboveRange = ean_num + 50;

        Log.d("coredictor", "the Input is " + ean_num);
        // Log.d("coredictor", "the Ma{ean} is" + ean_num_pred);
        // Log.d("coredictor", "the Below Value is " + belowRange);
        // Log.d("coredictor", "the Abouve Value is " + aboveRange);

        if (firstCompany!=secondCompany) {
            //selected = pselected;
            // String =dbcontroller.insertReport(editText.getText().toString());
          boolean isInserted = dbcontroller.insertReport(editText.getText().toString(),"5");
            //dbcontroller.insertReport("5");
            if (isInserted = true)
                Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
            selected = pselected;
            textView.setText("ITEM UNKNOWN");
            selected.clear();

            textView.setTextColor(Color.RED);
        } else {
            boolean isInserted = dbcontroller.insertReport(editText.getText().toString(),"4");
            if (isInserted = true)
                Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
            selected = pselected;
            textView.setText("ITEM PREDICTED");
            editText.setText("");
            textView.setTextColor(Color.GREEN);
        }

    } else {
        for (HashMap<String, String> map : allItems) {
            if (map.get("EAN").equals(s2)) {
                boolean isInserted = dbcontroller.insertReport(editText.getText().toString(),"1");
                if (isInserted = true)
                    Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
                selected.add(map);
                textView.setText("ITEM FOUND!!!!!");
                textView.setTextColor(Color.BLUE);
                editText.setText("");

            }

    ListAdapter adapter = new SimpleAdapter(Search.this, selected,R.layout.displays_searchitems, new String[]{"EAN","COMPANY", "NAME","DESCRIPTION", "BRAND", "CBRAND"}, new int[]{
    R.id.ets_ean, R.id.ets_company, R.id.ets_name,   R.id.ets_desc, R.id.ets_brand, R.id.ets_cbrands});
    customList.setAdapter(adapter);

So this my adapter. Search is the name of my class. R.id.ets_ean, R.id.ets_company,.... are all the id of the editText that i'm displaying the data into from the database.
The problem is, each time i search for new result it's displaying one below the other than auto-refreshing.
notifyDataSetChanged() is not working.


text:
Q: Python MSAL Example App - Not configured as multi-tenant application I am new to oauth and trying to add microsoft oauth login to my Quart (async Flask) app which serves a ReactJS app, for now I am just experimenting with the example app, found here:
git clone https://github.com/Azure-Samples/ms-identity-python-webapp.git
I am configuring my app registration on azure to be single-tenant, for my organization only, which I believe is the problem. But I am not sure what to do in this example app to make it work for this setting.
Here is the error I am receiving after logging in with my microsoft account:
(Operations) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.


text:
Q: PayPal Checkout - Create a Logout link I'm working on integrating PayPal Checkout into a new shopping cart and everything is working fine on the payment end. Once the user has logged in I place a custom welcome message on the page:
Custom welcome message
I'd like to allow the customer to logout from PayPal directly from the cart (a la Amazon) without having to get back into the PayPal popup to use their (sometimes missing) 'Not you?' link.
The issue is what URL or method should the click trigger? I've been unable to find any reference to a logout method in the Checkout docs and examples.
Here's what I've tried so far:

*

*I have tried using the URL directly off of the 'Not you?' link inside the popup to no avail. Inspecting that element it looks to be using Angular to trigger the logout:
ng-click='actions.logout()'
I'm not at all familiar with Angular, so am unsure if this is something I can work with and hook into using jQuery or vanilla JS.

*Came across this question on SO -
https://stackoverflow.com/questions/38873040/logout-paypal-express-account-after-payment-is-completed - but the URL does not log the user out (maybe I'm missing some required params?)

*I cannot simply remove the PayPal cookie to wipe the session since the cookie belongs to the paypal domain and not my domain.
I'm using PayPal's checkout.js version 4.0.172
If anyone has experience with a similar task or can make any suggestions I'd greatly appreciate it.


text:
Q: How to type event.target properly? Whenever I use TypeScript, the thing which annoys me the most is, that event.target is always EventTarget | null. First of all, I would like to know under which circumstances target is null because I never came across this and also:
Is there a way to type event.target so that it is bound to the correct element type already?


text:
Q: How to show Array of Strings from Assets on Recyclerview list? im new to software coding and i'm trying to make an app on Android Studio that lists all of my files from the assets folder and show them in a Recyclerview. Right now it shows me the items that i put manually into "myListData" ("Email", "Info", "Delete", etc.. but i want it to show me automatically every item in the assets/gpcs/ folders (those items are listed in the "listofassets" string) and it only show them if i put the "[numerofasset]" of each one. Sorry if this is too obvious.
This is my MainActivity
package madrigal.gpcsinfecto;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AssetManager assetManager = getAssets();
    try {
       String[] listofassets = assetManager.list("gpcs");
        String[] filelist = assetManager.list("");
        if (filelist == null) {
            // dir does not exist or is not a directory
        } else {
            for (int i = 0; i < filelist.length; i++) {
                String filename = filelist[i];
            }

            MyListData[] myListData = new MyListData[]{
                new MyListData(listofassets[0], android.R.drawable.ic_dialog_email),
                new MyListData("Info", android.R.drawable.ic_dialog_info),
                new MyListData("Delete", android.R.drawable.ic_delete),
                new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),
                new MyListData("Alert", android.R.drawable.ic_dialog_alert),
                new MyListData("Map", android.R.drawable.ic_dialog_map),
                new MyListData("Email", android.R.drawable.ic_dialog_email),
                new MyListData("Info", android.R.drawable.ic_dialog_info),
                new MyListData("Delete", android.R.drawable.ic_delete),
                new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),
                new MyListData("Alert", android.R.drawable.ic_dialog_alert),
                new MyListData("Map", android.R.drawable.ic_dialog_map),

        };
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);;
        MyListAdapter adapter = new MyListAdapter(myListData);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

    }} catch (IOException e) {
        e.printStackTrace();
    }

};

}

This is MyListAdapter class
package madrigal.gpcsinfecto;

import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder>{
    private MyListData[] listdata;

// RecyclerView recyclerView;
public MyListAdapter(MyListData[] listdata) {
    this.listdata = listdata;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    View listItem= layoutInflater.inflate(R.layout.list_item, parent, false);
    ViewHolder viewHolder = new ViewHolder(listItem);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final MyListData myListData = listdata[position];
    holder.textView.setText(listdata[position].getDescription());
    holder.imageView.setImageResource(listdata[position].getImgId());
    holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();
        }
    });
}

@Override
public int getItemCount() {
    return listdata.length;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    public ImageView imageView;
    public TextView textView;
    public RelativeLayout relativeLayout;
    public ViewHolder(View itemView) {
        super(itemView);
        this.imageView = (ImageView) itemView.findViewById(R.id.imageView);
        this.textView = (TextView) itemView.findViewById(R.id.textView);
        relativeLayout = (RelativeLayout)itemView.findViewById(R.id.relativeLayout);
    }
    }
}

MyListData class
    package madrigal.gpcsinfecto;

public class MyListData{
    private String description;
    private int imgId;
    public MyListData(String description, int imgId) {
        this.description = description;
        this.imgId = imgId;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public int getImgId() {
        return imgId;
    }
    public void setImgId(int imgId) {
        this.imgId = imgId;
    }
}

Thank you in advance


text:
Q: Brockwell & Davis, Time Series Theory and Methods, problem 4.4 If $\{X_t\}$ is the process defined by $$X_t=\sum_{j=1}^n A(\lambda_j)e^{it\lambda_j}$$ in which $-\pi<\lambda_1<\lambda_2<...<\lambda_n=\pi$, and $A(\lambda_1), ..., A(\lambda_n)$ are uncorrelated complex-valued random coefficients (possibly zero) with zero mean. Then $\{X_t\}$ is real-valued if and only if $\lambda_j=-\lambda_{n-j}$ and $A(\lambda_j)=\overline{A(\lambda_{n-j})}$, $j=1,...,n-1$ and $A(\lambda_n)$ is real.
This is problem 4.4 from Brockwell & Davis. The "if" direction is easy, but the "only if" seems very difficult. I can only prove the almost trivial $n=1,2$ cases. Any suggestions?


text:
Q: How to remove padding from TextButton and place it under widget Flutter Need help. I want to put the text Want to get your money? and TextButton Redeem under button 611 (screenshot below) removing all padding. I have already tried many methods, but in the end it did not work out to place the widget under the button itself. Through the Flutter Inspector, you can see that there is still a distance at the top, but I don't understand how to put it there. I will be grateful for help.
body
Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24),
        child: Column(
          children: [
            const SizedBox(height: 24),
            const TotalCoinsWidget(
              coins: '611',
            ),
            const RedeemButton(
                textStyle: constants.Styles.smallBookTextStyleWhite,
                buttonStyle: constants.Styles.smallMediumTextStyleWhite),
            Padding(
              padding: EdgeInsets.only(bottom: 50),
              child: Text('Hello'),
            )
          ],
        ),
      );

textbutton
Widget build(BuildContext context) => Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Want to get your money?', style: textStyle),
          TextButton(
            style: TextButton.styleFrom(
              padding: EdgeInsets.zero,
              minimumSize: Size.zero,
            ),
            onPressed: () {},
            child: Text(
              'Redeem',
              style: buttonStyle,
            ),
          ),
        ],
      );

TotalCoinsWidget
Widget build(BuildContext context) => Container(
        alignment: Alignment.center,
        width: _width,
        height: _height,
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(25),
          boxShadow: [
            BoxShadow(
                color: color.withOpacity(0.5),
                blurRadius: _blurRadius,
                offset: Offset(_xOffset, _yOffset)),
          ],
        ),
        child: Text(
          coins,
          style: textStyle,
        ),
      );

A: you are using TextButton widget, and if you check out the property style: TextButton.styleFrom(), you will find a property called tapTargetSize, by default tapTargetSize property uses MaterialTapTargetSize.padded, and to fix your problem you must assign tapTargetSize property to MaterialTapTargetSize.shrinkWrap to shrinks the tap target size to the minimum size.

A: tapTargetSize: MaterialTapTargetSize.shrinkWrap

is not sufficient. Just add
padding: EdgeInsets.zero


text:
Q: Cocoa encryption plain text? I'm working on an encryption application that for now encrypts text-only files. I need some help in the connections and how to go about the actual encryption. I received this snippet of code to encrypt a file, but I am a bit confused. What I need to do is have a button (encrypt) that takes this text file and encrypts it. Am I supposed to extract the contents of the file first, then encrypt it? How so? The program must know what file has been selected so it encrypts it, and I'm a complete noob right now, and I need some help.
Step by step instructions would be greatly appreciated.
This was the code:
- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}

I've implemented a file chooser with the following snippet:
- (IBAction)fileChooser:(id)sender {
    int i;
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    [openDlg setCanChooseFiles:YES];
    [openDlg setCanChooseDirectories:YES];
    [openDlg setPrompt:@"Select"];
    if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton )
    {
        NSArray* files = [openDlg filenames];
        for( i = 0; i < [files count]; i++ )
        {
            [files objectAtIndex:i];

        }

    }
}

A:
This was the code:
- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}

First, look at the receiver of the AES256EncryptWithKey: message. This is another, nested message:
[plaintext dataUsingEncoding:NSUTF8StringEncoding]

What's plaintext? It's declared there in your encryptString:withKey: method: It is a variable holding a pointer to an NSString.
So you're sending the dataUsingEncoding: message to an NSString instance.
That's good if you intend to encrypt some plain-text user input, but it's not so good for encrypting files. NSStrings are for nothing but human characters; the user will probably want to encrypt files that are not plain text, such as images and video files.
I know you said that your application "for now encrypts text-only files", but the solution is actually simpler when you throw out this restriction.
So you need to encrypt any data, not just a string. Delete your encryptString:withKey: method—it is useless.
From the implementation of that late method, we know that you were sending AES256EncryptWithKey: to an object obtained by sending dataUsingEncoding: to an NSString instance.
If you look in the documentation for NSString, you can see what dataUsingEncoding: returns. Spoiler: It returns an NSData object.
From there, it's one hyperlink away to the NSData documentation, where you will find two things:

*

*It has no method by the selector AES256EncryptWithKey:.

*It does have methods to create a data object from the contents of a file. (I'll let you find them.)

I'm assuming that you knew #1, and downloaded a category implementation from somewhere. I'm also assuming that, in fact, this category is on NSData; the category's @interface, in its header, will tell you.
In Objective-C, you should not use an index loop to iterate through an array unless you actually need the index for something, which you generally don't and you, specifically, don't. Instead, use fast enumeration:
for (NSString *path in [openPanel filenames]) {
}

You can see how, again, this makes the solution simpler. It's also faster.
Inside that loop, pass that path to the NSData class method that creates an NSData object from the contents of a file. Then, send that data object the AES256EncryptWithKey: message to obtain the ciphertext, which you should probably write out to a separate file. I'll refer you back to the NSString documentation for the path-manipulation methods you'll need to compute the output file path, and the NSData documentation for the method you'll need to write the ciphertext data out to the output file.


text:
Q: Triangle to draw a triangle on a swing high Hi I'm trying to draw a triangle every time there is a swing high. I define a swing high as when there are three candles where the first candle's high is lower than the second candle's high and the third candle's high is lower than the second candle's high.
//@version=4
study(title = "Swing High", overlay = true)
if(high[1] > high and high[2] < high[1])

    plotshape(bar_index[1], shape.triangleup)

Right now i'm getting the error "line 5: Cannot use 'plotshape' in local scope."

A: Error message is clear. You cannot have that funciton in a local scope (if block etc.).
However, you can apply your condition directly in the plotshape() function like so:
//@version=4
study(title = "Swing High", overlay = true)

swing_high = (high[1] > high and high[2] < high[1])

plotshape(swing_high[1], style=shape.triangleup)


text:
Q: Why is reflection in a plane an automorphism? I have not studied group theory, but would like to know in simple terms why reflection in a plane is an automorphism.
Dr. Hermann Weyl gives the definition of automorphism in his book 'symmetry' as

A transformation which preserves the structure of space

What does he mean by the structure of space? Why can reflection preserve the structure?

A: The phrase "structure of a space" has different meaning in different contexts.
The quote from Weyl probably gives the structure implicitly, and I am guessing that he is talking about planes in Euclidean 3-space. In that case, an automorphism is a bijection of the points of Euclidean 3-space which preserves all the structures of Euclidean geometry: lines; planes; distance; angle. In analytic geometry we learn a powerful theorem which says that any bijection of the points of Euclidean 3-space that preserves distance also preserves all the other structure: lines; planes; angle.
So Weyl's quote simply means that reflection across a plane preserves distance: using Cartesian coordinates $\mathbb{R}^3$ for Euclidean 3-space, with the usual distance formula $d(x,y)$ for points $x,y \in \mathbb{R}^3$, if $P \subset \mathbb{R}^3$ is the plane and if $r : \mathbb{R}^3 \to \mathbb{R}^3$ is the reflection across $P$ then $d(r(x),r(y)) = d(x,y)$. This is pretty easy to prove using ordinary tools of analytic geometry: use a description of $P$ to write down a formula for $r$ and use that formula with coordinates for $x,y$ to prove $d(r(x),r(y))=d(x,y)$.

A: The word automorphism can be used in a lot of contexts, as for example the sense here of a mapping of space (?) onto itself in a way that "preserves the structure".
This is a reference to the Euclidean properties of space, i.e. its distances and angles.  Reflection in any plane preserves the measures of distance and angles, and so is an automorphism in that sense.

A: https://en.wikipedia.org/wiki/Weyl_group
I am pretty sure he is discussing, without using the terms, Lie Algebras and what came to be known as Weyl Chambers.
The setting for a root lattice is a (positive) quadratic form, let us call it $Q.$ The (squared) norm of a lattice vector $x$ is precisely $Q(x)$ which is an integer; for the cases of interest, this is usually going to be required to be a even integer, as the root lattices are "even."
The quadratic form gives rise to a symmetric inner product,
$$ \langle x,y \rangle = (1/2) \left( Q(x+y) - Q(x) - Q(y) \right).  $$
It is required that this be an integer when $x,y$ are in the lattice. This is the reason that norms must come out even, the whole business needs to be doubled to avoid half-integers.
Given an inner product, the reflection in a fixed vector $w$ is
$$  z' = z - \frac{2 \langle z,w \rangle}{\langle w,w \rangle} w $$
You have seen this before, probably with ordinary dot product. Note that $w' = -w,$ but when $z$ is perpendicular to $w,$ then $z'=z.$
Next, given a even lattice, a root is a lattice vector $r$ such that $Q(r) = 2,$ or  $\langle r,r \rangle = 2$. It is because of this condition that reflection in $r$ becomes
$$ \color{magenta}{ z' = z -  \langle z,r \rangle r}  $$
Given any $z$ in the lattice, $z'$ is also in the lattice. This preserves the lattice and is called an automorphism. With positive $Q,$ the automorphism group is finite and is generated by the reflections.
Well, there is more to be said. I am now working in quadratic forms. I feel that if I had had a short course in quadratic forms, lattices, before Lie Algebras, it would have helped.
Enough for now


text:
Q: Items in menu not showing action bar, rather being displayed without any icons in three dots Previously my app name was being displayed hence I had to use getSupportActionBar().setDisplayShowTitleEnabled(false) to remove the text, but now in its place a blank action is displayed with three dots on the side showing the list items that I have defined.
I want Refresh and Back actions to be displayed directly into the action bar with their respective icons
eventdetails.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/action_refresh"
        app:showAsAction="always"
        android:title="Refresh"
        android:icon="@drawable/ic_action_refresh"
        />
    <item
        android:id="@+id/action_settings"
        android:title="Settings"
        app:showAsAction="ifRoom"
        >
    </item>
    <item
        android:id="@+id/action_back"
        android:title="Back"
        android:icon="@drawable/ic_action_back"
        app:showAsAction="always"
        />

</menu>

EventDetails.java
public class EventDetails extends AppCompatActivity {
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_details);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarEventDetails);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayShowTitleEnabled(false);

}

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.eventdetails, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.action_back:
                Intent action_back = new Intent(EventDetails.this, EventView.class);
                startActivity(action_back);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

A: Your xmlns:app is not setup properly
change:
xmlns:app="schemas.android.com/apk/res-auto"

to
xmlns:app="http://schemas.android.com/apk/res-auto"


text:
Q: Spring's Pageable with custom Sort using SQL function So I got the following JPA repository:
@Repository
public interface FooRepository extends JpaRepository<Foo, Long>, JpaSpecificationExecutor<Foo> {}

And I am querying it with the Specification interface and PageRequest:
final Specification<Foo> spec = ...
final PageRequest pageRequest = PageRequest.of(page, size, Sort.by(direction, order));
return fooRepo.findAll(spec, pageRequest)

Ist there a way to apply a function to the sorting algorithm so for example the sql of Sort.by("NAME", ASC)
ORDER BY NAME ASC

will be replaced with:
ORDER BY TRIM(NAME) ASC


text:
Q: Java - creating Web Service Request using JDOM - Header issue I done many integrations using JDOM in Eclipse but for first time I have an issue because my SOAP XML message should contain and HEADER element wuth specific elements. This is my whole message:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:agi="http://agilent.parlayx.sms">
   <soapenv:Header>
         <cppass>test</cppass>
         <cpuname>test</cpuname>
   </soapenv:Header>
   <soapenv:Body>
      <agi:sendBulkSms>
            <address>tel:3876123456</address>
      </agi:sendBulkSms>
   </soapenv:Body>
</soapenv:Envelope>

I created BODY structure using this:
Element top = new Element("sendBulkSms", agi);
Document jDoc = new Document(top);

Element address = new Element("address", agi);
address.setText("tel:3876123456");
top.addContent(address);

This works OK I did it many times before. But is it possible to create and header element of message uisng JDOM or not? Because as far as I know only BODY element can be defined but then my message will not be valid for web service request
Thank you, I will appreciate help

A: You are just creating standard XML there is no "header" you just have an Element named "Header" with namespace="soapenv". So in my opinion it should be like creating any other JDOM Element.


text:
Q: Plotting CDF of a dataset in R? I am not really sure about the difference between CDF (Cumulative Distribution Function) and ECDF (Empirical Cumulative Distribution Function) but I usually utilize a CDF plot to make observations about my data.
I have been using R recently and am desperately trying to find out how to plot a CDF and CCDF (Complementary CDF) of my data. All I could find was that R has ecdf but am not really sure if this is what I am looking for. Plotting an ECDF is as simple as:
plot.ecdf(data)

Does anyone know how to plot a CDF and CCDF of a dataset using R?

A: A CDF commonly requires closed form when you know or assume a distribution.  An ECDF, on the other hand, is 'empiricial' as it comes from your data.  I just answered a question about using ecdf() and Hmisc's Ecdf()   here the other day.
More generally, you can search here using terms such as
 [r] ecdf

in the search box to look for 'ecdf' within the R tag.   At rseek.org, little comes up for 'ccdf'. Is that maybe just the same as one minus the ECDF? If so, Ecdf() in Hmisc can do it.
I hope this helps, if not please re-phrase your question as it is not quite clear exactly what you are looking for. Both ecdf() and Ecdf() are pretty featureful so make sure to read their help pages.


text:
Q: How to check whether data existed or not in waterline of sails I desire to create application with parameters name, email of Candidate, title of Job, and description, salary and position of JobDetail.
Here are my code
create: async function (req, res) {
try {
  let { name, email, title, description, salary, position } = req.allParams();
  if (!name) {
    return res.badRequest('name is required');
  }
  if (!email) {
    return res.badRequest('email is required');
  }
  if (!salary) {
    return res.badRequest('salary is required');
  }
  //check job exist
  const checkExistence = await Job.findOne({
    title: title
  });
  if (!checkExistence) {
    return res.badRequest('Job does not exist!!!');
  }
  return res.ok('Ok!!!');
} catch (error) {
  res.serverError(error);
}

}
I'm stuck with checking whether the Job model possessed the input job or not?
I just applied findOne() or find() to check the existence, but I feel quite the solution is not best practice.
I am fresh to Sails. Hope you guys to help me. Thanks in advance.

A: Validation of request parameters in the backend is not a good practice. You should do it in the frontend. Anyway you can use above code to check the existence of a job title. Instead you can use traditional node.js callbacks for checking existence of a job title as below.
Job.findOne({ title: title}).exec(function(err, result){
    if (err) {
        return res.send({ message: 'error'});
    }
    else if (!result) {
        return res.send({ message: 'job does not exists'});
    }
    return res.send({ message: 'success'});
});


text:
Q: How to use Jest to write a unit test for canActivate Angular guards I want to use Jest instead of jasmine to write a unit test for my angular app.
a jest unit test for guard servcie for the mehtod canActivate.
My question is, how to mock the router?
describe('TestServiceGuard', () => {
  let service: testServiceGuard;
  let router: Router;

  beforeEach(() => {
    return MockBuilder(TestServiceGuard, TestModule)
      .mock(TranslateService, {
        instant: (value) => value,
      })
      .mock(Router)
  });

  it('should be created', () => {
    mockCurrentData(data);
    const fixture = MockRender

  });

  //this mehtod mock a servcie, which will be called in method canActivate.
  function mockCurrentData(fleet: Fleet): jest.Mock {
    return MockInstance(<the other servcie>, 'testData', jest.fn(), 'get') //
      .mockReturnValue(of(data));
  }

 // I just wannt to mock Router, but I do not know how?
  function mockRouter(){
    const router = new Mockr
  }

  //then
  function rediretToExpectedSite(){
    expect();
  }

});

I have also see some example such as
it('should navigate to home for a logged out user', () => {
  authService = { isLoggedIn: () => false };
  router = new MockRouter();
  authGuard = new AuthGuard(authService, router);
  spyOn(router, 'navigate');

  expect(authGuard.canActivate()).toEqual(false);
  expect(router.navigate).toHaveBeenCalledWith(['/']);
});

but in my jest test there is no MockRouter.
any solutions?

A: Because you are using ng-mocks and you want to mock all dependencies, such as Router, you can use ng-mocks documentation how to test a provider. It simply explains how to mock all dependencies of your provider: the guard.
Based on the documentation, you test should look like:
describe('TestServiceGuard', () => {
  MockInstance.scope(); // <- add to reset customizations after tests.

  // Simply mock all dependencies apart from the guard.
  // It will automatically mock Router and other services.
  beforeEach(() => {
    return MockBuilder(TestServiceGuard, TestModule)
      .mock(TranslateService, {
        instant: (value) => value,
      });
  });

  it('should be created', () => {
    MockInstance(TheOtherService, 'testData', jest.fn(), 'get')
      .mockReturnValue(of(data));

    const fixture = MockRender(TestServiceGuard);
    const service = fixture.point.componentInstance;

    // assertions
  });
});


text:
Q: Nativescript TabView using to much space when adding title text Is it possible to remove some of the padding inside a tabview item?

The TabView has a lot of empty unused space. If I could remove this then my tabs wouldn't get cutoff. This would greatly improve my app since now you have to swipe a bit to the right to see the full title of the last menu item.
The tabview is created in NS-Vue but I don't think that will matter since this is a native issue.

A: I'm using negative margins to remove padding from TabView items. That was the only solution I found to do this. This approach is needed only for Android, for iOS it works fine.
import { Component, OnInit, HostListener } from '@angular/core';
import { Page } from 'tns-core-modules/ui/page/page';
import { RouterExtensions } from 'nativescript-angular/router';
import { ActivatedRoute } from '@angular/router';
import { TabView } from 'tns-core-modules/ui/tab-view';
import * as platform from 'tns-core-modules/platform';

@Component({
  selector: 'app-tabs',
  moduleId: module.id,
  templateUrl: './tabs.component.html'
})
export class TabsComponent implements OnInit {

  tabView: TabView;

  constructor(
    private page: Page,
    private router: RouterExtensions,
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {
    this.tabView = this.page.getViewById('tab');

    this.router.navigate([
      {
        outlets: {
          homeTab: ['home'],
          organizadorTab: ['organizador'],
          favoritosTab: ['favoritos'],
          categoriasTab: ['categorias'],
          perfilTab: ['perfil']
        }
      }
    ], { relativeTo: this.route });
  }

  @HostListener('loaded')
  onLoaded() {
    if (platform.isAndroid) {
      this.tabView.android.tabLayout.setTabTextFontSize(10);

      const viewGroup = this.tabView.android.tabLayout.getChildAt(0);

      for (let i = 0; i < viewGroup.getChildCount(); i++) {
        const view = viewGroup.getChildAt(i);
        const layoutParams = view.getLayoutParams();
        layoutParams.width = 1;

        layoutParams.leftMargin = -20;
        layoutParams.rightMargin = -20;
        layoutParams.topMargin = -20;
        layoutParams.bottomMargin = -20;

        view.setLayoutParams(layoutParams);
      }

      this.tabView.requestLayout();
    }
  }
}


text:
Q: Proving Vectors Inside a Subspace Satisfy Given Condition I have a proof style question regarding vectors and orthonormal bases. It is as follows:
Let V1 and V2 be an orthonormal basis for W which is a subset of R^n. Prove that if w is a vector in W then the following holds:
||w||^2 = (w . V1)^2 + (w . V2)^2
I have tried a few things here however the first thing I noticed was this provided condition looks very similar to the Cauchy-Schwarz Inequality but was not really sure how that is relevant.
One of the things I have tried was breaking down each part of the equation. I thought if w is inside W which is an orthonormal basis it would have a length of 1 so the left hand side of the equation would be equal to 1 but then I got stuck as I know when orthogonal vectors are dotted against each other their dot product is 0 which would mean the left hand side would be 0 + 0 which is obviously not equal to 1.
I have in my notes all the properties of vector dot products as well as those of orthonormal bases but cannot seem to organise those in such a way that explains the given condition.
Thank you for any feedback or advice.

A: Suppose $w \in \mathbb{R}^n$ and $(v_1, \dotsc, v_n)$ is an orthonormal basis of $\mathbb{R}^n$. Then we can write $w$ as a (unique) linear combination $w = \sum_{i=1}^n \lambda_i v_i$ and thus have
$$
 w \cdot v_j
 = \left( \sum_{i=1}^n \lambda_i v_i \right) \cdot v_j
 = \sum_{i=1}^n \lambda_i \underbrace{v_i \cdot v_j}_{\delta_{ij}}
 = \lambda_j
$$
for all $1 \leq j \leq n$, and therefore
$$
 \|w\|^2
= w \cdot w
= \left( \sum_{i=1}^n \lambda_i v_i \right)
   \cdot \left( \sum_{i=1}^n \lambda_i v_i \right)
= \sum_{i,j=1}^n \lambda_i \lambda_j \underbrace{v_i \cdot v_j}_{\delta_{ij}}
= \sum_{i=1}^n \lambda_i^2
= \sum_{i=1}^n (w \cdot v_i)^2.
$$


text:
Q: How to set Italian as language for hyperref's backref option in moderncv I'm using moderncv package by using some \cite{} in the document:
\documentclass[11pt,a4paper]{moderncv}
\usepackage[italian]{babel}
\moderncvstyle{casual}
...
\usepackage{multibib}
\begin{document}
\section{\textbf{\textcolor{gray}{Section 1}}}
Text \cite{demo}
...
...
...
\section{\textbf{\textcolor{gray}{Section 2}}}
Other text \cite{demo}
...
\section{\textbf{\textcolor{gray}{Riferimenti}}}
\bibliographystyle{unsrt}
\bibliography{riferimenti}
\end{document}

and I customized the moderncv.cls file by adding backreferences, in this way:
\RequirePackage[unicode, pagebackref=true]{hyperref}
  %%%%  CUSTOM backref COMMAND: https://tex.stackexchange.com/a/183735
  \renewcommand*{\backref}[1]{}
  \renewcommand*{\backrefalt}[4]{[{%
      \ifcase #1 Nessuna citazione%
            \or Cit. a pagina~#2%
            \else Cit. alle pagine~#2%
      \fi%
      }]}

Now the problem is that the E conjunction (for the pages) remains in English, instead of in Italian, when the \cite{} command is repeated in different pages. So I get:

[1] ... [Cit. alle pagine 1 and 3]

Note the 'AND' (in English) instead of 'E' (in Italian) as conjunction.
I think the cause is to be found in the file backref.sty, where different languages seem to be supported, but not the Italian:
...
\def\backrefenglish{%
  \def\backrefpagesname{pages}%
  \def\backrefsectionsname{sections}%
  \def\backrefsep{, }%
  \def\backreftwosep{ and~}%
  \def\backreflastsep{, and~}%
}
\def\backrefgerman{%
  \def\backrefpagesname{Seiten}%
  \def\backrefsectionsname{Abschnitte}%
  \def\backrefsep{, }%
  \def\backreftwosep{ und~}%
  \def\backreflastsep{ und~}%
}
\def\backreffrench{%
  \def\backrefpagesname{pages}%
  \def\backrefsectionsname{sections}%
  \def\backrefsep{, }%
  \def\backreftwosep{ et~}%
  \def\backreflastsep{ et~}%
}
\def\backrefspanish{%
  \def\backrefpagesname{p\'aginas}%
  \def\backrefsectionsname{secciones}%
  \def\backrefsep{, }%
  \def\backreftwosep{ y~}%
  \def\backreflastsep{ y~}%
}
\def\backrefbrazil{%
  \def\backrefpagesname{p\'aginas}%
  \def\backrefsectionsname{se\c c\~oes}%
  \def\backrefsep{, }%
  \def\backreftwosep{ e~}%
  \def\backreflastsep{ e~}%
}
\def\backrefafrikaans{%
  \def\backrefpagesname{bladsye}%
  \def\backrefsectionsname{afdelings}%
  \def\backrefsep{, }%
  \def\backreftwosep{ en~}%
  \def\backreflastsep{ en~}%
}%
...
\BR@DeclareLang{english}{english}
\BR@DeclareLang{american}{english}
\BR@DeclareLang{australian}{english}
\BR@DeclareLang{british}{english}
\BR@DeclareLang{canadian}{english}
\BR@DeclareLang{newzealand}{english}
\BR@DeclareLang{UKenglish}{english}
\BR@DeclareLang{USenglish}{english}
\BR@DeclareLang{german}{german}
\BR@DeclareLang{ngerman}{german}
\BR@DeclareLang{austrian}{german}
\BR@DeclareLang{naustrian}{german}
\BR@DeclareLang{french}{french}
\BR@DeclareLang{acadian}{french}
\BR@DeclareLang{canadien}{french}
\BR@DeclareLang{frenchb}{french}
\BR@DeclareLang{francais}{french}
\BR@DeclareLang{spanish}{spanish}
\BR@DeclareLang{brazil}{brazil}
\BR@DeclareLang{brazilian}{brazil}
\BR@DeclareLang{afrikaans}{afrikaans}
...

I so tried to add:
...
\def\backrefafrikaans{%
  \def\backrefpagesname{bladsye}%
  \def\backrefsectionsname{afdelings}%
  \def\backrefsep{, }%
  \def\backreftwosep{ en~}%
  \def\backreflastsep{ en~}%
}
\def\backrefitalian{%
  \def\backrefpagesname{pagine}%
  \def\backrefsectionsname{sezioni}%
  \def\backrefsep{, }%
  \def\backreftwosep{ e~}%
  \def\backreflastsep{ e~}%
}%
...
\BR@DeclareLang{afrikaans}{afrikaans}
\BR@DeclareLang{italian}{italian}
...

but without success.
How to make the choice for the Italian language?
The only thing that worked has been to change \def\backrefenglish with:
\def\backrefenglish{%
  \def\backrefpagesname{pagine}%
  \def\backrefsectionsname{sezioni}%
  \def\backrefsep{, }%
  \def\backreftwosep{ e~}%
  \def\backreflastsep{, e~}%
}

Thank you

A: Great, solved: I just have to use the new created command \backrefitalian like so:
\section{\textbf{\textcolor{gray}{Riferimenti}}}
\backrefitalian
\bibliographystyle{unsrt}
\bibliography{riferimenti}

How to make Italian language be added to hyperref package?
Edit:
I opened a new post to discuss a rearrangement of the code presented here. Thank you


text:
Q: How to catch an exception while initializing an object? When I initialise the object
SignInfo signInfo = signService.create(signConfiguration, file.getContent(), customSignInfo);

then an exception is visible in the error.log file:
SignEvidenceVerificationException: Error occurs while evidence verification (statusCode: censored)

but the object signInfo is created properly but i would need to change some properties of the object. So my question is: How can I catch this exception? I already tried it with
try {
  SignInfo signInfo = signService.create(signConfiguration, file.getContent(), customSignInfo);
} catch (SignEvidenceVerificationException | SignException e ) {

Even in the debug mode i'm not able to step in to this exception. As it's only visible in the logfiles and not in the debuger.
As far i understand, this exception is thrown in a thread from an external library. How can I access that thread?


text:
Q: Repair a ripped touchscreen cable I have an Ampire AM800480STMQWT00 touchscreen display. In the course of testing the device, the cable for the touchscreen proper got ripped by accident.
Is it possible at all to repair the cable itself, or would I be forced to simply acquire a brand new touchscreen to mount on the display? I tried searching around for the touchscreen display I have but there's not a lot of information available on it.
The actual rip is towards the end of the cable that would be plugged into a device.

A: The only way of really ghetto-fixing FFCs like this that I've found successful is to cut the cable where it ripped (straight across so you have an even end), and then scraping away at the insulation of the end that is to be inserted into the female mating connector. In order to get the FFC into the connector, sometimes it is necessary to reinforce the cable end by inserting it along with some thin plastic, or applying some tape to the back (to make it a bit thicker to have a firm fit inside the connector).
Keep in mind, this assumes you have enough (lengthwise) of the FFC remaining after the cut to work with. If you don't, you'll need a new FFC/display panel.
(FFC = Flat Flexible Cable)

A: If this is a typical ribbon cable you're talking about, there was a discussion a few months back on another forum , with plenty of "how-we-done-it-good-up-our-way" stories and advice, etc., ranging from "you're s.o.l." to "piece of cake".


text:
Q: I can't access a array with objects inside other object in React Native and Redux I'm currently developing an app with React Native and Redux.
My problem is that whenever I try to access an item of an array, which is inside another object (applicationState), it causes an error saying that its not an object.

I've tried to retrieve the array item as follows:
<Text style={styles.txtQuestion}>{this.props.survey.questions[0].question}</Text>

My applicationState:
surveySelected: {
        id: Math.random(),
        title: 'Idiomas',
        date: '01/10/2018',
        image: require('../../assets/imgs/enquetesItem/img1.jpg'),
        questions: [
            {
                question: 'Você fala um idioma diferente?',
            },
            {
                question: 'Qual idioma?',
            },
        ],
    },


text:
Q: CountVectorizer is not respecting the regex I'm using the following code to get the document term matrix:
from nltk.stem import SnowballStemmer
from sklearn.feature_extraction.text import CountVectorizer

stemmer = SnowballStemmer("english", ignore_stopwords=True)

class StemmedCountVectorizer(CountVectorizer):
    def build_analyzer(self):
        analyzer = super(StemmedCountVectorizer, self).build_analyzer()
        return lambda doc: ([stemmer.stem(w) for w in analyzer(doc)])

stemmed_count_vect = StemmedCountVectorizer(stop_words='english',
                                            ngram_range=(1,1),
                                            token_pattern=r'\b\w+\b',
                                            min_df=1,
                                            max_df=0.6)

However, I'm still getting items like these:
20009
2000mile
20011
20017
2001â
2007s
20081007
200h

How do I fix this?

A: This pattern token_pattern=r'\b\w+\b' says it wants one or more members of the \w character class between word boundaries. This character class

[m]atches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore.

So it seems to me you need less inclusive character class (leaving out digits for a start).


text:
Q: setDate with getDate + n returns today's date + n I want d2 to be d1 + 14 days, instead it's todays' date + 14 days.

How can I make d2 = d1 + 14 days?

A: setDate, somewhat surprisingly, sets the day-of-the-month of the existing instance. Since you've initialized d2 with today, you're just changing the day-of-month for that date, not taking on any other aspect of d1.
You probably want:
var d1 = new Date(2014, 7, 1);  // A specific date
var d2 = new Date(d1);          // Clone that date
d2.setDate(d1.getDate() + 14);  // Move forward 14 days

That gives us August 1st for d1, and August 15th for d2.
Another option is:
var d1 = new Date(2014, 7, 1);
var d2 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate() + 14);

Both of those work even when you're going past the end of the month, btw.
Complete example of the second option: Live Copy
<!DOCTYPE html>

<meta charset=utf-8 />
<title>Date plus 14 days</title>

A: You're making a new Date (today) for d2 but only changing the day, this should work:
var d1 = new Date(2014, 7, 1);
var d2 = new Date(2014, 7, d1.getDate()+14);

A: Only put getTime() function inside d2 Date() function,
Check this Demo jsFiddle
JavaScript
  var d1 = new Date(2014, 7, 1);
  var d2 = new Date(d1.getTime());
  d2.setDate(d1.getDate() + 14);

  // d1 = Fri Aug 01 2014 00:00:00 GMT+0100 (GMT Daylight Time)
  document.write("d1 = " + d1);
  document.write("

")

  // today's date is 16-04-2014
  // d2 = Tue Apr 15 2014 17:36:03 GMT+0100 (GMT Daylight Time)
  document.write("d2 = " + d2);

Result
d1 = Fri Aug 1 00:00:00 UTC+0530 2014

d2 = Fri Aug 15 00:00:00 UTC+0530 2014

A: d1 is a date in August, d2 is today.  You are setting d2 to today + 14 days.  The proper result is below:
var d1 = new Date(2014, 7, 1);
var d2 = new Date(d1.setDate(d1.getDate() + 12));