text:
Q: Find the maximum values of a variable in a list I have a list of the following structure & I intend to find the maximum value of X2 in the second variable (b) in the list
sample data
[[1]]

[[1]]$a

[1] 2

[[1]]$b

   X1  X2
1  58 1686729

2 106 1682303

[[2]]

[[2]]$a

[1] 3

[[2]]$b

   X1  X2

1  24 1642468

2  89 1695581

3 156 1634019

I looked into multiple filters that can be applied to the list like:
library(rlist)
list.filter(result, max(b$area))

and also tried lapply but with no success
lapply(result, function(x) x[which.max(x$b)])

I need the following output:
a      x1    x2
2      58   1686729
3      89   1695581

A: With lapply() you can find the max of X2 in $b in each list, then cbind() with the a element.
l_max <- lapply(l, function(x) {
  b <- x$b
  cbind(a=x$a, b[which.max(b$X2),])
})

Use bind_rows() from dplyr for binding together.
l_max %>%
  dplyr::bind_rows()
#     a X1      X2
# 1   2 58 1686729
# 2   3 89 1695581

Example data:
l <- list(
  list(a = 2,
       b = data.frame(X1 = c(58, 106),  X2 = c(1686729, 1682303))),
  list(a = 3,
       b = data.frame(X1 = c(24, 89,156),  X2 = c(1642468, 1695581,1634019)))
)

With your example:
l_max <- lapply(l, function(x) {
  b <- x$b
  cbind(a = x$a, b[which.max(b[,2]),]) # NOTICE I used [,2] to refer to the second column
                             #b$area works too if all df share the col name
})

l_max %>%
  dplyr::bind_rows()
#   a  rt    area
# 1 2  58 1686729
# 2 3  89 1695581
# 3 4 101 1679889
# 4 5  88 1695983
# 5 6 105 1706445
# 6 7 121 1702019

Another solution with purrr::map_df() avoids the use of bind_rows():
purrr::map_df(l, function(x) {
  b <- x$b
  cbind(a = x$a, b[which.max(b[,2]),])
})

All base R using mapply():
t(mapply(function(x) {
  b <- x$b
  cbind(a = x$a, b[which.max(b[,2]),])
}, l))

Or with Map():
do.call("rbind", Map(function(x) {
  b <- x$b
  cbind(a = x$a, b[which.max(b[,2]),])
}, l))

A: You can also use sapply():
t(sapply(list, function(elem){
  c(a = elem$a, elem$b[which.max(elem$b$area), ])
}))


text:
Q: Is it legal to for commercial software to a free package and not contribute anything significant? Say there is a npm package which enables me to do functionality A. Say I write a wrapping software which basically just offers functionality A, just packages it more nicely but -apart from that- is nothing more.
Would it be legal to sell this software? Does the original contributor of functionality A (the person who wrote the npm package) get anything?
I feel like some people have done some great work, and I don't understand how it's possible that I can just use their packages and, theoretically, sell them as mine (as it were). Or am I misunderstanding some fundamental things here?

A: Generally the answer is:

*

*Yes you are allowed to sell it (most of the time).

*Pretty much any software you buy these days includes free software

More detailed:

*

*there are really many licenses. Start with https://spdx.org/licenses/.

*the license of the original package may not allow the selling part. This is very rare

*Sometimes you need to distribute your code (e.g. GPL3) but you can sell the software.

*Most free licenses try to make sure the work gets reused and sometime add conditions that they or their software gets attributed. They are not so much interested in money

Where to ask these questions:

*

*https://opensource.stackexchange.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix error "GLib-GIO-ERROR**: No GSettings schemas are installed on the system"? I have to create a one-file (.exe) program with InstallShield2015LimitedEdition that works with GTK3.4.2 and OpenCV 3.0.0 in Windows 7 x64. In this program the user can choose a directory from their computer. But when I invoke FileChooser (click on executable) I get this error:
GLib-GIO-ERROR**: No GSettings schemas are installed on the system

and the program terminates.
I visited these pages:
Glib-GIO-ERROR when opening an file chooser dialog
GLib-GIO-ERROR**: No GSettings schemas are installed on the system
How deal with FileChooser in GTK with static compilation
But I never understood exactly how to fix this error. It is related to org.gtk.Settings.FileChooser.gschema.xml file in this path: ...\share\glib-2.0\schemas.
Is it related to system environment variable? What things should I add to it?

Add to system variable or User variable? What is name and path?
For example. I added GSETTINGS_SCHEMA_DIR as variable name and E:\Works for Gov Project\Help\Source codes for GTK+\gtk+-bundle_3.4.2-20130513_win64\share\glib-2.0\schemas as path for both of system variable and User variable.
Is this correct?

A: I solved it:
First: add GSETTINGS_SCHEMA_DIR as variable name and E:\Works for Gov Project\Help\Source codes for GTK+\gtk+-bundle_3.4.2-20130513_win64\share\glib-2.0\schemas as path for User variable.
Then, in system variable ---> path add E:\Works for Gov Project\Help\Source codes for GTK+\gtk+-bundle_3.4.2-20130513_win64\share\glib-2.0\schemas with ; in first it, e.g. ;E:\Works for Gov Project\Help\Source codes for GTK+\gtk+-bundle_3.4.2-20130513_win64\share\glib-2.0\schemas


text:
Q: Angular drag & drop: How to prevent an item from being dropped in an unwanted list I'm trying to use the drag and drop feature provided by angular material to be able to move items from the Options list to either the Incude or Exclude list(whatever is enabled depending on the selected radio button in the Where to move group)

So far it works, but there's something weird when only the Include list is enabled.
If I try to move an item to the Exclude list, instead of item the being returned to the Options list, it is added to the Include list. It only works as expected if I drag the item without hovering over the Include list.

Is there any way to prevent the item from being dropped inside the Include list when what I wanted to do was to drop it inside another list?
BTW, this has nothing to do with the Exclude list being disabled. I already tested this having both lists enabled and always wins the first list I passed on my way to dropping the item in the desired list.
Here's a demo in stackblitz

A: The drag and drop library saves the last active container and adds the draggable item to it when it's dropped. Which means if you drag an item over the Include list before you drop it on the invalid Exclude list, the last active container is still the Include list.
It's possible to use event.isPointerOverContainer in your drop method to check if it's dropped outside a dropcontainer. The disadvantage of this is the animation still returns the item back to the Include list first..


text:
Q: Solve inheritance dependency in a functional approach The problem:

Inheritance dependency

*

*Type A stores a value of type B in a property

*Type B inherits from type A
We'll consider a UI control hierarchy, where every control belongs to a top-level "Form", and the Form itself is a Control.

The author solves this problem by parameterizing classes:
[<AbstractClass>]
type Control<'Form>(name) =
    member this.Name = name

    abstract Form : 'Form

type Form(name) =
    inherit Control<Form>(name)

    override this.Form = this

type Button(name,form) =
    inherit Control<Form>(name)

    override this.Form = form

let form = new Form("form")
let button = new Button("button",form)

But how can I redesign in a functional approach: "We would not be using inheritance at all. Instead, we would use composition in conjunction with parameterization"?

A: This question is hard to answer, because the formulation of the question is inherently object-oriented. When you say "form is a control", the "is a" part of the question hints at an OO way of modelling the world that you would not typically use in functional programming.
Strictly speaking, your sample code does not actually do anything useful - it creates a bunch of objects, but does not use them to render any user interface or implement any other functionality.
Of course, I suspect this is what the question is getting at. If I wanted to model a very simple user interface that includes forms and buttons, I might start with something like this:
type SimpleControl =
  | Button of string
  | Label of string

type ContainerControl =
  | Form

type Control =
  | Container of ContainerControl * Control list
  | Simple of SimpleControl

This lets you define container controls (such as form) that can contain other controls and buttons and labels, which are simple controls and cannot contain other elements. This is just an example though - depending on what kind of user interfaces you actually want to build and what you want to do with them, you would define the types differently.
The short version is, functional programming often requires a different way of thinking and some of the questions that make sense in object-oriented world do not make sense in the functional world.


text:
Q: FormatMessage to a different language Is it possible to translate system error codes to a specific language?
I can only pass MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) to FormatMessage. Otherwise, function call fails with 15100 (The resource loader failed to find MUI file).
Where are system error messages stored? Why can't I load a message in a locale different from the system one?

A: Basically MUI stands for multilingual user interface.   These are language packs. In windows one won't get them by default. Instead they have to install
Below link helps you regarding procurement.
https://support.microsoft.com/en-us/help/14236/language-packs
By default the above page displays for windows 10 .  there is a drop down option to select for the other versions of windows.
If you have difficulty with above link, search in google for MUI language pack for windows 10 or any other version.

A: Use zero for language id, not MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US). Then FormatMessage will pick the resource based on thread's language id, or it uses GetUserDefaultLangID.
FormatMessage documentation:

DWORD WINAPI FormatMessage(
  _In_     DWORD   dwFlags,
  _In_opt_ LPCVOID lpSource,
  _In_     DWORD   dwMessageId,
  _In_     DWORD   dwLanguageId,
  _Out_    LPTSTR  lpBuffer,
  _In_     DWORD   nSize,
  _In_opt_ va_list *Arguments
);

dwLanguageId:
If you pass a specific LANGID in this parameter, FormatMessage will
  return a message for that LANGID only. If the function cannot find a
  message for that LANGID, it sets Last-Error to
  ERROR_RESOURCE_LANG_NOT_FOUND. If you pass in zero,
  FormatMessage looks for a message for LANGIDs in the following
  order:

*

*Language neutral

*Thread LANGID, based on the thread's locale value

*User default LANGID, based on the user's default locale value

*System default LANGID, based on the system default locale value

*US English


text:
Q: On VirtualBox, how to launch multiple instances of a VM that uses the .vmdk format? On VirtualBox, how to launch multiple instances of a VM that uses the .vmdk file format?
That mean, what are the alternates to do and run multiple copys or clones of the VM?
Possible small hint:
VirtualBox can run virtual hard disk files at minimum on follow modes:

*

*changeable

*carbon-less

*shareable

*multiple connectable...

A: I understand that you have a single disk image that contains, say the root filesystem of a run-able Ubuntu instance and you want to create more than one virtual machine that will run this Ubuntu disk image.
One option would be to clone your VirtualBox instance.
But, if you want to do this by using the same disk image for multiple virtual machines then you can change the Type of this disk image to Multi-attach.
According to VirtualBox documentation (section 5.4) the disk format (VMDK, VDI, etc.) is irrelevant to this.
Multi-attach mode disk images can be attached to more than one virtual machines at the same time, even if these machines are running simultaneously. For each virtual machine to which such an image is attached, a "differencing" image is created (under the Snapshots directory of the VM's VirtualBox definition directory). As a result, any data that is written to such a virtual disk by one machine is not seen by the other machines to which the image is also attached. Each machine creates its own write history of the multi-attach image and the original disk image is never updated.
A multi-attach type disk is like an immutable disk image, except that the "differencing" image is not reset every time the machine starts. In other words, the changes made by each virtual machine are persistent between VM restarts and this means that the "differencing" image of a VM is going to grow as the VM makes updates on the "multi-attach"ed disk.
Note that according to the documentation,

This mode is useful for sharing files which are almost never written,
for instance picture galleries, where every guest changes only a small
amount of data and the majority of the disk content remains unchanged.
The modified blocks are stored in differencing images which remain
relatively small and the shared content is stored only once at the
host.

IMHO a multi-attach type disk can be used for an operating system's root partition (I haven't tested though). However, I don't see any real advantage over creating clones.


text:
Q: php send user password via email We all know we shouldn't be storing user passwords as plain text on
the database. However I have seen some sites that have implemented
a send-forgotten-password feature. So if I ask my password, I type
my email and they send the password.
Note: I'm not talking about a password change (http://sample.com/forgot_pass?token=ddm39fhksnc)
How do these sites achieve it? They store plain passwords on their
databases (maybe a different database) because as far as I know you
can't reverse a password hash to the original string it was built from...
Is there anyway this feature can be implemented securely? Or I should
convince clients to stick with forgot-pass-link method.
Thanks.

A: If they are able to send you your password then they are storing your password in plain text.
Note that you can find out the original password from the hash if a deprecated hash function was used (like md5).
There is no way of doing it securely. If your database gets breached the attacker will be able to read out all the passwords and corresponding email addresses/usernames. If your users re-use the same password for different sites (which most people do) what can happen.
Even if there would be a "secure" way of finding out the password from its hash, what stops the attacker from doing the same?

A: Such a feature cannot be implemented securely. If the application can retrieve the original password (e.g. from an encrypted password), a successful attacker can retrieve the passwords as well. That's why one should use a hash function like BCrypt, SCrypt or PBKDF2.
Another weakness is sending the password at all per e-mail. A better way is to send a token, and let the user choose his own password after confirmation. The same code can be used to register a new user and to reset a password.

A: You open the door to major security issues if you store the actual password in the database. But if in fact you must resend their password to them, one way you could do it, is when they register, store the password in a text file located outside of the public directory.
Then create some sort of naming logic that associates the record to the text file. And then from there, make it so the only way you can access that text file is with the proper security checks in place, and then via your script.

A: My solution is adding two field in table "user" in my database: "token" field and "expired_time" field.

*

*When user send a request to reset password, your application will update token string and expired time to reset password for that user.

*Send an email with link has username (or email, or id,...) and token like http://example.com/resetpassword.php?id=userid&token=token

*In resetpassword.php, you will check authentication by userid, token and in expired time (maybe 5 minutes)

*Allow user to change their password.
This is my solution, I hope it'll helpful :)


text:
Q: Why does an INSERT take time when using subqueries  INSERT INTO TableA
    SELECT
       x,
       y,
       z
          FROM TableB
            WHERE x IN
                     (select DISTINCT x
                           FROM TableC
                               WHERE x NOT IN
                                             (SELECT DISTINCT x from TableD)
                     )

This query takes forever and it doesn't complete.
When I run the each select query it works fine but when I run it all it takes forever? Can you see the reason?

A: Try this query :
insert into TableA
select b.*
from TableB b               --with(nolock)
left outer join TableC c    --with(nolock)
on b.x = c.x
left outer join TableD d    --with(nolock)
on c.x = d.x
where c.x is not null and d.x is null

if it is also running infinite then uncomment with(nolock) and try again. if it does not work then check estimated execution plan.

A: Firstly you need to look at the execution plan for the query - it might tell you where the bottlenecks are or if there are missing indexes that would significantly speed up your query - I think this is likely as your query is simple so I don't see why it would take so long;

I think you could also restructure you query so that it uses Joins instead of the not in - it would help if i knew the data to see if this produced the same results, But i think it should;
    SELECT  B.x,
        B.y,
        B.Z
FROM TableB B
INNER JOIN --where in
    (
        SELECT DISTINCT x
        FROM TableC c
        LEFT JOIN TableD d
            ON c.x = d.x
        WHERE d.x IS NULL -- c x not in d x
    ) sub
on B.x = sub.x

A: Subqueries and DISTINCT when not needed are notoriously poor for performance.  You can accomplish what you need using JOINs.
SELECT b.x, b.y, b.z
FROM TableB b
INNER JOIN TableC c ON c.x=b.x
LEFT JOIN TableD d ON d.x=b.x
WHERE d.x IS NULL
GROUP BY b.x, b.y, b.z  -- only if you have duplicates and need unique records

The INNER JOIN on TableC fixes your 1st "IN", then the LEFT JOIN and d.x IS NULL fixes your "NOT IN" clause.
Lastly, make sure that you have indexes on the "x" column in each table.
CREATE INDEX IX_TableB_X ON TableB (X);
CREATE INDEX IX_TableC_X ON TableC (X);
CREATE INDEX IX_TableD_X ON TableD (X);


text:
Q: "tax cannot be resolved to a variable" I am in the process of debugging. The code is supposed to take the cost and calculate the new price. I'm not sure what I am missing.
    import javax.swing.JOptionPane;
        public class DebugTwo4 {
        public static void main(String[] args) {

          String costString;
          /* added semicolon */
          double cost;
          final double TAX = 0.06;
          costString = JOptionPane.showInputDialog("Enter price of item you are buying", "Purchases",
             JOptionPane.INFORMATION_MESSAGE);
          cost = Double.parseInt(costString);
          JOptionPane.showMessageDialog(null,"With " + tax * 100 +
             "% tax,  purchase  is $" + (cost - cost * tax));
       }

}

A: Java IS case-senstive.
Change 'tax' to 'TAX'.
// old: JOptionPane.showMessageDialog(null,"With " + tax* 100 + "% tax,  purchase  is $" + (cost - cost * tax));
JOptionPane.showMessageDialog(null,"With " + TAX * 100 + "% tax,  purchase  is $" + (cost - cost * TAX));


text:
Q: Automated running .bat with commands I have a automated.bat with the following lines:
cd C:\Users\user\Downloads\megatools-1.9.97-win64\megatools-1.9.97-win64\
megacmd.bat
megals /Root --username username@email.domain --password password
megamkdir /Root/testmake2 --username username@email.domain --password password

It will happily say the megacmd.bat is Megatools Shell, but then it won't excecute the commands that follow.
I figured it might be because the megacmd.bat is in a different programming language, hence the incomming commands aren't valid.
So I tried to fit it all in 1 line with:
cd C:\Users\a\Downloads\megatools-1.9.97-win64\megatools-1.9.97-win64\
megacmd.bat & megals /Root --username username@email.domain --password password & megamkdir /Root/testmake2 --username username@email.domain --password password

but that didn't do anything with the commands either so I also tried:
cd C:\Users\a\Downloads\megatools-1.9.97-win64\megatools-1.9.97-win64\
megacmd.bat & "megals /Root --username username@email.domain --password password" & "megamkdir /Root/testmake2 --username username@email.domain --password password"

And
cd C:\Users\a\Downloads\megatools-1.9.97-win64\megatools-1.9.97-win64\
megacmd.bat "megals /Root --username username@email.domain --password password" & "megamkdir /Root/testmake2 --username username@email.domain --password password"

And
cd C:\Users\a\Downloads\megatools-1.9.97-win64\megatools-1.9.97-win64\
megacmd.bat megals /Root --username username@email.domain --password password & megamkdir /Root/testmake2 --username username@email.domain --password password

But I can't seem to get the syntax right. What would be the command to have the megacmd.bat run and execute the above 2 commands consecutively?

A: your line
megacmd.bat

starts megacmd.bat and gives control to it. It never returns to your automated.bat.
You should
call megacmd.bat

to return control to your first .bat after megacmd.bat finishes.


text:
Q: Calculate distance from a point to a body of water We have a requirement to calculate the distance between a point and the nearest body of water (or other area, e.g. a geothermic area).
I have no idea where to start but my guess would be loading a subset of some publicly available water body data in to the database (postgresql) (currently we're only concerned with New Zealand), and then querying that data somehow.
My major sticking points (due to lack of direction) would be how to get the data loaded into the database, how to query for the distance from a point to the nearest edge of the water body shape, and also how to provide a user-friendly interface where this data could be added to (e.g. to add those geothermic areas).
I guess I don't want to reinvent the wheel if there are tools already out there to do this.


text:
Q: My NetBeans is showing my GUI chars cut and disappear Every time I run certain GUI interface excercises using swing the program works perfectly but something is wrong with what I suspect might be the jdk or something as it also happens like this on Eclypse.
It first appears to show correctly but with mouse over or when entering data in a textfield it all shows distorted.
Has anyone encountered these problems?

A: I managed to fix the problem re-installing the drivers to my graphics card!
Thank you.
Hope this helps anyone in the future with the same issue


text:
Q: When using parallelStream, a child thread throws an exception In a Spring Boot application, I'm writing files to S3 using list.stream().parallel().forEach. When trying to get the resource using resourceLoader.getResource(filePath), it throws the exception 'com.amazonaws.services.s3.AmazonS3 referenced from a method is not visible from class loader'. I've noticed that the main thread successfully writes the files, but the child thread throws an exception.
getAccountCommonList()
                .stream().parallel()
//                    .stream()
                .forEach(fileNumber -> {
                    String filePath =
                            "s3://xxxxx.net/Debug_"
                            + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmm"))
                            + "_"
                            + fileNumber;
                    WritableResource resource = (WritableResource) resourceLoader.getResource(filePath);

                    try (OutputStream outputStream = resource.getOutputStream()) {
                        write(outputStream);
                    } catch (IOException e) {
                        System.console().printf(e.getMessage(), e);
                        throw new RuntimeException(e);
                    }
                });

If I don't use parallel(), the code executes successfully.
I'd like to know how to proceed if I need to use parallel().
Could it be because the child thread cannot access the applicationContext?
Is it possible that the applicationContext is bound to the main thread through ThreadLocal?


text:
Q: Is there a way to redirect INSTALLDIR to another directory? is there a way to point the INSTALLDIR to another folder instead of C:\Program Files?
I have created a WIX installer for our MS-Outlook Add-In and I would like to have the VSTO installed in C:\ProgramData\MyCompany\MyCompanySoftwareProduct.
Is there a way to do this? I am currently using a WIXUI Installer and it defaults to C:\Program Files.
Thank you very much in advance.

A: Yes, use the following:
<Product ...>
    <Property Id="WIXUI_INSTALLDIR" Value="INSTALLFOLDER" />
</Product>

<Fragment>
    <Directory Id="TARGETDIR" Name="SourceDir">
        <Directory Id="CommonAppDataFolder">
            <Directory Id="YourCompanyFolder" Name="YourCompany">
                <!-- other nested directories -->
            </Directory>
        </Directory>
    </Directory>
</Fragment>


text:
Q: The largest integer dividing these $(n+19)(n+18)(n+17)(n+16)$
The largest integer that divides $(n+19)(n+18)(n+17)(n+16) ~ \forall ~ n \in \mathbb{N}? $ is?

It struck me that we should write this as:
$\dbinom{n+19}{4}\times 4!$
which is always divisible by $4!$. Now I am confused as to how do I take it from here? Because the question asks for largest positive integer.
Edit:
Is there no alternative to brute force method i.e. checking for few values then assuming the event would never occur?

A: Let $f(n) = (n + 16)(n + 17)(n + 18)(n + 19)$.
Then we have that
$$
  \gcd(f(1), f(4), f(5)) = \gcd(17 \cdot 18 \cdot 19 \cdot 20, 20 \cdot 21 \cdot 22 \cdot 23, 21 \cdot 22 \cdot 23 \cdot 24) = \gcd(2^3 \cdot 3^2 \cdot 5 \cdot 17 \cdot 19, 2^3 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 23, 2^4 \cdot 3^2
 \cdot 7 \cdot 11 \cdot 23) = 2^3 \cdot 3 = 24.
$$
Thus any number that divides $f(n)$ for all $n$ can be at most $24$. You've already shown that $24$ works, so $24$ is the largest such number.

Edit: Why did I consider $n = 1$, $n = 4$, and $n = 5$ in particular?
I took $n = 1$ because it is the smallest value that $n$ is allowed to be, and I'd prefer to work with fairly small numbers.
We now continue with the conjecture that the answer should be $24$. The number $f(1)$ has $17$ and $19$ as factors, so to rule out that these factors will divide $f(n)$ for all $n$, we need to find a $n$ such that $f(n)$ is not divisible by $17$ or $19$. If $n$ is less than $4$, then we can see that one of the numebrs that we are multiplying by to get $f(n)$ is going to be $19$, (since the smallest of the four numbers is $n + 16$, we need $n + 16 > 19$), we see that any $n$ such that $f(n)$ is not divisible by $19$ must be at least $5$. In accordance with our preference for using small numbers, we consider the value of $f(5)$. The other reason that we would like to use a number that is at least $5$ is that otherwise $20$ will divide $f(n)$, and we want to rule out the possibility of $5$ dividing $f(n)$ for all $n$.
The problem we now have is that both $f(1)$ and $f(5)$ are divisible by $9$, so we need to find an $n$ such that $f(n)$ is divisible by $3$, but not by $9$. Now if $(n + 16)$ is divisible by $3$, then so is $(n + 19)$, and so to avoid having a factor of $9$, we need to consider an $n$ such that $(n + 16)$ is not divisible by $3$. This rules out $n = 2$. It turns out that $n = 3$ works, but I overlooked this for some reason and went with $n = 4$ instead.

A: Good start!
When $n=0$ you get $19\cdot 18\cdot 17 \cdot 16,$ so the answer must divide this. Look for examples that allow you to discard some of the factors.  For example, when $n=4$ you get $23\cdot 22\cdot 21 \cdot 20,$ so we can forget about $17$ and $19,$ and we're down to $18 \cdot 16$.  Look at some more examples to whittle it down to $24$.

A: This can be treated as a case of product of four consecutive natural numbers since it is $~ \forall ~ n \in \mathbb{N}$:
Suppose four consecutive natural numbers are: $2k-1$, $2k$, $2k+1$, and $2k+2$ where $k$ is some natural number $\ge 1$. Thus product of them will be:
$$(2k-1)(2k)(2k+1)(2k+2)=4k(2k-1)(2k+1)(k+1)=4k(4k^2-1)(k+1)$$
For apply it for all $n$, $k=1$ and then $$4k(4k^2-1)(k+1)=4(4-1)(1+1)=24$$


text:
Q: How fast can the spectral gap of a translation-invariant Hamiltonian close? Consider an arbitrary local Hamiltonian defined on some lattice of size L where the local Hilbert space dimension associated with each site on the lattice is finite. If there is no constraint on the Hamiltonian besides locality, then the spectral gap between the ground state and the first excited can often be exponentially small in V (e.g. spin glasses) and the density of states exponentially large in V. The intuition is that different terms in the Hamiltonian with random signs create a complex energy landscape with many metastable states. However, such random signs are forbidden when translation invariance is imposed in addition. So one naive guess would be that the spectral gap cannot close exponentially fast and the density of states near the ground state energy can at most be a polynomial in V.
Is this guess correct? If not, would a weaker statement (Hamiltonians with exponentially large density of states near the ground state form a set of measure zero in the space of all translation-invariant local Hamiltonians) still be true?
note added: there are examples like the ferromagnetic Ising model or the toric code where the ground state and the first excited state are separated by an exponentially small gap (due to symmetry breaking order or topological order). But these models do not have a continuum density of states near the ground state energy.


text:
Q: Iframe content URL disappear after 3 second I'm trying to dynamically change the iframe URL, for doing so I'm calling to the window.onmessage = (event) => function and fire the URL as event.data variable, this happened from external button.
When I click on the external button the iframe is shown the right URL but after 3 seconds change to black (blank URL), why does it happen, and how to solve it?
**

*

*The ifame code

**
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#000000">
    <link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico">
    <link rel="shortcut icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico">

    <title>Tech Ops PH | your < IT / design < partner </title>


text:
Q: Memory size exhausted on customer login Some time ago some customers of my site started to experience login problems: after clicking login button they need to wait for like few minutes and then this error show up

Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 20480 bytes) in /lib/Zend/Db/Adapter/Abstract.php on line 1015

After that i got this problem on every page although before it was working fine.
I think the problem is in cookies because i got 2 sites in on magento and on different domains and one of then is working fine. I need to fix it but have no idea how.
I have tried to change cookie domain in backend but it didn't help. Same with changing cookie save path - after this i can not login at all, just got redirect on the same page.


text:
Q: Restcomm cdr files Having integrated our Billing system Meveo with RestComm to provision accounts and phone numbers, I would like to know where I can get CDR files and what is their format.
Thank you

A: One straightforward way it to fetch CDRs via the REST API. You can fetch records in a time frame (via list filter) and paginate to control overload of the Restcomm server:
Calls logs API:
http://docs.telestax.com/restcomm-api-calls/
SMS message logs API:
http://docs.telestax.com/restcomm-api-sms-messages/
Notice that some records returned by this API may be fore calls in-progress. To fetch only calls that completed or failed, use list filter parameters.
For very high load systems, it is better to read from the rolling CDR log files from a shared file system. We can discuss how this can be done in a separate thread.


text:
Q: Using CCSchedulers/CCTimers in Cocos2d Project I have a GameController object, which is meant to manage stuff like the scores.
The score is based on how long the user has played, so I want to increase the score by one every 2 seconds. So my GameController is a subclass of NSObject, and I'm trying to use a CCTimer or CCScheduler (CCTimer seems to be depreciated?) But using this line, the method never fires:
[[CCScheduler sharedScheduler] scheduleSelector:@selector(updateNaturalScore:) forTarget:self interval:1 paused:NO];

Do I have to user this in a Cocos2d object? If so which one? Or should it work in an NSObject subclass?

A: Is it a cocos2D project?
have you tried [NSTimer scheduleTimer...];
it will work for your purpose, for the method not getting fired, the class being NSObject how is it accessing the classes from Cocos2D framework? Has the method written in the same class?


text:
Q: What things SQL Server takes backup of when we run a full backup Like I am trying to ask that, suppose we run a full backup using GUI or T-SQL, which file SQL Server takes backup of i.e, only data file or log file as well.
I have read that it takes active transaction portion (Log File) of SQL Server as well. please confirm.
If yes, then what will happen to a transaction that was running at that time, and committed next, logs of the transaction will there on backup or not.
how will sql server revert back to it, if the database fails.

A: A Full Backup contains a copy of all the database pages, and all the log records from the LSN at which the first database page was copied through the LSN at which the last database page was copied.
On restore the database pages are copied into the new database files, then the log records are replayed to to bring the database up to the point-in-time at which the backup completed.
If you restore WITH RECOVERY, then any transactions that were open at the time the backup completed are rolled-back and the database is brought online.
If you restore WITH NORECOVERY, then you can restore additional Log Backups to restore the database to a later point-in-time.

A: Full Backup : Backs up all the data pages.
Differential Backup : Backs up all the extents which have been modified since the last full backup.
Log backup : A transaction log backup allows you to backup the active part of the transaction log.  Log backup can only work when the recovery model is Full/Bulk-logged and there has been a full backup taken . It has all transactions logged and is a very important part of point in time recovery.


text:
Q: Mysql Group By and ABS function Stack I have sql code like this, when I execute the code with GROUP BY it just shows record number one and it doesn't use the ABS  function. Anyone can help me please?
SELECT *, `tblLifeAgency`.`AgencyName`, `mlp`.`Basic40`, `mlp`.`ADB40`, `mlp`.`CiAccel40`, `mlp`.`Basic50`, `mlp`.`ADB50`, `mlp`.`CiAccel50`, `mlp`.`Basic60`, `mlp`.`ADB60`, `mlp`.`CiAccel60`
FROM (`tblPackage`)
INNER JOIN `tblMatrixLifePackage` mlp ON `mlp`.`PackageID` = `tblPackage`.`PackageID`
INNER JOIN `tblCompany` ON `tblPackage`.`CompanyID` = `tblCompany`.`CompanyID`
INNER JOIN `tblLifeAgency` ON `tblLifeAgency`.`CompanyID` = `tblCompany`.`CompanyID`
AND `tblPackage`.`IsActive` =  '1'
WHERE `tblPackage`.`PackageType` =  '2'
GROUP BY tblPackage.CompanyID
ORDER BY abs(tblPackage.TotalPremi - 250000)

A: GROUP BY groups your records. If you have record values, you have to decides which result to show as a summary for a line. For example, you can take all values in one group as positive (ABS) and sum them (SUM). Then try converting this pattern into your case (to understand better):
SELECT
  `group`,
  ABS(
    SUM(`value`)) AS `sum`
FROM my_table
GROUP BY `group`


text:
Q: How to properly insert the values from my output to a dictionary Text = '''Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. The show was both produced and filmed in Belfast elsewhere in the United Kingdom.'''

import re
new_text = ''
punctuations = '''!.,'''
for character in Text:
    if character not in punctuations:
        new_text = new_text + character
from collections import Counter
split_text = Text.split(' ')
count = Counter(split_text)
most_freq_word_new = [key for key,valu in count.items() if valu == max(count.values())]

result =  {i: [] for i in most_freq_word_new}     #Create Dict with word as key and list as value
for index, word in enumerate(split_text):
    for i in most_freq_word_new:
        if word == i:
            #print (word)
            suffix_word =  split_text[index + 1]
            #print (suffix_word)
            prefix_word =  split_text[index - 1]
            #print (prefix_word)
            result[word].extend([suffix_word, prefix_word])  #Use list.extend to add to result.
            #print (result[word])
print(result)

My current output is below:
{'and': ['D.', 'Benioff', 'filmed', 'produced'], 'in': ['Belfast', 'filmed', 'the', 'elsewhere']}

My desired output is below:
{'and':
     {suffix_word:['D.', 'filmed'],
     prefix_word: ['Benioff', 'produced']}
'in':
    {suffix_word:['Belfast', 'the'],
    prefix_word: ['filmed','elsewhere']}}

A: You were almost there. Just need to slightly change your code to achieve that:
import re
from collections import Counter

Text = '''Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. The show was both produced and filmed in Belfast elsewhere in the United Kingdom.'''

split_text = Text.split(' ')
count = Counter(split_text)
most_freq_word_new = [key for key,valu in count.items() if valu == max(count.values())]

result =  {i: {"suffix_word": [], "prefix_word": []} for i in most_freq_word_new}     #Create Dict with word as key and list as value
for index, word in enumerate(split_text):
    for i in most_freq_word_new:
        if word == i:
            suffix_word =  split_text[index + 1] if index < len(split_text)-1 else ""
            prefix_word =  split_text[index - 1] if index > 0 else ""
            result[word]["suffix_word"].append(suffix_word)
            result[word]["prefix_word"].append(prefix_word)

print(result)

Output:
{'and': {'suffix_word': ['D.', 'filmed'], 'prefix_word': ['Benioff', 'produced']}, 'in': {'suffix_word': ['Belfast', 'the'], 'prefix_word': ['filmed', 'elsewhere']}}

A: You can use regex for this purpose. I used  re.findall for this
import re
from collections import Counter
Text = '''Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. The show was both produced and filmed in Belfast elsewhere in the United Kingdom.'''
count=Counter(Text.split())
most_freq_word_new = [key for key,valu in count.items() if valu == max(count.values())]
result =  {i: {"suffix_word": [], "prefix_word": []} for i in most_freq_word_new}
for word in most_freq_word_new:
    for prefix,suffix in re.findall(r'([\w.]+) '+ word + r' ([\w.]+)',Text):
        result[word]['prefix_word'] .append( prefix)
        result[word]['suffix_word'] .append( suffix)
print(result)

OUTPUT
{'and': {'prefix_word': ['Benioff', 'produced'], 'suffix_word': ['D.', 'filmed']}, 'in': {'prefix_word': ['filmed', 'elsewhere'], 'suffix_word': ['Belfast', 'the']}}


text:
Q: About the DECISION TREE and accuracy rate I am trying to convert the information that has been converted to 0101 to the original text And to calculate the accuracy rate .
Is my code able to do this? >>>"Use Python and the decision tree suite to write programs for decision tree model training and model performance evaluation."
I want to know how to do that.
 here is my data

import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import tree
from sklearn import preprocessing
import pandas as pd
from sklearn import metrics
myData = open(r'C:\Users\USER\Desktop\all.csv')
reader = csv.reader(myData)
headers=next(reader)
print (headers)

le = preprocessing.LabelEncoder()
balance_data = balance_data.apply(le.fit_transform)

print ("tt,",balance_data)
Y = balance_data.values[:,0]
X = balance_data.values[:, 1:7]
X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size =0.3, random_state = 100)
clf_gini = DecisionTreeClassifier(criterion = "gini",
                               max_depth=5, min_samples_leaf=5)

clf_gini.fit(X_train, y_train)

DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=5,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            presort=False,  splitter='best')

clf_entropy = DecisionTreeClassifier(criterion = "entropy", random_state = 100,
 max_depth=3, min_samples_leaf=5)
clf_entropy.fit(X_train, y_train)
DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=3,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=5,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            presort=False,  splitter='best')

with open('ppp','w') as f:
    f=tree.export_graphviz(clf_entropy,out_file=f)

y_pred_en = clf_entropy.predict(X_test)
y_pred_en

print("Accuracy is ", accuracy_score(y_test,y_pred_en))

y_pred_en = clf_entropy.predict(X_test)
y_pred_en

print("Accuracy is ", accuracy_score(y_test,y_pred_en))
accuracy = metrics.accuracy_score(y_test,y_pred_en)

print("asd",accuracy)

enter image description here


text:
Q: node.js processes with the same name in forever are closed when trying to close only one I am deploying two node.js apps on the aws, the two apps are in the paths shown as
/home/ubuntu/nodes/app1/app.js
/home/ubuntu/nodes/app2/app.js

respectively
to run the node.js apps in the background, I used forever to start two apps, so like
   $ sudo forever start /home/ubuntu/nodes/app1/app.js
   $ sudo forever start /home/ubuntu/nodes/app2/app.js

so forever works well by running the two node.js apps in the background process.
However, when I tried to stop one process with forever command like this.
   $ sudo forever stop /home/ubuntu/nodes/app1/app.js

unexpectedly, both node.js process are closed with info like this
info:    Forever stopped process:
data:        uid  command         script forever pid   logfile                 uptime
[0] r2pZ /usr/bin/nodejs app.js 24852   24854 /root/.forever/r2pZ.log 0:0:1:14.775
[1] 9f2h /usr/bin/nodejs app.js 24870   24872 /root/.forever/9f2h.log 0:0:0:58.733

I assume it is because two node.js process has the same name - app.js, how to avoid this by close only one process

A: You can use an uid (see here):
$ sudo forever --uid "app1" start app.js
$ sudo forever --uid "app2" start app.js

And to stop:
$ sudo forever stop app1

Update
The --uid option is deprecated.
Now you can use the --pidFile option. Example:
forever start --pidFile /some/path/app1.pid app.js
forever start --pidFile /some/path/app2.pid app.js

And to stop:
forever stop --pidFile /some/path/app1.pid

A: You can kill only one process using the index of the process shown in the forever list command. For example, if you type forever stop 1, only the process with the index 1 will be killed


text:
Q: How To Navigate From Child Window To User Control Silverlight? I have a child window with two buttons.  When a button click event occurs I need to navigate to a specific user control. How to do this in Prism Framework?

A: If you are using PRISM will be simple as fires  a notification event  using the event aggregator. Anyway if not, this will solve your problem.
You need when you fire the childwindow  to add  the close  event to that childwindow, like this:
YourChildWindow childWindow = new YourChildWindow ();

childWindow.Closed += new EventHandler

(YourChildWindowClosed);

childWindow.Show();

Then,
?
void YourChildWindowClosed(object sender, EventArgs e)

{

YourChildWindow yourChildWindow = ((YourChildWindow)sender);

if

(yourChildWindow.DialogResult.Value)

{

... do your things here ...

}

}

I hope this can help you.


text:
Q: Multiple images/objects recognition in a single image I am looking for a best approach for the following problem:
I have 10.000 images, pictures (art or cliparts) to be more precise. I am looking for a method to search for those images appearing in the evaluation image ( the evaluation image may contain any number of 10.000 images, but in most cases will be none to 4 ).
Here is an example:
10.000 images are pictures published in newspaper in a last year. The evaluation image is the newspaper scan. I want to find which picture ( of 10.000 ) appears on the scan.
It's important to know which image appears and not just "one of training set" appears.
Ideas?


text:
Q: Touch only on non-transparent pixels of SKSpriteNode in Swift3 I have sprite node over all screen, but images are only somewhere, not over all screen. How to set touch only on non transparent images or how to delete transparent pixels or something... Maybe use physicsBody? Thanks for help!
        node = SKSpriteNode()
        node.texture = SKTexture(imageNamed: "yes.png")
        node.name = "yes"
        node.size = self.frame.size
        node.position = CGPoint(x: 0, y: node.size.height)
        node.zPosition = 3

        self.addChild(node)

A: Without seeing your picture it's quite hard to give you a clear answer other than what I assume your issue looks like.
You can use SKPhysicsBody to solve your issue by doing this.
let texture =  SKTexture(imageNamed: "yes.png")
let node = SKSpriteNode(texture: texture)

node.name = "yes"
node.size = self.frame.size
node.position = CGPoint(x: 0, y: node.size.height)
node.zPosition = 3
node.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
self.addChild(node)

You will need to configure your physics body as well in order to get the correct collision behaviour.


text:
Q: How to get started on making an http server?
Possible Duplicate:
Implementation of a web-server

I am trying to make an http server in java that can handle http requests.  if the user types in http://www.example.com/Weather/94901 i want the program to be able to get the string "Weather/94901" then have my application process that and then display to results in the text of the webpage.

A: Why would you write a web server for that? In PHP, for example, you could use $_SERVER['PATH_INFO'] or in JSP request.getPathInfo()
Or if you really must, start with Jetty for example, an already existing Java HTTP server


text:
Q: Rest api Upload attachments not working for multiple uploads I am using Rest api to upload the attachments
function uploadattachment(itemId, listname) {
    if ($("#ticketAttachments")[0].files.length > 0) {
        $($("#ticketAttachments")[0].files).each(function (i, file) {
                getFileBuffer(file).then(function (buffer) {
                    $.ajax({
                        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + itemId + ")/AttachmentFiles/add(FileName='" + file.name + "')",
                        method: 'POST',
                        data: buffer,
                        processData: false,
                        headers: {
                            "Accept": "application/json; odata=verbose",
                            "content-type": "application/json; odata=verbose",
                            "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
                        },
                        success: function () {
                            if ($("#ticketAttachments")[0].files.length == i + 1) {
                                RefreshPage();
                            }
                        },
                        error: function (data) {
                            console.log(data);
                        }
                    });
                });
        });
    }
    else {
        RefreshPage();
    }
};

This one works for uploading single file, but when I have 2 or more files, it goes to the error part giving the below error

"{" error ": {" code ":" - 2130246326,
  Microsoft.SharePoint.SPException "," message ": {" lang ":" en-US ","
  value ":" Registration conflict \ n \ nYour changes conflict with
  those made by another user at the same time. If you want your changes
  to be applied, click Previous in your web browser, refresh the page
  and resubmit them. "}}}"

Not sure what I have missed. Can someone please advise?


text:
Q: Single SCSS rule showing 'undefined' on server but works in localhost I have an app built using React with Parcel. I am attempting code splitting via modules, but have a strange issue.
On my home page, I am importing a module that has its own css. When the component is showing on the page, there is one single css rule that is showing as 'undefined' in the inspector.
When I run this in my local, or on another page in my app such as About, the rule is recognized and everything works perfectly.
I've tried everything I can think of, but I am lost as to what to try next.
Here's the code in my js file:

The rule being ignored is 'styles.columns'. As you can see it is in between styles.content__move and styles.column, and BOTH of those are working as expected.
When inspecting I see this:

But if I add the module on another page, it shows correctly as:

What might I be missing?

A: I'm not sure what the problem was, but I renamed the class in the JS and CSS, rebuilt, and it started working right away. I would suggest to try this before changing style loaders for anybody that has the same problem.
I added:
class="styles.columns_f"

in the JS, and in the SCSS:
.columns_f {...}

Ran a production build, and that was the fix.


text:
Q: React-Native Native Android Module - Toast Example I'm trying to learn to work with android native module and using the toast example in the react-native docs. (https://facebook.github.io/react-native/docs/native-modules-android). However, I am facing an issue where the native module that I was trying to export was unable to be resolved/undefine.
My directory structure is as followed:
example
 -android
   -app
     -src
       -main
        - java
          -com
           -example
             -CustomToastPackage.java
             -ToastModule.java
             -MainActivity.java
             -MainApplication.java
        - res
        - AndroidManifest.xml
 -ios
 -app.js
 -index.js
 -package.json

My index.js:
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

import {NativeModules} from 'react-native';//Added this

module.exports = NativeModules.ToastAndroidTutorial;//Added this

AppRegistry.registerComponent(appName, () => App);

And my App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

import ToastExample from './ToastExample';//Added this

const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
  'Double tap R on your keyboard to reload,\n' +
  'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {
 render() {
  return (
  <View style={styles.container}>

     ToastExample.show('Awesome', ToastExample.SHORT);//Added this

    <Text style={styles.welcome}>Welcome to React Native!</Text>
    <Text style={styles.instructions}>To get started, edit App.js</Text>
    <Text style={styles.instructions}>{instructions}</Text>
     </View>
   );
  }
 }

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
  instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
  },
  });

This is the error I am getting.

A: Based on the code you are showing, this is because you are not correctly importing the Module in your App.js, you should create a file named ToastExample.js in the same directory as App.js and then place
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;

if in your ToastModule.java you have
@Override
  public String getName() {
    return "ToastExample";
  }

on the getName() method.


text:
Q: ℃ from mysql database cannot display on website I have a Mysql database having data below:
Thermometer -10℃ - 110℃
I copied that degree symbol from other website.
I did declare on my html like some example here:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

But it just wont show up when I call this data using php to my website, it only display
Thermometer -10?C - 110?C

What else do I need to do??

A: I'm hearing that the single Unicode character ℃ (hex E28483) is turning into the two Unicode characters °C (hex C2B0 43).  Let's verify this.  If encoded as latin1, the latter hex will be B0 43.
If the character(s) are in the database, then do
SELECT col, HEX(col) FROM ...

If they are in PHP, then do
echo bin2hex($str);

Then report back which hex you get.
This discusses why the two character version could turn into ?C.  It suggests:

*

*The bytes to be stored are not encoded as utf8/utf8mb4.  In particular, hex B0 is the latin1 encoding for °.

*The column in the database is not CHARACTER SET utf8 (or utf8mb4). Fix this. (Use SHOW CREATE TABLE.)

*Also, check that the connection during reading is UTF-8.

Meanwhile, there is nothing (that I know of) in either MySQL or PHP that would turn the one-char encoding into the two-char version.  Is there any other process involved?
In the Unicode specification, there is a "Decomposition" of the 1-char version into the 2-char version, but I don't know what product would make use of such.  Another example: Lj vs Lj
Who is converting?
If MySQL were converting from utf8 to latin1, I would expect
CONVERT(CONVERT(BINARY('℃') USING utf8) USING latin1)

to return the two-char version.  But, no, it returns '?'.  I have to assume some other process that the data is going through is being kind enough to convert the 1-char thing into 2-chars, perhaps then converting to latin1 (which is almost identical to cp1252 and ISO-8859-1 and ISO-8859-15)


text:
Q: Change Base class at runtime java Hello I have a an Activity (class) that i want to enable NFC feature for it when the android API level is 14 and up . and i dont want to enable it below. now the Activity is 1000 lines and to use NFC i have to extend a class in a jar file . so what should i do ??? i cant use aggregation for the NFC !! and i dont want to make 2 Activities and copy past the same code to them and make one of them extends NFC . any work around , sorry if you want more clarification post a comment . I am not an OOP super star.
Edit

What i want to be able to do is on android API level 14 to make the VideoActivity to extends NFC custom class . because the NFC custom class continas api's that is available on android API level 14
and when the API level is below 14 i want the VideoActivity to extends Activity class .

Note: the NFC custom class exist in a jar (library jar).


text:
Q: creating class object that normally looks like a float I'm looking to roll my own simple object that can keep track of units for variables (maybe I'll be adding other attributes like tolerances too). Here is what I have so far:
class newVar():
    def __init__(self,value=0.0,units='unknown'):
        self.value=value
        self.units=units

    def __str__(self):
        return str(self.value) + '(' + self.units + ')'

    def __magicmethodIdontknow__(self):
        return self.value

diameter=newVar(10.0,'m') #define diameter's value and units

print diameter #printing will print value followed by units

#intention is that I can still do ALL operations of the object
#and they will be performed on the self.value inside the object.

B=diameter*2

Because I don't have the right magic method i get the following output
10.0(m)
Traceback (most recent call last):
  File "C:\Users\user\workspace\pineCar\src\sandBox.py", line 25, in <module>
     B=diameter*2
TypeError: unsupported operand type(s) for *: 'instance' and 'int'

I guess i could override every magic method to just return self.value but that sounds wrong. Maybe I need a decorator?
Also, I know I can just call diameter.value but that seems repetative

A: I once tried to implement something similar myself, but never managed to finish it. One way is to implement a new class from scratch, which contains both the value and the units. But if you want to use it in calculations, you have to implement all the magic methods like __add__ and __mul__. An alternative is to sub-class float itself:
class FloatWithUnit(float):
    def __new__(cls, val, unit):
        return float.__new__(cls, val)
    def __init__(self, val, unit):
        self.unit = unit
    def __str__(self):
        return '%g %s' % (self, self.unit)
    def __repr__(self):
        return self.__str__()

Subclassing float is apparently a bit tricky, so you have to implement __new__ in addition to __init__, see here for more discussion. When entering such an object on the command line, it shows its units:
In [2]: g = FloatWithUnit(9.81, 'm/s^2')

In [3]: g
Out[3]: 9.81 m/s^2

In [4]: type(g)
Out[4]: __main__.FloatWithUnit

But when used in caluations, it behaves like a normal float
In [5]: g2 = 2 * g

In [6]: g2
Out[6]: 19.62

In [7]: type(g2)
Out[7]: float

A: In Python you can override many different operators, some of which are for emulating numeric types. You can find out more here.
In the case of multiplication, all you need to do is override __mul__(self, other) like so:
def __mul__(self, other):
    return self.value * other

You can also override other numeric operations like __add__(self, other) (for addition), __sub__(self, other) etc.
On a somewhat unrelated note, you might also want to think about what you want the behaviour be if one wanted to multiply to diameters together or add a weight to a diameter.
UPDATE
Based on your comment, you are probably better off overriding the the object's float representation as also mentioned by John, though it's not as clean as overriding the mathematical operators:
def __float__(self):
    return self.value

A: class newVar():

    def __init__(self,value=0.0,units='unknown'):
        self.value=value
        self.units=units

    def __repr__(self):
        return str(self.value) + '(' + self.units + ')'

    def __mul__(self, other):

        if hasattr(other, "value"):
            return self.value * other.value
        else:
            return self.value * other

diameter=newVar(10.0,'m')

print diameter
print diameter*2

another possible solution would be to override the object float representation
class newVar():

    def __init__(self,value=0.0,units='unknown'):
        self.value=value
        self.units=units

    def __repr__(self):
        return str(self.value) + '(' + self.units + ')'

    def __float__(self):

        return self.value

diameter=newVar(10.0,'m')

print diameter
print float(diameter)*2


text:
Q: prolog - DCG transformation What does E -> T mean ? Variable E implies variable T ?
This the code which is linked :
e(TS,R) :- t(TS,R).

Thanks for your help

A: Are you sure that you asking about E -> T (if E then T) and not about e --> t (lower case (thanks lurker!) and DCG syntax, where "DCG" is for "Definite Clause Grammar")?
Because the DCG syntax
e --> t.

is an alias (or a shortcut or syntactic sugar, if you prefer) for
e(L1, L2) :- t(L1, L2).

More generally speaking, the DCG syntax adds a couple of arguments, at the end of the clauses involved, making a chain on the right side of the :- operator where the the start and the end of the chain are the arguments added on the left side.
So (by example)
d --> c1, c2, ...., cn.

is an alias for
d(L1, Lnp1) :- c1(L1, L2), c2(L2, L3), ..., cn(Ln, Lnp1).


text:
Q: How can I reset the default Chakra UI button styles?     baseStyle: {
        borderRadius: '6px',
        fontWeight: 700,
        fontSize: '14px',
    },
    variants: {
        solid: (props) => ({
            bg: mode('light', 'dark')(props),
            color: mode('white', 'darkLight')(props),
            _hover: {
                opacity: 0.5,
            },
        }),
    },
};

When hovering over the button, the standard Chakra UI hover styles are applied to the opacity, I would like to remove this.

A: I can solve this by adding property bg: null, if you know a better solution let me know


text:
Q: Save the current selection as HTML in Excel with VBA In Excel, when saving a workbook to an HTML file, one has the choice to save the entire workbook or the current selection only.
How can one programmatically perform the latter using VBA?


text:
Q: Find the radius of convergence $\sum_{n=0}^{\infty} \frac{x^n}{n!}$ $\sum_{n=0}^{\infty} \frac{x^n}{n!}$
Using the ratio test, I get the value $$\frac{x}{(n+1)}$$ Then to evaluate the limit, I move x outside and get $$ x \lim_{n\to\infty}\frac{1}{n+1} = x\lim_{n\to\infty} \frac{1/n}{1 + 1/n}$$ then the  limit becomes  $x\times 1 = x$ so $x < 1$ and $R = 1?$
The answer is supposed to be $\infty$ as the radius of convergence. Did I do something wrong with my evaluation of the limit and finding R? It doesn't seem obvious why the answer is $\infty$

A: The limit is $0$, not $1$, so the radius is $+\infty$.

A: We have $\sum\limits_{n\in \mathbb{N}}\frac{x^n}{n!}$. Using the result the radius of convergence (R) is given by, $\frac{1}{R}=\text{lim}_{n\rightarrow \infty}\frac{a_{n+1}}{a_n}=\text{lim}_{\rightarrow \infty}\frac{n!}{(n+1)!}=\text{lim}_{\rightarrow \infty}\frac{1}{n+1}=0$. Therefore $R=\infty$.

A: You evaluated the limit wrong , the statement 1/(n+1)  is not equal to 1 since you can't cancel n from denominator since there is no n in numerator. The limit would be 1/infinity =0. And hence  R is infinity.

A: $$
\lim\limits_{n\to \infty} \dfrac{\dfrac{1}{(n+1)!}}{\dfrac{1}{n!}}=\lim\limits_{n\to \infty} \dfrac{n!}{(n+1)!}=\lim\limits_{n\to \infty} \dfrac{1}{n+1}=0.
$$


text:
Q: Creating pdf with cakephp 3 and doompdf, the pdf is not being generated I'm trying to create PDF reports with cakephp3 and doompdf but the pdf is not being generated, just the html.
bootstrap.php:
Plugin::load('Dompdf');

routes.php:
 Router::scope('/', function ($routes) {

$routes->extensions(['pdf']);

});

'controller:'
  public function pdf() {

$this->viewBuilder()
->className('Dompdf.Pdf')
->layout('Dompdf.default')
->options(['config' => [
    'filename' => 'voluntariopdf',
    'render' => 'download',
]]);
}

'view:'
<?php $this->start('header'); ?>

Header.

<?php $this->end(); ?>

<?php $this->start('footer'); ?>

Footer.

<?php $this->end(); ?>

Teste

Teste

teste

The HTML is being generated as expected, but the pdf is not. Can anyone please explain why?

A: try to do that:
$this->viewBuilder()
    ->className('Dompdf.Pdf')
    ->layout('Dompdf.default')
    ->options(['config' => [
        'upload_filename' => WWW_ROOT.'pdf/mydocument.pdf',
        'render' => 'upload',
]]);

After installation, did you generate a symbolic link?
// In a shell
bin/cake plugin assets symlink


text:
Q: Mostrar datos a usuarios logeados PHP Estoy haciendo una pagina web donde tengo un login y cuando inicias sesión te lleva a un archivo que se llama usuario.php
Lo que quiero conseguir es que solo los usuarios logeados puedan ver el contenido del archivo usuario.php
Quiero evitar que en el buscador del navegador poniendo ruta/usuario.php te muestre los datos sin haberte logeado,para asi dar mas seguridad .
Actualmente con lo que tengo hecho,consigo que nadie entre al archivo usuario.php pero tampoco los usuarios que se logean ,les redirige a todos a index.html
Este es mi login.php

//CAPTURO LOS INPUTS
$user=$_POST["email"];
$passw=$_POST["password"];

//CONECTAMOS CON LA BBDD
$conexion=mysqli_connect("localhost","root","x", "bbdd");
if(mysqli_connect_errno($conexion)) {
    printf("Falló la conexión: ",mysqli_connect_errno());

}
//comprobamos que exista el usuario
$resultado=mysqli_query($conexion,
    "SELECT * FROM usuarios WHERE
    correo='$user' and
    contrasena='$passw'");
$usuExiste=mysqli_num_rows($resultado);

if($usuExiste >0){
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $user;
    $_SESSION['start'] = time();
    $_SESSION['expire'] = $_SESSION['start'] + (5 * 60);
    header('location:usuario.php');
    echo "";

} else {
    echo "";
}
session_destroy();
?>

y este mi usuario.php
<?php
session_start();

if (isset($_SESSION['loggedin'])) {

} else {
  echo "";

header("location:index.html");

exit;
}

$now = time();

if($now > $_SESSION['expire']) {
session_destroy();

echo "Su sesion a terminado,
Necesita Hacer Login";
exit;
}
?>

A: En el login.php también tienes que poner el
session_start();

El session_destroy(); ponlo dentro de la parte else del if (soy paranóico) y cierra el punto y coma del echo:
} else {
    echo "";
    session_destroy();
}

Del mismo modo que pones exit en el usuario.php, hazlo en el login.php:
$_SESSION['expire'] = $_SESSION['start'] + (5 * 60);
header('location:usuario.php');
//echo ""; // No vale para nada
exit;

Busca y lee información sobre SQL Injection, tu código es vulnerable a un ataque muy conocido que todo el mundo puede explotar sin muchos conocimientos.
Con estos cambios te debería funcionar.


text:
Q: Need help to create a Jolt specification Need help with a JOLT specification for converting the JSON from the shared input format to the expected format.
[
  {
    "Header": {
        "TeamCD": 2
    },
    "Player": [
               {
                 "PlayerNumber": 1,
                 "ShortName": "John",
                 "UniformNO": 11,
                 "SmartStart": 20200201,
                 "SmartEnd": 99999999
               },
               {
                 "PlayerNumber": 2,
                 "ShortName": "James",
                 "UniformNO": 12,
                 "SmartStart": 20200201,
                 "SmartEnd": 99999999
               }
              ]
  }
]

Desired output:
[
    {
      "Field": "TeamCD",
      "Type": "20"
      "Value": 2,
      "Vendor": "Vendor1"
    },
    {
    "Field": "PlayerNumber",
    "Type": "23"
    "Value": 1,
    "Vendor": "Vendor1"
  },
  {
    "Field": "ShortName",
    "Type": "24"
    "Value": "John",
    "Vendor": "Vendor1"
  },
  {
    "Field": "PlayerNumber",
    "Type": "23"
    "Value": 2,
    "Vendor": "Vendor1"
  },
  {
    "Field": "ShortName",
    "Type": "24"
    "Value": "James",
    "Vendor": "Vendor1"
  }
]

I am trying to achieve this using JoltTransformJSON now. Is this achievable using JoltTransformJSON? I have it running on Nifi, if not possible with Jolt what are my options?


text:
Q: Batteries react strangely A school has several identical laptops bought 5 years ago: Fujistu Lifebook model A530
Since several weeks ago, around 50% of them randomly turn off after 1 to 5 minutes:

*

*The shutdown is sudden: one second you work on the laptop, the next second it is completely powered off

*Swapping the batteries of a working laptop and a broken laptop causes the working one to fail, and the failing one to work. So the problem follow the batteries

*Only when on battery. Plugging the power cord in fixes the problem. Once unplugged, the laptop will shut down after 1 to 5 minutes again

*Idle CPU, low memory usage. Happens even when no one is using the laptop

*The battery charge state doesn't change anything

*After a sudden shutdown, we can reboot the laptop without problem because the battery is still charged as before. But it will stop 1 to 5 minutes later

*Only happens while in BIOS or running Windows 7 pro 64-bit. Everything is fine while running Linux booted from a USB key: it runs 1 hour without problem

*The laptops worked several years without problem, and nothing as been done recently (and more: they are theoretically identical from a software point of view, so why only 50% of them?)

*I don't see any strange programs or anything

A: I flashed the BIOS et voilà, evrything is back to expected behaviour.
So I flashed each laptops. They can now use the laptops during more than 40 minutes (which is good for 5 years old batteries).
With Linux this changed nothing, so probably relying on a driver resetting the battery controler after boot.


text:
Q: LyX doesn't wrap underlined text I'm using LyX 1.6.6.1 under Windows XP, and, as the title says, it doesn't wrap underlined text - i.e., the underlined text is "overflowing" outside of the page.

A: What are you using to underline text? I'm guessing that it is something other than \underbar{} which doesn't affect the flow and wrapping. You can see the underlying TeX in LyX with View ➤ View Source.
Furthermore, in TeX generally, underlining should rarely be used as it is a convention of typewriters, not typesetters. Italics, font changes, even boxes are better ways to set off text in TeX. I'm also guessing that it was pretty hard to force LyX to underline and so you wound up accidentally forming an indivisible TeX box that - by definition - can't wrap.
LyX is pretty nifty for what it does, but it is only a wrapper for TeX and will likely produce more such mysteries when provoked. I'm not saying "learn TeX", I am suggesting that you become familiar with the 'real document' by keeping the source view open.


text:
Q: What happened to the other slaves on the Wheel of Pain? When Conan is shackled to the Wheel of Pain as a child other slave-children are as well, but years later Conan is pushing the wheel alone. Did the other slaves die? Were they sold off over time?

A: The film's official novelisation (based on the screenplay) indicates that the other slaves on the wheel were worked to death or possibly taken to slave elsewhere.

So Conan and his fellows laboured day after day, month after month, until time lost all meaning for them. Faces slack, eyes dull, hearts emptied of emotion, time for them contracted to the present moment only. Yesterday was mercifully obliterated from their consciousness; tomorrow was a nightmare yet undreamed. When a wheel-slave fell and could rise to toil no more, the Master summoned the ever-present Vanir guards with a curt gesture to unshackle the gasping body and bear it off—no one knew where.
Conan dully wondered at times if that was how the Vanir fed their dogs.
The seasons changed; months stumbled into years. Wheel-slaves died, only to be replaced by other slaves, reaved by the Vanir raiders. Some of the new captives were youths and men of Cimmerian stock; others were golden-haired boys from Asgard: a few were gaunt Hyperboreans with limp, flaxen locks and, it was said, a knowledge of sorcery. Not that it seemed to do them any good.

For the record, the others from his village were sold off immediately.

As for the captive women and girl-children of his village, they were led away to face a different, perhaps even uglier fate. Conan never heard of them again.

A: They were unnecessary.  The point of the sequence is that turning the wheel—which originally required a whole gang of slaves—could be accomplished by the adult Conan entirely on his own.  There was no need for the other slaves, so they were given other duties, or sold.


text:
Q: mod_rewrite works for URLs with en, es but not zh-tw and zh-cn? My sites are in 4 languages and they are accessed with the following pattern:
http://example/index.php?lang=en
http://example/index.php?lang=es
http://example/index.php?lang=zh-tw
http://example/index.php?lang=zh-cn

I'm using the following mod_rewrite rule in my .htaccess file:
RewriteEngine on
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA]

So typing http://example/en/index.php and http://example/es/index.php efectively redirects me to http://example/index.php?lang=en and http://example/index.php?lang=es respectively. But that doesn't work with  http://example/index.php?lang=zh-tw and http://example/index.php?lang=zh-cn
It just says: The requested document was not found on this server.
It is something to do with the hyphen (zh-tw and zh-cn)?
How can I fix this problem?

A: Replace [A-Z] with [a-z].


text:
Q: How to prove that this block-matrix is positive-definite? I have a $3n\times3n$ symmetric block matrix that I need to prove is positive definite:
$$
M = \left(\begin{array}{ccc}
 M_{1,1}&\dots&M_{1,n}\\
 \vdots&\ddots&\vdots\\
 M_{n,1}&\dots&M_{n,n}\\
 \end{array}\right).
$$
Given a set of points $\{ \mathbf{x}_i \}_{i=1}^n$ define $\mathbf{x}_{ij} = \mathbf{x}_{i}-\mathbf{x}_{j}\in\mathbb{R}^3$ as the vector joining the $i$th and $j$th point then $$M_{ij} = (d_{ij}+\frac{\epsilon^2}{2}d_{ij}^3)I+(d_{ij}^3-\frac{3\epsilon^2}{2}d_{ij}^5)\mathbf{x}_{ij}\mathbf{x}_{ij}^T$$ is a $3\times3$ symmetric positive definite(*) matrix, $I$ the 3D identity matrix, $d_{ij} = (\mathbf{x}_{ij}^T\mathbf{x}_{ij}+\epsilon^2)^{-1/2}$ is a positive definite scalar function and $0<\epsilon<<1$ is a small positive parameter.
I have a lot of numerical evidence(**) to believe that the this matrix is positive definite for any reasonable choice of $\epsilon$ and any distribution/number of points $\{ \mathbf{x}_i \}_{i=1}^n$; however, a general proof eludes me. Any ideas on how to prove that this matrix is positive definite?
If this is easy for you: what about the case where $\epsilon=\epsilon_j$ depends on $j$ but not $i$, such that $M_{ij}\ne M_{ji}$? (Although $M_{ij}^T=M_{ij}$ still)
If it turns out that this matrix is not positive definite in general, are there conditions on the distribution of points that guarantee that it will be positive definite?
Thank you in advanced!
(*) We know $M_{ij}$ is SPD as the eigenvalues, which can be easily calculated with MAPLE, are all positive and real.
(**) The eigenvalues, which are numerically calculated in MATLAB, asymptotically approach zero from above as $\epsilon$, $1/n$ and $||\mathbf{x}_{ij}||$ all approach zero.

A: Some thoughts on the problem:
The matrix $A$ with blocks $A_{ij} = d_{ij} I$ can be written as $A = D \otimes I$, where $D$ has entries $d_{ij}$ and $\otimes$ is a Kronecker product. The matrix $B$ with blocks $B_{ij} = d_{ij}^3\mathbf x_{ij}\mathbf x_{ij}^T$ is given by
$$
B = \sum_{i,j} d_{ij}^3 (\mathbf e_i\mathbf e_j)^T \otimes (\mathbf x_i - \mathbf x_j)(\mathbf x_i - \mathbf x_j)^T
\\
= \sum_{i,j} d_{ij}^3 [\mathbf e_i \otimes (\mathbf x_i - \mathbf x_j)][\mathbf e_j \otimes (\mathbf x_i - \mathbf x_j)]^T
\\
= [\mathbf e^T \otimes \mathbf X - \mathbf X \otimes \mathbf e^T]
\operatorname{diag}(\operatorname{vec}(D))
[\mathbf e^T \otimes \mathbf X - \mathbf X \otimes \mathbf e^T]^T,
$$
where $\mathbf X$ is the matrix with columns $\mathbf x_i$, $\mathbf e_i \in \Bbb R^n$ denotes the $i$th standard basis vector, $\mathbf e = (1,\dots,1)^T \in \Bbb R^n$, and vec denotes the vectorization operator.
The limit of $M$ as $\epsilon \to 0^+$ is $A + B$.


text:
Q: Invalid_Client error when trying to get a token We use  https://[tenant].acumatica.com/identity/connect/authorize to get an authorization code which works fine then we call
https://[tenant].acumatica.com/identity/connect/token
endpoint with below params:
grant_type: authorization_code
client_id: [client id]
client_secret: [client secret]
code: (the value from "code" query parameter from the first request respomse)
redirect_uri: https://[local].ngrok.io/accumatica/access-token

We get a bad request with error message:
{
    "error": "invalid_client"
}

What could be the reason?
Thanks

A: Most common explanation is that Client ID and Client Secret values passed by the OAuth client don't match the Client ID and Client Secret values configured in the OAuth server (Acumatica).

A: I'm not sure whether you're still having this issue - but perhaps it would be best to use grant_type = password.
That is the method recommended in Acumatica training documentation and we have used it that way to successfully get a token.
Here is a screen shot of the parameters from Postman...
enter image description here


text:
Q: angular4 rxjs Observable reduce returns type different then original passed in angular4 typescript rxjs 5
I have complex type passed in reduce method but i want return type to be different boolean .
Rite now with following code i am getting return type error not match
Observable.from(myList).reduce((complex1, complex2) => {
return complex1.flag && complex2.flag; // gives me error
})

A: Guessing that myList is Array<{ flag: bool }> and you want to check if all flags are true, you probably want:
Observable.from(myList)
          .reduce((accumulated, complex) => accumulated && complex.flag, true);

Your reducing function is responsible for combining the previous iteration value (or second argument, initially) with the newly-emitted value from your Observable, in order to reduce your stream to a scalar value. This way, your reducing function has the same return type and first-argument type as the final value.


text:
Q: Does linear independence imply algebraic independence for partitioned homogeneous polynomials? Define a partitioned homogeneous polynomial of degree $d$ to be a polynomial in $$\mathbb Z[x_{11},\dots,x_{1n},\dots,x_{d1},\dots,x_{dn}]$$ with monomials from entries in (polynomials that are $d$-linear forms of a particular structure) vector $$(x_{11},\dots,x_{1n})\otimes\dots\otimes(x_{d1},\dots,x_{dn}).$$

*

*Supposing if $f,g$ are two such polynomials with coefficient vectors linearly independent then when does it hold that they are algebraically independent?

*Will it work if $\mathbb Z$ is replaced by another commutative ring?


text: Q: codec encoding video efficiency test in webrtc I would like to build automatic tool that will test encoding efficiency on enter website. I'm using webrtc for video streaming and some users with weaker hardware experiencing problems with encoding efficiency. So ideally I would like to measure how the device behaves respectively with vp9, vp8 and h.264 encoding and choose that which will ensure smmoth stream and highest quality. I build simple tool that measures frames per second and resolution in each codec, but it seems that it is not the best measurement - webrtc manages resolution on it's own, sometimes keeps lowers resolution and more stable fps, but it is not always the case, it's quite unpredictable on older computers. I have another idea to make some benchmark, but I'm not sure if it's possible to make meaningful measurement in a few seconds (I don't want user wait too long). And it's problematic to measure cpu usage from website. What's the best approach for this? I would be grateful for some advices, I'm not very advanced in webrtc and maybe I'm missing something.


text:
Q: How to set primary key in table using googledatastore.? hi i have one doubt.How to set primary key in table using googledatastore.

A: @PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;

Documentation can be found here.


text:
Q: How to find the logs on Android Studio? I have tried to import my project to Android Studio and I got this error. I need to know where I can get the logs.
Consult IDE log for more details (Help | Show Log)

A: There is no way to get the logs for installing problems.

A: Had a hard time finding the logs because the IDE was crashing on launch, if you are on Mac and use Android Studio 4.1 then the logs location may be found at /Users/{user}/Library/Logs/Google/AndroidStudio4.1/
And to be specific for me it is on macOS Big Sur

A: Android Studio find a log
MacOS version
Help -> Show Log in Finder

In my case it is:
/Users/alex/Library/Logs/Google/AndroidStudio4.2/idea.log

A: On a Mac, the idea.log is contained in
/Users/<user>/Library/Logs/AndroidStudio/idea.log

The new stable version (1.2) is in
/Users/<user>/Library/Logs/AndroidStudio1.2/

The new stable version (2.2) is in
/Users/<user>/Library/Logs/AndroidStudio2.2/

The new stable version (3.4) is in
/Users/<user>/Library/Logs/AndroidStudio3.4/

(From auspicious99 comment)
On MacOS Catalina and Big Sur (at least), Android Studio 4.1, the idea.log can be found in,
/Users/<user>/Library/Logs/Google/AndroidStudio4.1/

A: On toolbar -> Help Menu -> Show log in Explorer or Show log in Finder (for Mac users).
It opens log folder, where you can find all logs.

A: You could open Messages or Event Log tool window to see your log.
In addition to that if you want to see device log then you could open Logcat tool window to view your log : View > Tool Windows > Logcat

A: I had the same problem and after some searching I was able to find my logs at the following location:
C:\Users\<yourid>\.AndroidStudioPreview\system\log

A: My Android Studio is 3.0, please follow the two steps below,hope this will help;)

A: Just because none of these pointed to the correct location on my Win10 system
C:\Users[User Name]\AppData\Local\Google\AndroidStudio4.2\log\idea.log

A: Hope this helps someone: on Mac OS X, the logs are within /Users/<user>/Library/Logs/AndroidStudio<version>/

A: The path to the log files in Windows has been moved.
They appear to be under C:\Program Files\Android\Android Studio\caches\trunk-system\log\idea.log in Android Studio 4.1.1

A: If you got here because you can't start an emulator and Android Studio gives you that error message:

*

*kill qemu-system-x86_64.exe and adb processes

(Windows 10)

A: In ubuntu it should be under

/home/user_name/product_name/system/log

where
user_name is logged in user name and
product_name could be e.g. .AndroidStudio1.5

A: In windows version
you can find the log in the bottom of the IDE, click the "Gradle Console", and then choose the "Android Monitor". You will see a Droplistbox control which shows "Verbose" as a default value.
If you use log.v() . Verbose option is okay. if you use log.d(), just change it to Debug.
So when you run your emulator, you can catch your log from this window.

A: C:\Users\bob.AndroidStudio2.3\system\log


text:
Q: Check if a specific user did a command discord.py Im trying to make a command that I could use in every server, but when others use "-help" it doesn't show in the list of commands. I know the normal way to do this would be:
if ctx.author.id == myID:
  #do some code

But if I do it like this, the user can still see that the command exists when using "-help". Is there any way to get around this? Is there a
@commands.command
@commands.is_user(myID)
?

A: There are three options, you can either make a check, make a decorator, or make a global check:
1.
def is_user(ctx):
    return not ctx.author.id == myID

@bot.command()
@commands.check(is_user)
async def foo(ctx):
    ...

*decorator

def is_user(func):
    def wrapper(ctx):
        return not ctx.author.id == myID
    return commands.check(wrapper)

@bot.command()
@is_user
async def foo(ctx):
    ...

*global check

@bot.check
async def is_user(ctx):
    return not ctx.author.id == myID

If a check returns False, commands.CheckFailure is going to be raised, you can make an error handler and send something like "You can't use this command" or whatever.
Reference:

*

*commands.check

*commands.Bot.check

*commands.CheckFailure

A: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#help-commands
Help commands can have a hidden attribute, which makes them not show up in the help command.
@commands.command(..., hidden=True)
def my_command(...):
    ...


text:
Q: Autofilter on Mutliple Columns Excel VBA I need to filter a data table where 3 columns can contain the result I am looking for:
So if the criteria is found in columns 1, 2 or 3 then the row should be returned.

(source: gulfup.com)
So in the above sample data lets say I select the criteria as "Fat"
I am looking for the autofilter to return rows 1 & 2; if I select the criteria as "Funny" I need rows 2 & 6 and so on....
Below is my code which is not working since apparently it tries to find the rows in which all columns contain the criteria, and it is not what I am looking to do.
With Sheet1
    .AutoFilterMode = False

    With .Range("A1:D6")
    .AutoFilter
    .AutoFilter Field:=2, Criteria1:="Fat", Operator:=xlFilterValues
    .AutoFilter Field:=3, Criteria1:="Fat", Operator:=xlFilterValues
    .AutoFilter Field:=4, Criteria1:="Fat", Operator:=xlFilterValues
    End With
End With

I have also tried to use Operator:=xlor but when I ran the code it returned no results.
In short: The row must be returned by the filter is the criteria is found in column B or C or D.
Help is definitely appreciated.

A: As follow up from comments, there are two ways for you.
Use additional column with formula:
Dim copyFrom As Range

With Sheet1
    .AutoFilterMode = False

    With .Range("A1:E6")
        'apply formula in column E
        .Columns(.Columns.Count).Formula = "=OR(B1=""Fat"",C1=""Fat"",D1=""Fat"")"
        .AutoFilter Field:=5, Criteria1:=True

        On Error Resume Next
        Set copyFrom = .Offset(1).Resize(.Rows.count - 1).SpecialCells(xlCellTypeVisible)
        On Error GoTo 0
    End With
End With

If Not copyFrom Is Nothing Then copyFrom.EntireRow.Copy

Use For loop with Union:
Dim copyFrom As Range
Dim i As Long

With Sheet1
    For i = 2 To 6
        If .Range("B" & i) = "Fat" Or .Range("C" & i) = "Fat" Or .Range("D" & i) = "Fat" Then
            If copyFrom Is Nothing Then
                Set copyFrom = .Range("B" & i)
            Else
                Set copyFrom = Union(.Range("B" & i), copyFrom)
            End If
        End If
    Next
End With

If Not copyFrom Is Nothing Then copyFrom.EntireRow.Copy

For copying also header:
Dim copyFrom As Range
Dim i As Long

With Sheet1
    Set copyFrom = .Range("B1")
    For i = 2 To 6
        If .Range("B" & i) = "Fat" Or .Range("C" & i) = "Fat" Or .Range("D" & i) = "Fat" Then
            Set copyFrom = Union(.Range("B" & i), copyFrom)
        End If
    Next
End With

copyFrom.EntireRow.Copy

UPDATE:
Dim hideRng As Range, copyRng As Range
Dim i As Long
Dim lastrow As Long

With Sheet1
    lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
    .Cells.EntireRow.Hidden = False
    For i = 2 To lastrow
        If Not (.Range("B" & i) = "Fat" Or .Range("C" & i) = "Fat" Or .Range("D" & i) = "Fat") Then
            If hideRng Is Nothing Then
                Set hideRng = .Range("B" & i)
            Else
                Set hideRng = Union(.Range("B" & i), hideRng)
            End If
        End If
    Next
    If Not hideRng Is Nothing Then hideRng.EntireRow.Hidden = True

    On Error Resume Next
    Set copyRng = .Range("B1:B" & lastrow).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
End With

If copyRng Is Nothing Then
    MsgBox "There is no rows matching criteria - nothing to copy"
    Exit Sub
Else
    copyRng.EntireRow.Copy
End If


text:
Q: Why CSS Isolation in Blazor is not working? I read in many tutorials :

*

*Just create a file containing the same filename of the page plus .css - Example: for Orders.razor, create a file Orders.razor.css

*Add your style on the css file and have fun
Ok, but this is not working. So, what is the correct approach ? To reproduce:

*

*Create a new solution, client side

*Wait for the solution being created and the sample boilerplate (counter, fetchdata, etc)

*On the pages folder, create a file"Index.razor.css"

*On the created file, add: h1 { color : red }

*Execute the solution

Expected result: Hello, world! in red
Received: Hello, world! in black
Index.razor
@page "/"

Hello, world!

Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />

Index.razor.css
h1 {
   color: red
}

A: For .razor.css files to work, you need to be using .net5
Take a look at the docs and see if you didn't miss any step


text:
Q: How to write tests in junit for methods that return void and implement runnable? I need to write junit tests for a method that implements the runnable and the whole logic of the code is within run() method.
for example:
public  class BookmarkController{
 public void addBookmark(final String url, final String title) {
       Runnable r = new Runnable() {
                   @Override
                   public void run() {
                                     //some logic

                                    };
}
}

can anybody tell me how to write tests for the method.

A: You run addBookmark() then I'm assuming you have a getBookmarks() method.  After you run the addBookmark()method, you check the getBookmarks() method to see if the bookmark you added with addBookmark() has been added.  If the thread that implements Runnable is expected to take some time, you do the test in a RetriedAssert which will retry the test over and over for a certain length of time.  Effectively waiting a certain length of time for a pass, if it still finds fails after the length of time, it's a fail.
new RetriedAssert(2000,100){
  public void run() throws Exception{
    assertTrue(yourClass.getBookMarks().contains(bookmark));
  }
}.start();

A: In general , anonymous classes is equivalent to private methods, ie: implementation details are private, and ideally you should test the behaviour. It should be sufficient enough if your test  check if BookMark is added. Also you can think of using Mock framework (Setting expectations/ Verifying )


text:
Q: Location of input for negative feeback bandpass filter I came across a reference design on a TI application imaged here:

It is clear to me that there is a bandpass filter on the negative loopback branch of the amplier. However, from the few electronics classes I have taken in school, typically the input is seen where the group is placed. Is there any purpose as to why?
From the figure, I deduced the transfer function as:

That is mainly just a sanity check that I can workout the transfer characteristics properly.
This is my first post so don't rip me apart (or do, if I so deserve it.)

A: In thinking thru such circuits, one approach is to have the INPUT be still, unmoving. Then examine the "noise" response.
In this opamp circuit, if the Vin is unmoving (Vin+), then the opamp strives to make the other input also be unmoving.
If Vin- is unmoving, then the networks around Vin- are DECOUPLED,
and you can examine them separately.
The network to Ground is a high_pass filter. This is easy to see, if you realize DC impedance is infinite, making the total gain be Feedback/infinity.
The Feedback network is a low_pass filter, and at very high frequencies the impedance IS zero, so the total gain is Zero/Input_network_impedance = zero.
If you properly set the two corner frequencies, you have a well-controlled passband with gain set by Rfeedback/Rin. In this case, gain is R5/R6.
For accurate gain in the "passband" (accurate within a few percent), you need a passband width of several decades (such as 100Hz to 10,000Hz, not quite adequate for audio signals).
Here the low_frequency time_constant (as someone tries to SLOWLY SLOWLY move thru the field_of_view of the PIR, is 33uF * 40Kohm. This is 1.3 second time_constant, thus by moving VERY SLOWLY, you can trespass at will.
The upper end is 100pF and 15Meg ohm. Given 1pF and 1MegOhm is 1 uS, we easily compute a 1.5 millisecond time_constant, or about 100Hz upper corner (F3dB, 45 degree phase shift). Note this DOES NOT attenuate 60Hz energy, thus electro_static power line interference may be a problem; some thinking about shielding might be useful to prevent surprises, or false triggers.

A: This op-amp appears to be used in a non-inverting configuration, meaning the input comes from the positive terminal and the other side is grounded. However, a feed back network is still useful to control the poles and zeroes of the system.A bandpass filter resembling one of the more complex feedback networks.
I am assuming PIR stands for passive infrared sensor and that is what is providing the input.
I think that might answer your question about the location of the input, but more about the how the feedback network actually influences output must me in the TI paper. Maybe you can leave a link in the comments.

A: Your equation has one big mistake: you've added R5 and Zc1 but they are in fact in parallel.
There are 3 independent filters going on here:
The input coupling of C1 with the parallel combo of R3 and R4 yields a .02Hz high pass. This is undoubtedly intended merely as a DC blocker. It is meant to pass all non-zero frequencies.
The R6 and C3 cutoff frequency is not much higher, at just 0.12 Hz. So for any frequency >1Hz or so we can treat C3 as a short and only R6 is in the circuit.
Finally, C2 and R5 form a cutoff at 106Hz. For frequencies below that C2 is pretty much a non-factor, leaving only the huge R5.
This leaves us with a cirucuit that has a gain of R5/R6 (50dB) for frequencies in about the 0.2Hz-50Hz range, dropping off to zero at DC (with the 3dB point at 0.12Hz) and a high end rolloff at 106Hz that drops to a minimum gain of 1.0.
I would call this either a bandpass filter, or just a low pass with a DC blocker. Or I suppose more accurately, a "low shelf filter" as the high end gain doesn't go to zero but to unity.


text:
Q: How to create mongodb schema with indexes using phpunit setup? (SF2) I want to create the mongodb schema ensuring indexes using doctrine mongodb odm.
I'm using Symfony 2, Doctrine ODM with mongodb and PHPUnit 4.5.0
One similar question has as suggestions using commands: Symfony2: Creating Schema in PHPUnit only runs one command at a time
But I want to do something more internal like:
PHPUnit code
public function setUp() {
    //Get kernel and create mongodb schema with indexes
    $kernel->getContainer()->get('doctrine.odm.mongodb.document_manager')->  Generate Schema??
}

public function tearDown() {
    //Drop entire schema
}

What are my options?


text:
Q: how can i append selected row data in another table what my task is I am using a table with two different conditions like in the first table whatever data coming I will show that in the first table and in the second table whatever row I select in the first table that I want to show in the second table as the second table I called select summary so my task is in the first table whatever row I selected in need to how that row in the second table I am using same table component for this for better you can see CodeSandBox link
import React, { useState, useMemo, useEffect } from "react";
import {
  Grid,
  makeStyles,
  CardContent,
  Card,
  Box
} from "@material-ui/core";
import EnhancedTable from "./EnhancedTable";

const useStyles = makeStyles((theme) => ({
  root: {
    padding: theme.spacing(0, 2, 2),
  },
  formGrid: {
    padding: theme.spacing(2),
  },
  cardColor: {
    borderColor: "#0bb7a7",
  },

}));

function AddToExclusionList() {
  const classes = useStyles();
  const [sanctionsList, setSanctionsList] = useState([]);
  const updateListsRow = ({ index, value, row }, listType) => {
    switch (listType) {
      case "sanctions":
        setSanctionsList((prevState) => {
          prevState[index].status = value;
          return [...prevState];
        });
        break;
      default:
    }
  };

  return (
    <Grid className={classes.root}>
      <Grid item xs={12} style={{ textTransform: "capitalize" }}>
        <Card className={classes.cardColor} variant="outlined">
          <CardContent>
              <>
                <EnhancedTable
                  show={true}
                  step="first"
                />
              </>
          </CardContent>
        </Card>
      </Grid>
      <Box mt={3}></Box>
      <Grid item xs={12} style={{ textTransform: "capitalize" }}>
        <Card className={classes.cardColor} variant="outlined">
          <CardContent>
              <>

summary table

                <EnhancedTable
                checkboxToggle={(rowDetails) => {
                  updateListsRow(rowDetails, "sanctions");
                }}
                />
              </>
          </CardContent>
        </Card>
      </Grid>
    </Grid>
  );
}

export default AddToExclusionList;

CodeSandBox Link

A: You've achieved your goal very weird! Anyway, based on your code in codesandbox. You need to add a state to AddToExclusionList component, like this:
  const [newRows, setNewRows] = useState([]);
  const setSummaryRows = (selectedRows) => {
    const copy = [...rows];
    const filteredRows = copy.filter((x) => selectedRows.includes(x.name));
    setNewRows(filteredRows);
  };

We need the mentioned state to update the summary table's rows.
Also add rows and setNewRows prop to EnhancedTable and give it rows from out of the component. In addition move rows and createData to App.js. So you should use EnhancedTable in App.js same as bellow:
<Grid className={classes.root}>
      <Grid item xs={12} style={{ textTransform: "capitalize" }}>
        <Card className={classes.cardColor} variant="outlined">
          <CardContent>
            <>

first table

              <EnhancedTable
                // passing data for rendering table according condition
                step="first"
                rows={rows}
                setNewRows={(selected) => {
                  setSummaryRows(selected);
                }}
              />
            </>
          </CardContent>
        </Card>
      </Grid>
      <Box mt={3}></Box>
      <Grid item xs={12} style={{ textTransform: "capitalize" }}>
        <Card className={classes.cardColor} variant="outlined">
          <CardContent>
            <>

summary table

              <EnhancedTable
                // trying to pasing selected data
                rows={newRows}
                setNewRows={() => {}}
              />
            </>
          </CardContent>
        </Card>
      </Grid>
    </Grid>

And the last part is using useEffect based on selected in EnhancedTable component:
  useEffect(() => {
    setNewRows(selected);
  }, [selected]);


text:
Q: Is it possible to use Digest Auth with Fetch in React Native? I am wondering if it is possible to use digest auth as headers together with Fetch in React Native? Or, are there any other alternatives? I have tried the following:
  const headers = new Headers();
  headers.append("Authorization", "Digest " + ("username:password"));
  return fetch(`url`,{
  headers: {
  headers,
  'Accept': 'application/json',
            'Content-Type': 'application/json'
 }
 })
.then((response) => response.json())
.then((responseJson) => {
  console.log("checked if on local server response")

  return responseJson;
})
.catch((error) => {
  console.log('checked if on local server response error')
});

A: There is an external module that works for RN:
https://github.com/besing/digest-auth-request-rn
This worked fine for me on Android but I had to make some local changes to get it working on iOS. I'll submit those modifications for you to benefit from.