text:
Q: Firebase FaceBookAuthUI not working? I am trying to add facebook based login using firebaseUI,however it is not working .
The gist of MainActivity is gist
The code that has been used to display  the fb based login is
AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setIsSmartLockEnabled(false)
                                    .setProviders(

                                            AuthUI.FACEBOOK_PROVIDER,
                                            AuthUI.EMAIL_PROVIDER,
                                            AuthUI.GOOGLE_PROVIDER)
                                    .build(),
                            RC_SIGN_IN);

I have added the app id to string's .xml
<string name="facebook_app_id" translatable="false">XXXXXXXXXXXXXX</string>
<string name="fb_login_protocol_scheme">fbXXXXXXXXXXXXXXXXX</string>

Below is the video of what happens on login.
https://www.youtube.com/watch?v=5PiCFiY3GH8
I have searched a lot on internet but am unable to resolve this.
A similar Stack-overflow question but with no resolution is
FirebaseUI authentication with Facebook not working
Below is The logcat that i am seeing.
01-01 15:44:30.126 1563-1633/? I/ActivityManager: Displayed com.google.firebase.udacity.friendlychat/com.facebook.FacebookActivity: +248ms
01-01 15:44:31.189 4811-14350/? W/fb4a.BlueServiceQueue: Exception during service
                                                         X.2Oo: [code] 100 [message]: invalid app id (100) [extra]: null
                                                             at X.11M.a(:172024)
                                                             at X.1pN.j(:329316)
                                                             at X.2R7.a(:409495)
                                                             at X.159.handleResponse(:180125)
                                                             at com.facebook.tigon.httpclientadapter.TigonHttpClientAdapterImpl$ClientCallbacks$1.run(:327964)
                                                             at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
                                                             at com.facebook.common.executors.WrappingExecutorService$1.run(:77498)
                                                             at com.facebook.common.executors.DefaultConstrainedListeningExecutorService$Worker.run(:63229)
                                                             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                             at com.facebook.common.executors.NamedThreadFactory$1.run(:77690)
                                                             at java.lang.Thread.run(Thread.java:818)
01-01 15:44:31.222 1563-3453/? I/ActivityManager: START u0 {cmp=com.facebook.katana/.ProxyAuth (has extras)} from uid 10164 on display 0
01-01 15:44:31.250 13879-13930/com.google.firebase.udacity.friendlychat D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=1230, _sc=FacebookActivity, _si=2594922199852488391}]
01-01 15:44:31.320 1563-3871/? I/ActivityManager: START u0 {cmp=com.facebook.katana/.gdp.WebViewProxyAuth (has extras)} from uid 10140 on display 0
01-01 15:44:31.340 3456-13966/? V/FA-SVC: Event recorded: Event{appId='com.google.firebase.udacity.friendlychat', name='_e', params=Bundle[{_o=auto, _et=1230, _sc=FacebookActivity, _si=2594922199852488391}]}
01-01 15:44:31.358 1563-3883/? I/ActivityManager: START u0 {cmp=com.facebook.katana/.gdp.ProxyAuthDialog (has extras)} from uid 10140 on display 0
01-01 15:44:31.981 1563-1633/? I/ActivityManager: Displayed com.facebook.katana/.gdp.ProxyAuthDialog: +613ms (total +736ms)
01-01 15:44:32.759 4811-14396/? W/fb4a.BlueServiceQueue: Exception during service
                                                         X.2Oo: [code] 100 [message]: (#100) Param third_party_app_id must be a valid application id [extra]:
                                                             at X.11M.a(:172075)
                                                             at X.11M.a(:171971)
                                                             at X.11M.a(:171960)
                                                             at X.11M.a(:171979)
                                                             at X.2CN.a(:382666)
                                                             at X.159.b(:180159)
                                                             at X.159.handleResponse(:180124)
                                                             at com.facebook.tigon.httpclientadapter.TigonHttpClientAdapterImpl$ClientCallbacks$1.run(:327964)
                                                             at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
                                                             at com.facebook.common.executors.WrappingExecutorService$1.run(:77498)
                                                             at com.facebook.common.executors.DefaultConstrainedListeningExecutorService$Worker.run(:63229)
                                                             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                             at com.facebook.common.executors.NamedThreadFactory$1.run(:77690)
                                                             at java.lang.Thread.run(Thread.java:818)
01-01 15:44:46.906 3456-13966/? V/FA-SVC: Uploading data. app, uncompressed size, data: com.google.firebase.udacity.friendlychat, 737,
                                          batch {
                                            bundle {
                                              protocol_version: 1
                                              platform: android
                                              gmp_version: 10084
                                              uploading_gmp_version: 10084
                                              config_version: 1483190241814000
                                              gmp_app_id: 1:1020544687127:android:64e58dacc0483faa
                                              app_id: com.google.firebase.udacity.friendlychat
                                              app_version: 1.0
                                              app_version_major: 1
                                              firebase_instance_id: dsAOV03UKx4
                                              app_store: manual_install
                                              upload_timestamp_millis: 1483265686855

A: This is due the fact that i was using
<string name="facebook_app_id" translatable="false">XXXXXXXXXXXXXX</string>

Whereas i should have used
<string name="facebook_application_id" translatable="false">XXXXXXXXXXXXX</string>

Confusion was because the facebook quickstart guide had said to use facebook_app_id wheras it should have been facebook_application_id in case FireBaseUIAuth.


text:
Q: Наследование перегруженных арифметических операторов c++ Есть шаблонные классы
template< int rows, int columns, typename Type >
class Matrix : public Tensor<rows*columns, Type> {...}

template< int size, typename Type >
class Vector : public Tensor<size, Type> {...}

template< typename Type >
class Quaternion : public Tensor<4, Type> {...}

Которые все унаследованы от шаблонного базового класса:
template< int elements, typename Type = DEFUALT_TYPE >
class Tensor {
  Tensor() {...}
  Tensor( const Tensor<elements, Type>& other ) {...}
 ~Tensor() {...}

  template< int elements, typename Type, typename Scalar >
  friend Tensor< elements, Type> operator+( const Tensor< elements, Type>& left, const Scalar right );
  ...
  // overloading operators -,*,/,+=,-=,*=,/=
protected:
  Type array[elements];
}

Который, в основном, отвечает за базовые арифметические операции: сложение, вычитание, умножение, деление на скаляр, так как для всех наследованных типов эти операции одинаковы.
Но проблема в том, что эти операторы возвращают базовый класс Tensor, что, в свою очередь, порождает некоторые проблемы:

*

*Нельзя присвоить результат сложение вектора и скаляра вектору:
Vector<3,double> vec1;
Vector<3,doubel> vec2 = vec1+1;

*Для классов Matrix, Vector, Quaternion перегружен оператор стандартного вывода, но такое не сработает:
std::cout << vec1+2;

*Нельзя сразу же использовать результат сложения:
(vec1+5).length();

Хотя, это почти то же самое что и 2 пункт.
Первую проблему можно решить, например, создав для Matrix, Vector, Quaternion конструктор копирования, который бы создавал объект из объекта класса Tensor:
Vector( const Tensor<size, Type>& tensor ) : Tensor<size, Type>( tensor ) {...}

Но это не решает остальных проблем, и пропускает такой, заведомо ложный код:
Matrix<2,2,double> mat1;
Vector<4,double> vec1 = mat1+2;

Сейчас я решил проблему тем, что для каждого наследуемого класса я определяю эти операторы заново. Но это во-первых муторно, ведь для каждого класса их примерно 12 штук. А если надо что-то поменять? Добавить новый класс? А во-вторых это дублирование идентичного кода.
Как можно разрешить эту проблему поэлегантнее?

A: Можно воспользоваться техникой известной под именем CRTP.
Приведу пример, как Вам можно это реализовать, а Вы уже сами заточите под свой код:
#include <iostream>

template<typename T, typename Derived>
class Base
{
public:
    Derived operator+(int scalar)
    {
        //добавим сюда сложение
        return *self();
    }
private:
    Derived* self()
    {
        return static_cast<Derived*>(this);
    }
};

template<typename T>
class A: public Base<T, A<T>>
{
public:
    A() = default;
    A(const A&)
    {
        std::cout << "A copy ctor\n";
    }
};

template<typename T>
class B: public Base<T, B<T>>
{
public:
    B() = default;
    B(const B&)
    {
        std::cout << "B copy ctor\n";
    }
};

int main(int argc, char* argv[])
{
    A<int> a;
    B<float> b;
    a = a + 1;
    b = b + 5;

    // Следующие строки не скомпилируются
    //a = b + 1;
    //b = a + 1;
}

A: Сразу скажу, что ответ не претендует на звание максимально полного. Имхо, лучший ответ стоит искать в реализации популярных математических библиотек. Но для решения обозначенных проблем могу предложить следующие решения:

*

*Для запрета неявного преобразования Tensor в Vector достаточно
сделать соответствующий конструктор явным:
explicit Vector(const Tensor<size, Type>& tensor);

*Для реализации бинарных операторов типа operator+ всё таки придется
определеять его для каждого нового класса. Необходимость этого вытекает
из-за возвращения нового свежесозданного объекта (а не ссылки на
существующий). При этом код оператора каждого нового класса вполне
может использовать вызов оператора базового класса, уменьшая таким
образом дублирование кода.
В качестве демонстрации прилагаю код с иерархией из двух классов. Параллели с тензорами, матрицами и векторами попробуйте провести сами.
#include <iostream>

struct B {
    B(int i): i{i} {}
    int i;
};

B operator+(const B& lhs, const B& rhs) { return B(lhs.i + rhs.i); }

struct D : B {
    explicit D(int i, double j=0) : B{i}, j{j} {}
    explicit D(const B& b, double j=0): B{b}, j{j} {}
    double j;
};

D operator+(const D& lhs, const D& rhs) {
    return D(static_cast<const B&>(lhs) + static_cast<const B&>(rhs), lhs.j + rhs.j);
}

D operator+(const D& lhs, const B& rhs) {
    return D(static_cast<const B&>(lhs) + static_cast<const B&>(rhs), lhs.j);
}

D operator+(const B& lhs, const D& rhs) {
    return D(static_cast<const B&>(lhs) + static_cast<const B&>(rhs), rhs.j);
}

std::ostream& operator<<(std::ostream& o, const B& b) {
    return o << b.i;
}

std::ostream& operator<<(std::ostream& o, const D& d) {
    return o << static_cast<const B&>(d) << ' ' << d.j;
}

int main()
{
    D d{1, 2.25};

    B b{5};

    std::cout << d + 2 << '\n';
    std::cout << 2 + d << '\n';
    std::cout << b + d << '\n';
    std::cout << d + b << '\n';
    std::cout << b + 3 << '\n';
    std::cout << 3 + b << '\n';
    std::cout << (d + 10).j << '\n';
}

Результаты выполнения

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a known way to formalise notion that certain theorems are essential ones?
*

*Suppose You ask a question beginning from "Why some structure is..." or "Why some object has property..." and several
answers arises. Which criteria do You
use to qualify which answer is correct?
For example here You may find interesting picture (gzipped postscript file) of proofs formalized in Mizar system.. Mizar library of formalized theorems is really huge. On the picture You may see, that theorems arises from other and are used in proofs of another ones, forming big graph of structure of theorems formalized in Mizar so far. If I may read something from this graph, there is no theorem which will have more that 3 or 4 incoming edges what means there is no theorem which is used in more that 3 or 4 proofs. Of course there are some with 5 incoming edges, but in fact there is many theorems which have more or less equal number of incoming edges, which may mean that most theorems are equivalently important. Maybe it should be measured by tree deepness? Maybe there is something like Google page rank algorithm for theorems?
Probably we would like to have such relation: "theorems recognized as important should be influential, or foundational for broad area of theory".

*

*I understand that one may believe that this is a real state of matter,
but are there any strict results
based on real data in this matter?
By real data I mean at best proof theory analysis, or even citation analysis, but not someone opinion (which of course may be enlightening and inspirational). I would like to learn something about structure of deductive theories, and not about "real practice". It is the same as in real life: we try to measure risks, and income rate not based on someone opinion but on facts. Could we know the facts here?
It seems from Mizar graph ( which is the only one accessible for me in this area) I could not find any object which will correspond to our intuition of importance of theorems. Maybe this is effect of present Mizar state of affair, and in bigger/other system, some theorems begin central one? Are there any conditions to state such position?

*

*What about other proof assistants, as
Isabelle or COQ. Is there any similar
graph from other systems suitable for
such analysis?

A: Although your question is vague in certain ways, one robust answer to it is provided by the subject known as Reverse Mathematics. The nature of this answer is different from what you had suggested or solicited, in that it is not based on any observed data of mathematical practice, but rather is based on the provable logical relations among the classical theorems of mathematics. Thus, it is a mathematical answer, rather than an engineering answer.
The project of Reverse Mathematics is to reverse the usual process of mathematics, by proving the axioms from the theorems, rather than the theorems from the axioms. Thus, one comes to know exactly which axioms are required for which theorems. These reversals have now been carried out for an enormous number of the classical theorems of mathematics, and a rich subject is developing. (Harvey Friedman and Steve Simpson among others are prominent researchers in this area.)
The main, perhaps surprising conclusion of the project of Reverse Mathematics is that it turns out that almost every theorem of classical mathematics is provably equivalent, over a very weak base theory, to one of five possibilities. That is, most of the theorems of classical mathematics turn out to be equivalent to each other in five large equivalence classes.
For example,

*

*Provable in and equivalent to the theory RCA0 (and each other) are: basic properties of the natural/rational numbers, the Baire Cateogory theorem, the Intermediate Value theorem, the Banach-Steinhaus theorem, the existence of the algebraic closure of a countable field, etc. etc. etc.

*Equivalent to WKL0 (and each other) are the Heine Borel theorem, the Brouer fixed-point theorem, the Hahn-Banach theorem, the Jordan curve theorem, the uniqueness of algebraic closures, etc. , etc. etc.

*Equivalent to ACA0 (and each other) are the Bolzano-Weierstraus theorem, Ascoli's theorem, sequential completeness of the reals, existence of transcendental basis for countable fields, Konig's lemma, etc., etc.

*Equivalent to ATR0 (and each other) are the comparability of countable well orderings, Ulm's theorem, Lusin's separation theorem, Determinacy for open sets, etc.

*Equivalent to Π11 comprehension (and each other) are the Cantor-Bendixion theorem and the theorem that every Abelian group is the direct sum of a divisible group and a reduced group, etc.
The naturality and canonical nature of these five axiom systems is proved by the fact that they are equivalent to so many different classical theorems of mathematics. At the same time, these results prove that those theorems themselves are natural and essential in the sense of the title of your question.
The overall lesson of Reverse mathematics is the fact that there are not actually so many different theorems, in a strictly logical sense, since these theorems all turn out to be logically equivalent to each other in those five categories. In this sense, there are essentially only five theorems, and these are all essential. But their essential nature is mutable, in the sense that any of them could be replaced by any other within the same class.
I take this as a robust answer to the question that you asked (and perhaps it fulfills your remark that you thought ideally the answer would come from proof theory). The essential nature of those five classes of theorems is not proved by looking at their citation statistics in the google page-rank style, however, but by considering their logical structure and the fact that they are logically equivalent to each other over a very weak base theory.
Finally, let me say that of course, the Reverse Mathematicians have by now discovered various exceptions to the five classes, and it is now no longer fully true to say that ALL of the known reversals fit so neatly into those categories. The exceptional theorems are often very interesting cases which do not fit into the otherwise canonical categories.


text:
Q: sd 5:0:0:0: [sda] Attached SCSI disk, what are these four numbers? Will they change? I can usually see this log in dmesg:
sd 5:0:0:0: [sda] Attached SCSI disk

Can you please explain what are these 4 numbers?
Will these numbers change after reboot? or it should be constant?

A: The four numbers represent a SCSI address, often referred to as H:C:T:L. The four components are host, channel (or bus), target, and LUN.
With drives you're likely to encounter on an end-user system (SATA, consumer NVMe, USB), the channel, target, and LUN will all be zero. The host number will depend on which port the drive is connected to, and how it's enumerated; for fixed drives (SATA, NVMe), it won't vary most of the time, but it's not impossible for it to change.


text:
Q: Evaluate ${n \choose 1}+2{n \choose 2}+...+n{n \choose n}$ I have trouble finding an explicit expression to prove this sum using induction, and would like a hint. It would also help if someone provided a non-induction question.

A: Hint: $$ \binom{n}{k}k = \frac{n!}{k!(n-k)!}k = \frac{n!}{(k-1)!(n-k)!}=n\binom{n-1}{k-1} $$
For the last step, note that $n-k = (n-1)-(k-1)$

A: Hint:
What is the derivative of $(1+x)^n$?


text:
Q: htaccess from subdomain www to domain name I have a link that i need to have a 301 redirect from
www.subdirectory.domain.com to http://subdirectory.domain.com
Ive seen plenty of combinations but am unsure how to achieve this
Not sure if something like this works but i get an error
RewriteCond %{HTTP_HOST} ^www\.(subdirectory)\.domain.com$ [NC]
RewriteRule ^(.*) http://%subdirectory.domain.com/$1 [L,R,301]

A: I see two issues with your rewrite:
First, you need to remove the % from %subdirectory.domain.com, since it's not part of your domain name and is probably not a valid character for domain names.
Second, the redirect flag should be R=301 instead of R,301 — I'd guess that's  what's giving you the error.
Other than those things, your rewrite should work.


text:
Q: Some code search tools for Gerrit to match keyword I want a tool to search code line based on keywords such as function names and macros in multiple projects in gerrit, and only show matching lines instead of the entire file, because the code has different permission allocation policies

A: I suggest to take a look at the OpenGrok - a wicked fast source browser.


text:
Q: AWS CloudWatch Alarm for Aurora Instance Memory Utilization above 80% I am looking to create a CloudWatch alarm to check for Aurora Postgres Memory Utilization. My requirement is to be notified when the Memory Utilization of an Aurora Instance stays above 80% for 5 minutes out of 10.
For testing purposes, I created a CW alarm and Selected:

*

*Per-Database Metrics

*DBInstanceIdentifier = the Aurora Instance I wanted to monitor

*Metric name = Freeable Memory

*Period = 1 Minute

*Threshold Type = Static

*Whenever FreeableMemory is Lowe/Equal than 20 (Assuming that Freeable Memory less then eq to 20 means memory usage going above 80%)

*Datapoints to alarm 1 out of 1

*Notification to a SNS topic (which will send me an email)

I ran some queries on this Aurora Instance which brought its Freeable memory from 3.7 GB to ~160MB for more than a minute, however the CW alarm did not work and did not go into "In Alarm" state. No SNS email received as well.
Can someone tell me what am I doing wrong and how to configure this Memory Util Alarm correctly?
Thanks


text:
Q: MYSQL Inner Join , group by and order by using I want merge datas from mysql database with sql reqeust
this messages.tbl
id : 1
sender : ali
responder : aishe
message : hi,how are you aishe
xid : md5($sender.$responder)--for using group by xid
id : 1
sender : ali
responder : aishe
message : answer me aishe plase
xid : md5($sender.$responder)--for using group by xid

and this  members.tbl
id : 1
nickname  : ali
img : ali.jpg

second record in members.tbl
id:2
nickname : aishe
img : aishe.jpg

i want list group by xid and in messages lastest showing
my english so poor sorry .
please help me guys
so ali sent 50 posts messages
and john post 20 messages
and mike 5 messages
i want writen to page
like  :
 Ali's lastest message and ali's picture
 John's lastest message and his picture
 Mike's lastest message and his picture
order by lastest messages and group by xid(like : 44asd32asd12)
understanding?

A: If I understand correctly, you want to show the messages sent by every user, or you want to show the last message sent by each user.
If you want to show the messages for every user, you can use this query:
select
    members.*, -- Put the fields you want from table members (e.g. members.id, ...)
    messages.* -- Put the fields you want from table messages (e.g. messages.message, ...)
from
    members
    inner join messages on members.nickname = messages.sender;

If you want the last message sent by every user, you can use a subquery to filter the data:
select
    members.*,
    messages.*
from
    members
    inner join messages on members.nickname = messages.sender
    inner join (
        select sender, max(id) as maxId
        from messages
        group by sender
    ) as a on messages.id = a.maxId;

Hope this helps


text:
Q: Property does not exist on a function's return value of multiple types I'm using typescript to write NodeJS program.
In this program, I import a node module called ts-md5, in which there is a function hashStr(), it could return a value of string or Int32Array.
I need to do things like this in my program:
Md5.hashStr(str).toUpperCase();

However, the compiler complains error:
error TS2339: Property 'toUpperCase' does not exist on type 'string | Int32Array'.

The program runs successfully. Because it always returns string during runtime. But I want to know if there is a way to get rid of this annoying error?

A: You can use a type guard, or a type assertion.
type guard
let hash = Md5.hashStr(str);
if (typeof hash === 'string') {
    hash = hash.toUpperCase();
}

type assertion
let hash = (<string>Md5.hashStr(str)).toUpperCase();

The benefit of the type guard is that it technically safer - because if you ever did get something that wasn't a string at runtime, it would still work. The type assertion is simply you overriding the compiler, so it isn't technically as safe, but it is entirely erased and therefore results in the same runtime code you have at the point you have the error.

A: hashStr is declared in ts-md5 typings as
static hashStr(str: string, raw?: boolean): string | Int32Array;

Looking at the implementation, is seems that it returns Int32Array when raw is true, and returns string otherwise.
Given that declaration, you can't do much better than use type assertion:
let hash = (Md5.hashStr(str) as string).toUpperCase()

The proper way to express that return type is dependent on the parameter in TypeScript is via overload declarations. Something like this should work:
static hashStr(str: string): string;
static hashStr(str: string, raw: false): string;
static hashStr(str: string, raw: true): Int32Array;
static hashStr(str: string, raw: boolean): Int32Array | string;
static hashStr(str: string, raw?: boolean): string | Int32Array {
    // implementation goes here...
}

I'd suggest posting an issue with ts-md5 about this.


text:
Q: Iterate through words of a file in Python I need to iterate through the words of a large file, which consists of a single, long long line. I am aware of methods iterating through the file line by line, however they are not applicable in my case, because of its single line structure.
Any alternatives?

A: It really depends on your definition of word. But try this:
f = file("your-filename-here").read()
for word in f.split():
    # do something with word
    print word

This will use whitespace characters as word boundaries.
Of course, remember to properly open and close the file, this is just a quick example.

A: Long long line? I assume the line is too big to reasonably fit in memory, so you want some kind of buffering.
First of all, this is a bad format; if you have any kind of control over the file, make it one word per line.
If not, use something like:
line = ''
while True:
    word, space, line = line.partition(' ')
    if space:
        # A word was found
        yield word
    else:
        # A word was not found; read a chunk of data from file
        next_chunk = input_file.read(1000)
        if next_chunk:
            # Add the chunk to our line
            line = word + next_chunk
        else:
            # No more data; yield the last word and return
            yield word.rstrip('\n')
            return

A: You really should consider using Generator
def word_gen(file):
    for line in file:
        for word in line.split():
            yield word

with open('somefile') as f:
    word_gen(f)

A: There are more efficient ways of doing this, but syntactically, this might be the shortest:
 words = open('myfile').read().split()

If memory is a concern, you aren't going to want to do this because it will load the entire thing into memory, instead of iterating over it.

A: I've answered a similar question before, but I have refined the method used in that answer and here is the updated version (copied from a recent answer):

Here is my totally functional approach which avoids having to read and
split lines. It makes use of the itertools module:
Note for python 3, replace itertools.imap with map
import itertools

def readwords(mfile):
    byte_stream = itertools.groupby(
      itertools.takewhile(lambda c: bool(c),
          itertools.imap(mfile.read,
              itertools.repeat(1))), str.isspace)

    return ("".join(group) for pred, group in byte_stream if not pred)

Sample usage:
>>> import sys
>>> for w in readwords(sys.stdin):
...     print (w)
...
I really love this new method of reading words in python
I
really
love
this
new
method
of
reading
words
in
python

It's soo very Functional!
It's
soo
very
Functional!
>>>

I guess in your case, this would be the way to use the function:
with open('words.txt', 'r') as f:
    for word in readwords(f):
        print(word)

A: Read in the line as normal, then split it on whitespace to break it down into words?
Something like:
word_list = loaded_string.split()

A: After reading the line you could do:
l = len(pattern)
i = 0
while True:
    i = str.find(pattern, i)
    if i == -1:
        break
    print str[i:i+l] # or do whatever
    i += l

Alex.

A: What Donald Miner suggested looks good. Simple and short. I used the below in a code that I have written some time ago:
l = []
f = open("filename.txt", "rU")
for line in f:
    for word in line.split()
        l.append(word)

longer version of what Donald Miner suggested.


text:
Q: 2CHECKOUT ERROR CODE:PE102 I am currently developing a website that uses the online payment module 2CHECKOUT. I configured my account in demo mode to test it, and it goes well.
On the contrary, if I cancel the demo mode for my account to accept real payments, I get this error "ERROR CODE: PE102" knowing that I have input all my banking information in my profile.
Thanks for your help.

A: Reference: http://help.2checkout.com/articles/Knowledge_Article/Error-Code-PE102
Sellers as well as buyers may receive the message ERROR CODE PE102 for several reasons, outlined below:
All Parameter Sets:
Account is not approved to sell.
Account has been closed.
Nonexistent seller, or an invalid value for "sid" or "x_login" was passed in.


text:
Q: Listen Event for Any Object in a Table Another newbie query. Now on my third day of working with Corona.
The following code works fine: Balloons are generated and float into the air. Now I want to use :addEventListener( "tap", pushBalloon ) to make it so that when a balloon is clicked the pushBalloon is executed. Can anyone tell me what variable I would use and how I would define it? And also I guess I would have to change the pushBalloon function too for the new variable.
Thank you.
local function createBalloon()
local randomBalloon = math.random( 10 )

    local newBalloon = display.newImageRect( objectSheet, randomBalloon, 112, 142 )
    table.insert( balloonsTable, newBalloon )
    physics.addBody( newBalloon, "dynamic", { radius=70, bounce=0 } )
    newBalloon.myName = "bigBalloon"
newBalloon.alpha = 0.75
newBalloon.gravityScale = randomBalloon/-150

local whereFrom = math.random( 3 )

    if ( whereFrom == 1 ) then
        -- From the left
        newBalloon.x = 100
        newBalloon.y = display.contentHeight+150

    elseif ( whereFrom == 2 ) then
        -- From the top
        newBalloon.x = 160
        newBalloon.y = display.contentHeight+150
    elseif ( whereFrom == 3 ) then
        -- From the right
        newBalloon.x = 220
        newBalloon.y = display.contentHeight+150

end
end

local function gameLoop()
    -- Create new balloon
    createBalloon()
     -- Remove balloons which have drifted off screen
    for i = #balloonsTable, 1, -1 do
     local thisBalloon = balloonsTable[i]

        if ( thisBalloon.x < -100 or
             thisBalloon.x > display.contentWidth + 100 or
             thisBalloon.y < -100  )
        then
            display.remove( thisBalloon )
            table.remove( balloonsTable, i )
        end

    end

end

local function pushBalloon()
    --  balloon:applyLinearImpulse( 0.2, -2, balloon.x, balloon.y )
    -- tapCount = tapCount + 1
    -- tapText.text = tapCount
     newBalloon.gravityScale = 10

end

A: You are adding the newBalloon objects to a table, but you should add the event listener to each newBalloon DisplayObject as it is instantiated.  This doesn't do exactly what you ask in the title (where simply inserting an object into a table would effectively add an event listener to that object), but achieves the event response I think you are looking for.
If you are tapping the balloon, you would put the listener on the balloon. If you use a "tap" event, the target property tells you which object was touched, so your pushBalloon() function works for any balloon.
local pushBalloon( event )
   local balloon = event.target

   if event.phase == "began"

       -- do something to the balloon object (apply impulse, etc.)

   end

end

local function createBalloon()
    ...
    local newBalloon = display.newImageRect( ... )

    if newBalloon then

        -- set properties of DisplayObject and add event listener

        newBallon:addEventListener( "tap", pushBalloon )

    end
    ...
end

I have wrapped the call to addEventListener() in a check to make sure newBalloon ~= nil.


text:
Q: can someone explain what is the meaning of this code under the elbow meshing in k-means Instantiate the clustering model and visualizer
model = KMeans(random_state = 42)

visualizer = KElbowVisualizer(model, k=(2,10))

Fit the data to the visualizer
visualizer.fit(df_final.values)

Finalize and render the figure
visualizer.show()

A: K-means is an unsupervised learning, the number of clusters in the technique is called K and user has to define this number.
Now,
visualizer = KElbowVisualizer(model, k=(2,10))

In the above line of code, we are defining a range for the number of K to pass to the model in a range of 2-9 and select K where an elbow is formed which basically means that where ever the value of K and sum of squared errors is less, that K is selected.
Also this elbow method works well only when the data is very clustered.
Later,
visualizer.fit(df_final.values)

The above line is going to fit the data on the visualizer and plot different values on the figure with different K on x-axis and distortion score on y-axis.
Example code:(https://www.scikit-yb.org/en/latest/api/cluster/elbow.html)
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

from yellowbrick.cluster import KElbowVisualizer

# Generate synthetic dataset with 8 random clusters
X, y = make_blobs(n_samples=1000, n_features=12, centers=8, random_state=42)

# Instantiate the clustering model and visualizer
model = KMeans()
visualizer = KElbowVisualizer(model, k=(4,12),)

visualizer.fit(X)        # Fit the data to the visualizer
visualizer.draw()

Output:


text:
Q: Wordpress: Disable align for core/columns block in theme.json I want to completely disable align (wide and full) options and anchor from columns core block in theme.json. My code now looks like this:
{
    "version": 1,
    "settings": {
      "blocks": {
          "core/columns":{
            "align": false,
            "anchor: false
          }
       }
    }
}

I was trying many things, but nothings works. Is it possible to do it?

A: No, this is not possible to do with theme.json yet.
Theme.json reference


text: Q: Are there any access modifiers we can use in React for components? The default export <component name> statement in React makes the component available globally & it can be imported in any other component. Can we restrict this import somehow and only make the component available to select few. I cannot think of a use case for this right now but, I relate the component architecture of React with OOPs concepts as dividing the webpage into components is similar to dividing your program in classes. Hence I am asking this just to gain knowledge and make my understanding better on React.


text:
Q: Dynamically creating new tag in main window of core-drawer-panel I have the following drawer-form component
drawer-form.html
<!DOCTYPE html>
<link rel="import" href="../../../packages/polymer/polymer.html">
<link rel="import" href="../../../packages/paper_elements/paper_icon_button.html">
<polymer-element name='drawer-form'>
  <template>

      <paper-icon-button
        icon="menu"
        id='menu_icon'
        on-click='{{clickHandler}}'>
      </paper-icon-button>

New Patient

  </template>

</polymer-element>

The drawer-form is used in a main-form component:
main-form.html
<!DOCTYPE html>
<link rel="import" href="../../../packages/polymer/polymer.html">
<link rel="import" href="../../../packages/core_elements/core_drawer_panel.html">
<link rel="import" href="../../../packages/core_elements/core_icon_button.html">
<link rel="import" href="../../../packages/core_elements/core_toolbar.html">
<link rel="import" href="../../../packages/paper_elements/roboto.html">
<link rel="import" href="../../../packages/core_elements/core_toolbar.html">
<link rel="import" href="../../../packages/paper_elements/paper_icon_button.html">
<link rel="import" href="../../../packages/fontawesome_elements/fontawesome_icon.html">
<link rel="import" href="drawer-form.html">

<polymer-element name="main-form">
  <template>
    <core-drawer-panel id="core_drawer_panel">

        <drawer-form></drawer-form>

        <core-toolbar id="core_toolbar">
          <paper-icon-button
            icon="menu"
            id='menu_icon'
            on-click='{{menu_icon_handler}}'>
          </paper-icon-button>

Toolbar

        </core-toolbar>

    </core-drawer-panel>
  </template>

</polymer-element>

The clickHandloer in drawer-form.html fires a 'CREATE_NEW_PATIENT' event. How do I capture this event in the main-form component to dyanmically create the new-patient?

A: You should only use lowercase characters and dash for the event name (I very recently saw a bug report that this doesn't work).
I don't think anybody is able to catch an event fired from an element not yet attached to the DOM.
The constructor is therefore a bad place to put your 'fire' code to, use attached() (after super.attached()) instead.
Then you can listen in code like
// main-form
@override
void attached() {
  super.attached();
  this.shadowRoot.querySelector('drawer-form').on['create-new-patient'].listen((e) {
    print('create-new-patient received');
  }
}

or declaratively
<drawer-form on-create-new-patient='{{myEventHandlerInMainForm}}'>


text:
Q: cannot find package on travis-ci -golang I'm trying to run a go script as part of the build process. The script imports a 'custom' package.  However I get this import error.
 The repository name is bis. The script which I run is configbis.go. The package imported configbis.go is mymodule
The project structure is as following:
bisrepo -------
 |            |
mymodule    configbis.go

go run configbis.go
configbis.go:16:2: cannot find package "bisrepo/mymodule" in any of:

/home/travis/.gvm/gos/go1.1.2/src/pkg/bisrepo/mymodule (from $GOROOT)

/home/travis/.gvm/pkgsets/go1.1.2/global/src/bisrepo/mymodule (from $GOPATH)

I've tried to import mymodule in configbis.go as  following:
import "mymodule"
import "bisrepo/mymodule"
import "github.com/user/bisrepo/mymodule"

None of them works. I run out of ideas/options ...
I read the the travis-ci documentation and I found it useless.

A: You could try to add something like that in your .travis.yml:
install:
    - go get github.com/user/bisrepo/mymodule

A: in order to use private repos you must provide a github api auth token (similarly so when deploying go projects which reference private repos on Heroku). You can try adding something like this in your .travis.yml
before_install:
- echo "machine github.com login $GITHUB_AUTH_TOKEN" > ~/.netrc


text:
Q: How do I let apache have permissions to change any files? I have a directory:
/home/sites/

I want apache to be able to change any files that end up in this directory. It doesn't matter what permissions or ownership individual users who log into these sites may put on their files - apache can change them.
How is this possible?

A: If you are using PHP, the best way to avoid changing ownership to apache is to use mod_fcgid with suexec. With that, each PHP files will be executes as the owner of the file. You can also use suPHP but it is less performant.

A: You can set the group of the folder sticky with following
chown -R :<apache group> /home/sites
chmod -R g+s /home/sites

That way all files saved to the directory will have group < apache group >.


text:
Q: Where can I find the complete list of attributes for a control? Where can I find the complete list of attributes for a control? If I wanted to use textbox control on my asp.net application, where can I find the complete list of attributes associated with it? I know some of the them can be found in the properties area in the IDE. But the properties area did not have the "OnTextChanged" attribute listed.

A: When you click on a web control, if you have the properties window open, then you will see it's properties, which contain the attributes of a web control. Another way is to click on the control and the right click and select properties.
By the way the OnTextChanged is an event, which you can associate it with a method, when this event happens.
OnTextChange="TextBoxText_Changed"

The TextBoxText_Changed would be a server side method, which will reside in your code behind class. In this method you will declare, what you want to happen, when this event is triggered,

A: ![Properties][1]
[1]: http://i.stack.imgur.com/iUUqZ.png
go to property window click on event icon and you can see all events associated to text box.

A: You can look it up on the MSDN documentation page:
http://msdn.microsoft.com/en-us/library/System.Web.UI.WebControls.TextBox(v=vs.110).aspx


text:
Q: How to call multiple functions by using hc-05 bluetooth module? I am really new here. I am making an LED project using Arduino uno, WS28128B, HC-05 module.
 Also using Fastled library.
So I want to create 3 or 4 functions which should be my led effects And whenever I press button in my phone that specific function will run.
But how can I do this?

A: What you want to do is break down your project into different parts.
Your project is basically a chain: phone->HC-05->Arduino->WS2812B . So you can easily divide it into parts:

*

*Writing the RGB value to WS2812B. You can install an Arduino library for this LED. You can simply run the example code from the library to test your LED.

*Writing your effects. Write functions that write different RGB values to the LED with some delays. You can test it by calling them directly in loop().

*Write the bluetooth part. All you need to do is send one byte from your phone to the Arduino. For instance 0x01 or 0x31 ('1') for function 1.
You can find many tutorials online for the bluetooth part. Example: https://exploreembedded.com/wiki/Setting_up_Bluetooth_HC-05_with_Arduino

*Connect the bluetooth part to the effects. You can use switch-case to use the received byte to call the desired effect.


text:
Q: How to count rows based on multiple column conditions using pandas? How can I count csv file rows with pandas using & and or condition?
In the below code I want to count all rows that have True/False=FALSE and status = OK, and have '+' value in any of those columns openingSoon, underConstruction, comingSoon.
I've tried:
checkOne =  df['id'].loc[(df['True/False'] == 'FALSE') & (df['status'] == 'OK') & (df['comingSoon'] == '+') or (df['openingSoon'] == '+') or (df['underConstruction'] == '+')].count()

error:
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/lib/python3.9/site-packages/pandas/core/generic.py", line 1329, in __nonzero__
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: Use | for bitwise or and for count Trues values filtering not necessary, use sum:
Also for testing boolean df['True/False'] == False is possible simplify by ~df['True/False']
checkOne =  (~df['True/False'] &
             (df['status'] == 'OK') &
             (df['comingSoon'] == '+') |
             (df['openingSoon'] == '+') |
             (df['underConstruction'] == '+')).sum()

If True/False are strings TRUE/FALSE use:
checkOne =  ((df['True/False'] == 'FALSE') &
             (df['status'] == 'OK') &
             (df['comingSoon'] == '+') |
             (df['openingSoon'] == '+') |
             (df['underConstruction'] == '+')).sum()


text:
Q: C++/cli interface with properties not usable from c# Cli interface looks like this:
using namespace System::Timer
namespace Interfaces
{
    public interface class ITimerProvider
    {
        property Timer AppTimer
        {
             Timer get();
        }
    }
}

Getting to a c# class deriving from that interface and using "implement interface" from right-click menu in VS2013, it creates:
public void get_AppTimer(ref Timer value)
{
   throw new NotImplementedException();
}

The compiler complains "MyProject does not implement interface member MyCLIProject.Interfaces.ITimerprovider.get_AppTimer()"
It does so, even when it has put it inside by itself.

A: Hans has given the answer. Correcting interface declaration leads to expected auto-generated code and the project compiles fine:
property Timer^ AppTimer
    {
         Timer^ get();
    }

A: I think this might be due to Visual Studio not generating the code correctly for you.
While technically properties are just syntactic sugar for the methods get_propertyName() and set_PropertyName(), you don't actually write those methods in C# when implementing a property. The correct C# code for implementing the property would be this:
class MyProject
{
    public Timer AppTimer
    {
        get
        {
            // return the value here
        }
    }
}

If you change your code to something like this, that should fix the error.


text:
Q: How to perform file copying in multiple threads or processor in python? I"m trying to copy files in python , it'll take long time in sequential approach so I wanted to do it in multiple threads. Below is my code to copy files in sequential
for file in files:
    shutil.copy(file,destination_path)

this took around 1.2 sec to complete
I tried to implement multithreading as below
import multiprocessing
copy_instance(src,dest):
    shutil.copy(src,dest)
for file in files:
    p1 = multiprocessing.process(target=copy_instance,args=(file,destination_path)
    p1.start()

this took 168.8 sec to complete
Doing it in multiprocessing taking way more time then sequential approach , what am I doing wrong? how can I correctly implement multithreading to speed up my copying process? any help or suggestion on this will be very helpful, thanks

A: Spawning new processes is slow, particularly in windows. Instead of multiprocessing you should use multithreading, which in CPython can be good for I/O (and is bad for CPU bound processes):
import shutil
import itertools
from concurrent.futures import ThreadPoolExecutor

def copy_instance(args):
    shutil.copy(*args)

#   ... snipped definition of files and destination

with ThreadPoolExecutor() as pool:
    pool.map(copy_instance, zip(files, itertools.repeat(destination)))

Nevertheless, as noted in the comments, depending on you storage you probably won't see any difference.


text:
Q: How to debug unstable internet connection? I have a following setup:

*

*Laptop uses home internet through WiFi, and the WiFi router sits in another room.

*The Wifi router itself uses cellural internet to connect to the outside world.

Most of the times everything works. But, when it doesn't, then I am basically without internet connection and all the new tabs in Chrome will fail to load. After hitting refresh one to few times and waiting 10-120 seconds, the tab finds internet connection again.
Details

*

*I measured the internet connection speed with two different websites, the download speeds were 60-100Mbs, Upload speeds 40Mbs, and ping 20-30ms. This of course is when there is no interruption.

*The problem exists with every device connected to the WiFi, not just this one. (this is Windows 10 laptop, but I'm looking for a general solution)

*The problem exists only randomly, and there is no way to reproduce it.

Question
I'm looking for a way to find the root cause to the problem. Since the problem is not reproducible, I guess I should setup logging for something, but for what?

A: Does your main router have an Ethernet port? Most do. When Internet is out, hook up to the Ethernet port to verify the outage.
From there you need to place a Service Call with the ISP.
It may be your gear, but the ISP can help you with this. Otherwise it is up to the ISP.
It may be a bit onerous to keep a PC connected by Ethernet but they will want this information or without it may just blame you.
I did look at my own Router Logging, but it does not log external events (loss of Internet at the Modem).

A: I have infrequent 'Your internet connection is unstable' popups when playing on-line bridge on BBO.  BBO generates these popups.  Their system constantly checks for my presence and drops me if internet connection is lost for more than a few seconds.  My setup is similar to np8's, with cable modem and separate AC router at one end of the house, my laptop at the other end, about 40 ft away with four walls in between.  Small house 1700ft, four drywall/2x4 walls between router and laptop.  Not the ideal arrangement for wifi, I know.  ISP is Spectrum cable, they came out and couldn't find any problems between their modem and their system.  Found 'Wifi Analyzer' app by Matt Hafner.  I had been using 2.4G wireless but Wifi Analyzer showed there's a lot of traffic on all of the 2.4G channels, so I switched my laptop to 5G and found a quiet channel on that band.  That helped noticeably but didn't completely cure the problem.  My 5G signal strength is around -55 dB, not sure what minimum signal should be.  With 5G, I run speed tests and normally get better than 200Mb/s with my laptop so this isn't a 'speed' problem, it an intermittent disruption problem.  The unstable internet problem always corrects itself within a few seconds.  I've noticed the events seem to occur when my Trane furnace's VSD blower kicks on.  I haven't noticed anything else triggering the events.  I'm thinking it is VSD-induced noise in home's AC wiring causing radio-frequency electromagnetic interference with the wi-fi signal.  Asked my furnace installer about this - they hadn't heard of it before so they tapped into nationwide network of service people - the only reply was a possible defective choke on the VSD motor wiring.  They want $140 to come out and look.  I don't see how a choke could go bad, but may try that at some point.  The modem & router were on a 3-wire 120/240 circut that shared a neutral with the furnace so I put fed them with an extension cord from another circuit, didn't help.  I bought a 250VA isolation transformer for the modem and router, didn't help.  I added a small ferrite core on the hot wire feeding the furnace, that didn't help.  Considering a small APC 600VA UPS for $70 for the modem & router, but not sure an inexpensive UPS really provides clean AC power.


text:
Q: How do you use SetEnv to read variables in Apache? I want to set an env variable that has the DOC_ROOT info but nothing
SetEnv PROJECT_BASE %{ENV:DOC_ROOT}
SetEnv LAYOUT_HOME  %{ENV:PROJECT_BASE}"/html/app/wordpress/"

and then be able to access LAYOUT_HOME in php
How can I do this? The above is not working for me...
The problem is the base path is different on diff environments =/

A: SetEnv is a directive for mod_env, and mod_env doesn't support %{ENV:var} -- only mod_rewrite does this.  Don't forget that apache is modular, and modules define their own directives.  You can do this with mod_rewrite like this:
 RewriteRule .* -  [E=PROJECT_BASE:%{ENV:DOC_ROOT}]
  ... etc

I must ask, what are you really trying to do?  There must be a better way.  I can't think of any reason to define your LAYOUT_HOME variable in apache instead of php.

A: Use getenv, doc here.
It will get any Environment Variable, just use it to get the one you set on Apache.


text:
Q: How to loop through all the Childs under a tag in PHP DOMDocument I have the following html
$html =  '
Hello

My name is rasid
new to you

New here
';

$dom = new DOMDocument();
$dom->loadHTML($html);

$elements = $dom->getElementsByTagName('body');

I have tried
foreach($elements as $child)
 {
        echo $child->nodeName;
 }

The Ouput is
body

But I need to loop through all the tags under body not the body. How can I do that.
I have also tried in above example to replace
$elements = $dom->getElementsByTagName('body');

with
$elements = $dom->getElementsByTagName('body')->item(0);

But It gives Error. Any Solution??

A: try this
    $elements = $dom->getElementsByTagName('*');
    $i = 1; //counter to output from 3rd one, since foreach loop below will output" html  body div span div div"

    foreach($elements as $child)
    {

    if ($i > 2) echo $child->nodeName."
";   //output "div span div div"
    ++$i;
    }

A: If you only want child nodes of the body element, you can use:
$body = $dom->getElementsByTagName( 'body' )->item( 0 );
foreach( $body->childNodes as $node )
{
    echo $node->nodeName . PHP_EOL;
}

If you want all descending nodes of the body element, you could use DOMXPath:
$xpath = new DOMXPath( $dom );
$bodyDescendants = $xpath->query( '//body//node()' );
foreach( $bodyDescendants as $node )
{
    echo $node->nodeName . PHP_EOL;
}

A: use this code
 $elements = $dom->getElementsByTagName('*');

        foreach($elements as $child)
        {

              echo $child->nodeName;

        }


text:
Q: Fluid Player Does Not Work After Browser Re-Size I am using 100% in the width and height tags and the player works fine no matter what size the browser is when it is first opened but as soon as I resize the browser none of the controls work any longer and it a video is playing the video quits playing and the screen goes black. Do I have to add something or is this just a bug? Oh yeah, this happens in firefox 10.0.2.
Here is my code:
<video width="100%" height="100%" id="player2" poster="media/Memphis-Beat_Ring-of-Fire.jpg" controls="controls" preload="none">
                    <source type="video/mp4" src="media/Memphis-Beat_Ring-of-Fire.mp4" />
                </video>
                <script>
                    $('audio,video').mediaelementplayer({
                        success: function(player, node) {
                            //$('#' + node.id + '-mode').html('mode: ' + player.pluginType);
                        }
                    });
                </script>

A: This really annoyed me too. I solved it by creating a function for resizing the player...
// For adjusting the player size on the fly
            var adjustVideoSize = function(me, el) {
                var width = $('.a_wrapper_that_is_fluid_width').width();
                var height = $('.a_wrapper_that_is_fluid_width').height();
                // min dimensions for the player
                if (width < 256) width = 256;
                if (height < 110) height = 110;
                // MediaElement methods for resizing
                me.setVideoSize(width, height);
                var player = me.player || el.player;
                player.setPlayerSize(width, height);
                player.setControlsSize();
            };

And calling it every time the window was resized.


text:
Q: JavaScript/JQuery String comparison not working or at least not the way I think it should? I have 2 - 2D arrays, "item" and "data2". data2 is a very large array which contains ~22k items that each have a second item(id[0] and name[1]) where as item is a variable length with 9 items each. I am trying to filter through the two arrays to match data[1] to item[0] which both contain the name of the item.
I have tried jQuery.inArray() which i have never used before so im not sure if it will work for sub arrays:
for(var i = 0; i < item.length; i++){
        console.log(jQuery.inArray( item[i][0].text, data2 ));
}

and then every way I could find or think of doing a normal string compare:
for(var i = 0; i < item.length; i++){
        for(var k = 0; k < data2.length; k++){
            if(String(item[i][0].val) == String(data2[k][1].val){
                item[i][6] = data2[k][1];
            }else{

            }
        }
    }

I am at a lot of why it wont compare the data. I have also used .text instead I am some what new to JS JQuery so not sure which one I should be using
Array:
item:
[0][0]"Armor Thermal Hardener II"
   [1]""
   [2]"Armor Hardener"
   [3]""
   [4]"Low"
   [5]"5 m3"
[1][0]"Armor Kinetic Hardener II"
   [1]""
   [2]"Armor Hardener"
   [3]""
   [4]"Low"
   [5]"5 m3"
[2][0]"Armor EM Hardener II"
   [1]""
   [2]"Armor Hardener"
   [3]""
   [4]"Low"
   [5]"5 m3"

data:
[0][0]"599"
   [1]"Armor Thermal Hardener II"
[1][0]"600"
   [1]"Armor Kinetic Hardener II"
[2][0]"601"
   [1]"Armor EM Hardener II"

A: For what I understood, you would be better using .filter; besides, I´m not sure about String constructor is ideal, as it will return a String object, which I´m not sure if will perform the comparation as expected; besides, if data2 is so large, I would put its iterator on top; try something like this instead:
for ( var i = 0; i < data2.length; i++ ){
    var it = item.filter(function(el){ return el[0] == data2[i][1]; });
    if (it.length){ //exists
        it[6] = data2[i][1];
    }
}

However, I don´t know what do you pretend using data2[k][1].val on a String; also, doesn´t make much sense to me to check if data2[k][1] is the same that item[i][0] and then assign the same value;  maybe you could explain what does .value means, and I could expand my answer


text:
Q: LINQtoSQL Data not Inserting into SQL Combact Edition
Possible Duplicate:
Why are my LINQ INSERTS not persisting in SQL Server CE 3.5?

I have a local database "Database1.sdf" and i'm trying to insert data into the table "User" using LinqToSql.
    public void DBTest()
    {
        string con = "Data Source=|DataDirectory|\\Database1.sdf";
        Database1 db = new Database1(con);
        User user=new User();
        user.ID=3;
        user.Name="testdata";
        db.User.InsertOnSubmit(user);
        db.SubmitChanges();

        var q = from t in db.User
                select t;
        foreach (var t in q)
        {
            Console.Out.WriteLine(t.Name);
        }
    }

The select query after the insertion works fine and shows the result, but the database is not updated. If i go and check the table manually it is empty. If i run the program again it doesn't throw any exception of primary key violation.

Thanks

A: Why are my LINQ INSERTS not persisting in SQL Server CE 3.5?


text:
Q: 2d array in C. Fixed width but unknown height? Is it possible to make an array with an unknown height but a set width?
So that It can be something like:
|----------8-----------|

[0][0][0][0][0][0][0][0]  |
[1][1][1][1][1][1][1][1]  |
[2][2][2][2][2][2][2][2]  |
[3][3][3][3][3][3][3][3] \|/

So that it can be as big as it needs but stays 8 floats wide.
I have a feeling that the declaration will look somewhat like:
    float *array[8] // maybe???

or
    float array[8][] // idk???

Im not used to multiple pointers on a var (I get confused still). I use apple's cocoa framework a lot so I would normally use NSArray but the thing I'm building requires a C-based array not a class.

A: Try this:
float (*array)[8];

...which declares array as a pointer to 8-element arrays of float.
You can then allocate space for the whole thing as follows:
array = malloc(sizeof(*array) * num_elements);

Then, array[3][0], for example, would access the first float in the 4th array of 8 floats.

A: float *array[8];

Now you have an array of 8 float pointers.
For each one of these, you would then need to allocate space when you know how large it needs to be:
array[0] = calloc(numMembers, sizeof(float));

If you later decided you needed a specific second dimension to be larger, you would need to reallocate.

A: Yes It definatly is:
  float *p2DArray[8];

  for (int i = 0; i < HEIGHT; ++i) {
    p2DArray[i] = (float*)malloc(sizeof(float)*WIDTH);
  }

taken from Multi-Dimensional Arrays

A: As an argument to a function, you can require a 2d array of unknown height, as so
void foo(int arr[][8])
{
     //...do stuff with arr...
}


text:
Q: Image color differences in different browsers. (Firefox, Chrome, IE) Oi!
I have a question regarding the differences in how images are being rendered inside of Firefox then in Internet Explorer. Firefox version is 3.5.19 and Internet Explorer version is MSIE 7.0.
Firefox http://www.wmclan.net/i/images/15877834356924635314.png
Internet Explorer http://www.wmclan.net/i/images/95502460007153569229.png
I was thinking a possible solution from Firefox 3.5 color correction hack? but is there a better way of doing that instead of running every single image through that process? How do I make it so that the images have the same background color as the background... I selected the color from the background with photoshop's color picker and used the same color code for each the image and the background image. This works fine with IE and also Chrome.. have not tested on other browsers.

A: This has to do with the gamma data that is added to the images. I thinks this is only a mac issue. The image is altered based on the gamma data, and doesn't match the css color values.
The solution you found is the only way to disable this "feature".
If you don't like the command line there is also easy drag and drop tool called PngThing.app for mac. I'm not using windows, so you'll have to google for that.


text:
Q: How to get all direct children of a BeautifulSoup Tag? How to retrieve (not recursively) all children using BeautifulSoup (bs4) ?

ABC

I want to get blocks like this :
block1 : A
block2 : B
block3 : C

I'm doing this way :
for j in soup.find_all(True)[:1]:
            if isinstance(j, NavigableString):
                continue
            if isinstance(j, Tag):
                tags.append(j.name)
                # Get siblings
                for k in j.find_next_siblings():
                    # k is sibling of first element

Is there a cleaner way to do that?

A: You can set the recursive argument to False if you want to select only direct descendants.
An example with the html you provided:
from bs4 import BeautifulSoup

html = "
ABC
"
soup = BeautifulSoup(html, "lxml")
for j in soup.div.find_all(recursive=False):
    print(j)

A
B
C


text:
Q: Acceder desde otra maquina por IP a proyecto, no muestra datos de select Necesito saber como solucionar o porque sucede lo siguiente...
Necesito hacer pruebas desde una laptop accediendo por IP a la maquina donde esta todo el proyecto, estando allí, se visualiza todo, los botones functions y demás, pero al abrir los formularios para algún registro o update, los select no cargan las información solo están en blanco y no puedo avanzar así, los select se cargan con información de la BD no son estáticos.
Las dos maquinas están en la misma red.
En la maquina donde esta el proyecto están activados los servicios de apache y mysql de XAMPP ademas que la BD esta en MARIADB de la misma.
Haciendo pruebas, si pongo datos estáticos en el html, de esta manera si aparece en la interfaz de la laptop. Pero es incorrecto.
Como puedo solucionar esto y que carguen los datos?

A: Ya he solucionado mi problema, en los JS para mandar a llamar una api, tenia la dirección de carpeta..
x.open('GET', 'http://localhost/WareHouse/apis/xxxx.php?getAll=true', true);

Solamente cambie el localhost por la ip de la maquina, quedando de la siguiente manera:
x.open('GET', 'http://192.168.0.1/WareHouse/apis/xxxx.php?getAll=true', true);

De esta manera en la maquina donde intento acceder ya cargan los combobox.


text:
Q: Chartkick.js how to remove x and y lines I have simple chart made with chartkick.js (http://chartkick.com/) - not in ruby. I just want to delete X and Y lines. Doesn't matter how.
I want remove lines which I marked with red color.
enter image description here
This is my code :
<script>
new Chartkick.LineChart("wykres-1", {"1":0,"2":20,"3":65,"4":120,"5":280,"6":370}, {"max": 370});
</script>


text:
Q: Node js - React : Fetching API request does not return any data I am trying to fetch an API request to obtain some information of research vessels.
I am trying to use the API from AIS Hub. After following their documentation and applying simple request such as:
http://data.aishub.net/ws.php?username=USERNAME&format=1&output=json&compress=1

I am still not able to obtain any data in return.
After launching a python -m SimpleHTTPServer 8000 on my terminal I obtain the following output:

Serving HTTP on 0.0.0.0 port 8000 ...
127.0.0.1 - - [24/Jan/2020 12:16:16] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/Jan/2020 12:16:16] "GET /boat.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Jan/2020 12:16:16] "GET /boat.js HTTP/1.1" 200 -

I know that at this point the fetch is probably not working. I am also not sure if I am putting correctly the request. If that useful here is the Sample tab that shows how data are structured.
Below the sample code I am using:
const btnSearch = document.getElementById('btnSearch');
const txtSearch = document.getElementById('boat');
const resultArea = document.getElementById('result');
let out = '';

btnSearch.onClick = function() {
    var searchTerm = txtSearch.value;
    const url = `http://data.aishub.net/ws.php?username=USERNAME&format=1&output=json&compress=3&latmin=20.5&latmax=30.8&lonmin=-15&lonmax=18.6=${searchTerm}`;
    console.log(url);
    fetch(url)
        .then(function(data) {
            console.log(data);
            return data.json();
        })
        .then(function(jsonObject) {
            console.log('Read This??????');
            console.log(jsonObject);
            for (boat in jsonObject) {
                const boatInfo = new Array(
                    jsonObject[boat].mmsi,
                    jsonObject[boat].time,
                    jsonObject[boat].longitude,
                    jsonObject[boat].latitude,
                    jsonObject[boat].cog,
                    jsonObject[boat].sog,
                    jsonObject[boat].heading,
                    jsonObject[boat].navsat,
                    jsonObject[boat].imo,
                    jsonObject[boat].name,
                    jsonObject[boat].callsign,
                    jsonObject[boat].type,
                    jsonObject[boat].a,
                    jsonObject[boat].b,
                    jsonObject[boat].c,
                    jsonObject[boat].d,
                    jsonObject[boat].draught,
                    jsonObject[boat].dest,
                    jsonObject[boat].eta
                );
                boatOut(boatInfo);
                console.log(boatInfo);
            }
            resultArea.innerHTML = out;
        })
        .catch(function(e) {
            console.log('Error' + e);
        });
};

function boatOut(boat) {
    console.log(boat);
    out += `

${boat[9]}

${boat[1]}

${boat[8]}

`;
}

What I have done so far:
I was researching on the official documentation and tried different combination of the API listed. I was trying to look for potential examples online but I could not find anything in particular. The way this API works is a little bit difficult for me to understand because it is different from the usual type that is possible to find for other applications (e.g. recipes, food etc).
I am running out of ideas as I don't know what else to try.
Thanks if someone already found in this situation and that can point to the right direction to solve the issue.

A: Looks like there are a couple of issues. The url appears to be malformed. I see you're using a test url from the "official document" link you provided. Please remove the template literal from the end of the url. Your url looks like this:  const url = http://data.aishub.net/ws.php?username=USERNAME&format=1&output=json&compress=3&latmin=20.5&latmax=30.8&lonmin=-15&lonmax=18.6=${searchTerm};  I removed the backticks for formatting reasons. Once you remove the template literal you will no longer need backticks and can switch to quotes.  Now your url should look like this: const url = "http://data.aishub.net/ws.php?username=USERNAME&format=1&output=json&compress=3&latmin=20.5&latmax=30.8&lonmin=-15&lonmax=18.6";  It appears based on the comments that your onclick function is never running. This is due to using camel case in onclick. You have:  btnSearch.onClick = function() {. Please change that to btnSearch.onclick = function() { Notice that onClick is now onclick. When using onclick in js it must be all lowercase.

A: I found the answer to my question and will post it so that it could benefit others. The problem I had was that a GET request had to be implemented otherwise nothing would be received. Below the working code if anyone needs:
const btnSearch = document.getElementById('btnSearch');
const txtSearch = document.getElementById('boat');
const resultArea = document.getElementById('result');
let out = '';

const fetchConfig = {
    method: 'GET',
    mode: 'cors'
};

btnSearch.onclick = function() {
    var searchTerm = txtSearch.value;
    const url = 'http://data.aishub.net/ws.php?username=My_KEY&format=1&output=json&compress=1';
    console.log(url);
    fetch(url, fetchConfig)
        .then(function(data) {
            console.log(data);
            return data.json();
        })
        .then(function(jsonObject) {
            console.log('Read This??????');
            console.log(jsonObject);
            for (boat in jsonObject) {
                const boatInfo = [
                    jsonObject[boat].mmsi,
                    jsonObject[boat].time,
                    jsonObject[boat].longitude,
                    jsonObject[boat].latitude,
                    jsonObject[boat].cog,
                    jsonObject[boat].sog,
                    jsonObject[boat].heading,
                    jsonObject[boat].navsat,
                    jsonObject[boat].imo,
                    jsonObject[boat].name,
                    jsonObject[boat].callsign,
                    jsonObject[boat].type,
                    jsonObject[boat].a,
                    jsonObject[boat].b,
                    jsonObject[boat].c,
                    jsonObject[boat].d,
                    jsonObject[boat].draught,
                    jsonObject[boat].dest,
                    jsonObject[boat].eta
                ];
                boatOut(boatInfo);
                console.log(boatInfo);
            }
            resultArea.innerHTML = out;
        })
        .catch(function(e) {
            console.log('Error' + e);
        });
};

function boatOut(boat) {
    console.log(boat);
    out += `

${boat[0]}

${boat[0]}

${boat[0]}

`;
}


text:
Q: How do I collect input from an external window using SDL? I'm currently trying to re-write my binder between Ogre and SDL in my game engine.  Originally I used the method outlined in the Ogre Wiki here.  I recently updated my version of SDL to 1.3 and noticed the "SDL_CreateWindowFrom()" function call and re-implemented my binder to allow Ogre to build the window, and then get the HWND from Ogre to be passed into SDL.
Only one window is made and I see everything renders properly, however no input is collected.  I have no idea why.  Here's the code I am currently working with (on windows):
OgreWindow = Ogre::Root::getSingleton().createRenderWindow(WindowCaption, Settings.RenderWidth, Settings.RenderHeight, Settings.Fullscreen, &Opts);
size_t Data = 0;
OgreWindow->getCustomAttribute("WINDOW",&Data);
SDLWindow = SDL_CreateWindowFrom(&Data);
SDL_SetWindowGrab(SDLWindow,SDL_TRUE);

I've tried looking around and there are a number of people that have done this to one degree of success or another(such as here or here).  But no one seems to comment on handling the input after implementing this.
I originally thought that maybe since SDL does not own the window it wouldn't collect input from it by default, which is reasonable.  So I searched the SDL API and only found that one function "SDL_SetWindowGrab()" that seems to relate to input capture.  But calling that has no effect.
How can I get SDL to collect input from my Ogre-made window?

A: It has been a while, but I figured I would put in the answer for others that may need it.  It turned out to be a bug/incomplete feature in SDL 1.3.  The "CreateWindowFrom" method wasn't originally intended to be used exclusively as an input handler.  At the time of this writing I know myself and another on my team wrote patches for Windows and Linux that permitted this use to work and submitted those patches to SDL.


text:
Q: Раcширеный поиск в yii2 Есть три таблицы (house, apartment, land_parts). На сайте есть поиск (расширенный поиск так сказать). К примеру:

Я хочу | (Купить, Продать, Аренда)
  Тип Недвижимости | (Дом, Квартира, Участок земли)
  Город | (New York, San Andreas, Vice City)

Есть соответственно три модели на каждую таблицу.
Нужно если пользователь выбирает "Тип Недвижимости" к примеру "Дом" то что бы запрос обрабатывался нужной моделью.
Получается что поле "Тип Недвижимости" не должно передаваться в форме, а должно быть как поле так сказать для выбора модели которая будет выполнять запрос.
Может кто-нибудь знает как это решить другим способом или может какой то плагин есть.

A: Если вы хотите сделать это в одном экшене, то это можно решить так (я кстати не особо понял как это выглядит во вью, если там из определенных значений выбор - значит там select ):
Вы передаете в селекте некий параметр, по которому будете видеть, какую модель нужно использовать; в экшене, через switch case, просто делаете условия для существующих вариантом, а по дефолту (default case) какое-то исключение, чтобы значения не подменялись, ну или то, что сами захотите.
Если мы говорим о разных вещах, то вам нужно расширить свой вопрос.


text:
Q: Python mouse event I am trying to activate a function in python which will save a timestamp to a file. However, I wish to activate that function after the first mouse click that accurses outside the Tk window.
For example, after running the program I will minimize it and press on the chrome browser icon and while doing so my program will log the time stamp.
I tried to use the bind function but it works for clicks that accrue only in the Tk window
By the way, I am currently using Tkinter as my GUI platform however if there is a way to do it with another libraries please share and I will adjust my program
thanks :)

A: Use the <FocusOut> event:
import tkinter as tk

root = tk.Tk()

def focus_lost(event):
    print("Clicked outside the window")

root.bind("<FocusOut>", focus_lost)

root.mainloop()

If you are focussed on the tkinter window (e.g. if you have clicked on it), then when you click elsewhere it will detect this as a <FocusOut> event.


text:
Q: In SQL, how can I count the number of values in a column and then pivot it so the column becomes the row? I have a survey database with one column for each question and one row for each person who responds. Each question is answered with a value from 1 to 3.
Id    Quality?  Speed?
--    -------   -----
1     3         1
2     2         1
3     2         3
4     3         2

Now, I need to display the results as one row per question, with a column for each response number, and the value in each column being the number of responses that used that answer. Finally, I need to calculate the total score, which is the number of 1's plus two times the number of 2's plus three times the number of threes.
Question  1    2    3    Total
--------  --   --   --   -----
Quality?  0    2    2    10
Speed?    2    1    1    7

Is there a way to do this in set-based SQL? I know how to do it using loops in C# or cursors in SQL, but I'm trying to make it work in a reporting tool that doesn't support cursors.

A: This will give you what you're asking for:
SELECT
    'quality' AS question,
    SUM(CASE WHEN quality = 1 THEN 1 ELSE 0 END) AS [1],
    SUM(CASE WHEN quality = 2 THEN 1 ELSE 0 END) AS [2],
    SUM(CASE WHEN quality = 3 THEN 1 ELSE 0 END) AS [3],
    SUM(quality)
FROM
    dbo.Answers
UNION ALL
SELECT
    'speed' AS question,
    SUM(CASE WHEN speed = 1 THEN 1 ELSE 0 END) AS [1],
    SUM(CASE WHEN speed = 2 THEN 1 ELSE 0 END) AS [2],
    SUM(CASE WHEN speed = 3 THEN 1 ELSE 0 END) AS [3],
    SUM(speed)
FROM
    dbo.Answers

Keep in mind though that this will quickly balloon as you add questions or even potential answers. You might be much better off if you normalized a bit and had an Answers table with a row for each answer with a question code or id, instead of putting them across as columns in one table. It starts to look a little bit like the entity-value pair design, but I think that it's different enough to be useful here.

A: You can also leverage SQL 2005's pivoting functions to achieve what you want.  This way you don't need to hard code any questions as you do in cross-tabulation.  Note that I called the source table "mytable" and I used common table expressions for readability but you could also use subqueries.
WITH unpivoted AS (
    SELECT id, value, question
    FROM mytable a
    UNPIVOT (value FOR question IN (quality,speed) ) p
)
,counts AS (
    SELECT question, value, count(*) AS counts
    FROM unpivoted
    GROUP BY question, value
)
, repivoted AS (
    SELECT question, counts, [1], [2], [3]
    FROM counts
    PIVOT (count(value) FOR value IN ([1],[2],[3])) p
)
SELECT question, sum(counts*[1]) AS [1], sum(counts*[2]) AS [2], sum(counts*[3]) AS [3]
    ,sum(counts*[1]) + 2*sum(counts*[2]) + 3*sum(counts*[3]) AS Total
FROM repivoted
GROUP BY question

Note if you don't want the breakdown the query is simpler:
WITH unpivoted AS (
    SELECT id, value, question
    FROM mytable a
    UNPIVOT (value FOR question IN (quality,speed) ) p
)
, totals AS (
    SELECT question, value, count(value)*value AS score
    FROM unpivoted
    GROUP BY question, value
)
SELECT question, sum(score) AS score
FROM totals
GROUP BY question


text:
Q: jQuery selector for first appearance of span in td I have the following HTML

I need to select the first appearance of span in each td.
I would exepcted 3 spans from the above HTML.
$('td span') returns all (4) spans
$('td span:first-child') return all spans also
$('td span:first') return only first
$('td > span') return only 2 spans.
Could I do this by selector or filter?
What do I have to use to achieve this?

A: After fixing the HTML, this will work:
$('td').find('span:first');

DEMO
The DEMO above uses the following sample HTML and visualy highlights the matching elements:

        span 1.1span 1.2
        span 2.1span 2.2
        span 3.1span 3.2

A: Try this:
$('td').find('span:first')

http://jsfiddle.net/qDAt8/
Please note that your markup is not valid.

A: $("table td").find("span:first")

Gives you the three first spans. jQuery finds element more efficiently when you provide a more detailed search.


text:
Q: Catching exception: error: svd() failed to converge I've written a function that uses Armadillo svd_econ function. I'm trying to handle the case where the svd fails to converge, because for some reason it doesn't abort the function in that case.
The error in question reads:
error: svd_econ(): failed to converge

Based on my reading of the SVD documentation, this should throw a std::runtime_error, and based on my reading of the Exceptions tutorial, I should be able to handle it like so:
arma::mat U, V;
arma::vec S;
try {
  // aDat and subsetRows are previously defined
  arma::svd_econ(U, S, V, aDat.rows(subsetRows), "right", "dc");
} catch (std::runtime_error e) {
  std::cout << "Exception caught!" << std::endl;
  // I want to abort, and return the error to R:
  throw Rcpp::exception(e.what());
}

However, when I run this code with a case that gives me the error message above, I get a segfault. If I remove the try-catch block, the code keeps going, and throws an error further down when the code tries to use the results of the SVD.
I assume I'm just missing something obvious since I haven't formally learnt any C++

A: Looks good, I'd just try a few things:

*

*a reference to the exception,

*just error forwarding to R, not another throw(),

*a default block with Rf_error()
So maybe (untested)
try {
  arma::svd_econ(U, S, V, aDat.rows(subsetRows), "right", "dc");
} catch (std::runtime_error & e) {
  std::cout << "Exception caught!" << std::endl;
  forward_exception_to_r(e);
} default(...) {
  Rf_error("Unknown exception");
}

but in essence you get all this for free via Rcpp Attributes as this is what the (automatically inserted) END_RCPP macro does --- see Section 2.7 of the Rcpp book for more details.
Edit But @mtall, in his comment, does what we should have done first: check the Armadillo docs. So you can simply check the return value.  But you may want to try the suggested try/catch as well.


text:
Q: How to set the computed value on a property of an object in Vuejs? Below is essentially psuedo code which gives context on where I might want to compute the value of a property on an object referenced in the data object
<template lang="html">

                <form action="" @submit.prevent="onSubmit">
                    <vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>

                        <input type="submit" class="btn btn-primary" value="Submit">

                </form>

</template>


text:
Q: Prevent "title" attribute of parent element from causing a browser flyover The good browsers all work such that an empty "title" attribute for an element means, "don't bother to show a title flyover here".  That makes sense, as a little white flyover with nothing in it (edit — or nothing but a space character) is, for most people, completely useless.
The designers of IE do not agree.
My problem is that I've got a little "what's this?" mechanism on a site that involves an absolutely-positioned
 containing a little graphic of a question mark. That
 has a "title" attribute with a question like, "What does the 'History Eraser Button' do?"  When you click on the question mark, a little "Help" bubble pops out and you can read about the topic. The idea of the "title" is that if the user mouses over the question mark, they see a question that's (hopefully) one they might be wondering about.
Well the problem with the "title" is that the pop-out "help" balloon is inside the absolutely-positioned
 so that it is correctly situated on the page. In other words, the absolutely-positioned
 just has "position: absolute", but it's allowed to be dropped on the page in the "right" place without any offset computation. The "help" balloon is thus in the right place sort-of automatically.  But: that "title" on the parent
 is pesky because the browser pops it up after the balloon is open. Why? because the "help" balloon is lexically contained in the outer
, even though the outer
 is just a little bitty thing with a question mark in it.
Thus solution #1 was to give the "help" balloon
 its own "title" attribute, with nothing in it (edit — I got that wrong; it's not nothing in the title, it's a space character). That works great, except in IE.  In IE now, that empty "title" attribute causes the browser to put up a little blank rectangle.  Helpful.
I could of course fiddle with the Javascript and just nuke the "title" attribute off the parent
 while the balloon is showing, but I'm curious about possible ways to "override" the parent element "title" in IE that can be done with nothing but markup. If it's not possible, then oh well.
Simple demo page: http://gutfullofbeer.net/title.html (try it with IE 7 or 8 to see the little empty white box)
edit — ha ha ha - when I change my code so that I explicitly null out the "title" attributes on all the parent elements, IE shows a flyover with the word "null" in it :-)

A: Why not assign the title to the question mark element (#qmark) instead of the containing div?
So instead of:

?

it would be

?

A: I don't think you can do what you want.  It seems like a hack anyway -- child DOM element attributes aren't meant to "override" parent attributes.  You should probably wrap the specific text with the correct title, such as this:
http://jsbin.com/ezipe

A: I ended up augmenting my existing code that opens/closes the "help" bubble so that it runs up the chain of parent elements and stashes the "title" code with the jQuery "data" facility. When the bubble closes, the titles are restored.


text:
Q: New to jest - how would I write a test for this method? I have this method below:
onViewed() {
  const { current } = this.state;
  this.slides[current] = { ...this.slides[current], viewed: true };

  const filtered = _.filter(this.slides,
    slide => slide.section === this.slides[current].section);

  if (filtered.every(slide => slide.viewed)) {
    this.onSectionComplete(this.slides[current].section);
  }
}

And I do not know Jest very well and wondered how you would unit test a method like this so that I can learn from it. I know that the expectation is whether the method 'onSectionComplete()' was fired or not but I don't know how would you set up to achieve this. I really appreciate your help.
Here is my test as is:
test('method onViewed()', () => {
  const wrapper = shallow(<TutorialCarousel {...mockProps} />);
  wrapper.instance().onViewed();
  expect(wrapper.instance().onSectionComplete).toHaveBeenCalled();
});

Thanks

A: You can put a spy on a method like this:
const onSectionComplete = jest.spyOn(TutorialCarousel.prototype, 'onSectionComplete');

const wrapper = shallow(<TutorialCarousel {...mockProps} />);
  wrapper.instance().onViewed();

expect(onSectionComplete).toHaveBeenCalled();


text:
Q: Making GPA calculator in java, need a little adjusting to finish it Ok so I've done pretty much all of it but can't figure out why the grades being put in aren't converting to the corresponding numbers and actually computing the gpa. If someone could please try and fix it so that it works properly, that would be awesome! Thank you.
here is the code I have:
import java.util.Scanner;

public class StudentGPA {

public static void main (String args[]){

//User inputs the number of classes he/she has
Scanner input = new Scanner (System.in);
System.out.println("Please enter the amount of grades you have");
int classes;
classes = input.nextInt();
String Grade = "";
int totalCredits = 0;
int totalCreditsEarned = 0;
int credits;
double gpa;
double number=0;

//String of if and else statements that set the number to the appropriate GPA
if(Grade.equals("A")){
number = 4.0;
} else if(Grade.equals("A-")){
number = 3.67;
} else if(Grade.equals("B+")){
number = 3.33;
} else if(Grade.equals("B")){
number = 3.0;
} else if(Grade.equals("B-")){
number = 2.67;
} else if(Grade.equals("C+")){
number = 2.33;
} else if(Grade.equals("C")){
number = 2.0;
} else if(Grade.equals("C-")){
number = 1.67;
} else if(Grade.equals("D+")){
number = 1.33;
} else if(Grade.equals("D")){
number = 1.0;
} else if(Grade.equals("D-")){
number = 0.67;
} else if(Grade.equals("F")){
number = 0;
} else {
number = 0;

//Loop that ends once the student has put information in on all his classes
for(int count = 0; count < classes; count++)
{

//Reads the number of credits each class was
Scanner input2 = new Scanner (System.in);
System.out.println("Please enter the number of credits this class was (A number)");
credits = input2.nextInt();
//reads the letter grade using the String Grade prompt
Scanner input3 = new Scanner(System.in);
System.out.println("Please enter your grade for this class (Capital letters such as A,           B+, C-)");
Grade = input3.next();

//algorithm for finding the GPA
totalCredits += credits;
totalCreditsEarned += (credits * number);
}
//for loop ends

//GPA is calculated for all the students classes
gpa = totalCreditsEarned / totalCredits;

//GPA is printed to the screen
System.out.println(gpa);
}
}

}`

A: easy fix, put your if block in the loop.
before the algorith for finding the gpa


text:
Q: Matching end of ine in GREP I have this piece of bash script which is supposed to match words that end with an 'a'. However, when I run this, I get no output, despite the fact that my text file has words that end with 'a'.
cat $1 | cut -d'|' -f3 | cut -d',' -f2 | sed 's/^ //' | egrep -i "a$"

If I remove the '$' it shows output, but with '$' it returns nothing. It still works, just doesn't match.
Would appreciate some help with this. Thanks.
A sample of the file

MTNG1511|5013566|Xin, Mackenzie Darren MTNG9902|5079970|Park, Xue
  Hannah Vanessa MTNG1511|5059072|Chung, Michael Jia Tianyu
  MTNG1521|5060774|Lim, Stephanie Lauren MTNG1531|5060774|Lim, Stephanie
  Lauren MTNG2521|5060774|Lim, Stephanie Lauren MTNG9020|5060538|Bi,
  Samuel Shiyu MTNG9021|5060538|Bi, Samuel Shiyu MTNG9902|5072116|Hu,
  Kai Zhi Patrick

Output should be

Park, Xue Hannah Vanessa

Since it ends with an 'a'

A: There's probably extra whitespace at the end of your word.
Try adding
sed 's/[ \t]*$//'

to remove the whitespace -- or else change your grep to allow for whitespace at the end.

A: This is very simple using grep
grep -o '[^\|]\+$' < "$1" | grep 'a\s*$'

Output
$ bash example file.txt
Park, Xue Hannah Vanessa
$

[^\|]\+ match one or more characters that aren't | to the end of the line.
a\s*$    match a as last character but check for some spaces before the line feed.


text:
Q: What is $f(r\cos(\theta), r\sin(\theta))$ equal to $1$ in this double integral? Use a double integral to find the area of the region.
The region inside the circle
$(x − 2)^2 + y^2 = 4$
and outside the circle
$x^2 + y^2 = 4$.
I understand how to get the limits of integrand for this region on $r$ and $\theta$, but when you set up the integral it is as follows.
The general form of a double integral in polar is:
$$\iint f(r\cos(\theta), r\sin(\theta)) r \, dr \, d\theta$$
However when evaluating this integral it becomes:
$$\iint r \, dr \, d\theta$$
Can someone please explain why
$$f(r\cos(\theta), r\sin(\theta)) =1$$
here?

A: You are integrating to find the area.  If $f(x, y)$ is any constant, $f$, then $\iint f \,dA=  f\iint dA= fA$ where $A$ is the area of the region of integration.  In particular, since we are trying to find the area, we want to take $f= 1$: $\iint dA= A$.


text:
Q: Method ReflectionParameter::getClass() is deprecated, even after downgrading php version to 7.4 I am having difficulty with Method ReflectionParameter::getClass() is deprecated, as suggested by many other posts, I downgraded the php version to 7.4, which didn't help. I am new to the php, so might not understand
downgraded php to 7.4.33


text:
Q: What does this long sentence mean and what kind of structure does it have?
Repetitive, pulse-driven figures have remained a characteristic, but so have the slips and leaps of a lively mind.

'but so have (...)' part of the sentence confuses me a lot. Does the verb 'remain' affect the part after the second comma or not? How do I determine this? I comprehended the sentence in two slightly different ways:

*

*Repetitive, pulse-driven figures have remained a characteristic, but they also have remained the slips and leaps of a lively mind.

*Repetitive, pulse-driven figures have remained a characteristic, but they also have had the quality of slips and leaps of a lively mind.

I don't understand the structure of this long sentence; thus, I don't understand the meaning.
The source (requires a subscription and/or institutional login): https://doi.org/10.1093/omo/9781561592630.013.90000334653
For the people who don't have an access to the article:

A: The first comma is to separate elements of a list. The second comma is separating two independent clauses. See this thread.
You can rephrase the sentence to see the structure better:

A, B and C have remained characteristic, but so have D, E and F.

The sentence says that the artist's music developed over time without abandoning the underlying core principles. The music still has the characteristic repetitive and pulse-driven figures it originally did, but it also still displays the "slips and leaps of a lively mind", whatever that means.
"slips and leaps of a lively mind" could mean dynamic evolution, reinvention or freshness but that is not clearly explained in the provided excerpt.


text:
Q: Unity Facebook Parse Login gets stuck using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;
using Parse;
using System;
using System.Threading.Tasks;

public class FacebookLogin : MonoBehaviour
{
    #region Variables
    // Inspector Assigned.
    public Text _Username;

    // Private.
    private static Dictionary<string, string> _Profile          = null;

    // Store searched friends data.
    #endregion

    #region Functions
    public void Awake()
    {
        FB.Init( SetInit, OnHideUnity );
        ParseClient.Initialize( "IdidPutThis", "AlsoThis" );
    }
    #endregion

    #region Setup
    void SetInit()
    {
        if( FB.IsLoggedIn )
            OnLoggedIn();
    }

    void OnHideUnity( bool shown )
    {
        if( shown )
            Time.timeScale = 1f;
        else
            Time.timeScale = 0f;
    }
    #endregion

    #region Login
    void OnLoggedIn()
    {
        // Request player info and profile picture.
        FB.API( "/me?fields=id,first_name", Facebook.HttpMethod.GET, OnLoginCallback );
        LoadPictureAPI( Util.GetPictureURL( "me", 128, 128 ), MyPictureCallback );
    }

    void LoginCallback( FBResult result )
    {
        if( FB.IsLoggedIn )
            OnLoggedIn();
    }
    #endregion

    #region Callbacks
    void OnLoginCallback( FBResult result )
    {
        if( result.Error != null )
        {
            Debug.Log( "Trying again.." );
            FB.API( "/me?fields=id,first_name,invitable_friends.limit(100).fields(first_name,last_name,id,picture.width(128).height(128))", Facebook.HttpMethod.GET, OnLoginCallback );
            return;
        }
        else
            StartCoroutine( "ParseLogin" );

        // Get user profile, and invitable friends list.
        _Profile          = Util.DeserializeJSONProfile( result.Text );

        _Username.text = "Name: " + _Profile[ "first_name" ];
    }

    private void appRequestCallback( FBResult result )
    {
        if( result != null )
        {
            var responseObject = Json.Deserialize( result.Text ) as Dictionary<string, object>;
            object obj = 0;

            if( responseObject.TryGetValue( "cancelled", out obj ) )
                Util.Log("Request cancelled");
        }
    }

    void MyPictureCallback( Texture texture )
    {
        if( texture == null )
        {
            // Let's just try again
            LoadPictureAPI( Util.GetPictureURL( "me", 128, 128 ), MyPictureCallback );
            return;
        }

//      GlobalVars._ProfilePic = texture;
    }

    IEnumerator ParseLogin()
    {
        if( FB.IsLoggedIn )
        {
            Debug.Log( "SHIT" );
            var loginTask = ParseFacebookUtils.LogInAsync( FB.UserId, FB.AccessToken, DateTime.Now );

            while( !loginTask.IsCompleted )
            {
                Debug.Log( "Testing..." );
                yield return null;
            }

            if( loginTask.IsFaulted || loginTask.IsCanceled )
                Debug.Log( "PARSE ERROR" );
            else
                Debug.Log( "Parse login successful" );
        }
    }

    #endregion

    #region Click Functions.
    public void Login()
    {
        if( FB.IsInitialized )
            FB.Login( "public_profile,user_friends,email", LoginCallback );
    }
    #endregion

    #region Picture
    delegate void LoadPictureCallback( Texture texture );

    IEnumerator LoadPictureEnumerator( string url, LoadPictureCallback callback )
    {
        WWW www = new WWW( url );
        yield return www;
        callback( www.texture );
    }

    void LoadPictureAPI( string url, LoadPictureCallback callback )
    {
        FB.API(url,Facebook.HttpMethod.GET,result =>
               {
            if (result.Error != null)
            {
                Util.LogError(result.Error);
                return;
            }

            var imageUrl = Util.DeserializePictureURLString(result.Text);

            StartCoroutine(LoadPictureEnumerator(imageUrl,callback));
        });
    }

    void LoadPictureURL (string url, LoadPictureCallback callback)
    {
        StartCoroutine(LoadPictureEnumerator(url,callback));

    }
    #endregion
}

Facebook logs in, and I display the users name, which works correctly. However it gets struck when logging in Parse, it just keeps logging "Testing..." in the debug log. No errors are shown, it just doesn't proceed.
Using Unity 5.0.1p1, the latest Facebook SDK, and Parse SDK.
Thanks


text:
Q: Perl GD does not draw circles, instead it draws a rectangle every time I recently discovered the Perl module GD and I wanted to try it out a little bit.
So far I haven't got any problems creating a new object, allocating a color and redirecting the whole bunch of data into a file.
The problem came up as I opened the image file in a viewer:
No matter what I changed, it just displayed a rectangle. And to make fun of me it only got the right color (blue).
What is wrong? Is the creation of a circle not correct?
I will keep trying, but any help is appreciated.
Thanks in advance for your help!
This is my code so far:
my $image1 = new GD::Image(100,100);
my $blue = $image1->colorAllocate(0,0,255);
$image1->arc(100,100,50,50,0,360,$blue);
my $print = $image1->png;

open(IMG,">","/home/bernd/perl/pie.png");
binmode IMG;
print IMG $print;
close(IMG);

A: I believe the problem was that the background and foreground were the same color.
Here's a working example which draws a blue circle on a transparent
background:
use GD::Image;
use File::Slurp;

my $image1 = GD::Image->new(100,100);
my $white = $image1->colorAllocate(255,255,255);
my $blue = $image1->colorAllocate(0,0,255);
$image1->transparent($white);
$image1->interlaced('true');

$image1->arc(50,50,100,100,0,360,$blue);

write_file("/home/bernd/perl/pie.png", $image1->png);

I also updated the object creation to avoid using using the indirect
object notation style of new GD::Image() which is not recommended. File::Slurp was used to clean up writing out the file.
If you are new to image manipulation with Perl, I recommend that you
also check out Imager.pm, which has a more modern design.

A: try adding :
my $image1 = new GD::Image(100,100);
my $white = $image1->colorAllocate(255,255,255);
my $blue = $image1->colorAllocate(0,0,255);

you are drawing the arc in the same color as your background