Q: Move factory method from AppModule to AppComponent in Angular 7 I use ngx-translate-multi-http-loader loader to create specific translations. The documentation requires that this factory has to be created within the app.module.ts:
export function multiTranslateHttpLoaderFactory(http: HttpClient) {
  return new MultiTranslateHttpLoader(http, [
    {prefix: './assets/i18n/default/', suffix: '.json'},
    {prefix: './assets/i18n/bc/', suffix: '.json'}
  ]);
}

This factory is configured inside the import arrays in this way:
TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: multiTranslateHttpLoaderFactory,
    deps: [HttpClient]
  }
}),

I need a way to put the factory into my app.component.ts, because I still have to program some logic and do not want to do that within my app.module.ts.
But if I move the method into my app.component.ts and make all the necessary import statements on top of the file, angular doesn't compile and returns this error message:

ERROR in src / app / app.module.ts (55,21): error TS2304: Can not find
  name 'multiTranslateHttpLoaderFactory'.

Is there a possibility or do I really have to define the factory within app.module.ts ???

A: It really should not matter where you define your factory, or any other function for that matter. Just be sure to import it correctly, somewhere in the top of app.module.ts
import {multiTranslateHttpLoaderFactory} from 'path/to/your/component'


Q: super priviliege not set for master user in aws rds mysql I have created an AWS RDS instance, I have created my master user with master password, and it is working/connecting fine.
But when I am going to create a function on that instance, it shows me the following error:
ERROR 1418: This function has none of DETERMINISTIC, NO SQL,
or READS SQL DATA in its declaration and binary logging is enabled
(you might want to use the less safe log_bin_trust_function_creator variable).

In my instance the variable log_bin_trust_function_creators shows OFF, and if I try to change the variable using SET GLOBAL log_bin_trust_function_creators = 1;, it gives me another error "Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation"

A: Set log_bin_trust_function_creators = 1 for Parameter group of the RDS instance.
Note: Default Parameter-Group is not editable. Create a new Parameter-Group and assign it to the RDS instance by modifying it from UI (AWS Admin Console) OR maybe using commands
DELIMITER $$
CREATE DEFINER=`DB_USERNAME_HERE`@`%` FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120)) RETURNS decimal(12,8)
READS SQL DATA
BEGIN
   DECLARE distance DECIMAL(12,8);
   /*Business logic goes here for the function*/
   RETURN distance;
END $$
DELIMITER ;

Here, you have to replace DB_USERNAME_HERE with you RDS database username and function names according to you need.
Important thing is: DEFINER=`DB_USERNAME_HERE`@`%`
This was the problem I was facing after setting log_bin_trust_function_creators = 1 in parameter group. And it worked like a charm.

A: A better way is to apply your own parameter group, with log_bin_trust_function_creators set to true. (its false by default)

A: This happens when you try to create a procedure/function/view with a DEFINER that is not the current user.
To solve this remove or update the DEFINER clause.


Q: How to call a function when pressing the default react native picker in react native I'm using react-native picker in dialog mode. Now I want to call a function whenever the dialog opens. How can I achieve that because there is no onPress prop? Any help will be appreciated. Please don't recommend any other packages because I want to use the default one.

A: You can achieve it without using Picker, use TouchableOpacity to call a function, and in the same function just open a Modal for showing the list of items of Picker and close the Modal when selecting any item from the list.


Q: WMS/WFS server: am I crazy to write my own? I'm a "do it yourself" kind of guy, but I want to make sure I'm not going to do myself in by trying to bite off more than I can chew.
I am writing a browser-based mapping application that needs to have the option to run standalone (no internet connection) on the end-user's machine. That is, the application is some kind of server that will, in many cases, get installed on the end user's machine and the browser will point to some localhost URL to access it.
I will be using MapLayers on the client side, and the server side will have a bunch of custom logic specific to the application, such as handling click events on the map in certain custom ways, creating various custom objects on the map at certain times, and so on.
For the "business logic" part of the server, I'm happy using paste/webob with python. It's a simple infrastructure that lets me put all this custom logic in easily.
I had been thinking that the client would communicate with two servers: this paste/webob business logic server, and a server just for serving WMS and WFS map elements. So I was looking at MapServer and GeoServer to handle the map parts and ... I'm not happy.
I'm not happy because I don't want to have to install and worry about a "beast" on the client machines. For MapServer, I don't really want to install a full-blown web server like Apache, and have to deal with CGI and PHP and MapScript. For GeoServer, there's (potentially) installing Java, and dealing with various complexities of the GeoServer setup and administration.
Part of this is simply a learning curve issue. If I can avoid it, I'm not especially interested in learning the intricacies of either MapServer or GeoServer. I installed GeoServer, pointed it to some of my data, and was able to use the MapLayers preview built into GeoServer's nice web admin to view my data. But when I tried to serve the data for real using my own MapLayers web page pointed at GeoServer, I crashed GeoServer. That I could crash the server just be sending some presumably malformed requests from the client was quite surprising to me. And I could dig into the GeoServer logs to try to figure out what I did wrong, but ... I don't really want to spend a lot of time on that.
So, I am considering implementing parts of the WMS and WFS interface myself just using the paste/webob server I already have. It may in fact be that I only need the WMS, since I might handle vector objects through a simple custom protocol that I make to pass data to the client, which can then create and manipulate the objects directly using OpenLayers.
I've looked at the specs and example messages for WMS (and a bit less at WFS). It seems not so difficult just to implement this protocol myself, especially because I have full control of the client in this case -- it's not like I need to be able to act as a generic WMS or WFS server; I just have to make my own OpenLayers client happy.
The two main abilities that I need the WMS server to have are:

*

*Serve tiles from a store of prerendered tiles that I've created ahead of time (I'll prerender the tiles using OpenStreetMap data and mapnik as the redering engine; and I'll store and access them using the normal Google Maps style tile naming scheme that OpenLayers expects)

*Have the ability to server modified versions of these tiles where certain data that I store locally is drawn on top of the tiles. For instance, I might have, say, 10000 points on one "layer" and 10000 polygons on another layer, and when the user activates these layers I will serve my same base tiles, but as I'm serving these tiles I'll render these additional features on top of them, and probably I'll implement a simple caching scheme to keep these over-rendered tiles around for some amount of time.
So my question is: Even though I know there are existing tools that do these things (MapServer, GeoServer, TileCache, and others), I'm actually feeling like it's less work for me to just to respond to some simple WMS messages, and do this additional over-drawing on my tiles myself in python, making sure everything is projected correctly, etc. I don't need to draw fancy wide streets or anything for these over-layers, just simple lines, icons, and perhaps labels. It sure sounds nice and simple to have a python-only solution.
I figure if I ever need to expand into supporting more of the WMS/WFS protocol, or doing fancier overdrawing, I can just insert MapServer/GeoServer at that time.
Are there pitfalls here I'm not considering?

A: Mapserver is very easy to setup and learn. Implementing any kind of rendering by yourself is going to require much more effort, and you will probably find a lots of unexpected traps.
mapserver cgi should be enough for your needs. If you require some very specific tweak, then mapscript can be useful.
I think it could be interesting if you could make a pure JavaScript application, and save yourself from installing a web server (and a map server). If you just needed browsing a tile mosaic, may be you could do it just with JavaScript (generate an html table with a cell for each tile). You can render points or polygons, with JavaScript, using a canvas and doing some basic coordinate conversion to translate geographic points to pixels. Openlayers have this functionality, I think.
EDIT: I just checked and with Openlayers you can browse local tiles, and you can render kml and some other vect data. So, I think you should give Openlayers a try.

A: No need to have a wms/wfs. What you need is a tile implementation. Basically you should have some sort of central service, or desktop service that generates the tiles. Once these tiles are generated, you can simply transform them to your "no-real-webserver-architecture" filesystem. You can create a directory structure that conforms to /{x}/{y}/{z}.png and call it from javascript.
An example of how openstreetmap does this can be found here: http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example

A: You may like featureserver: http://featureserver.org/.
It has its own WFS. I am using it right now.


Q: Oracle APEX: Text wrapping issue with a display-only page item I have a display-only page item on an inline dialog region. The value of the item is set via hidden page item that retrieves the value from the database using PL/SQL.
The issue is that the text is rather long, so instead of text wrapping, it extends beyond the width of the inline dialog causing a horizontal scroll bar to appear. How can I set the width of the page item to be no wider than the inline dialog default width and make the page item text wrap around?

A: Did you try to

*

*set display only item's template to "optional" (instead of e.g. "optional - floating"), and then

*set its "custom attributes" property (which is in the "Advanced" set of properties) to e.g. style="width:300px"
Illustration:


Q: SharePoint Visual Studio Build - error : '.', hexadecimal value 0x00 When I deploy my SharePoint project I receive the following error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets(375,5): error : '.', hexadecimal value 0x00, is an invalid character. Line 1, position 1.

The line number relates to the following in the build XML:
<CreateSharePointProjectService Configuration="$(Configuration)"
              Platform="$(Platform)"
              ProjectFile="$(MSBuildProjectFile)"
              ProjectReferences="@(SharePointProjectReference)"
              OutDir="$(TargetDir)">
  <Output PropertyName="ProjectService" TaskParameter="ProjectService" />
</CreateSharePointProjectService>

Furthermore I've managed to whittle down the problem (or at least seemingly) to the following property:
ProjectFile="$(MSBuildProjectFile)"

i.e. if I remove this property then I no longer get the same error message (but I get others as a consequence).
I'm not sure what's going on here as I know nothing about MSBuild.  Obviously this always used to work before so I don't know what's changed to cause it to no longer work.  Any suggestions will be greatly appreciated as I've wasted a lot of time on this already.  BTW, this problem occurs in both Visual Studio 2010 and 2012.
Thanks

A: OK, problem sorted.  It turns out that the error message actually referred to an XML file referenced by the solution (containing some deployment files).  This XML had somehow become corrupted which does fit the message '.', hexadecimal value 0x00.  After removing this feature (which didn't need deploying anyway) the problem disappeared so the world can go on being a happy place again (or at least my manager is!)

A: I just ran into this after downloading an msbuild file from the internet.  Opening the newly downloaded file in a hex editor showed me what the problem was pretty quickly.  The file was downloaded with 2 byte characters, and every other byte was a 0.  I think Notepad++ said the encoding was UCS-2.  In any case, the fix was pretty simple.  Notepad++ has an Encoding menu option that I used to rewrite the file as UTF-8.  Changing the file back to UTF-8 immediately fixed the problem.
Hope this helps people in the future.
--Addendum - I might have tried to muck with the file using PowerShell before its encoding changed.


Q: If limit exists, is that function continuous? If I have a function $f$, and the limit exists at $a$, and    $\lim\limits_{x \to a} f(x) = \infty $ or $\lim\limits_{x \to a} f(x) = k $,  where $k$ is a constant, does that mean that the function is continuous on some interval in the domain of $f$?
I think this is true, but I am not sure. Because for example, if $\lim\limits_{x \to a} f(x) = \infty $, if I graph a function that fulfills this, there is at least some interval in its domain where it is continuous.

A: The existence of a limit does not imply that the function is continuous somewhere. Some counterexamples:
$$\text{Let }f_1(x) = \begin{cases}
0&x=0\\
\frac1{x^2}&x\in\mathbb{Q}\backslash\{0\}\\
\frac1{2x^2}&x\notin\mathbb{Q}
\end{cases}$$
$$\text{and let }f_2(x) = \begin{cases}
1&x=0\\
x&x\in\mathbb{Q}\backslash\{0\}\\
-x&x\notin\mathbb{Q}\end{cases}$$
Here, we can see that $\lim\limits_{x\to0}f_1(x)=\infty$ and $\lim\limits_{x\to0}f_2(x)=0$, but $f_1$ and $f_2$ are nowhere continuous.

A: Let $$f(x) = \begin{cases} x \quad{} &\text{if $x \ne 0$ and $x$ is rational}\\ 0 &\text{if $x$ is irrational} \\ 1 & \text{if $x = 0$}\end{cases}.$$ You can see that $\lim_{x \to 0} f(x) = 0$, but $f$ is continuous nowhere.


Q: How the number of charges (colors) and the number of photons (gluons) is connected? This question is a continuation of "Can a third type of electrical charge exist?" and specifically this comment.
I know the common knowledge that there is 1 kind of electric charge and thus 1 kind of photon; there are 2 kinds of weak isospin and thus 3 kinds of weak bosons; there are 3 kinds of color charge and thus 8 kinds of gluons. But I wonder if this is fixed.
How I understand this: if there are $n$ possible charges then there are $n$ identical fermion fields each carrying its own kind of charge. Then the gauge field acts on them changing their phases (only! to conserve the probability, probably). So its group should be some group acting on $\mathbb{C}^n$ and conserving the norm. Usually the maximal such group is considered, that is $\mathrm{U}(1)$, $\mathrm{SU}(2)$ and $\mathrm{SU}(3)$ respectively.
1 . May some subgroup of the maximal one be used instead? For example, $\mathrm{SO}(n)$ or $\mathrm{SU}(m)$ for $m<n$?
2 . May fermions make up not the fundamental representation of the gauge group but some other representation?
Positive answers would lead to possible less numbers of photons.
Next, I notice that the maximal group for several charges is $\mathrm{U}(n)$, but in weak and color interactions $\mathrm{SU}(n)$'s are used instead. $\mathrm{U}(n)=\mathrm{U}(1)\rtimes\mathrm{SU}(n)$, and as I understand, the common phase factor cannot belong to every interaction in the Standard Model, so it belongs only to the electromagnetic interaction, and other interactions lose it, and so their maximal groups are restricted to $\mathrm{SU}(n)$'s.
3 . Is this right?
If yes, then in the case we imagine more kinds of electric charge, then the electromagnetic gauge group can be $\mathrm{U}(n)$ instead of $\mathrm{SU}(n)$, and the number of photons $n^2$ instead of $n^2-1$ respectively.


Q: How is arctangent [function a()] implemented in bc? I wanted to see and possibly modify how the arctangent function a() was implemented in bc (the arbitrary precision calculator language) but was unable to find it. I even found a git repo of the project https://github.com/gavinhoward/bc, however was unable to locate the implementation code for it. This should be part of the matlib library for bc.
Please share link, location of the directory or source code below.


Q: Using mapply to plot I'm trying to iteratively plot scatterplots ONLY using mapply.
Let's say I have the iris dataset:
> names(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length"
[4] "Petal.Width"  "Species"

I would like to use mapply() and only mapply() to plot Sepal.Width, Petal.Length, and Petal.Width against Sepal.Length
I have this starter code:
    mapply(function(ii){plot(x = iris[["Sepal.Length"]],
           y = ii, ylab = paste(names(ii)), xlab = "Sepal Length")},
           ii = iris[c(2,3,4)])

Everything works fine here EXCEPT the y axis labels. I want it to display the column names of the y-axis values, but this does not work.

A: Neither mapply nor lapply pass the names of the items in their data objects to the "working functions". What you see after the function completion is that they add back the names to the results. Even if you use the deparse(substitute)) strategy you end up with a useless name like "dots[[1L]][[1L]]". So you are condemned to either index by the names themselves or by a numeric index into the names(dataframe) values.

A: Consider passing column names to fit your column assignment and ylab character requirement. And as @alistaire comments, you are only passing one vector into your function. Mapply (informally as multivariate apply) is designed to iterate elementwise through more than one equal-length or multiple-length vectors. This would be akin to passing in Sepal.Length 1 or 3 times:
plotfct <- function(ii, jj)
  plot(x = iris[[ii]], y = iris[[jj]],
       xlab = paste(ii), ylab = paste(ii))

mapply(plotfct, c("Sepal.Length", "Sepal.Length", "Sepal.Length"),
                c("Sepal.Width", "Petal.Length", "Petal.Width"))

But since Sepal.Length does not change, repeating its value to meet the length of longer is redundant. Simply use lapply or its simplified wrapper, sapply:
plotfct <- function(ii)
  plot(x = iris[["Sepal.Length"]], y = iris[[ii]],
       xlab = "Sepal Length", ylab = paste(ii))

lapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)

# EQUIVALENTLY:
# sapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)


Q: paginated calls on a service method without changing signature of original method I have a use case where I need to add pagination inputs (viz. page number and page size) to existing service calls (that returns a list of results) without changing the existing signature (because it will break existing clients). One way of achieving this is that we set the inputs in a threadlocal and have the implementation read the threadlocal and do its pagination logic. From a code point of view, it would look something like:
try {
    PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
    List<SpecialObject> results = specialService.getSpecialObjs(); //results count will be equal to pageSize value
} finally {
    PaginationKit.clearPaginationInput(); // Clear threadlocal
}

From a client's point of view, this is not at all elegant and I wanted to wrap this functionality into some better syntactic sugar. There were two approaches I had in mind and I wanted to know if this is a generic enough use case that has been solved as a pattern elsewhere. There are many such services and trying to put up a decorator for each of the services is not desirable.
Approach 1:
I like the mockito style of Mockito.when(methodCall).thenReturn(result) kind of sugar.
So the code may look like:
SpecialService specialService = PaginationDecorator.prepare(SpecialService.class); // Get a spy that is capable of forwarding calls to the actual instance
List<SpecialObject> results = PaginationDecorator.withPageSize(pageSize).onPage(pageNumber).get(specialService.getSpecialObjs()).get(); // The get() is added to clear the threadlocal

I tried to borrow code from Mockito to create the spy, but the OngoingStubbing<T> interface is quite intertwined in the subsequent call chaining/creation code and is smelling of something that I should avoid.
Approach 2:
Use java.util.Function to capture the method call and accept two additional parameters pageNumber and pageSize to play with the threadlocals. The code may look like
List<SpecialObject> results = PaginationDecorator.withPaging(specialService.getSpecialObjs(), pageSize, pageNumber);

PaginationDecorator.java:
public static List<T> withPaging(Function<U, List<T>> call, int pageSize, int pageNumber) {
    try {
        PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
        return call.apply(); // Clearly, something is missing here!
    } finally {
        PaginationKit.clearPaginationInput(); // Clear threadlocal
    }
}

I am not able to clearly formulate how to use call correctly here.
Can someone please tell me :

*

*which of these two is the better approach

*if this is available as a recipe elsewhere using a different approach

*suggest ways forward to implement approach 1 or 2. Personally #2 seems cleaner to me (if it works).

Feel free to critique the approach and thanks in advance for the read!
P.S.: I also liked the iterator recipe in this question, but the primary problem of syntactic sugar is still desired.

A: Your second variant does not work, because you are using the wrong interface (Function expects an input argument) and no syntax to create a function instance, but just an ordinary invocation expression.
You have several choices

*

*Use Supplier. This interface describes a function without parameters and returning a value.
public static <T> T withPaging(Supplier<T> call, int pageSize, int pageNumber) {
    try {
        PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
        return call.get();
    } finally {
        PaginationKit.clearPaginationInput(); // Clear threadlocal
    }
}

Instead of insisting on it to return List<T>, we simply allow any return type which raises its versatility. It includes the possibility to return a List of something.
Then, we may use either, a method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
                    specialService::getSpecialObjs, pageSize, pageNumber);

or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
                    () -> specialService.getSpecialObjs(), pageSize, pageNumber);

*Stay with Function, but allow the caller to pass the required argument
public static <T,R> R withPaging(
    Function<T,R> call, T argument, int pageSize, int pageNumber) {

    try {
        PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
        return call.apply(argument);
    } finally {
        PaginationKit.clearPaginationInput(); // Clear threadlocal
    }
}

Now, the caller has to provide a function and a value. Since the intended method is an instance method, the receiver instance can be treated like a function argument
Then, the function might be again specified either, as a (now unbound) method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
        SpecialService::getSpecialObjs, specialService, pageSize, pageNumber);

or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
        ss -> ss.getSpecialObjs(), specialService, pageSize, pageNumber);

*There is an alternative to both, resorting to AutoCloseable and try-with-resource, rather than try…finally. Define the helper class as:
interface Paging extends AutoCloseable {
    void close();
    static Paging withPaging(int pageSize, int pageNumber) {
        PaginationKit.setPaginationInput(pageSize, pageNumber);
        return ()->PaginationKit.clearPaginationInput();
    }
}

and use it like
List<SpecialObject> results;
try(Paging pg=Paging.withPaging(pageSize, pageNumber)) {
    results=specialService.getSpecialObjs();
}

The advantage is that this will not break the code flow regarding your intended action, i.e. unlike lambda expressions you may modify all local variables inside the guarded code. Recent IDEs will also warn you if you forget to put the result of withPaging inside a proper try(…) statement. Further, if an exception is thrown and another one occurs inside the cleanup (i.e. clearPaginationInput()), unlike finally, the secondary exception will not mask the primary one but get recorded via addSuppressed instead.
That’s what I would prefer here.

A: Your second approach seems cleaner and easier for this task. As for implementation you can just use Java's Proxy class. It seems easy enough. I don't know any libraries that somehow make it even more easier.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class PagingDecorator {
    public static void setPaginationInput(int pageSize, int pageNumber) {
    }

    public static void clearPaginationInput() {
    }

    public static <T> T wrap(final Class<T> interfaceClass, final T object, final int pageSize, final int pageNumber) {
        if (object == null) {
            throw new IllegalArgumentException("argument shouldn't be null");
        }

        ClassLoader classLoader = object.getClass().getClassLoader();
        return (T) Proxy.newProxyInstance(classLoader, new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                setPaginationInput(pageSize, pageNumber);
                try {
                    return method.invoke(object, args);
                } catch (InvocationTargetException e) {
                    throw e.getTargetException();
                } catch (Exception e) {
                    throw e;
                } finally {
                    clearPaginationInput();
                }
            }
        });
    }

    public static <T> T wrap(final T object, final int pageSize, final int pageNumber) {
        if (object == null) {
            throw new IllegalArgumentException("argument shouldn't be null");
        }

        Class<?>[] iFaces = object.getClass().getInterfaces();

        //you can use all interfaces, when creating proxy, but it seems cleaner to only mock the concreate interface that you want..
        //unfortunately, you can't just grab T as interface here, becuase of Java's generics' mechanic
        if (iFaces.length != 1) {
            throw new IllegalArgumentException("Object implements more than 1 interface - use wrap() with explicit interface argument.");
        }

        Class<T> iFace = (Class<T>) iFaces[0];
        return wrap(iFace, object, pageSize, pageNumber);
    }

    public interface Some {
    }

    public static void main(String[] args) {
        Some s = new Some() {};

        Some wrapped1 = wrap(Some.class, s, 20, 20);
        Some wrapped2 = wrap(s, 20, 20);
    }
}

A: You are using Java 8, right? Maybe you can add a default method without any implementation (sounds a litte weird, I know) like this:
// Your current service interface
interface ServiceInterface <T> {

    // Existing method
    List<T> getObjects();

    // New method with pagination atributes
    default List<T> getObjects(int pageSize, int pageNumber) {
        throw new UnsupportedOperationException();
    }
}

The new services (with pagination suport) must override this method. In my opinion, this way You "keep it simple".


Q: Is there such a thing as a muggle werewolf? I was reading Fantastic Beasts and Where to find them, and I found this quote:

“Werewolves spend most of their time as humans (whether wizard or
Muggle).”

(Fantastic Beasts and Where to Find Them)
Does this mean, if a muggle is bitten by a werewolf, and somehow survives (rescued by wizards, then had their memory modified), that they will become a werewolf?
I may make a second question on this topic regarding how the wizarding world would remain hidden to this muggle, if they do indeed become a werewolf.
I am looking for canon answers based on JKR interviews, the books, or simply your own canon-based speculation!

A: Muggles can become werewolves, if they survive the bite.
From J.K. Rowling on Pottermore:

the great English authority on werewolves, Professor Marlowe Forfang,
undertook the first comprehensive study of their habits. He found that
nearly all those he managed to study and question had been wizards
before being bitten. He also learned from the werewolves that Muggles
‘taste’ different to wizards and that they are much more likely to die
of their wounds, whereas witches and wizards survive to become
werewolves.


Q: Need Rally Burndown chart API implementation to show in our dashboard I am creating Dashboard(dashing.IO) in which i want to display the Rally Burn down chart.

A: You'll need to create your app in an html file and then embed it in an iframe element in a widget.
https://help.rallydev.com/apps/2.1/doc/#!/guide/embedding_apps
The burn down chart is accessible via the Standard Report component:
https://help.rallydev.com/apps/2.1/doc/#!/api/Rally.ui.report.StandardReport


Q: Vue.js - Data lost in karma/phantomjs tests I'm writting some unit tests for a Vue app. Everything is workign good when I try to test the DOM content, but I can't access the data of my components. In fact there is no data if I console.log my component $data property, it prints an empty object, no initially defined data or any other data. Just nothing.
Here is some code
some vue component
<template>
   <form @submit.prevent="saveAccount">
      Tipo de cuenta
        <select class="form-control" id="accountType" v-model="newAccount.type">
          <option v-for="type in accountTypes" v-bind:value="type.value">
            {{type.label}}
          </option>
        </select>
   </form>
</template>

My tests
  beforeAll(() => {
    vm = new Vue({
      template: '
<account></account>
',
      components: { account }
    }).$mount()
  })

  afterAll(() => {
    vm.$destroy(true)
  })

  it('account type', () => {
    // this pass
    expect(vm.$el.querySelectorAll('#accountType option').length).toBe(4)
    const options = vm.$el.querySelectorAll('#accountType option')
    // here accountTypes is undefined
    const accountValues = vm.accountTypes.map(type => {
      return type.value
    })
    options.forEach(option => {
      expect(accountValues.indexOf(option.value)).not.toBe(-1)
    })
  })

Some code is omitted. So, why is that my component data is empty but at the same time, properly rendered in the DOM?

A: After some try and error I found the answer and it's pretty obvious now. The thing is, that I was searching for data in the wrong place. The vmobject that I defined like this
vm = new Vue({
  template: '
<account></account>
',
  components: { account }
}).$mount()

Is a Vue instance that only have a component and a template option, the data I was searching for was in the child of that instance. So, I have to use this way to access data
const accountInstance = vm.$children[0]

This works, because to test I defined a single child easy to identify. I also tried before using const accountInstance = new account() but that throws an error because vue components ar not constructors


Q: Is there any way to get a warning in eg. GCC or Clang about this strict aliasing violation? The rationale for this being a strict aliasing violation is that
the buffer has declared type char array and is being aliased by
a pointer to struct
#include<string.h>
#include<stdalign.h>
#include<stdio.h>

struct thing {
  int a;
  char x;
};

int main() {
  char alignas(struct thing) buffer[128];

  struct thing s = {10,'a'};

  struct thing *ptr = memcpy(buffer,&s,sizeof(struct thing));

  // violation at ptr->a
  printf("%d\n",ptr->a);

  return 0;
}

A: A compiler that warned about all constructs that violate the constraints in N1570 6.5p7 as written would generate a lot of warnings about constructs which all quality implementations would support without difficulty.  The only way those parts of the Standard would make any sense would be if the authors expected quality implementations to extend the semantics of the language to support use cases which, even if they're not mandated by the Standard, they should have no reason not to support.  The use case illustrated in the presented code is an example of this.
Although the Standard would not forbid implementations from using N1570 6.5p7 as an excuse to behave nonsensically even in situations where an object is only ever used as a single type of storage, the stated purpose of the rules is to describe situations where implementations would or would not be required to allow for the possibility of pointer aliasing.  Forbidding the particular construct at issue even in cases where storage is only used as a single type would do nothing to further that aim.  If code were to use the subscripting operator on buffer, in addition to accessing the storage via a struct thing*, a compiler might legitimately fail to recognize the possibility that accesses using the latter lvalue might interact with those using the former.  In the presented code, however, the storage is only used as type struct thing or via memcpy, usage cases that there would have been no reason to prohibit.  Writing the rules in such a way as to only forbid use of a char[] to hold data of some other type in situations where it was also subscripted would definitely add complexity, but would not have been expected to make compilers support any constructs they wouldn't have supported anyway.
If the Standard had been intended to characterize programs into those that were correct or incorrect, it would need to have been worthwhile to write more detailed rules.  Since it made no attempt to distinguish constructs which are erroneous from those which are correct but "non-portable" (in the sense that there might exist some implementations which don't process them meaningfully), however, there was no need to try to explicitly identify and provide for all of the constructs which compilers would have no reason not to process meaningfully.


Q: Overriding an external style sheet without access to  I have a Ecommerce Host that does not allow access to the Header Tag or the External .CSS file.
I have to override using inline styles.
Problem is, I have to override Pseudo Class :active
Is there way to link an external style sheet from within an inline style so that I can style the pseudo classes?
Any simple alternatives? Without  access?

A: You don't need to put your <link rel="stylesheet" href="blah-blah.css"> tag into head to make it work, but it's a bad practice, because it works slower and looks a bit bad, but I understand your situation :) Just put <link> at the end of the  and it'll work fine! For example:
File styles.css
p {
    color: blue;
}

File index.html
<!DOCTYPE html>

I am blue, da ba dee da ba dai!

  <link rel="stylesheet" href="styles.css"/>


Q: C#: RunWorkerAsync() doesn't trigger DoWork() I am writing a small forms based application to connect to an LDAP server, and I wanted the "connect" button to work in the background.  So I was following the information and discussion
here
but for whatever reason my code doesn't appear to be working right:  I set a breakpoint at 'worker.RunWorkerAsync();'  And it just steps right through it.
What am I doing wrong?  I am working in Visual Studio 2010, in case it matters.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Threading;

namespace ldapconnect
{

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public Form1()
    {
        InitializeComponent();
    }

    //server
    public string lds;
    //naming context
    public string root;

    public string username;
    public string password;

    BackgroundWorker worker = new BackgroundWorker();

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        worker = sender as BackgroundWorker;
        foreach (string s in connect(worker, e, lds + "/" + root, txt_user.Text.ToString(), txt_pass.Text.ToString()))
        {
            rtb_results.Text += s + "\r\n";
        }
    }

    private List<string> connect(BackgroundWorker worker, DoWorkEventArgs e, String serv, string usr, string pass)
    {
        //Directory search code taking server path and creds passed in from form
        DirectoryEntry conn = new DirectoryEntry(serv, usr, pass);
        DirectorySearcher ds = new DirectorySearcher(conn);

        //I only want users
        ds.Filter = "objectClass=user";

        List<string> sendBack = new List<string>();

        try
        {
            SearchResultCollection results = ds.FindAll();

            foreach (SearchResult result in results)
            {
                sendBack.Add(result.ToString());
            }
        }
        catch (Exception ex)
        {
            sendBack.Clear();
            sendBack.Add(ex.ToString());
        }

        return sendBack;
    }

    //connect button start background worker
    private void btn_connect_Click(object sender, EventArgs e)
    {
        worker.RunWorkerAsync();
    }

    //Exit Button
    private void btn_close_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    //set server path
    private void btn_server_Click(object sender, EventArgs e)
    {
        string serv = inputBox("ldap://", "IP or DNS Name of LDS Server", "");
        lds = serv;
        lbl_server.Text = lds;
    }

    //set default context
    private void btn_context_Click(object sender, EventArgs e)
    {
        string cntx = inputBox("In CN=,DC=,DC= Form:", "Default Naming Context", "");
        root = cntx;
        lbl_cntx.Text = root;
    }

    //VB interaction box
    private string inputBox(string a,string b,string c)
    {
        return Microsoft.VisualBasic.Interaction.InputBox(a, b, c);
    }

    private void btn_Defaults_Click(object sender, EventArgs e)
    {
        lds = "LDAP://127.0.0.1";
        root = "DC=USERS,DC=TEST,DC=LOCAL";
        txt_user.Text = "reader";
        txt_pass.Text = "password";
        lbl_server.Text = lds;
        lbl_cntx.Text = root;
    }
}
}

A: You have not set
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
before calling worker.RunAsync()

A: You are never wiring up the event.
   public Form1()
    {
        InitializeComponent();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    }

A: RunWorkerAsync() starts the worker thread and immediately returns thus the debugger seems to  "step through it". Set a breakpoint in the worker_DoWork() method.

A: If u still have event and is not working, try the following
Just call

System.Windows.Forms.Application.DoEvents();

before calling RunWorkerAsync()


Q: Qt QInputDialog parameter list I am starting a Qt course this semester. Having looked at the official documentation as well as some on line examples I am confused by the parameter lists of the QInputDialog and QMessagebox classes.
Is there anywhere where one could find some decent info as to what to pass when creating the class / form?
Right now I have this by trial error
tempC = QInputDialog::getDouble(0, "Temperature Converter",
                                "Enter the temperature in Celsius to convert to Fahrenheit:", 1);

Looking at the official docs doesn't help a lot either (at least not for me yet) as it says this:
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
                                   tr("Amount:"), 37.56, -10000, 10000, 2, &ok);

as an example.
Any links will be much appreciated.

A: double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
                                   tr("Amount:"), 37.56, -10000, 10000, 2, &ok);

*

*A dialog will popup with parent the widget in which you are using this function. (this)

*The dialog's title will be  QInputDialog::getDouble() (tr is used in order to translate this string if you want using QtLinguist)

*Inside the dialog will be a double spibox and a label

*The label's string will be Amount:

*The default value of the spinbox (what you see when the dialog popups) will be 37.56

*The minimum value will be -10000 (you will not be able to set a value less than this)

*The maximum value will be 10000 (you will not be able to set a value greater than this)

*Two decimal point will be displayed, eg 3.478 will be displayed as 3.48.

*If the user presses the Ok button then the ok argument will be set to true, otherwise it will be set to false
Check the documentation which includes an example for more details.


Q: Object of type Period is not JSON serializable in plotly I am trying to plot a line chart. Below is my code
CODE :
import plotly.offline as pyo
import plotly.graph_objects as go
flag = determineFlag('2020-03-01','2020-03-30')

df_r = getDataForTrend(df,'2020-03-01','2020-03-30','d')

colors = {
    'background': '#111111',
    'text': '#7FDBFF'
}

data = [go.Scatter(x = df_r[df_r['S2PName-Category']==category]['S2BillDate'],
                    y = df_r[df_r['S2PName-Category']==category]['totSale'],
                    mode = 'lines',
                    name = category) for category in df_r['S2PName-Category'].unique()]

layout = {'title':'Category Trend',
         'xaxis':{'title':'Time Frame'},
         'yaxis':{'title':'Total Sales Amount','tickformat' : '.2f'}}

fig = go.Figure(data=data,layout=layout)

pyo.iplot(fig)

when I run the above code I get the below error:
ERROR:
TypeError: Object of type Period is not JSON serializable

While tying to debug, I try to execute the below code
DEBUG CODE :
df_r[df_r['S2PName-Category']==category]['S2BillDate']

OP :
3     2020-03-01
11    2020-03-02
21    2020-03-03
26    2020-03-04
41    2020-03-06
42    2020-03-05
46    2020-03-07
Name: S2BillDate, dtype: period[D]

How can I fix the type error ? Is there any tweaks to this ? Any help is much appreciated! Thanks !

A: AFAIK this is still an issue and plotly will fail in such situation. There is still an open issue at github: Support for Pandas Time spans as index col.
As proposed in the comments one of the solution is to use to_timestatmp conversion, see this.

*

*Create MWE (this is just for reproducibility since there is no data provided in the question)

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.offline as pyo

df = pd.DataFrame({"one": np.random.random(10)}, index=pd.period_range("2020-03-01", freq="M", periods=10))
# Out:
#               one
# 2020-03  0.302359
# 2020-04  0.919923
# 2020-05  0.673808
# 2020-06  0.718974
# 2020-07  0.754675
# 2020-08  0.731673
# 2020-09  0.772382
# 2020-10  0.654555
# 2020-11  0.549314
# 2020-12  0.101696

data = [
    go.Scatter(
        x=df.index,
        y=df["one"],
    )
]
fig = go.Figure(data=data)
pyo.iplot(fig)
# -> will fail ("TypeError: Object of type Period is not JSON serializable")

*Use to_timestamp conversion (-> df.index.to_timestamp())

data = [
    go.Scatter(
        x=df.index.to_timestamp(), # period to datetime conversion
        y=df["one"],
    )
]
fig = go.Figure(data=data)
pyo.iplot(fig)

Or, if you do not need datetime format you can convert this to string as well:
data = [
    go.Scatter(
        x=df.index.strftime("%Y-%m"),  # You can define your own format
        y=df["one"],
    )
]
fig = go.Figure(data=data)
pyo.iplot(fig)

You can of course do this conversion right on the original dataframe (so you do not need to do it iteratively inside go.Scatter), but this is just minor stuff. There might be also a way of using custom encoder instead of the default one, but I think it's not worthy of trying and afaik there is no better solution than using one of possible conversion from Period to datetime or string.


Q: Start Activity while Countdown is running I have a problem with my Android app at the moment. I use the Google Client Message Service to send messages to my Android App. If the user opens the app, he starts on the HomeActivity.
When the user now receives my message from the server and press on the push message, the app starts a new intent with the AlertActivity.
At this point, I pass the time (saved in the message) with putExtra to the new activity, where i use it for a CownDownTimer. Till this point everything is ok and the countdown works perfect.
The problem is now, when the user minimizes the app and open it again.
At this Point the user is not redirected to my AlertActivity again but to my HomeActivity.
After the CountDownTimer Ends the AlertSound is played, but he can't cancel it, because he can't show the activity again.
How can I redirect the User to the AlertActivity if he starts the app while the CountDown is running?
My AlertActivity
package com.prgguru.example;

public class AlertActivity extends Activity {

    String str;
    Boolean running;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alert);

        final TextView txttime = (TextView) findViewById(R.id.txtalert);
        str = getIntent().getStringExtra("msg");
        Integer time = Integer.parseInt(str);

        time = time; //*60000;

        txttime.setText(time+"");

        CountDownTimer Count = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                running = true;
                txttime.setText(String.format("%02d:%02d:%02d",
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
                                TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
                //txttime.setText(""+millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                txttime.setText("Finished");

                final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.alarm);
                mp.start();
            }
        };

        Count.start();
    }

    public boolean getRunning(){
        return false;
    }
}

GCMIntentService
public class GCMIntentService extends IntentService {
    // Sets an ID for the notification, so it can be updated
    public static final int notifyID = 9001;
    NotificationCompat.Builder builder;

    public GCMIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                sendNotification("Deleted messages on server: "
                        + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {
                sendNotification(extras.get(ApplicationConstants.MSG_KEY)+"");
            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String msg) {
            Intent resultIntent = new Intent(this, AlertActivity.class);
            resultIntent.putExtra("msg", msg);
            PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
                    resultIntent, PendingIntent.FLAG_ONE_SHOT);

            NotificationCompat.Builder mNotifyBuilder;
            NotificationManager mNotificationManager;

            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            mNotifyBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle("Alert")
                    .setContentText("You've received new message.")
                    .setSmallIcon(R.drawable.ic_launcher);
            // Set pending intent
            mNotifyBuilder.setContentIntent(resultPendingIntent);

            // Set Vibrate, Sound and Light
            int defaults = 0;
            //defaults = defaults | Notification.DEFAULT_LIGHTS;
            //defaults = defaults | Notification.DEFAULT_VIBRATE;
            // defaults = defaults | Notification.DEFAULT_SOUND;

            Notification notification = mNotifyBuilder.build();

            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alarm);
            notification.defaults |= Notification.DEFAULT_VIBRATE;

            mNotifyBuilder.setDefaults(defaults);
            // Set the content for Notification
            mNotifyBuilder.setContentText("New message from Server");
            // Set autocancel
            mNotifyBuilder.setAutoCancel(true);
            // Post a notification
            mNotificationManager.notify(notifyID, notification);
    }
}


Q: Handle multiple login page for different type of user in asp.net core mvc 6 In asp.net core i need to manage two different types of user (administrator and normal user).
When user session is expired i want administrater to be redirected to baseurl/admistrator/login  and for normal user redirect to baseurl/login
   services.AddIdentity<User, Role>(op =>
                {
                    op.SecurityStampValidationInterval = TimeSpan.FromSeconds(0);
                    op.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                    op.Cookies.ApplicationCookie.SlidingExpiration = true;

//here how can i set multiple login path
                    //op.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNetCore.Http.PathString("/administrator/account/login");
                    //op.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNetCore.Http.PathString("/login");

Does anyone have idea how to do it ?
Thanks


Q: Google Drive API with Python from server(Backend) without browser autentication I'd like to save the files of my Saas Appication to my Google Drive Account, all the examples I've seen was with oauth2 autentication and needs the end user autenticate openning the browser, I need to upload files from my server without any user interation, sending files direct to my account!
I have try many tutorials I found on internet with no success, mainly the oficial
Google Drive API with Python
How can I autenticate programatically from my server and upload files and use API features such as share folders and others?
I'm using Python, the lib PyDrive uses the same aproach to autenticate

A: To add to andyhasit's answer, using a service account is the correct and easiest way to do this.
The problem with using the JSON key file is it becomes hard to deploy code anywhere else, because you don't want the file in version control. An easier solution is to use an environment variable like so:
https://benjames.io/2020/09/13/authorise-your-python-google-drive-api-the-easy-way/

A: You can do this, but need to use a Service Account, which is (or rather can be used as) an account for an application, and doesn't require a browser to open.
The documentation is here: https://developers.google.com/api-client-library/python/auth/service-accounts
And an example (without PyDrive, which is just a wrapper around all this, but makes service account a bit trickier):
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http

scopes = ['https://www.googleapis.com/auth/drive.readonly']

credentials = ServiceAccountCredentials.from_json_keyfile_name('YourDownloadedFile-5ahjaosi2df2d.json', scopes)

http_auth = credentials.authorize(Http())
drive = build('drive', 'v3', http=http_auth)

request = drive.files().list().execute()
files = request.get('items', [])
for f in files:
    print(f)

A: I know it's quite late for answer but this worked for me:
Use the same API you were using, this time in your computer, it will generate a Storage.json which  using it along with your scripts will solve the issue (specially in read-ony platforms like heroku)

A: Checkout the Using OAuth 2.0 for Web Server Applications. It seems that's what you're looking for.

Any application that uses OAuth 2.0 to access Google APIs must have
  authorization credentials that identify the application to Google's
  OAuth 2.0 server. The following steps explain how to create
  credentials for your project. Your applications can then use the
  credentials to access APIs that you have enabled for that project.
Open the Credentials page in the API Console. Click Create credentials
   OAuth client ID. Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP,
  Java, Python, Ruby, and .NET must specify authorized redirect URIs.
  The redirect URIs are the endpoints to which the OAuth 2.0 server can
  send responses. For testing, you can specify URIs that refer to the
  local machine, such as http://localhost:8080.
We recommend that you design your app's auth endpoints so that your
  application does not expose authorization codes to other resources on
  the page.

A: Might be a bit late but I've been working with gdrive over python, js and .net and here's one proposed solution (REST API) once you get the authorization code on authorization code
How to refresh token in .net google api v3?
Please let me know if you have any questions


Q: How can I delete the selected messages (with checkboxes) in jQuery? I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
    if ($('#checkbox_' + id).is(':checked')) {
        $('#' + id).addClass("selected");
    }
    else {
        $('#' + id).removeClass("selected");
    }
}

But, I don't know where to go from there.

Here is some example markup for one of the lines [generated by PHP] of the list of messages:

<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />

Nathan
Test
[Time sent]

As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {

}
else {
alertBox('No messages selected.'); //this is a custom function
}
});

I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!

A: How about this
$('#delete').click(function() {
    var checked = $('.inbox_check:checked');
    var ids = checked.map(function() {
        return this.value;  // why not store the message id in the value?
    }).get().join(",");
    if (ids) {
        $.post(deleteUrl, {idsToDelete:ids}, function() {
            checked.closest(".line").remove();
        });
    }
    else {
        alertBox('No messages selected.'); // this is a custom function
    }
});

Edit: Just as a side comment, you don't need to be generating those incremental ids.  You can eliminate a lot of that string parsing and leverage jQuery instead.  First, store the message id in the value of the checkbox.  Then, in any click handler for a given line:
var line = $(this).closest(".line");  // the current line
var isSelected = line.has(":checked");  // true if the checkbox is checked
var msgId = line.find(":checkbox").val();  // the message id
var starImg = line.find(".star_clicker img");  // the star image

A: Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
    var result = null;
    var scriptUrl = './databaseDelete.php';
    $.ajax({
        url: scriptUrl,
        type: 'post',
        async: false,
        data: {id: reference_id},
        success: function(response)
        {
            result = response;
        }
    )};
    return result;
}
$('.inbox_check').each(function(){
    if ($(this).is(':checked')){
        var row = $(this).parent().parent();
        var id = row.attr('id');
        if (id == null)
        {
            alert('My selector needs updating');
            return false;
        }
        var debug = 'Deleting ' + id + ' now...';
        if (console) console.log(debug);
        else alert(debug);
        row.remove();
        var response = removeDatabaseEntry(id);

        // Tell the user something happened
        $('#response_div').html(response);
    }
});


Q: Getting Error after implementing ROOM database in kotlin Gradle (Module) :
def room_ver = "2.2.5"

dependencies {
  implementation "androidx.room:room-ktx:" + room_ver
    kapt "androidx.room:room-compiler:" + room_ver
    androidTestImplementation "androidx.room:room-testing:" + room_ver
}

Error :

Tried adding :
gradle (app level)
dependencies {
   classpath "com.android.tools.build:gradle:3.1.3"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}

gradle : Module
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-kapt'

Dashboard.kt
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.view.inputmethod.EditorInfo
import android.widget.TextView.GONE
import android.widget.TextView.OnEditorActionListener
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.ddnsoftech.mrenvois.R
import com.ddnsoftech.mrenvois.common.APIService.Const
import com.ddnsoftech.mrenvois.common.APIService.IntentKeys
import com.ddnsoftech.mrenvois.common.`interface`.BackButtonClickIntefrace
import com.ddnsoftech.mrenvois.common.helpers.UserSession
import com.ddnsoftech.mrenvois.common.util.SnackNotify
import com.ddnsoftech.mrenvois.common.util.hideKeyboard
import com.ddnsoftech.mrenvois.model.Restaurant
import com.ddnsoftech.mrenvois.view.Activities.RestaurantsDetails.ResturantsDetailsActivity
import com.ddnsoftech.mrenvois.view.Adapter.CategoryAdapter
import com.ddnsoftech.mrenvois.view.Adapter.ResturantAdapter
import com.ddnsoftech.mrenvois.view.BaseActivity.BaseActivity
import com.ddnsoftech.mrenvois.view.ServiceNotAvailable.ServiceNotAvailableActivity
import kotlinx.android.synthetic.main.filer_search_view.*
import kotlinx.android.synthetic.main.fragment_dashboard.*

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [DashboardFragment.newInstance] factory method to
 * create an instance of this fragment.
 */

private enum class DashboardListType {
    FILTER_VIEW,HOME_VIEW
}

enum class FilterType {
    popular,promo,location
}

class DashboardFragment : Fragment(), BackButtonClickIntefrace {

    val viewModel = DashboardFragmentVM()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
//            param1 = it.getString(ARG_PARAM1)
//            param2 = it.getString(ARG_PARAM2)
        }
        hideKeyboard()
    }

    lateinit var popularRestaurantAdapter: ResturantAdapter
    lateinit var nearRestaurantAdapter: ResturantAdapter
    lateinit var categoryAdapter: CategoryAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_dashboard, container, false)
    }

    override fun onStart() {
        super.onStart()
        txtDeliveringTo.text =  "${getString(R.string.delivering_to)} ${UserSession.shared.currentAddress?.address ?: ""}"
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initialSetup()
        getHomePageData()
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            DashboardFragment().apply {
//                arguments = Bundle().apply {
//                    putString(ARG_PARAM1, param1)
//                    putString(ARG_PARAM2, param2)
//                }
            }
    }

    @SuppressLint("ClickableViewAccessibility")
    fun initialSetup() {
        viewModel.clearFilter()
        popularRestaurantAdapter = ResturantAdapter(viewModel.popular_restaurant,requireActivity())
        nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
        categoryAdapter = CategoryAdapter(viewModel.categories,requireContext())

        popularRestaurantAdapter.onItemSelect = { restaurant ->
            redirectToRestaurantDetails(restaurant)
        }

        nearRestaurantAdapter.onItemSelect = { restaurant ->
            redirectToRestaurantDetails(restaurant)
        }

        categoryAdapter.onItemSelect = { index,value ->
            viewModel.restaurants.clear()
            viewModel.categories[index] = value
            getHomePageData()
        }

        val manager1 =  GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
        recyclerViewMostPopular.layoutManager = manager1

        val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
        recyclerViewNearBy.layoutManager = manager2

        val manager3 =  LinearLayoutManager(requireActivity(),LinearLayoutManager.HORIZONTAL,false)

          //  GridLayoutManager(requireActivity(), 4, GridLayoutManager.HORIZONTAL, false)
        recyclerViewCategory.layoutManager = manager3

        recyclerViewMostPopular.adapter = popularRestaurantAdapter
        recyclerViewNearBy.adapter = nearRestaurantAdapter
        recyclerViewCategory.adapter = categoryAdapter

        scrollView.viewTreeObserver
            .addOnScrollChangedListener(OnScrollChangedListener {

                if (scrollView != null) {
                    val bottom: Int =
                        scrollView.getChildAt(scrollView.childCount - 1)
                            .height - scrollView.height - scrollView.scrollY
//                if (scrollView.scrollY === 0) {
//                    //top detected
//                    SnackNotify.showMessage("Reached to top",relyMain,SnackNotify.MSGType.SUCCESS)
//                }

                    if (scrollView.scrollY == 120) {
                        hideKeyboard()
                    }

                    if (bottom == 0) {
                        //bottom detected
                        if (viewModel.isFilterApplied()) {
                            getHomePageData()
                        }
                        //SnackNotify.showMessage("Reached to Bottom",relyMain,SnackNotify.MSGType.SUCCESS)
                    }
                }
            })

        swipeRefreshLayout.setOnRefreshListener {
            viewModel.restaurants.clear()
            getHomePageData()
        }

        /// Ser view handler
//        etSearchView.

        setupSearchView()
        setUpFilerView()
        reloadList()
    }

    fun redirectToRestaurantDetails(restaurant: Restaurant) {
       var intent = Intent(requireActivity(),  ResturantsDetailsActivity::class.java)
        intent.putExtra(IntentKeys.RESTAURANT,restaurant)
        activity?.startActivity(intent)
    }

    fun setUpFilerView() {
        lnrPopular.setOnClickListener { view ->
            onFilterButtonClick(view)
        }

        lnrPromos.setOnClickListener { view ->
           onFilterButtonClick(view)
        }

        lnrLocation.setOnClickListener { view ->
            onFilterButtonClick(view)
        }

        txtNearByViewAll.setOnClickListener {
            onFilterButtonClick(lnrLocation)
        }

        txtPopularViewAll.setOnClickListener {
            onFilterButtonClick(lnrPopular)
        }

        txtDeliveringTo.setOnClickListener {
            (requireActivity() as? BaseActivity)?.openSetLocation()
        }
    }

    fun setupSearchView() {
        etSearchView.setOnTouchListener(View.OnTouchListener { _ , event ->
            val DRAWABLE_RIGHT = 2
            if (event.action == MotionEvent.ACTION_UP) {
                if (event.rawX >= etSearchView.right - etSearchView.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
                ) {
                    viewModel.restaurants.clear()
                    getHomePageData()
                    true
                }
            }
            false
        })

        etSearchView.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.restaurants.clear()
                getHomePageData()
                true
            } else false
        })
//        etSearchView.doOnTextChanged { text, start, before, count ->
//        }
    }

    fun getHomePageData() {
        hideKeyboard()
        viewModel.search = etSearchView.text?.toString()
        swipeRefreshLayout.isRefreshing = true
        viewModel.getHomeData {  success,errMsg ->
            swipeRefreshLayout.isRefreshing = false
            if (success) {
                reloadList()
            }else {
                SnackNotify.showMessage(errMsg,relyMain, SnackNotify.MSGType.ERROR)
                reloadList()
            }
        }
    }

    fun getSearchData() {

    }

    fun reloadList() {
        if (viewModel.isFilterApplied()) {

            if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.VERTICAL) {
                val handler = nearRestaurantAdapter.onItemSelect
                nearRestaurantAdapter = ResturantAdapter(viewModel.restaurants,requireActivity(), GridLayoutManager.VERTICAL)
                nearRestaurantAdapter.onItemSelect = handler
                val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.VERTICAL, false)
                recyclerViewNearBy.layoutManager = manager2
                recyclerViewNearBy.adapter = nearRestaurantAdapter
          }

            lnrMostPopularContainer.visibility = View.GONE
            lnrTopCategoryContainer.visibility =
                if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE

            lnrNearByContainer.visibility =
                if (viewModel.restaurants.count() == 0) View.GONE else View.VISIBLE

            viewNoRecordFound.visibility =
                if (viewModel.restaurants.count() != 0) View.GONE else View.VISIBLE

            //popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
            nearRestaurantAdapter.updateList(viewModel.restaurants)
            categoryAdapter.updateList(viewModel.categories)

            txtNearByTitle.text =  getString(R.string.restaurants)
            txtNearByViewAll.visibility = View.GONE
            reloadFilterTab(true)
        }else{

            if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.HORIZONTAL) {
                nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
                val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
                recyclerViewNearBy.layoutManager = manager2
                recyclerViewNearBy.adapter = nearRestaurantAdapter
            }

            txtNearByTitle.text =  getString(R.string.near_by)
            txtNearByViewAll.visibility = View.VISIBLE

            viewNoRecordFound.visibility =  if (viewModel.near_restaurants.count() == 0 && viewModel.popular_restaurant.count() == 0)  View.VISIBLE else  View.GONE

            lnrMostPopularContainer.visibility =
                if (viewModel.popular_restaurant.count() == 0) View.GONE else View.VISIBLE
            lnrNearByContainer.visibility =
                if (viewModel.near_restaurants.count() == 0) View.GONE else View.VISIBLE
            lnrTopCategoryContainer.visibility =
                if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE
            popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
            nearRestaurantAdapter.updateList(viewModel.near_restaurants)
            categoryAdapter.updateList(viewModel.categories)
            reloadFilterTab(false)
        }
    }

    fun reloadFilterTab(filterApplied:Boolean) {
        if (filterApplied && viewModel.filterType != null)
        {
             when (viewModel.filterType!!) {

                 FilterType.popular -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.filter_active_border)
                     lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
                 }

                 FilterType.promo -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrPromos.background = resources.getDrawable(R.drawable.filter_active_border)
                     lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
                 }

                 FilterType.location -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrLocation.background = resources.getDrawable(R.drawable.filter_active_border)
                 }

             }
        }else{
            lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
            lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
            lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
        }

    }

    override fun onBackClicked(): Boolean{
//        TODO("Not yet implemented")
        if (viewModel.isFilterApplied())
        {
            viewModel.clearFilter()
            getHomePageData()
            return true
        }

        return false
    }

    fun onFilterButtonClick(v: View) {
       when (v) {
           lnrPopular -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.popular ) null else FilterType.popular
           }

           lnrPromos -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.promo ) null else FilterType.promo
           }

           lnrLocation -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.location ) null else FilterType.location
           }
       }

        reloadFilterTab(viewModel.filterType != null)
        viewModel.restaurants.clear()
        getHomePageData()
    }
}


Q: Geometry based sum Suppose $A_1A_2...A_{20}$  is a $20$-sided polygon. How many non-isosceles(scalene) triangles can be formed whose vertices are among the vertices of the polygon but whose sides are not the sides of the polygon?

A: Easily done by inclusion-exclusion. The number of triangles having their vertices among the vertices of the $20$-agon, but with their sides out of the sides of the $20$-agon, equals the number of ways for choosing $3$ non-adjacent people among $20$ people seated around a circular table. By stars and bars, this is $\binom{17}{3}$. It just remains to count the number of isosceles triangles among the previous ones. There are no equilateral triangles since $3\nmid 20$, and each vertex of the $20$-agon is the apex of $8$ isosceles triangles among the previous ones. It follows that the answer is given by
$$ \binom{17}{3}-20\cdot 8 = \color{red}{520}.$$


Q: modal does not load form data I have the data form and the data update views, when I'm not using the modal, it works perfectly, however when using modal, it loads the empty forms, and if I load without the modal, the data saved in the database appear .
I do not know where I'm going wrong.
I can change the user name and save, the problem is that let's say user1 and I want to change to the user2 name, when I click to change the name, the form field does not come with user1 filled in.
and if I do not use the modal, it comes with the user1 already filled in
views.py
class UserNameUpdate(LoginRequiredMixin, UpdateView):
    model= User
    fields = ['username']
    template_name=' /change-username.html'

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()   # This should help to get current user

        # Next, try looking up by primary key of Usario model.
        queryset = queryset.filter(pk=self.request.user.usuario.pk)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except queryset.model.DoesNotExist:
            raise Http404("No user matching this query")
        return obj

    def get_success_url(self):
        return reverse('sistema_perfil')

change-username.html
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}

          Home /
          Perfil /
          Usúario

 Alterar Nome do Usúario

<form method="post" action="{% url 'sistema_change_username' %}" class="form-signin" enctype="multipart/form-data" id="form" name="form" validate>
{% csrf_token %}

        {{ form.username| as_crispy_field}}

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

</form>

Voltar

{% endblock %}

menu_perfil.html
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
            Launch demo modal
        </button>

Modal title

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

    {% include 'profile/change-username.html' %}

A: Am I right that the with-modal and without-modal templates load from two different views? If so, the problem is how you are using Django's {% include %} template tag. Here are the docs:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include
Key line: "An included template is rendered within the context of the template that includes it."
It looks like menu_perfil.html is rendered from a different view, which doesn't pass the form object into its context. So menu_perfil.html doesn't know what {{ form }} is. Whereas change-username.html is rendered with your UsernameUpdate view with the form object.  Try moving your modal HTML into change-username.html, around your form code, instead of including a separate snippet, and see if that solves the problem.
In general, inheriting from base templates using {% extends %} is preferable to using includes unless you really have to, because of limitations like this.


Q: printing BST IN order I am trying to print out tree nodes IN order however all that it is coming out are the noes of the lowest depth! I'm not sure what is wrong with my logic so I was wondering if another set of eyes would help me or give me a hint thanks!!
Expected output:
1
2
3
4
6
8
10

my code:
class Node:
    def __init__(self,value):
        self.right = None
        self.left = None
        self.value = value

def BST_Insert(root, node):     # root --> root of tree or subtree!
    if root.value is None:
        root = node             # beginning of tree
    else:
        if root.value > node.value:     # go to left
            if root.left is None:
                root.left = node
            else:
                BST_Insert(root.left, node)

        if root.value < node.value:    # go to right
            if root.right is None:
                root.right = node
            else:
                BST_Insert(root.right, node)

def inorder_print(root):
    if root.left is not None:
        inorder_print(root.left)
    else:
        print root.value
    if root.right is not None:
        inorder_print(root.right)

r = Node(4)
# left
a = Node(2)
b = Node(1)
c = Node(3)
# right
d = Node(8)
e = Node(6)
f = Node(10)

BST_Insert(r, a)
BST_Insert(r, b)
BST_Insert(r, c)
BST_Insert(r, d)
BST_Insert(r, e)
BST_Insert(r, f)

print "in order:"
inorder_print(r)

A: I don't think you need the else after the the first if statement.
Something like the following might work,
if left!=null:
    inorder(left)
print(current_node.val)
if (right!=null):
    inorder(right)


Q: htaccess [L] flag didn't work I have .htaccess file like this inside searchEngine folder inside htdocs of xampps
    RewriteEngine On
    RewriteRule ^\/?test$ view/index.php [NC,L]
    RewriteRule ^(.*)$   http://google.com [NC,L]

then I type this in the address bar:

*

*localhost/searchEngine/test

Why this redirect to

*

*http://google.com
not

*

*view/index.php?

I thought this must be redirected to

*

*view/index.php

not

*

*http://google.com

A: It is because mod_rewrite runs in a loop. First rule is doing this:
Starting URL:
/searchEngine/test

Ending URL:
/searchEngine/view/index.php

Now L flag causes mod_rewrite to loop again. So now your starting URL becomes:
Starting URL:
/searchEngine/view/index.php

Now 1st rule' pattern ^test doesn't match but your 2nd rule is using .* as matching pattern hence redirects to google.
You can have your rules as follows to prevent this behavior:
RewriteEngine On

RewriteRule ^/?test$ view/index.php [NC,L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^ http://google.com [R,L]

2nd rule has this additional condition:
RewriteCond %{ENV:REDIRECT_STATUS} ^$

REDIRECT_STATUS is set to 200 after first rule's execution. So 2nd rule will redirect only if first rule hasn't executed first hence it will skip /test.
If you're using Apache 2.4+ then you can use END instead of L to end the execution:
RewriteEngine On

RewriteRule ^/?test$ view/index.php [NC,END]

RewriteRule ^ http://google.com [R,L]

A: This is happening because of the internal redirection, You can use the END flag instead of L to stop this behaviour :
    RewriteEngine On
    RewriteRule ^\/?test$ view/index.php [NC,END]
    RewriteRule ^(.*)$   http://google.com [NC,L]


Q: Is there a way to reduce duplication here? I am creating a prisoner's dilemma simulation and I have two functions that are counting cooperations and defections done by the two players and outputting them as a tuple. I see a lot of similarities and would like some guidance on how to consolidate the two functions into another function that the two can call upon so I am not reusing code. I am very new in OCaml so I am struggling to find a way to do this!
Here is the necessary information:
type action = bool ;;
type play = action * action ;;
type history = play list

let rec count_defections (history : history) : (int * int) =
  match history with
  | [] -> (0, 0)
  | play :: rest ->
    match play with
    | (player1, player2) ->
      match count_defections rest with
      | (d1, d2) ->
        if (player1, player2) = (false, false) then (d1 + 1, d2 + 1)
        else if (player1, player2) = (false, true) then (d1 + 1, d2)
        else if (player1, player2) = (true, false) then (d1, d2 + 1)
        else (d1, d2) ;;

let rec count_cooperations (history : history) : (int * int) =
  match history with
  | [] -> (0, 0)
  | play :: rest ->
    match play with
    | (player1, player2) ->
      match count_cooperations rest with
      | (d1, d2) ->
        if (player1, player2) = (true, true) then (d1 + 1, d2 + 1)
        else if (player1, player2) = (true, false) then (d1 + 1, d2)
        else if (player1, player2) = (false, true) then (d1, d2 + 1)
        else (d1, d2) ;;

My first thoughts were:
let count_common (history : history) : (int * int) =
  match history with
  | [] -> (0, 0)
  | play :: rest ->
    match play with
    | (player1, player2) ->
      match .....

But I don't really understand  how to do the rest.

A: Here's a function that counts the two parts of a pair separately, counting elements that equal a given value.
let count_val_in_pairs value pairs =
    List.fold_left
        (fun (cta, ctb) (a, b) ->
            ((if a = value then cta + 1 else cta),
             (if b = value then ctb + 1 else ctb)))
        (0, 0)
        pairs

Your count_defections is this:
let count_defections history =
    count_val_in_pairs false history

Your count_cooperations is this:
let count_cooperations history =
    count_val_in_pairs true history


Q: taking input from file using scanner class in java I am trying store a list of cities in a class using two co-ordinates(x,y) in java
My class is as follows:
public class City {
    int x;
    int y;

    // Constructs a city at chosen x, y location
    public City(int x, int y){
        this.x = x;
        this.y = y;
    }
}

I have made another class to store the cities in an ArrayList:
public class TourManager {

    // Holds our cities
    private static ArrayList destinationCities = new ArrayList<City>();

    // Adds a destination city
    public static void addCity(City city) {
        destinationCities.add(city);
    }
}

My main class is as follows:
public class Final {
    public static void main(String[] args) {
        // Create and add our cities
        City city = new City(60, 200);
        TourManager.addCity(city);
        City city2 = new City(180, 200);
        TourManager.addCity(city2);
        City city3 = new City(80, 180);
        TourManager.addCity(city3);
    }
}

Here, I have stored three cities in the ArrayList inside the main function. But now I want to take the input from a file in the following format. I just want to take the co-ordinates ignoring all other lines.

NAME: sample.tsp
TYPE: TSP
COMMENT: Odyssey of Ulysses (Groetschel/Padberg)
DIMENSION: 3
EDGE_WEIGHT_TYPE: GEO
NODE_COORD_SECTION
1 60 200
2 180 200
3 80  180

I want to use the scanner class to take the input but getting confused in using it. i have made a partial code fragment to take input but it isn't working:
Scanner in = new Scanner(new File("sample.tsp"));
String line = "";
int n;
in.nextLine();
in.nextLine();
in.nextLine();
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
in.nextLine();
in.nextLine();

But how will I take the coordinates using the City class object as I have done before from this file?

A: You need to skip the first few lines, which you don't need.
Then split the lines to get the various numbers. Index 0 contains the serial no., 1 and 2 contain the coordinates. Then parse them to int. eg:
in.nextLine();// multiple times.
//...
String cs = in.nextLine(); // get the line
City city = new City(Integer.parseInt(cs.split(" ")[1]), Integer.parseInt(cs.split(" ")[2]));
TourManager.addCity(city);

String cs2 = in.nextLine();
City city2 = new City(Integer.parseInt(cs2.split(" ")[1]), Integer.parseInt(cs2.split(" ")[2]));
TourManager.addCity(city2);

String cs3 = in.nextLine();
City city3 = new City(Integer.parseInt(cs3.split(" ")[1]), Integer.parseInt(cs3.split(" ")[2]));
TourManager.addCity(city3);

A: Whenever you use in.nextLine(), actually it takes the string that you entered. So try to assign it to some string variable. For example:
String s =in.nextLine();

Also, just using in.nextLine(); which you did in 2nd,3rd 4th,8th and 9th line is not needed.


Q: Better terminology than "equivalence class of functions" Let $X = C(\mathbb R)$ be the Fréchet space of real-valued continuous functions.  For each $f \in X$ and each compact set $D \subseteq \mathbb R$, let $$[f]_D = \{ g \in X : \mbox{$g(t) = f(t)$ for all $t \in D$} \} $$ be the equivalence class of functions which agree with $f$ on the set $D$.
I refer to this object frequently in a paper I am writing.  The notation $[f]_D$ is short and sweet, but the terminology "equivalence class of functions" is too clunky.
Question:  Is there a better name for the object $[f]_D$?

A: For ease of exposition, it is often good to supress those parameters that do not vary often.  In the fragment suggested by Tom LaGatta in the comments, there is enough explanatory information and samples of forms of usage that I am quite comfortable with it as a first, second, or even third paragraph.  I, too, would get tired of writing or reading 10 such paragraphs.  So I would set up a context paragraph and occasional reminder sentences, such as follows (forgive the lack of Tex):
"Since D won't change much in the following, we will write [f] sometimes to hide the dependence on D.  Also, we will use the nickname 'class' sometimes to refer to the fact that [f]_D is an equivalence class of functions."
And then occasionally
" so we have that expression(h) does this for us (remember [h] is short for the class [h]_D)..."
I hope this helps.
Gerhard "Ask Me About System Design" Paseman, 2011.08.26

A: What about "an extension class" or "an extension family" (from D)?

A: How about "$D$-class"?

A: Why don't you just say that for any function $\phi\in C(D)$ there is a measure $P_\phi$ on the class $[\phi]$ of functions $f\in C(\mathbb R)$ whose restriction $f|_D$ coincides with $\phi$?


Q: Outlook 2010 crash repair cycle On my computer, Outlook 2010:

*

*Reports an error and then crashes.

*The next time it's started it offers to start in safe mode, which I select, and then it crashes.

*The third time it asks if I want to repair it which it successfully does and then...

*on the fourth time it starts.

This cycle is repeated each time I start outlook. Any ideas why this might be happening or what to do for a permanent fix?


Q: How to get last updated row or ID in wordpress How to get last updated row or ID in wordpress.
Like :  $wpdb->insert_id;

A: I had the same problem.

There is no equivalent function. $wpdb->insert_id works only after $wpdb->insert

Alternative way
If it's an update, you can either get the id with a query based on the data you have got, or most of the time, you should have already got the id before update it.
global $wpdb;

$data = array(
    'first_name' => "John",
    'last_name' => "Doe"
);

$where = array(
    'id' => $my_id
);

$res_update = $wpdb->update( $wpdb->prefix . "my_table", $data, $where );

if( $res_update === false ){
     error_log( 'my error');
}

return $my_id;

A: Once again select the same row updated on success.
 if($wpdb->last_error !== '') {
      //throw error stuffs
    }else{
     $last_updated_row = $wpdb->get_row("SELECT * FROM $wpdb->prefix . 'my_table' WHERE id = $my_id");

    }


Q: sql query to fetch the third highest sale grouped by sales Fetch the third highest sale amount from the table (group by sale amount) in MySQL
 select Top 3 * from t1 group by sale_Amnt

|Id|product_name|product_group    |sale_Amnt(INR)
------------------------------------------------
 1|  p1       |   Cosmetic       |4485
 2|  p2       |   Cosmetic       |8525
 3|  p3       |   Health         |12589
 4|  p4       |   Health         |8525
 5|  p5       |   Home Appliances|9858
 6|  p6       |   Home Appliances|12589

Expected output
|Id|product_name|product_group    |sale_Amnt(INR)
------------------------------------------------
 2|  p2       |   Cosmetic       |8525
 4|  p4       |   Health         |8525`

A: The proposed duplicate is a misunderstanding of the question.  This question appears to be looking for the third highest value overall, but taking duplicates into account.
You can get the third row using offset/fetch in SQL Server:
select t.*
from t
where t.sale_amount = (select t2.sale_amount
                       from t t2
                       group by t2.sale_amount
                       order by t2.sale_amount desc
                       offset 2 fetch first 1 row only
                      );

In MySQL, that would be:
select t.*
from t
where t.sale_amount = (select t2.sale_amount
                       from t t2
                       group by t2.sale_amount
                       order by t2.sale_amount desc
                       limit 1 offset 2
                      );

A:

SELECT * FROM `sale_amnt` ORDER BY `sale_Amnt` DESC LIMIT 2,1


Q: SQL divide by shifted value of other field I have a table that looks like this:

Where RETENTION is the division of N_CUSTOMERS by CUSTOMER_WHEN_0 for each PERIOD_NUMBER.
Now I need to get another new field that is the result of dividing each retention value of thar PERIOD_NUMBER by the retetion value of the previous PERIOUD_NUMBER. In the example of the image it's not appreciated, but I have all the consecutive values for PERIOD_NUMBER. When the PERIOD_NUMBER is 0, it doesn't matter that the division by its shifter value is NAN or similar, I will replace it later.
So, summarizing, my desired output is a ner field that shows the result of dividing the RETENTION value of the PERIOD_NUMBER of that row by the RETENTION value of the previous PERIOD_NUMBER. I'm using DBT and in case is useful I have the querys I used to get these fields and I have the code to do that process in Python, but I need to do it in SQL
first purchase of the user, ORDER_MONTH is the date  of that purchase, and PERIOD_NUMBER is the date difference in months between COHORT and ORDER_MONTH. N_CUSTOMERS is the number of customers in each PERIOD_NUMBER in each COHORT, and CUSTOMER_WHEN_0 is the number of users in each cohort when the PERIOD_NUMBER is 0.
I had to use a window function in order to achive this last field.

A: Here is an example of how you can get the previous RETENTION using a subquery, assuming that the period numbers are all consecutive:
SELECT
    N_CUSTOMERS,
    PERIOD_NUMBER,
    CUSTOMER_WHEN_0,
    RETENTION,
    (SELECT st_inner.RETENTION
        FROM sourcetable st_inner
        WHERE st_inner.PERIOD_NUMBER = st_outer.PERIOD_NUMBER - 1
    ) as PREVIOUS_RETENTION
FROM sourcetable st_outer

I left out the calculation for readability's sake, but I think it should be clear how to do this.


Q: AngularJS. Displaying custom popup on user's attempt to leave the page Is it possible to synchronously display bootstrap modal (instead of native confirm) when user tries:

*

*change route

*leave the page

(AngularJS)

A: You must separate your code into two different functions.
If you have this:
var txt;
var r = confirm("Press a button!");
if (r == true) {
    // Put this in a function ...
    txt = "You pressed OK!";
} else {
    // ... and this in another function
    txt = "You pressed Cancel!";
}

Would like this:
var onOkClick = function(){
  txt = "You pressed OK!";
};

var onCancelClick = function(){
  txt = "You pressed Cancel!";
};

And in the buttons of your modal:
<button type='button' class='btn btn-success' onclick="onOkClick()">OK</button>
<button type='button' class='btn btn-default' onclick="onCancelClick()">Cancel</button>


Q: "It isn't a circumstance to what is going to happen" - meaning? For the context, a character is going to attack an unsuspecting enemy, who just woke up and:

"What happened?" he articulated at last.
"Never mind what happened. It isn't a circumstance to what's going to
happen now.

What does the " It isn't a circumstance to" phrase mean? Does express something like "it is nothing compared to.."?

A: Cambridge dictionary defines a circumstance as "a fact or event that makes a situation the way it is": literally, it means things that are standing around a particular situation. Halpin's question refers to what has just happened (the transfer to the fourth dimension). The protagonist's reply is probably intended to indicate that the transfer is irrelevant to what is about to happen (the protagonist murdering Halpin).
It's certainly a very unusual usage of the word: firstly because we normally talk about "circumstances of" rather than "circumstances to": and secondly because we generally use it only about things that happened in the past, or about hypothetical future situations- we don't tend to use it for planned future events.