text:
Q: Randomize a string list from a text file in an array Python? I have a text file with several countries listed in it called countries.txt. I am trying to take those countries from the text file and place them in an array where they will then be randomized and the randomized list gets printed. I have tried editing the code in a few ways and none of them produce the outcome that I want.
Below is the first way I tried it. I know I'm printing the actual array but I was trying something:
results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            print(str(results))

And the outcome was as follows:
['Armenia\n']
['Bangladesh\n', 'Armenia\n']
['China\n', 'Armenia\n', 'Bangladesh\n']
['Denmark\n', 'Bangladesh\n', 'Armenia\n', 'China\n']
['Armenia\n', 'Bangladesh\n', 'Denmark\n', 'China\n', 'Estonia\n']
['Armenia\n', 'Estonia\n', 'Bangladesh\n', 'China\n', 'France\n', 'Denmark\n']
['France\n', 'China\n', 'Bangladesh\n', 'Armenia\n', 'Estonia\n', 'Denmark\n', 'Ghana']

The second attempt used the following code below:
results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            print(str(line))

And the outcome was right in the sense that it listed the countries the way i wanted it, but it did not randomize them. The outcome was:
Armenia
Bangladesh
China
Denmark
Estonia
France
Ghana

The last attempt I made was with the following code:
results = []
def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(line)
            print(str(line))

But this function produced the following error:
File "C:\Users\redcode\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 274, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

And the specific line producing the error is random.shuffle(line).
Am I missing something or is there a different way to do this because I cannot find anything different from what I've been trying.
So how can I get the list from a text file into an array, randomize that list and print the outcome (without []or "\n" and in a normal list format as shown in the second example)?

A: In your second attempt, you're printing the line variable directly. You should print the items from the results list. Something like this should work:
results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            for result in results:
                print(str(result))

You might want to take the internal for loop I added out depending on how you want your results to show.

A: The first works -- except you shuffle the list again and again, after adding each line. Once at the end is enough.
The second does the same, except you don't print the list, you print the line you just added. Those are in the order in which they are in the file.
The third fails because you can't shuffle a string (because it's immutable). It makes no sense anyway.
The '\n' characters are newlines from the file. Use the string method .strip() to remove them.
Files have a handy helper method readlines() to read all the lines into a list at once.
But if you also want to use strip, it's easier to use a list comprehension:
with open('countries.txt') as inputfile:
    results = [line.strip() for line in inputfile]
results.shuffle()
for result in results:
    print(result)


text:
Q: Download Google Docs document as text file using Google Drive API for Android I have been able to set up a Google Drive file picker so that I can read the contents of any file selected by the user. However, I would like to be able to download Google Docs files selected by the user as text files and then read their content, though I have only been able to find solutions to do this using the Drive Rest API, which I believe is separate from the Google Drive API for Android. Is there any solution that would allow me to do this? Currently, my code for downloading files is as follows:
final private class RetrieveDriveFileContentsAsyncTask
        extends ApiClientAsyncTask<DriveId, Boolean, String> {

    public RetrieveDriveFileContentsAsyncTask(Context context) {
        super(context);
    }

    @Override
    protected String doInBackgroundConnected(DriveId... params) throws IOException {
        String contents = null;
        DriveId driveId=params[0];
        DriveFile file = driveId.asDriveFile();
        DriveApi.DriveContentsResult driveContentsResult =
                file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
            return null;
        }
        DriveContents driveContents = driveContentsResult.getDriveContents();
        BufferedReader reader = new BufferedReader(new InputStreamReader(driveContents.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append('\n');
        }
        contents = builder.toString();
        driveContents.discard(getGoogleApiClient());
        return contents;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result == null) {
            return;
        }
        Intent intent=new Intent(getContext(),NotesActivity.class);
        intent.putExtra("setTextTo",result);
        startActivity(intent);
    }
}

A: No Google Drive Android API doesn't provide the convert functionality. You would need to use the REST API for that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that the change of variables transforms a linear system Show that the change of variables $x=2u+v$, $y=3u+v$ transforms the linear system
$$
\left\{
\begin{aligned}
x'(t) &= \phantom{3}x-2y \\
y'(t) &= 3x-4y
\end{aligned}
\right.
$$
into
$$
\left\{
\begin{aligned}
u'(t) & = -2u \\
v'(t) &= -v
\end{aligned}
\right.
$$
Verify that the $u$-axis maps to the line $y=\frac{3}{2}x$ and the $v$-axis maps to the line $y=x$.
I thought for this I would just have to plug the substitutions into $x'(t)$ and $y'(t)$ but when doing this I receive
$$
\left\{
\begin{aligned}
u'(t) &= 2u+v-2(3u+v)    \hskip-15pt&= -4u-v \\
v'(t) &= 3(2u+v)-4(3u+v) \hskip-15pt&= -6u-v
\end{aligned}
\right.
$$
What am I doing wrong?

A: You're on the right track, but what you've shown is that
$$
\left\{
\begin{aligned}
x' &= -4u-v \\
y' &= -6u-v
\end{aligned}
\right.
$$
By subbing in expressions in $u$ and $v$ for $x$ and $y$, you can convert the right sides of these equations to the new variables. But you also need to convert the left sides (the derivatives), and for that you need to reverse that change of variables.

Details: using your favorite technique from linear algebra, you can find
$$
\left\{
\begin{aligned}
x &= 2u + v \\
y &= 3u + v
\end{aligned}
\right.
\qquad\Longleftrightarrow\qquad
\left\{
\begin{aligned}
u &= -x + \phantom{2}y \\
v &= \hskip2.5pt 3x - 2y
\end{aligned}
\right.
$$
Thus,
\begin{align}
u' &= (-x + y)' \\
&= -x' + y' \\
&= -(x-2y) + (3x-4y) \\
&= 2x - 2y \\
&= 2(2u+v) - 2(3u+v) \\
&= -2u
\end{align}
I leave the analogous calculation that $v' = -v$ up to you.

If you squint really hard, you can see that what you are doing is diagonalizing a square matrix by converting to basis of eigenvalues:
$P^{-1}AP = D$, i.e.
$$
\begin{bmatrix}
-1 & 1 \\ 3 & -2
\end{bmatrix}
\begin{bmatrix}
1 & -2 \\ 3 & -4
\end{bmatrix}
\begin{bmatrix}
2 & 1 \\ 3 & 1
\end{bmatrix}
=
\begin{bmatrix}
-2 & 0 \\ 0 & -1
\end{bmatrix}
$$


text:
Q: how to provide jks file (two way auth) on openssl or curl cmd I need to connect to a web service that listens on a port 11902 .
URL of WS = https://apps1618:11902/sng/recon. There is  two way authentication  enabled here. I have been provided two jks file  app_01.jks (with keypass ) and  app_trust_01.jks (along with capass ) . To test that web service listens I want to use openssl or curl or wget cmd to post some data to WS .
I ran openssl cmd =>
openssl s_client -connect apps1618:11902

CONNECTED(000000003)

depth=0 /C=PK/Lopac/o=apps/OU=plsop/CN=app_01
verify error:num=18:self signed certificate

verify return :1

depth=0 /C=PK/Lopac/o=apps/OU=plsop/CN=app_01

verify return:1

28693:error:14094412:SSL routines:SSL_READ_BYTES:ssl alert bad certificate:s3_pkt.c:SSL alert number 42

28684:error:1409401E:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:

I believe above error is coming because it is two way authentication and i have not provided private key and trust cert  through the cmd .
I am not aware  how to provide jks file  through openssl cmd .
I extracted certificate from both jks files in their respective .cer files and ran below curl cmd
curl -X POST -d @< path >/mydata --cacert < path >/apps_trust_01.cer https://apps1618:11902

curl(:60) error setting certificate verify location

I am unable to use  either of the command to connect to  server.
However  , i checked logs at server side and found that it is getting  my request and  printing  ssl handshake exception (certificate_unknown)
Please provide some pointer that can help me  in understanding how to provide public and  private keys or certificate through any of those commands.
Apologies for my ignorance .
--
Thanks in advance .


text:
Q: Excluding a JPA entity from Hibernate persistenceContext caching? I'm building a web-app with Spring, and JPA backed by Hibernate 4.3.6 for persistence. Some background: job results are being stored in a repository, and a ResultsController checks on them. The front-end uses long polling, so the ResultsController creates a DeferredResult object and then spins off a thread to check periodically for completion of the job so that it can fill in the deferred result and trigger the response.
private DeferredResultsResponse getResults(String idString, String runType, boolean returnOnNotDone) {
    String userId = userService.getCurrentUser();

    // Some basic checks; is the ID a valid format, etc. Not relevant,
    // but the "response" variable is set if we find a problem

    final DeferredResultsResponse deferredResult = new DeferredResultsResponse(runId, runType, userId, returnOnNotDone);
    if (response != null) {
        deferredResult.setResult(response);
    } else {
        Thread t = new Thread(() -> completeResult(deferredResult));
        t.run();
    }

    return deferredResult;
}

private void completeResult(final DeferredResultsResponse result) {
    final ResultsIdentifier id = new ResultsIdentifier(result.getJobId(), result.getRunType());
    int attemptCount = 0;
    boolean returnOnUnfinished = result.isReturnOnUnfinished();

    while (!result.hasResult() && attemptCount < MAX_ATTEMPTS) {
        attemptCount++;
 // ------- Problem line: -----------
        Optional<JobStatus> statusMaybe = jobStatusService.get(new ResultsIdentifier(result.getJobId(), result.getRunType()));

        if (!statusMaybe.isPresent()) {
            result.setResult(new ResultsResponse(null, false, null, "Unable to find job status entry."));
            continue;
        }

        JobStatus status = statusMaybe.get();
        // Incomplete job cases: sleep or respond "not done" based on the flag
        if (!status.isComplete() && returnOnUnfinished) {
            result.setResult(new ResultsResponse(false, false, null, null));
            continue;
        } else if (!status.isComplete()) {
            sleep();
            continue;
        }

        // Cases of completion: respond based on success
        // Various business logic of processing results
    }
    if (!result.hasResult()) {
        result.setResult(new ResultsResponse(true, false, null, String.format("Time out after %d checks", MAX_ATTEMPTS)));
    }
}

The issue is this: the query on the Problem Line doesn't ever report changes in the job's status. After some looking, I tracked this down to the innards of Hibernate. In SessionImpl there is a field of type StatefulPersistenceContext, and it is keeping a copy of the JobStatus object from the first time it's pulled out of the database. It then reuses that copy on all subsequent queries in the same session.
Now, I gather that I can solve this by getting the current session and calling clear(), or refresh(status). However, to me, having to pull back the JPA curtain and use Hibernate stuff directly when everywhere else it's mediated through the Spring/JPA repositories is bad form. So, is there any way to mark up an ORM XML file to exclude a particular type from being cached in the PersistanceContext?

For reference, here is JobStatus.xml:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
             version="2.0">
<entity class="project.model.JobStatus">
<attributes>
  <embedded-id name="jobIdentifier" />

  <basic name="complete" optional="false" />
  <basic name="userId" optional="false" />

  <basic name="successful" optional="true" />
  <basic name="message" optional="true" />

  <basic name="lastUpdateTime" optional="false">
    <temporal>TIMESTAMP</temporal>
  </basic>
</attributes>
</entity>
</entity-mappings>

jobIdentifier is an  which contains nothing but the single  element with no children.
Also, here is the JobStatusService with transaction annotations:
public interface JobStatusService {

/**
 * Retrieve the statuses of all jobs for the current user.
 * @return All jobs' statuses
 */
@Transactional(readOnly = true)
Iterable<JobStatus> getAllByUser();

/**
 * Retrieve the status of a particular job
 * @param identifier the combined job ID and type
 * @return  The persisted job status
 */
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
Optional<JobStatus> get(ResultsIdentifier identifier);

/**
 * Save the passed status, subbing in the current user's ID if none is set,
 * and updating the "last updated" time
 * @param status the job status object
 * @return  The persisted status object
 */
@Transactional(readOnly = false)
@Modifying
JobStatus save(JobStatus status);

/**
 * Delete the status of a particular job
 * @param identifier the combined job ID and type
 */
@Transactional(readOnly = false)
@Modifying
void remove(ResultsIdentifier identifier);

/**
 * Remove all stored job statuses for the given user id.
 * @param userId User id
 */
@Transactional(readOnly = false)
@Modifying
void clearByUser(String userId);

A:
the ResultsController creates a DeferredResult object and then spins off a thread

Actually, no, that's not what it does. You never start the thread. You're executing everything in the same thread, and you only return the deferred result once completeResult() has returned. To really start a thread, you would have to replace
t.run();

by
t.start();

Now, to make sure the problem line always goes to the database and reloads the new value of the job status,what you should do is to make sure that jobStatusService.get() runs in a separate transaction. Using Spring, that is typically done by annotating the method with
@Transactional(propagation = Propagation.REQUIRES_NEW)


text:
Q: Ag-Grid - display custom groups without having records in that group? I've got a grid with records grouped by Category.  Here's an example of the data I'd have:
[{id:1, category:"a", status: "open"},{id:2, category:"b", status: "open"},{id:3, category:"b", status: "closed"}]
So, grouped by category, it would show

*

*a (1)

*b (2)

and if I click the expander for "b", it would show records 2 and 3.
Now....  let's say I change the category of record 1 to "b", it would show:

*

*b (3)

What my client wants to see is this:

*

*a (0)

*b (3)

Since the grouping is automatic, can I do that?
I tried adding a fake record and then customizing the group header title to show 0, since it would otherwise show 1 record (the blank one), but it's such a lame hack, I was sure there must be a better way.


text:
Q: SQL, how to join three tables with no xref in second table? I have three tables in below format:
Table_1
Plan_ID  Plan_Code   Plan_Description  Location_ID
 1          A           Plan A             1

Table_2 (Currently now rows)
ID   Plan_ID  Procedure_ID   Discount

Table_3
Procedure_ID   Procedure_Name  Procedure_Fee     Location_ID
   1                 P1             10              1
   2                 P2             20              1
   3                 P3             30              1
   4                 P3             30              2

So I need to write a query which outputs below result when Plan_Id is passed and also by matching Table 1 and 3 Location_ID:
Plan_ID  Plan_Code   ID   Procedure_ID  Procedure_Name  Procedure_Fee Discount
   1          A       0        1               P1            10          0
   1          A       0        2               P2            20          0
   1          A       0        3               P3            30          0

Also in Table_2, if we have a cross reference rows
ID   Plan_ID  Procedure_ID   Discount
 1      1          2            5

Below should be the query output:
Plan_ID  Plan_Code   ID   Procedure_ID  Procedure_Name  Procedure_Fee Discount
   1          A       0        1               P1            10          0
   1          A       1        2               P2            20          5
   1          A       0        3               P3            30          0

So far I have tried :
declare @planID int =1
SELECT t1.Plan_ID,
    t1.Plan_Code,
    t2.ID,
    t3.Procedure_ID,
    t3.Procedure_Name,
    t3.Procedure_Fee,
    t2.Discount
FROM table1 tl
LEFT JOIN table2 t2
    on t1.Plan_ID=t2.Plan_ID
RIGHT JOIN table3 t3
    ON t2.Procedure_ID  = t3.Procedure_ID and t1.Location_Id=t3.LocationID
where t1.Plan_Id = @planID

But because of where condition, query does not output any result but when i replace where condition in first join, I get incorrect output. I have tried running query with different table sequence and join option but could not succeed.

A: Since table 2 may or may not have a matching row, you need to handle the missing data in the matches between table 1 and table 2:
declare @planID int = 1;

SELECT t1.Plan_ID,
    t1.Plan_Code,
    if(t2.ID IS NULL,0,t2.ID) as `ID`,
    t3.Procedure_ID,
    t3.Procedure_Name,
    t3.Procedure_Fee,
    IF(t2.Discount IS NULL,0,t2.Discount) as `Discount`
FROM table1 tl
JOIN table3 t3
    ON t1.Location_Id = t3.LocationID
LEFT JOIN table2 t2
    ON t2.Procedure_ID  = t3.Procedure_ID and t1.Plan_ID = t2.Plan_ID
where t1.Plan_Id = @planID;


text:
Q: Ubuntu Gnome 3.0 Ctrl+Alt+Shift+R Screencast Recorder not working I'm trying to record a video, but nothing is happening when I'm pressing Ctrl+Alt+Shift+R, while the wiki claims that I'm supposed at least to see a red circle at the bottom.
Are there some prerequisites? I've just installed the Gnome and haven't tweaked any settings. Here's some system info:
lsb_release -a
Release:    12.10

and,
$ gnome-shell --version
GNOME Shell 3.6.3.1

A: I upgraded the gnome shell to v 3.8 and the recording is working as expected now.


text:
Q: Kafka multiple partitions of the same topic in the same broker While diving deep into Kafka, a question like below came to mind.
Can Kafka have multiple partitions of the same topic in the same broker?
At first, I thought I would be undesirable since it contradicts to the purpose of partitions - making redundancy for high availability. But in some way, there are no reasons not to supply this.
Is this possible in Kafka? If so, is this kind of setting used a lot in practice?

A:
Can Kafka have multiple partitions of the same topic in the same broker?

Yes, it totally can. For example:
╰─$ ./bin/kafka-topics.sh --bootstrap-server localhost:9092 \
                          --create --topic rmoff-test \
                          --partitions 6 \
                          --replication-factor 1
Created topic rmoff-test.

╭─rmoff@asgard03 ~/Downloads/kafka_2.13-3.1.0
╰─$ kcat -b localhost:9092 -L
Metadata for all topics (from broker 1: localhost:9092/1):
 1 brokers:
  broker 1 at localhost:9092 (controller)
 1 topics:
  topic "rmoff-test" with 6 partitions:
    partition 0, leader 1, replicas: 1, isrs: 1
    partition 1, leader 1, replicas: 1, isrs: 1
    partition 2, leader 1, replicas: 1, isrs: 1
    partition 3, leader 1, replicas: 1, isrs: 1
    partition 4, leader 1, replicas: 1, isrs: 1
    partition 5, leader 1, replicas: 1, isrs: 1

It's possible you're mixing up the concept of partitions (used for strict ordering and high throughput) with that of partition replicas (used for availability/fault tolerance).
You cannot have multiple replicas on one broker. If you try to create a topic with more replicas than available brokers it will fail:
╰─$ # There is one broker running
╰─$ kcat -b localhost:9092 -L | grep broker
Metadata for all topics (from broker 1: localhost:9092/1):
 1 brokers:
  broker 1 at localhost:9092 (controller)

╰─$ # Now try to create a topic with _one_ partition but _two_ replicas:
╰─$ ./bin/kafka-topics.sh --bootstrap-server localhost:9092 \
                          --create --topic rmoff-test-2 \
                          --partitions 1 \
                          --replication-factor 2

Error while executing topic command : Unable to replicate the partition 2 time(s): The target replication factor of 2 cannot be reached because only 1 broker(s) are registered.
[2022-03-11 09:51:33,721] ERROR org.apache.kafka.common.errors.InvalidReplicationFactorException: Unable to replicate the partition 2 time(s): The target replication factor of 2 cannot be reached because only 1 broker(s) are registered.
 (kafka.admin.TopicCommand$)


text:
Q: Logitech M705 left mouse button doesn't stay down when pressed I'm nearly sure that this is only solvable by replacement of the device but I'd like to vent the issue.
About 9 months ago i got a nice Logitech M705 mouse. which inspired me to add paging via scroll wheel to my mupdf and now i think i wouldn't like it any other way. well, back to the present.
The symptoms are that the left mouse button can't be held down. It'll emit multiple button release and press events when pressed down and more when released. This makes drag and drop impossible. I've opened the mouse and verified that it has the same problem even when the actual button is pressed by hand and that it's not due to any damage nor dirt. What's funny is that the scroll wheel and the right button work as they should producing only one press event when pressed and one release event when released.
Due to that I know that it isn't a problem with anything in my computer as if it was you'd think it would effect the right mouse button too. And it's not a problem with the wireless as the mouse tracks nicely (although it doesn't track as good on worn particle board which is uneven do to water exposure as this Logitech M-UR69 but that's a wired usb mouse).
And I can see the extra button events using xev these only appear when the left button is pressed but not the right for that it gives the perfect response of one press event when pressed and one release event when released.
So if its not my laptop nor the wireless and it doesn't effect the right button or the wheel nor the tracking, it must be that i broke in some weird way the left mouse button's switch.

I did find that some one else had this issue with this mouse:

I've recently encountered problems with the left mouse button not
  staying closed when I hold it down. Trying to drag things across the
  screen becomes a major malfunction when the button lets go and I have
  no idea where the icon was just dropped. Taking the mouse apart and
  blowing it out thoroughly seemed to resolve the issue but why did I
  need to do that to a six month old mouse in the first place? And how
  long before the problem comes back?

From http://reviews.logitech.com/7061/5843/logitech-marathon-mouse-m705-reviews/reviews.htm
That's what made me think that it could have been a dirt issue, but I didn't find that helped.

A: Well the best way to solve this would be to return the device, as it's supposed to have a 3 year warranty.
The microswitch is obviously damaged and all basic solutions would require you to attempt to modify it or its circuit. From your text, I can't see if it shows multiple clicks when the switch itself is held pressed. If it doesn't, then you could try to solve the problem by adding something between the switch itself and the button which would increase the pressure on the switch, but it won't be a long term solution. In situation such as this, the switch is already sparking too much and the contacts are probably already damaged with tendency to get worse so even if this helps, it won't be a long term solution.
If the switch opens even while held pressed, then a little bit of some sort of contact cleaner could be helpful if there's a way to actually insert it inside the switch, but that could be difficult since most of those switches aren't constructed with ability to be opened in mind.
If you happen to have a similar switch,  you could try to replace the whole switch, but then you'd probably lose the warranty, in case something similar happens again.

A: I had the same problem with the left button of my M705 and it turned out that it was indeed caused by a bad contact in one of the microswitches (an Omron D2FC-F-7N), which contained a copper part that was oxidized. I managed to fix this issue by opening the switch and removing the oxide from the contact pad, here's how to do it:

*

*First, open the mouse. To do this, you need to remove the five screws that hold together the housing: Three of them are located under the black contact pads on which the mouse glides (the pads are just glued so you can remove them by pulling) and two are on the bottom of the battery compartment.

*Open the housing of the defective microswitch by inserting the tip of a sharp knife or screwdriver into the slit between the black, upper part of the housing and the dark grey, lower part, first pushing the upper part slightly to the side and then upwards.

*In the switch there is a small copper plate that connects to a contact pad on the lower part of the switch when the button is pressed down. Remove the plate by gently pulling it first to the side and then up. There is a small bump on the bottom right side of the plate that makes the contact with the lower part of the switch:
Both the bump on the plate and its counterpart on the switch will probably be covered with a dark, bluish oxide that we want to remove: To do this, use a knife or a rasp to slightly roughen up the surface until it appears shiny and bright again. Then put all parts back into place and close the switch and the mouse.

*Now the switch should again establish a reliable electric contact when pressed down, at least until it re-oxidizes...

Alternatively you could just replace the whole microswitch by a new one, which should cost less than a few dollars but is much less fun of course ;)
Also, before you jump into repairing your mouse check if it's still under warranty and if so consider having it replaced by Logitech, since opening it up will usually void its warranty.
This procedure should also be applicable to other mice that contain the same microswitch, most notably to Logitech G series, Apple's 3G, 4G, 5G series, some Razer mice and Microsoft's Intellimouse Optical.


text:
Q: How to use png files as icons in a Flutter app? To be able to use my icons, I upload them to fluttericon.com but it only accepts svg files. Since my icons are in .png format, I'm using a converter to convert them into svg. After the conversion, I upload them but it seems like they are not identified correctly by fluttericon.com, yet I'm unable to see icons on the app.
There is a custom bottom navigation bar in my app and it only accepts iconData as argument. So I have to use an actual icon. I tried using the custom icon on AppBar to be able know if it's bottom navigation bar causing the problem but it's same.
I read some comments saying the content of svg matters. Cause when I download a random icon in svg format directly and upload it, it's identified properly on fluttericon.com. What do I need to do?

A: Use icon: Image.asset("assets/home.png")
full code example:
class MyTabBar extends StatefulWidget {
  @override
  _MyTabBarState createState() => _MyTabBarState();
}

class _MyTabBarState extends State<MyTabBar>  with TickerProviderStateMixin {
  int tabIndex=0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: tabIndex ==0 ?BottomTabBarHome()
        :tabIndex == 1? BottomTabBarMail(): BottomTabBarProfile()
      ),

      bottomNavigationBar: BottomNavigationBar(
        items:  <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Image.asset("assets/home.png", color: Colors.grey,),
            activeIcon: Image.asset("assets/home.png", color: Colors.blue,),
            title: Text('')
          ),
           BottomNavigationBarItem(
            icon: Image.asset("assets/mail.png", color: Colors.grey,),
            activeIcon: Image.asset("assets/mail.png", color: Colors.blue,),
            title: Text('')
          ),
           BottomNavigationBarItem(
            icon: Image.asset("assets/account.png", color: Colors.grey,),
            activeIcon: Image.asset("assets/account.png", color: Colors.blue,),
            title: Text('')
          )
        ],
        currentIndex: tabIndex,
        selectedItemColor: Colors.blueAccent,
        onTap: (int index){
          setState(() {
            tabIndex = index;
          });
        },
      ),
    );
  }

}

class BottomTabBarHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(" Home Screen"),
      ),
    );
  }
}
class BottomTabBarMail extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("Mail Screen"),
      ),
    );
  }
}
class BottomTabBarProfile extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(" Profile Screen"),
      ),
    );
  }
}

A: pulled some code from my old project:
basic idea is that the icon or activeIcon named parameter asks for a Widget, includes but not limited to an Icon widget.
            BottomNavigationBarItem(
              title: Text('REALTIME SCHEDULE'),
              activeIcon: TrackIcon(colorValue: Colors.white70),
              icon: TrackIcon(colorValue: Color(0xff424150)),
            ),

class TrackIcon extends StatelessWidget {
  final Color colorValue;
  TrackIcon({@required this.colorValue});
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 33,
      width: 99,
      child: Image.asset(
        'images/track_icon.png',
        height: 25,
        color: colorValue,
      ),
    );
  }
}

A: Here's how I used my png images as icons:
icon: const ImageIcon(
          AssetImage('assets/image.png'),
        ),

It worked perfectly for me :).

A: As the above answers are useful (with just a few lines of edit), let me simplify
Use this line of code for using you PNG icons
icon: Image.asset("assets/home.png", color: Colors.grey,)

Now go to the folder containing the files of your flutter package for bottomNavigationBar and either edit the package itself OR copy the files into a folder flutterApp/packages/your_package/[those dart files] (second option is better to test with hot reload).
Note: flutterApp is the root folder of your flutter app.
Note: If you decided to edit the package itself in flutter/.pub-cache/hosted/... then you have to stop and re-run the debugging session after each edit for it to take effect.
Note: If you decided to copy the package files in your flutterApp then add them in your pubspecs.yaml as
dependencies:
  your_package:
    path: packages/your_package

Now, what to edit?
Find the constructor parameter icon or whatever it is. Now change its type from IconData (mostly) to Widget and now find the usage with simple searching/looking for the keyword and adjust/fit in the changed icon parameter as a Widget.
for example, if the usage looks something like this:
Icon(
  widget.icon,
  ...
),

change it to:
widget.icon

because Icon() is also a widget which used the earlier IconData widget.icon and as we have converted that to Widget itself we can simply use widget.icon instead of Icon().

A: To add png to our code

*

*add the below lines on pubspec.yaml
  assets:
   - lib/images/swap.png

*in main.dart use the same directory

  child: Image.asset('lib/images/swap.png')


text: Q: kubeadm pro configured admin.conf Can I just use my own admin.conf before kubeadm init and after that kubeadm will use the file for authorization? This will be really convenient for accessing this cluster outside it because I don't need to process the certs and keys each time.


text:
Q: Nextjs SendGrid Mailing Warning: List API resolved I am trying to setup a Sendgrid Newletter signup, using the following code, stored in pages/api
import axios from "axios";

export default async function handler(req, res) {
 if (req.method === "PUT") {
   axios
     .put(
       "https://api.sendgrid.com/v3/marketing/contacts",
       {
         contacts: [{ email: `${req.body.mail}` }],
         list_ids: [process.env.SENDGRID_MAILING_ID],
       },
       {
         headers: {
           "content-type": "application/json",
           Authorization: `Bearer ${process.env.SENDGRID_SECRET}`,
         },
       }
     )
     .then((result) => {
       // return
       res.status(200).send({
         message:
           "Your email has been succesfully added to the mailing list. Welcome ",
       });
     })
     .catch((err) => {
       // return
        res.status(500).send({
         message:
           "Oups, there was a problem with your subscription, please try again or contact us",
       });
     });
 }
}

The front end component looks similar to
import axios from "axios";
import { toast } from "react-toastify";
import { useState } from "react";

const MailingList = () => {
  const [mail, setMail] = useState(null);
  const [loading, setLoading] = useState(false);

  const subscribe = () => {
    setLoading(true);
    axios
      .put("api/mailingList", {
        mail,
      })
      .then((result) => {
        if (result.status === 200) {
          toast.success(result.data.message);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  return (

        Stay Tuned!

          Want to be the first to know when SupaNexTail launches and get an
          exclusive discount? Sign up for the newsletter!

        <input
          onChange={(e) => {
            setMail(e.target.value);
          }}
          type='email'
          placeholder='Your email'
          className='input input-primary input-bordered'></input>
        <button
          onClick={subscribe}
          className={`btn ml-3 ${
            loading ? "btn-disabled loading" : "btn-primary"
          }`}>
          I'm in!
        </button>

  );
};

export default MailingList;

The emails are actually being added to the Sendgrid mailing list, but no response error is being displayed, email field is not cleared. And this is displayed in the console:
API resolved without sending a response for /api/MailingList, this may result in stalled requests.

The same console warning is displayed when return res.status(..
Need some advice on how to solve this!


text:
Q: jquery incorrect product availability result i made a custom product availability code in which it checks for product size (tshirts) being available or not . the problem is even if the size is not available its showing the defualt selected size its price + price of one more size which is available when we click on that size which is not available . For eg. three sizes , medium , small and large. suppose medium and large is available then when we click on small it should not show any price but its showing prices of all available in it. if there are more sizes such as extra small it shows its price to will rest of the sizes price which it should not. though it works fine when all sizes are available . the code i wrote is can anyone suggest me where i am wrong?
    $.fn.contentTabs = function(o){
        // default options
        var options = $.extend({
            activeClass:'active',
            addToParent:false,
            autoHeight:false,
            autoRotate:false,
            animSpeed:400,
            switchTime:3000,
            effect: 'none', // "fade", "slide"
            tabLinks:'a',
            event:'click'
        },o);

        return this.each(function(){
            var tabset = $(this);
            var tabLinks = tabset.find(options.tabLinks);
            var tabLinksParents = tabLinks.parent();
            var prevActiveLink = tabLinks.eq(0), currentTab, animating;
            var tabHolder;

            // init tabLinks
            tabLinks.each(function(){
                var link = $(this);
                var href = link.attr('href');
                var parent = link.parent();
                href = href.substr(href.lastIndexOf('#'));

                // get elements
                var tab = $(href);
                link.data('cparent', parent);
                link.data('ctab', tab);

// find tab holder
if(!tabHolder && tab.length > 0) {
   tabHolder = tab.parent();

}

                // show only active tab
                if((options.addToParent ? parent : link).hasClass(options.activeClass)) {
                    prevActiveLink = link; currentTab = tab;
                    tab.removeClass(tabHiddenClass).width("");
                    contentTabsEffect[options.effect].show({tab:tab, fast:true});
                } else {
                    contentTabsEffect[options.effect].hide({tab:tab, fast:true});
                    tab.width(tab.width()).addClass(tabHiddenClass);
                }

                // event handler
                link.bind(options.event, function(e){
                    if(link != prevActiveLink && !animating) {
                        switchTab(prevActiveLink, link);
                        prevActiveLink = link;
                    }
                    e.preventDefault();
                });
                if(options.event !== 'click') {
                    link.bind('click', function(e){
                        e.preventDefault();
                    });
                }
            });

            // tab switch function
            function switchTab(oldLink, newLink) {
                animating = true;
                var oldTab = oldLink.data('ctab');
                var newTab = newLink.data('ctab');
                currentTab = newTab;

                // refresh pagination links
                (options.addToParent ? tabLinksParents : tabLinks).removeClass(options.activeClass);
                (options.addToParent ? newLink.data('cparent') : newLink).addClass(options.activeClass);

                // hide old tab
                resizeHolder(oldTab, true);
                contentTabsEffect[options.effect].hide({
                    speed: options.animSpeed,
                    tab:oldTab,
                    complete: function() {
                        // show current tab
                        resizeHolder(newTab.removeClass(tabHiddenClass).width(''));
                        contentTabsEffect[options.effect].show({
                            speed: options.animSpeed,
                            tab:newTab,
                            complete: function() {
                                oldTab.width(oldTab.width()).addClass(tabHiddenClass);
                                animating = false;
                                resizeHolder(newTab, false);
                                autoRotate();
                            }
                        });
                    }
                });
            }

            // holder auto height
            function resizeHolder(block, state) {
                var curBlock = block && block.length ? block : currentTab;
                if(options.autoHeight && curBlock) {
                    tabHolder.stop();
                    if(state === false) {
                        tabHolder.css({height:''});
                    } else {
                        var origStyles = curBlock.attr('style');
                        curBlock.show().css({width:curBlock.width()});
                        var tabHeight = curBlock.outerHeight(true);
                        if(!origStyles) curBlock.removeAttr('style'); else curBlock.attr('style', origStyles);
                        if(state === true) {
                            tabHolder.css({height: tabHeight});
                        } else {
                            tabHolder.animate({height: tabHeight}, {duration: options.animSpeed});
                        }
                    }
                }
            }
            if(options.autoHeight) {
                $(window).bind('resize orientationchange', function(){
                    resizeHolder(currentTab, false);
                });
            }

            // autorotation handling
            var rotationTimer;
            function nextTab() {
                var activeItem = (options.addToParent ? tabLinksParents : tabLinks).filter('.' + options.activeClass);
                var activeIndex = (options.addToParent ? tabLinksParents : tabLinks).index(activeItem);
                var newLink = tabLinks.eq(activeIndex < tabLinks.length - 1 ? activeIndex + 1 : 0);
                prevActiveLink = tabLinks.eq(activeIndex);
                switchTab(prevActiveLink, newLink);
            }
            function autoRotate() {
                if(options.autoRotate && tabLinks.length > 1) {
                    clearTimeout(rotationTimer);
                    rotationTimer = setTimeout(nextTab, options.switchTime);
                }
            }
            autoRotate();
        });
    }


text:
Q: User permission and software security I am developing an application in php codeigniter. Now I am worrried abt the permission.
I need page wise permission, page may be add records page, edit page, delete page and print report etc. There will be many users as well, and applicaiton will grow with passage of time.
If I implement ACL that will better for me or not
what can be ideal for me any suggestion.

A: First, let's clear up some terms: I personally use the security term for things like preventing SQL injection, XSS attacks, where we have to validate input, filter/sanitize values, take care of the dynamically generated SQL commands, take care of properly escaping output (for JSON or HTML text or HTML attributes), etc. This is not about what you are asking, if I understood well.
The access control or permissions system is where you give or deny access to a function for a user. It can be secure or not. I understand that to deny a user which does not have permission the access to a function may sound like "security", but I wouldn't use this specific word in this context, to avoid confusion.
Now, the answer:

I strongly recommend you create a few base controller classes to your needs. Read the following blog post carefully (it is short and useful): http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-base-Classes-Keeping-it-DRY
A code to check if the user is properly authenticated (logged in) is essential. If the user is not logged in, redirect to home page or login page.
For fine-grained control, you could create your ACL in the database using the users table, plus an actions table, plus an acl table...
The users table would contain the users data (id, name, login, password, etc)
The actions table would contain the id field and at least one more field containing what suits best for your application: it can be only the controller class name (the first part of the URL, for example: "products"), granting access to the whole "products" controller or not. Or you may want to include both the controller class AND the method name (the first and second parts of the URL, for example: "products/add" and "products/delete"), and so on.
To decide about the actions table is the most decisive step. Think very well about it, balance your needs (your "true" needs)... I developed a system where each and every action has its entry. It is good, but it needs work to be maintained.
A very useful column for the actions table is a human-readable description of the action.
The acl then would be nothing more than a column for the user id and another column for the action id.
A "master" grant/deny access field in the users table is useful too, in case you want to temporarily deny access from a specific user, without having to delete all his permissions and maybe having to restore it later.
With the database tables and your "controller/method" or "actions" strategy well defined, you can easily code in your base controller class a function which checks if the user have permission to execute the requested action.

This is the basic. In my system, I have the users administration interface, where I can grant/deny the actions for each user (I use an ExtJS tree with checkboxes). One of these actions is the own user management. I have gone one step further, where the user who can access the user management may "delegate" (grant/deny) to other users only the actions he himself has access to.
The system has several modules, and functions. The interface does not show anything the user does not have access. So, I have users who can see only a single or a couple of modules, and they don't even imagine the existence of the other modules.
It requires more work to manage all this, but the result worths.
I also log each granted access, so it is possible to track who did what, and when. This log feature is very very easy to add, since you have this base controller "master function" allowing or disallowing the users to perform the actions.
I hope I have helped. I've just shared a bit of what worked (and works) for me...


text:
Q: Why there is no pattern between a fractional growth rate and a unit-multiplied growth rate? For example, when increasing $20$ by $75\%$, we add $75\%$ of $20$, to $20$.  But, why when we increase $20$ by $200\%$, we don't add $200\%$ of $20$, to $20$? (Or, do we?)
Due to this inconsistency, it almost makes me feel like this procedure was invented synthetically, but agreed upon, nevertheless.

A: There is no inconsistency. If you want to add $200\%$ of $20$ to $20$, then you'd do it the same way that you'd add $75\%$ of $20$ to $20$.
For example,
\[ 0.75\times 20+20=20\times 1.75=35 \]
\[ 2.00\times 20+20=20\times 3.00=60 \]
It's the same arithmetic with just different numbers.

A: Like everyone said, there is no inconsistency. However, method of calculation do differ.
You are asking about increasing $20$ by its $200\%$. A $200\%$ of any number, means you want to double up the value, because $100\%$ means the number itself.
So, $200\%$ of $y$ means $2y$, and then you are increasing $y$ by $200\%$, it becomes $y+2y$
eventually.
A $75\%$ increase in 20 will mean, multiplying $20$ by a factor of $1.75$. Why? Because it will (indirectly) mean $20 + 0.75\times 20=20(1+0.75)=1.75\times 20$
I am not sure if there is a name to this process, but that's a very good way to deal with $\%ages$.


text:
Q: How to monitor or profile a slow .Net Web Application Can anyone tell me how to go about determining the culprit on a slow running process.  I have a page that queries an Active Directory and a SharePoint Server to get information.  It makes several calls to each Server (retrieving customer information).  I am wondering if there are any tools available to profile a web application looking for this type of information, slow running methods, etc.
Thanks for any tips given...

A: Try setting Trace="true" for Page like this
 <%@ Page ... Trace="true" ... %>

and it will generate trace info at the bottom of the page like this

And here's an MSDN post related to that.

A: Without any tool, start by surrounding "interesting" methods calls with Stopwatch.
Log the results somewhere ( I suppose you already have a log enabled ) and you probably will discover the performance pitfall. If this fails, follow the Oded reply ;)

A: Attach a profiler to the process.
There are several commercial ones - dotTrace, ANTS, memprofiler and others.
These will give you statistics regarding where time is spent, what functions were called most etc...
See this SO thread with recommendations.

Update:
This will supplant the information that trace="true" will give (as answered by @Bala) and give you more detail (for example, if you are calling both AD and SharePoint in PageLoad, you are no closer to an answer).

A: I recommend YourKit over some of the others. An I believe there is a free trial
http://www.yourkit.com/


text:
Q: I have to calculate the following integral: $\int \lvert\sin(k\cdot x)\rvert\, \mathrm{d}x,\quad k\in\mathbb{Z}$ I have to calculate the following integral: $$\int_0^\pi \lvert\sin(k\cdot x)\rvert\, \mathrm{d}x,\quad k\in\mathbb{Z}.$$
What I've tried, but is undoubtedly wrong:

A: $$\int_0^\pi |\sin k x| dx = k \int_0^{\frac{\pi}{k}} \sin k x \, dx = k \cdot \frac{2}{k} =2, \quad (k \in \mathbb{Z}_{>0}).$$
Similarly for $k \in \mathbb{Z}_{<0}$,$$\int_0^\pi |\sin k x| dx =2.$$
Of course $k=0$ requires special treatment:
$$\int_0^\pi |\sin k x| dx =0, \quad \text{when } k=0.$$
UPDATE
To evaluate the integral:
$$\int_0^{\frac{\pi}{k}} \sin k x dx = \left.\frac{1}{k} \cos kx\right|_{\frac{\pi}{k}}^0=\frac{1}{k}(1-(-1))=\frac{2}{k}.$$


text:
Q: Oracle "Starts With" text join, excluding nulls I am having some trouble. I am trying to build a SQL query that uses "starts with" logic. A little background first...
In the database that I've been tasked to write reports from, there is a "user" table and a "salesperson" table, with salespersons belonging to a user. In a not-so-brilliant move, the designer of the database decided to associate the salespersons through a substring match to their employee code. For example:
John Smith's "employee_code" would be "JS". But he has multiple "salespersons" to distinguish his different sale types. So he might have "JS1", "JS2", "JS3", etc., as his "salesperson_code".
To illustrate:
user table:
|----------|-----------|----------|---------------|
| username | firstname | lastname | employee_code |
|----------|-----------|----------|---------------|
| JSMITH   | John      | Smith    | JS            |
|----------|-----------|----------|---------------|

salesperson table:
|------------------|------------------|
| salesperson_name | salesperson_code |
|------------------|------------------|
| John Smith 1     | JS1              |
| John Smith 2     | JS2              |
| John Smith 3     | JS3              |
|------------------|------------------|

There is no foreign key on the salesperson table linking them to the user table, only the substring from the employee code.
I do not remember where I found this answer, but in my queries I've been doing this:
select user.name
from user user
inner join salesperson spn on spn.salesperson_code like user.employee_code || '%'

This logic successfully does the "starts with" match. However, there are users with blank employee codes and they, also, match this query.
What I am looking for: how do I modify this query so that if the employee_code is blank it will not match? I'm pretty newbie with Oracle queries. Other DBMS' have a starts with clause that will not match blank fields.
Thank you in advance for your help!

A: Try this
select user.name
from user user
inner join salesperson spn
on spn.salesperson_code like nvl(trim(user.employee_code),'-') || '%'

A: try
select user.name
from user user
inner join salesperson spn
  on spn.salesperson_code like DECODE (user.employee_code,
                                         NULL, NULL,
                                               user.employee_code || '%')

A: I would suggest using a regular expression to extract the non-digit parts of the salesperson code and optionally the digits part. Create a view for the table with these added fields or use it as a table expression in the query.
SELECT regexp_substr(salesperson_code,'\D+') AS employee_code,
       regexp_substr(salesperson_code,'\d+') AS employee_sales_no,
       salesperson_name, salesperson_code
FROM salesperson

Note: the regular expressions match one or more non-digits and one or more digits respectively.

A: Add an IS NOT NULL condition:
select *
from user
inner join salesperson spn
        on spn.salesperson_code like user.employee_code || '%'
       and user.employee_code is not null;


text:
Q: How to know the last launch time of an app Hi After doing lots of Search , I could not find the answer of a question, that seems somewhat simple.
I have multiple apps installed on device. Is there any way of finding the last launching date of all apps?

A: You could put the time and date in an SharedPref when the app opens.
Then, the next time you open the app the app reads the SharedPref and displays it.
Something like this:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Calendar c = Calendar.getInstance();

    SharedPreferences sp = this.getPreferences(Context.MODE_PRIVATE);

    String lastLaunch = sp.getString("launch", "First launch!");

    SharedPreferences.Editor editor = sp.edit();
    editor.putString("launch", c.getTime().toString());
    editor.commit();
}

The String lastLaunch is the last time it launched! If it's the first time the string is: "First launch!"
I hope that i have helped you a little bit :)

A: Based on your requirements from the comments above, I'm providing a method to share the launch times between a bunch of our apps using SharedPreferences.
Firstly, we need to allow our apps to share local storage so they can access preference data. For this, we use the sharedUserId property in the app manifest. This can be your own unique string and each of the apps that share the space must have this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.com.myapp"
    android:sharedUserId="string.user.id.here">

    ...

</manifest>

Secondly, we use the Application class to determine when the app comes to the foreground and when it does, write the timestamp in Context.CONTEXT_IGNORE_SECURITY mode to share between our apps:
public class MyApp extends Application implements ActivityLifecycleCallbacks {

    private boolean appInBg;
    private int TIMEOUT = 5000;
    private Handler mHandler = new Handler();

    @Override
    public void onActivityResumed() {
        if (appInBg) {
            writeToPref();
        } else {
            mHandler.cancelCallbacksAndMessages(null);
        }
    }

    @Override
    public void onActivityPaused() {
        mHanlder.postDelayed(new Runnable() {

            @Override
            public void run() {
                appInBg = true;
            }

        }, TIMEOUT);
    }

    ...

    private void writeToPref() {
         SharedPreferences prefs = myContext.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
         prefs.edit().putInt("last_run", System.currentTimeMillis()).apply();
    }
}

Here, we allow a buffer time of 5 seconds to switch between screens. This should be adequate in most cases.
Finally, we can read the written SharedPreference value as follows:
Context context = createPackageContext("example.com.myapp", 0);
SharedPreferences pref = context.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
int lastLaunch = pref.getString("last_run", System.currentTimeMillis());
// Similarly, for other apps.

Hope this solves your issue.


text:
Q: Mime mapping in domain.xml (Wildfly) I'm trying to use the mime-mapping element in domain.xml, but it doesn't seem to work. I need to change the behaviour of an already-existing app, so that CSV files are opened by Excel.
The web.xml file, as already deployed, contains the following:
<mime-mapping>
    <extension>csv</extension>
    <mime-type>text/csv</mime-type>
</mime-mapping>

I was hoping to add this to domain.xml, to override the older setting, but it still doesn't work.
        <servlet-container name="default">
            <jsp-config/>
            <session-cookie http-only="true" secure="true"/>
            <websockets/>
            <mime-mappings>
                <mime-mapping name="csv" value="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
            </mime-mappings>
        </servlet-container>

I don't want to go down the path of using a deployment overlay, as I don't want to manage a whole new web.xml file.
Any ideas?
Thanks


text:
Q: BootLoader and Application memory size in AVR I searched a lot a bout this question and I did not find any clear answer yet.
As you know, AVR microcontrollers e.g. Atmega128 have a Flash memory which can be divided into Bootloader and Application memory. I've adjusted the parameters of each one and loaded my boot and application load. Is there any way (using code or from terminal) to know the exact size of each memory and the available bytes????
Some people may be mention avr-size command. This command give me the size of the whole flash memory. I want to distinguish between boot and application memory.
Thanks in Advance

A: You have two firmwares, the bootloader and application, each will have its own size.
For each build, add the linker flag to your linking command line -print-memory-usage to make it print how much flash and RAM is used.
(This flag is not supported by every tool-chain, but AVR might support it)
More info: https://stackoverflow.com/a/41389481/2002198
Or, you can get the memory usage with avr-size:
avr-size -C --mcu=atmega168 project.elf

Reference: http://www.avrfreaks.net/forum/know-code-size-and-data-size
There's other detail you have to be aware: Depending the way you are loading your application (flash writing vs bootload loading) you will align the application with FLASH blocks (usually 2 kibs). Depending the way you are doing you will have smaller available flash memory to the application.

A: Just read the manual:

The actual address of the start of the Boot Flash section is deter-
  mined by the BOOTSZ fuses

and you will find your answer.

A: If you have already built your bootloader then you should be able to tell how big it is either by looking carefully at the steps you performed to build it, or by examining the HEX file for the bootloader.  The HEX file says exactly what addresses the code in it are written to.


text:
Q: My Laravel Project .htaccess getting 403 error I installing a Laravel application in my Namecheap server. I'm getting a 403 Error.
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
</IfModule>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(.*)$ /public/$1 [L,QSA]
</IfModule>


text:
Q: Open subgroup of units of local field (norm index computation) Let $k$ be a $\mathfrak{p}$-adic field, $K/k$ be a cyclic extension with Galois group $G = \langle \sigma \rangle$, and $U_K$ be the group of units in (the valuation ring of) $K$.  One of the results of Chapter IX of Lang's Algebraic Number Theory is the computation of the Herbrand quotient $Q(G, U_K) := (U_k : N^K_kU_K)/(\ker N^K_k : (1-\sigma)U_K)$ where $\ker N^K_k$ is the kernel of the norm as a homomorphism from $U_K$ to $U_k$. Knowing the value of this quotient is useful, e.g. in computing the index $(k^* : N^K_kK^*) = [K:k]$.
The trick Lang uses is as follows (from p. 188):

Let $\{\omega_\tau\}$ be a normal basis for $K$ over $k$. After multiplying the elements of this basis by a high power of a prime element $\pi$ in $k$, we can assume that they have small absolute value. Let $M = \sum_{\tau \in G} \mathcal{O}_k\cdot \omega_\tau$.

As far as I can tell, the reason for this first step is to ensure that the exponential map is well-defined on $M$, since the power series defining it only converges on sufficiently small neighborhoods of $0$.

The $G$ acts on $M$ semilocally, with trivial decomposition group. Furthermore, $\exp M = V$ is $G$-isomorphic to $M$ (the inverse is given by the log), and $V$ is an open subgroup of the units, whence of finite index in $U_K$. Therefore $1 = Q(G, V) = Q(G, U_K)$.

It's clear to me why this implies that $V$ has finite index ($U_K$ is compact).  However, I don't understand exactly why $V$ is open in $U_K$. Should this be obvious? Also, why does this depend on  $G$ being cyclic?


text:
Q: jQuery error in MVC project: Datepicker is not a function This is what is in my view:
@Html.TextBox("toDateFilter", "", new { @class = "datepicker" })
...etc
...etc

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

<script>
    $(document).ready(function () {
        $(".datepicker").datepicker();
    });
</script>

I am getting the error:

Datepicker is not a function.

I have followed the advice of all the other similar questions, and nothing has worked. I also changed the View to these imports instead:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.min.css" />

I also tried this instead:
var $j = jQuery.noConflict();
$j("#datepicker").datepicker();

Also I did check that the jquery-ui.min.js file loaded correctly.
Any ideas why this is going wrong? Let me know if I can supply more info...

A: Datepicker is not a function. i am also facing this issue.i have resolved it  using Jquery Noconflict function.
$.noConflict();
jQuery(document).ready(function ($) {
    $(function () {
        $('.datefield').datepicker();
    });
});

A: This is the answer from Starscream1984 in the comments, so props to them!
The issue is that the ready() function was being called before the jquery-ui.js script had finished loading.
This could not be fixed by moving it into the <head> nor loading the scripts from my own domain.
I was able to fix it simply by removing the ready() function entirely, and just running the contents.
If anyone knows how I can force the script to load first, or the ready() function to be called last, please let me know.

A: Have you tried doing something like this:
$(function () {
    $("#nameOfTheFieldInModel").datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true
    });
});

In document ready?


text:
Q: Difference in sequence of query generated in Django and Postgres for select_for_update I'm facing a strange situation, where sequence of query logged in Django and Postgres is different when using select_for_update() inside transaction.atomic() block.
Basically I've a ModelForm where I'm validating the cleaned_data against the database, for duplicate request. And then in create view's form_valid() method, I'm saving the instance. To have both the operation inside same transaction, I'm overriding post() method, and wrapping those two method calls inside transaction.atomic().
Here's the code for whatever I said above:
# Form
class MenuForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        user_id = kwargs.pop('user_id', None)
        super(MenuForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(MenuForm, self).clean()
        dish_name = cleaned_data.get('dish_name')
        menus = Menu.objects.select_for_update().filter(user_id=self.user_id)

        for menu in menus:
            if menu.dish_name == dish_name:
                self.add_error('dish_name', 'Dish already exists')
                return cleaned_data
        return cleaned_data

# CreateView
class MenuCreateView(CreateView):
    form_class = MenuForm

    def get_form_kwargs(self):
        kwargs = super(MenuCreateView, self).get_form_kwargs()
        kwargs.update({'user_id': self.request.session.get('user_id')})
        return kwargs

    def form_valid(self, form):
        user = User.objects.get(id=self.request.session.get('user_id'))
        form.instance.user = user
        return super(MenuCreateView, self).form_valid(form)

    def post(self, request, *args, **kwargs):
        form = self.get_form()

        with transaction.atomic():
            if form.is_valid():
                return self.form_valid(form)
            else:
                return self.form_invalid(form)

Now suppose I fire two request at the same time, to create a menu with same dish. I expect the second request to fail. But, both of them are passing. It looks like, the second transaction is not seeing the changes done in previous transaction. Because of which, the total menus remain the same in both the transaction that is returned by select_for_update().
Given that Postgres default Isolation level is READ COMMITTED, I expect the changes to be visible. So, I tried logging the queries to see that COMMIT; is fired at right time. Here's the query log by django and in postgres:
Django Log:
SELECT "menu"."id", "menu"."dish_id", "menu"."dish_name" FROM "menu" WHERE ("menu"."dish_name" = "Test Dish") FOR UPDATE; args=("Test Dish")
INSERT INTO "menu" ("dish_id", "dish_name") VALUES (2, "Test Dish") RETURNING "menu"."id"; args=(2, "Test Dish")
SELECT "menu"."id", "menu"."dish_id", "menu"."dish_name" FROM "menu" WHERE ("menu"."dish_name" = "Test Dish") FOR UPDATE; args=("Test Dish")
INSERT INTO "menu" ("dish_id", "dish_name") VALUES (2, "Test Dish") RETURNING "menu"."id"; args=(2, "Test Dish")

Postgres Log:
<2016-03-18 17:55:46.176 IST  0  2/31  56ebf3ca.aac0>LOG:  statement: SHOW default_transaction_isolation
<2016-03-18 17:55:46.177 IST  0  2/32  56ebf3ca.aac0>LOG:  statement: SET TIME ZONE 'UTC'
<2016-03-18 17:55:46.178 IST  0  2/33  56ebf3ca.aac0>LOG:  statement: SELECT t.oid, typarray
    FROM pg_type t JOIN pg_namespace ns
        ON typnamespace = ns.oid
    WHERE typname = 'hstore';

<2016-03-18 17:55:46.182 IST  0  2/34  56ebf3ca.aac0>LOG:  statement: BEGIN
<2016-03-18 17:55:46.301 IST  0  3/2  56ebf3ca.aac1>LOG:  statement: SHOW default_transaction_isolation
<2016-03-18 17:55:46.302 IST  0  3/3  56ebf3ca.aac1>LOG:  statement: SET TIME ZONE 'UTC'
<2016-03-18 17:55:46.302 IST  0  3/4  56ebf3ca.aac1>LOG:  statement: SELECT t.oid, typarray
    FROM pg_type t JOIN pg_namespace ns
        ON typnamespace = ns.oid
    WHERE typname = 'hstore';

<2016-03-18 17:55:46.312 IST  0  3/5  56ebf3ca.aac1>LOG:  statement: BEGIN
<2016-03-18 17:55:46.963 IST  0  3/5  56ebf3ca.aac1>LOG:  statement: SELECT "menu"."id", "menu"."dish_id", "menu"."dish_name" FROM "menu"
WHERE ("menu"."dish_name" = "Test Dish") FOR UPDATE
<2016-03-18 17:55:46.964 IST  0  2/34  56ebf3ca.aac0>LOG:  statement: SELECT "menu"."id", "menu"."dish_id", "menu"."dish_name" FROM "menu"
WHERE ("menu"."dish_name" = "Test Dish") FOR UPDATE
<2016-03-18 17:55:47.040 IST  23712  3/5  56ebf3ca.aac1>LOG:  statement: INSERT INTO "menu" ("dish_id", "dish_name") VALUES (2, "Test Dish")RETURNING "menu"."id"
<2016-03-18 17:55:47.061 IST  23712  3/5  56ebf3ca.aac1>LOG:  statement: COMMIT
<2016-03-18 17:55:47.229 IST  23713  2/34  56ebf3ca.aac0>LOG:  statement: INSERT INTO "menu" ("dish_id", "dish_name") VALUES (2, "Test Dish")RETURNING "menu"."id"
<2016-03-18 17:55:47.231 IST  23713  2/34  56ebf3ca.aac0>LOG:  statement: COMMIT

Postgres.conf:
max_connections = 100
log_destination = 'stderr'
logging_collector = on
log_directory = 'pg_log'
log_line_prefix = '<%m  %x  %v  %c>'
log_statement = 'all'

As you can see, the order of SELECT and INSERT queries in not the same in both the logs. I'm unable to understand why this would happen. Also, if you notice, the session_id for the SELECT queries in Postgres log is different. Could that explain something here?
And if this is expected behaviour, how could I solve the core issue here? Avoid concurrent INSERT queries, based on existing record.
UPDATE:
I didn't mention that the actual logic to ignore duplicate menu is not just based on dish name. The one above is simplified example.
Considering menu model as:
class Menu:
    user_id = models.IntegerField()
    dish = models.ForeignKey(Dish)
    order_start_time = models.DateTimeField()
    order_end_time = models.DateTimeField()

The actual logic goes like this:

*

*Fetch all menu with the dish_name from db.

*Check the order_start_time and order_end_time for all the those menu, and see if any of them overlaps with the order_start_time and order_end_time for the new menu. If conflict found, avoid addition.

So, we can add two menu for dish - d1, having order window - [9am-10am] and [2pm-3pm].

A: EDITED:
How to make Django validate overlapping reservations?
It is possible to add special method for a model validate_unique:
    from django.db import models
    from django.core.validators import ValidationError
    from django.forms.forms import NON_FIELD_ERRORS

    class Dish(models.Model):
        name = models.CharField('Dish name', max_length=200)

    class Menu(models.Model):
        user_id = models.IntegerField()
        dish = models.ForeignKey(Dish)
        order_start_time = models.DateTimeField()
        order_end_time = models.DateTimeField()

        def validate_unique(self, *args, **kwargs):
            # call inherited unique validators
            super().validate_unique(*args, **kwargs)  # or super(Menu, self) for Python2.7
            # query if DB already has object with same dish
            # and overlapping reservation
            # [order_start_time, order_end_time]
            qs = self.__class__._default_manager.filter(
                    order_start_time__lte=self.order_end_time,
                    order_end_time__gte=self.order_start_time,
                    dish=self.dish,
                )
            # and this object is not the same we are working with
            if not self._state.adding and self.pk is not None:
                qs = qs.exclude(pk=self.pk)
            if qs.exists():
                raise ValidationError({
                    NON_FIELD_ERRORS: ['Overlapping order dates for dish'],
                    })

Lets try it in console:
    from core.models import *
    m=Menu(user_id=1, dish_id=1, order_start_time='2016-03-22 10:00', order_end_time='2016-03-22 15:00')
    m.validate_unique()
    # no output here - all is ok
    m.save()
    print(m.id)
    8

    # lets add duplicate
    m=Menu(user_id=1, dish_id=1, order_start_time='2016-03-22 12:00', order_end_time='2016-03-22 13:00')
    m.validate_unique()
    Traceback (most recent call last):
       File "<console>", line 1, in <module>
       File "/Users/el/tmp/hypothesis_test/menu/core/models.py", line 29, in validate_unique
           NON_FIELD_ERRORS: ['Overlapping order dates for dish'],
    django.core.exceptions.ValidationError: {'__all__': ['Overlapping order dates for dish']}

    # excellent!  dup is found!

    # But! Django helps you find dups but allows you to add them to db if you want it!
    # It's responsibility of your application not to add duplicates.

    m.save()
    print(m.id)
    9

How to be sure noboby can add duplicate?
In this case you need to make a CONSTRAINT on database-level.
In PostgreSQL console:
    CREATE EXTENSION btree_gist;

    -- our table:
    SELECT * FROM core_menu;
    id | user_id |    order_start_time    |     order_end_time     | dish_id
   ----+---------+------------------------+------------------------+---------
     8 |       1 | 2016-03-22 13:00:00+03 | 2016-03-22 18:00:00+03 |       1
     9 |       1 | 2016-03-22 15:00:00+03 | 2016-03-22 16:00:00+03 |       1

    DELETE FROM core_menu WHERE id=9; -- we should remove dups before adding unique constraint

    ALTER TABLE core_menu
        ADD CONSTRAINT core_menu_exclude_dish_same_tstzrange_constr
            EXCLUDE USING gist (dish_id WITH =, tstzrange(order_start_time, order_end_time)  WITH &&);

Now lets create the duplicate object and add it to db:
    m=Menu(user_id=1, dish_id=1, order_start_time='2016-03-22 13:00', order_end_time='2016-03-22 14:00')

    m.save()
    Traceback (most recent call last):
       File "/Users/el/tmp/hypothesis_test/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
         return self.cursor.execute(sql, params)
    psycopg2.IntegrityError: ОШИБКА:  конфликтующее значение ключа нарушает ограничение-исключение "core_menu_exclude_dish_same_tstzrange_constr"
    DETAIL:  Key (dish_id, tstzrange(order_start_time, order_end_time))=(1, ["2016-03-22 13:00:00+00","2016-03-22 14:00:00+00")) conflicts with existing key (dish_id, tstzrange(order_start_time, order_end_time))=(1, ["2016-03-22 10:00:00+00","2016-03-22 15:00:00+00")).

Excellent!
Now data is validated at program and db levels.


text:
Q: Numbers not matching I'm new to excel vba and have just written some code to track if a game participant has paid their debt or not.
I'll simplify the code here
If Sheets("Sheet1").Cells(1,1).Value = Sheets("Sheet2").Cells(1,1).Value Then
   'Do something
Else 'Do something else
End If

The value in Sheets("Sheet1").Cells(1,1).Value is 1
And the value in Sheets("Sheet2").Cells(1,1).Value is also 1, but excel is saying they are not matching
Any help is appreciated, thanks

A: 1
Sub New()
        If Sheets("Sheet1").Cells(1,1).Value = Sheets("Sheet2").Cells(1,1).Value Then
               Sheets("Sheet3").Cells(1,1).Value="Paid"
            Else
            Sheets("Sheet3").Cells(1,1).Value="Not Paid"
            End If
        end sub

2
 Sub New()
dim str as string
dim i,a as integer
  i=Sheets("Sheet1").Cells(1,1).Value
a=Sheets("Sheet2").Cells(1,1).Value
    If i =a  Then
           Sheets("Sheet3").Cells(1,1).Value="Paid"
        Else
        Sheets("Sheet3").Cells(1,1).Value="Not Paid"
        End If
    end sub


text:
Q: Is $\vDash \exists x ( Q x \to \forall x Qx)$ a valid sentence? Is $\vDash \exists x ( Q x \to \forall x Qx)$ a valid sentence?
$Q$ is a unitary relation.
I suppose that $\vDash  Q x \to \forall x Qx$ , which is equivalent to $\vDash  Q x \to \forall y Qy$ is invalid, since there is a structure $\mathfrak{A}$ with the universe $|\mathfrak{A}|=\{a,b\}$ plus one relation $Q = \{a\}$ and a function $s$ which sends the variable $x$ to $a$. But I got confused henceforth this point.
I'm inclined to reason that, since $x$ is bounded, the part $\forall x$ is redundant, the sentence should be valid.

A: Whether it's even well-formed depends on the low-level details of how you define syntax.
But even if it is well-formed in the syntax you use, using a variable $x$ as a dummy variable in a context where $x$ already has meaning is usually a bad idea.
That said, typically in syntax that allows such a thing, a variable acquires the innermost meaning. Therefore
$$\exists x ( Q x \to \forall x Qx)$$
is the same expression as
$$\exists x ( Q x \to \forall y Qy)$$
and is a different expression than
$$\exists x ( Q x \to \forall y Qx)$$

A: Yes, it is.
The "flaw" in your purported counterexample to the validity of:

(A) --- $∃x(Qx \rightarrow ∀xQx)$

is that you are "reading" it as : $∃xQx \rightarrow ∀xQx$, which is not [this is implied by the structure $\mathcal A$ with universe $|\mathcal A| = \{ a,b \}$ such that $Q^{\mathcal A} = \{ a \}$].

We prove the vaildity of (A) in two ways.
Formal proof
We have that :

$\vdash (∀xβ \rightarrow α) \leftrightarrow ∃x(β \rightarrow α)$, if $x$ does not occur free in α [see this post for the proof].

If we apply it to (A), we get :
(B) ---$∀xQx \rightarrow ∀xQx$
which is clearly valid.

Semantic proof
Consider an interpretation $\mathcal A$ whatever and consider the conditional : $Qx \rightarrow ∀xQx$ : if $Qx$ holds for all $x$, then the conditional is true; thus, also $∃x(Qx \rightarrow ∀xQx)$ is.
If there is an object $a \in |\mathcal A|$ such that $a \notin Q^{\mathcal A}$ , then $\forall xQx$ is false.
Now, what is the condition for $\mathcal A \vDash \exists x \varphi[s]$ , i.e. such that $\mathcal A$ satisfy $\varphi$ with the assignment $s : Var \mapsto |\mathcal A|$ ?
It is :

for some $a \in |\mathcal A|$, we have $\mathcal A \vDash \varphi[s(x|a)]$.

Thus, if we consider an assignment $s$, we have that $\mathcal A \vDash (Qx \rightarrow ∀xQx)[s(x|a)]$ [because $\forall xQx$ is false precisely because $Q$ does not hold for $a$, and so we have : $False \rightarrow False$, which is $True$ ].
But, having shown that :
for some $a \in |\mathcal A|$, we have $\mathcal A \vDash (Qx \rightarrow ∀xQx)[s(x|a)]$
we may conclude with :

$\mathcal A \vDash \exists x (Qx \rightarrow ∀xQx)[s]$.

But this holds for $s$ and $\mathcal A$ whatever; thus :

$\vDash \exists x (Qx \rightarrow ∀xQx)$.

Comment
A further "informal" argument is the following.
By tautological equivalence, we may rewrite : $\exists x (Qx \rightarrow ∀xQx)$ as :

$\exists x (\lnot Qx \lor ∀xQx)$.

$\exists$ "works" as a "generalized" disjunction; thus, we can "distribute" it over $\lor$, obtaining the equivalent formula :

$\exists x \lnot Qx \lor ∀xQx$,

due to the fact that $\exists x \forall xQx$ has the same meaning of $\forall xQx$, $x$ being already bound.
But $\exists x \lnot Qx \lor ∀xQx$ is clearly valid; it means that either all objects are $Q$ or there is some object which is not, and this must hold in all universes.


text:
Q: How to extend a formula to 2 datagridview I Would like to know how to make a calculated columns between 2 datagridviews
if we are developing point of sale software.
and purchase order get a 2 product lets say "2 laptops" and the total is 5
so the total nust be updated to be 3.
here is a note it could easly done if they are in the same datagrid views using this code
    Datacolumn column = new Datacolumn ();

column.Columnname = "Remaining";

Totaldataset.Tables[0].Columns.["Remaining"].Expression = "Total - Sold";

the question could it done if the column "Total" is in other Datagridview or any else column in other data grid view


text:
Q: Find the smallest positive integer $X$ such that $478^{870} \equiv X \ (\text{mod} \ 273)$ Appreciate if one could advise if my solution is correct. Here is my attempt of the problem:
Since $(273, 478) =1,$ by Euler's theorem, $478^{\phi(273)}=478^{144} \equiv 1 \ \ (\text{mod} \ 273) \implies 478^{864} \equiv 1 \ \ (\text{mod} \ 273).$
Next, $478^{2} \equiv 22 \ \ (\text{mod} \ 39) \implies 478^{6} \equiv 22^{3} \equiv 1 \  \ (\text{mod} \ 39)$ and $478^{\phi(7)} = 478^{6} \equiv 1 \ \ (\text{mod} \ 7) $
Hence, $478^{6} \equiv 1 \ \ (\text{mod} \ 273)$ and $478^{864+6}= 478^{870} \equiv 1 \ \ (\text{mod} \ 273)$

A: Euler's Theorem with $\phi(273)=144$ gives $478^{870}\equiv(-68)^{870}\equiv68^6\equiv4624^3\equiv-17^3\equiv1$.

A: Your idea to use Chinese Remainder Theorem is good, but we can apply it more cleanly.  We have $273 = 3\cdot 7\cdot 13,$ so we localize at each prime:
$$X\equiv 478^{870} \equiv 1^{870} \equiv 1 \pmod{3}$$
$$X\equiv 478^{870} \equiv 2^{6\cdot 145} \equiv 1 \pmod{7}$$
$$X\equiv 478^{870} \equiv (-3)^{6+12\cdot 72} \equiv 3^6 \equiv 27^2 \equiv 1^2 \equiv 1 \pmod{13}$$
By Chinese Remainder Theorem $X\equiv 1 \pmod{273}.$

A: Recall Carmichael's theorem: $a^{\lambda(m)} \equiv 1 \bmod m$ for all $a$ coprime with $m$.
Now $\lambda(273)=lcm(\phi(3),\phi(7),\phi(13))=lcm(2,6,12)=12$ and $870 \equiv 6 \bmod 12$.
Therefore
$
478^{870} \equiv 205^{6} \equiv (-68)^{6} \equiv 4^6 \cdot 17^6 \equiv 1 \bmod 273
$.

A: Hint $\ \ \begin{align}478\ \  &\equiv 1,2,-3\,\bmod 3,7,13\\ \Rightarrow\, 478^{\large\color{#0b0}3}&\equiv 1,1,\color{#c00}{{-}1}\,  \bmod 3,7,13\end{align}\ $ and $\ \ \color{#c00}2\cdot \color{#0b0}{3\ }\mid 870$
Remark $ $ The idea is that $\,6 = \color{#c00}2\cdot \color{#0b0}{3\ }$ is a common multiple of the orders of $a=478$ mod $\,3,7,13$  therefore $\,a^6\equiv 1$ for each modulus, hence also modulo their lcm = product $= 273$, i.e. $\,3,7,13\mid a^6-1\,\Rightarrow\, 273\mid a^6-1,\,$  This is the idea behind the Carmichael approach in lhf's answer, but it uses Euler's $\,\phi(m)\,$ as its multiple of the order $\!\bmod m$


text:
Q: na.pass in nlme (mixed models) leads to contrary results UPDATE - One of the authors of the nlme package wrote the following:
Internally the nlme package uses compiled code such as LAPACK which does not have provision for missing values. The results when using na.pass will be unpredictable and invalid.
I am calculating mixed models (linear growth models) with the nlme package in R for a sample with N = 45 and 10 time points measuring change in health over time. Health (outcome) is measured at all time points, but the predictors are only measured at one time point. I have some missing values in the predictors (10 people have missing values in the predictors) so I decided to use na.action = na.pass to include all persons. However, the results vary immensely when I conduct small changes that should not change a lot.
My basic function is:
lgm1 <- lme(health ~ predictor*time, data=data1, random= ~time | id, na.action = na.pass,
            correlation = corAR1())

With this function, the predictor and the predictor * time interaction are significant. However, when I change the order of the predictors (now: time * predictor), the result is completely different, there is not even a hint of significance in the predictor, only the interaction stays the same.
When I replace na.pass with na.omit, the result is completely different as well (n.s. for all). At least, with na.omit, the order of the predictors doesn't change the result anymore.
Does anybody know why this happens and how I can deal with it in a good way? What does na.pass do? I am not sure how to deal with this finding as the differences are huge and I don't want to draw the wrong conclusions from the data.


text:
Q: How to automate the creation of "this." variables in Angular Working on Javascript and more particulary Angular, I regulary use the this. syntax.
I'd like to know if I could concatenate variables to obtain a this. variable.
For example is that is doable ?
let variable = 'variable1';
let test = 'this.' + variable
test = false

My goal would be to automate the creation of this. variables.
Thank you very much for your help !

A: I think there is no reason to do this. With your way you are just initializing strings in variables and then overwrite them with a boolean.
In my opinion its good for readability and understanding to see "this.", which means the following is from this class you are in at the moment. If there isn't proper code highlighting it can be confusing without it. I think you just need to get comfortable with it, but doing something like you want to feels like working around the language and not with it.


text:
Q: Java Inheritance issue - try to understand the concept i try to understand the Inheritance  concept and i have a little question.
I have two classes A and B as:
public class B extends A
{
    public B()
    {
        System.out.println ("B");
    }

    public void arik ()
    {
        System.out.println("Arik_B");
    }
    public void yosef ()
    {
        System.out.println ("Yosef");
    }

    public void superYosef()
    {
        super.yosef();
    }
}

public class A
{
    public A()
    {
        System.out.println ("A");
    }

    public void arik ()
    {
        System.out.println ("Arik_A");
    }

    public void yosef ()
    {
        arik();
    }
}

Main:
A ab = new B();
((B) ab).superYosef();

The line A ab = new B(); will print A B and this is clear.
But the line ((B) ab).superYosef(); print Arik_B and i don't understand why.
before running ab is type A and while running it's B so it need to print Yosef

A: When an instance method is called on this, the only thing that matters is the type of the object on which it is called. This type is known only at runtime.
When an instance method is called on super, dynamic dispatch does not apply. The method is chosen at compile time.
In your code:

*

*you create a new B(); and call B.superYosef();

*the call super.yosef(); appearing in that method invokes A.yosef() statically (not subject to dynamic dispatch);

*A.yosef() calls this.arik()—unlike above, a method called on this is subject to dynamic dispatch;

*the type of this is B, therefore the method B.yosef() is called.

A: When you do
A ab = new B();

then the variable ab of of type A, but the actual object that it refers to is of type B. The actual type of the object determines which method will be called, not the type of the variable.
So, when you call any method on ab that has been overridden in class B, the version from class B will be called.
Let's see what happens here:
((B) ab).superYosef();

You need to cast, because the method superYosef is only defined in class B.
That method calls super.yosef();, which will call the yosef method in class A. The A.yosef calls arik, and this method is overridden in class B. Note that we have called the method on an object that is actually a B, so the arik method in B is called, which prints Arik_B.

A: When you invoke the method:
((B) ab).superYosef();

The actual instance being referred by ab reference is of class B only. Moving further, this invocation will call method superYosef() method in class B. Now, let's go to that method:
public void superYosef()
{
    super.yosef();
}

This will call the yosef() method in class A. Due to super. The instance is still B. And then in yosef() method:
public void yosef ()
{
    arik();  // equivalent to `this.arik();`
}

Here you have reference this holding reference to instance of class B. You invoke arik(), which is overridden in class B, and hence the method arik() of class B is invoked. The only thing which is important here is, the actual object is of type B.

A: Because with the class B you are overwriting the method arik, so that's why it's accessing this method in class B.
And your ab variable is still a B.


text:
Q: Trigger to update table column when new row is insert in postgresql? I want to write trigger to update table when new row is insert. I am using updatea Query like
UPDATE table SET
  geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)

A: You need to use a BEFORE trigger and then assign the new value:
CREATE OR REPLACE FUNCTION function_update()
  RETURNS trigger AS
$BODY$
BEGIN
    new.geom := ST_SetSRID(ST_MakePoint(new.longitude, new.latitude), 4326);
    RETURN new;
END;
$BODY$
LANGUAGE plpgsql;

This can only be done in a BEFORE trigger:
CREATE TRIGGER triggerinsert
  BEFORE INSERT
  ON rdpr
  FOR EACH ROW
  EXECUTE PROCEDURE function_update();

A: I Solved by writing trigger function like
CREATE OR REPLACE FUNCTION function_update()
  RETURNS trigger AS
$BODY$
BEGIN
   new.geom := ST_SetSRID(ST_MakePoint(new.longitude, new.latitude), 4326);

RETURN new;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION function_update()
  OWNER TO postgres;

and i wrote trigger to update
CREATE TRIGGER triggerinsert
  Before INSERT
  ON rdpr
  FOR EACH ROW
  EXECUTE PROCEDURE function_update();


text:
Q: Mapreduce job failed with IO Exception I am running a single node hadoop environment. I have a mapreduce job to calculate average of some monitored information for some specific time periods, say hourly average.This job write output to a path within hdfs.It is get cleaned up ech time before running the job. It was working fine for a month. Yesterday , while running job, I got an exception from jobclient, says:
File /user/root/out1/_temporary/_attempt_201401141113_0007_r_000000_0/hi/130-r-00000 could only be replicated to 0 nodes, instead of 1
Full stacktrace is as follows:

  ..........

14/01/17 12:00:09 INFO mapred.JobClient:  map 100% reduce 32%
14/01/17 12:00:12 INFO mapred.JobClient:  map 100% reduce 74%
14/01/17 12:00:17 INFO mapred.JobClient: Task Id : attempt_201401141113_0007_r_000000_0, Status : FAILED
org.apache.hadoop.ipc.RemoteException: java.io.IOException: File /user/root/out1/_temporary/_attempt_201401141113_0007_r_000000_0/hi/130-r-00000 could only be replicated to 0 nodes, instead of 1
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:1558)
    at org.apache.hadoop.hdfs.server.namenode.NameNode.addBlock(NameNode.java:696)
    at sun.reflect.GeneratedMethodAccessor20.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:563)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1388)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1384)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:396)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1382)

    at org.apache.hadoop.ipc.Client.call(Client.java:1070)
    at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:225)
    at $Proxy2.addBlock(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:82)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:59)
    at $Proxy2.addBlock(Unknown Source)
    at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.locateFollowingBlock(DFSClient.java:3510)
    at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.nextBlockOutputStream(DFSClient.java:3373)
    at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.access$2600(DFSClient.java:2589)
    at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream$DataStreamer.run(DFSClient.java:2829)

From the initial search on google, says about storage space issue.But I don't think so, because my whole input data should be less than 600MB and there is around 1.5GB free space available on node. I ran hadoop dfsadmin -report command and it return as follows:

 $hadoop dfsadmin -report
Configured Capacity: 11353194496 (10.57 GB)
Present Capacity: 2354425856 (2.19 GB)
DFS Remaining: 1633726464 (1.52 GB)
DFS Used: 720699392 (687.31 MB)
DFS Used%: 30.61%
Under replicated blocks: 49
Blocks with corrupt replicas: 0
Missing blocks: 0

-------------------------------------------------
Datanodes available: 1 (1 total, 0 dead)

Name: 192.168.1.149:50010
Decommission Status : Normal
Configured Capacity: 11353194496 (10.57 GB)
DFS Used: 720699392 (687.31 MB)
Non DFS Used: 8998768640 (8.38 GB)
DFS Remaining: 1633726464(1.52 GB)
DFS Used%: 6.35%
DFS Remaining%: 14.39%
Last contact: Fri Jan 17 04:36:55 GMT+05:30 2014

Please give me a solution.Is this can be a configuration issue. I dont know much about the hadoop configuration.Please help..

A: I think that, maybe, your problem is actually a space problem. You have one replica set, so if your input is 600 mb it will take 1.2 gb on your cluster.
You still have 300mb free that is probably not enough to send the data between nodes.
My advice is to use a smaller dataset to check if this is the problem, of around 300mb or less. Then, if you don't solve it this way, try to set the replicas to 0 on the conf/hdfs-site.xml
<property>
    <name>dfs.replication</name>
    <value>0</value>
</property>


text:
Q: How to rolling sum for specific intervals in time series data I have time series data and I want to create another column that sums the value for each day. For example:
df
timestamp             val    sum
2022-10-10 00:00:00   50      50
2022-10-10 00:01:00   10      60
2022-10-10 00:02:00   20      80
...
2022-10-10 23:59:00   10     2300
2022-10-11 00:00:00   20      20
...

How can I achieve this?

A: Use GroupBy.cumsum per dates:
df['sum'] = df.groupby(df['timestamp'].dt.date)['val'].cumsum()


text:
Q: Cordova never fires device ready I created a new Cordova 4.0 project, added android platform and added all the core plugins and the following is my index.html file.
<!DOCTYPE html>
    <title>Notification Example</title>

Show Alert

Play Beep

Vibrate

But I could never see the device ready firing. Any ideas on what is wrong with the abive snippet ?

A: Try to change

to


text:
Q: How to avoid ^C getting printed after handling KeyboardInterrupt This morning I decided to handle keyboard interrupt in my server program and exit gracefully. I know how to do it, but my finicky self didn't find it graceful enough that ^C still gets printed. How do I avoid ^C getting printed?
import sys
from time import sleep
try:
  sleep(5)
except KeyboardInterrupt, ke:
  sys.exit(0)

Press Ctrl+C to get out of above program and see ^C getting printed. Is there some sys.stdout or sys.stdin magic I can use?

A: It's your shell doing that, python has nothing to do with it.
If you put the following line into ~/.inputrc, it will suppress that behavior:
set echo-control-characters off

Of course, I'm assuming you're using bash which may not be the case.

A: try:
    while True:
        pass
except KeyboardInterrupt:
    print "\r  "

A: This will do the trick, at least in Linux
#! /usr/bin/env python
import sys
import termios
import copy
from time import sleep

fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = copy.deepcopy(old)
new[3] = new[3] & ~termios.ECHO

try:
  termios.tcsetattr(fd, termios.TCSADRAIN, new)
  sleep(5)
except KeyboardInterrupt, ke:
  pass
finally:
  termios.tcsetattr(fd, termios.TCSADRAIN, old)
  sys.exit(0)

A: I don't know if this is the best way of doing this, but I fix that problem by printing two \b (backspace escape sequence) and then a space or a series of characters. This might work fine
if __name__ == "__main__":
    try:
        # Your main code goes here
    except KeyboardInterrupt:
        print("\b\bProgram Ended")


text:
Q: Pandas is not empty but gets max() arg is an empty sequence This is toy data and it works fine to get the max index of True from each list of Pandas column allmz into  lastprec
df = pd.DataFrame({'time': pd.Series([1,1,1,3,3]),'allmz':([[True,True,True],[True,False,True],[False,True,False],[True,True,False],[True,False,False]]),'allint':([[11,31,31],[21,41,51],[41,51,51],[11,31,51],[1,51,11]])})

df['lastprec'] = df['allmz'].apply(lambda aa: max([i for i, x in enumerate(aa) if x]))
print df

>>>OUT
         allint                 allmz  time  lastprec
0  [11, 31, 31]    [True, True, True]     1         2
1  [21, 41, 51]   [True, False, True]     1         2
2  [41, 51, 51]  [False, True, False]     1         1
3  [11, 31, 51]   [True, True, False]     3         1
4   [1, 51, 11]  [True, False, False]     3         0

However, in my real data, I got ValueError: max() arg is an empty sequence. Only thing that is different is I open that DataFrame from Excel (but the toy data is not imported) by ref_df = pd.read_excel(ref_file, sheetname=ref_worksheet). Can this be a reason why I get this error? Or there is something else? I check the real data allmz, it is not empty and the data type is list. What can I fix to get the max index of the real data?

A: EDIT:
If not empty lists not all False lists and lenfth of lists is always same, you can use numpy for improving performance:
df['lastprec'] = 2 - np.array(df['allmz'].values.tolist())[:,::-1].argmax(axis=1)
print (df)

         allint                  allmz  time  lastprec
0  [11, 31, 31]  [False, False, False]     1         2
1  [21, 41, 51]    [True, False, True]     1         2
2  [41, 51, 51]   [False, True, False]     1         1
3  [11, 31, 51]    [True, True, False]     3         1
4   [1, 51, 11]   [True, False, False]     3         0


text:
Q: Error Installing Oracle Database Client 12c Getting this error While installing Oracle Database Client 12c Release 1
Error in writing to file 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\\..\..\Xml\Schemas\Oracle.ManagedDataAccess.Client.Configuration.Section.xsd'. [C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\..\..\Xml\Schemas\Oracle.ManagedDataAccess.Client.Configuration.Section.xsd (Access is denied)]

Any fix for this ?

A: I had the same problem here. Even after running as administrator, I still had to locate the file, in my case at "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Xml\Schemas" open properties window and uncheck read only (remember to aply the configuration to the subfolders and files). Hope it helps.