text:
Q: Comparing 2 lists and returning matches I have two functions that are related to one another - the first one removes characters that are the same and in the same position, and returns the ones that do not match:
def remove(l1, l2):
    r = []
    for char in range(len(l1)):
        if l1[char] != l2[char]:
            r.append(l1[char])
    return r

While this function goes through both lists, and removes the same values by using the previous function. Then using what's left it finds values that are the same in b (but they don't need to be in the same position).
def search(a, b):
    found = []
    elim = remove(a, b)
    for char in elim:
        if char in b:
            find = 'y'
            found.append(find)
    return found

While I am able to return the correct amount of 'y's for the other examples I use, it breaks when I have more than one of the same value. If there is only 1 'V' in list 'b', but 2 in list 'a', I only want 1 'y' returned for it, not 2. Since I'm not sure where to go from here, my function returns this:
    search(['L', 'F', 'V', 'V'], ['V', 'F', 'O', 'R'])
Expected:
    ['y']
Got:
    ['y', 'y']

Thanks in advance!

A: This should work for you:
def remove(l1, l2):
    return [char1 for char1, char2 in zip(l1, l2) if char1 != char2]

def search(a, b):
    elim = remove(a, b)
    return ['y' for char in set(elim) if char in b]

print(search(['L', 'F', 'V', 'V'], ['V', 'F', 'O', 'R']))

output: ['y']
I used set(elim) to remove the duplicates from the list created by remove().

A: try this
def remove(l1, l2):
    r = []
    print l1
    print l2
    for char in range(len(l1)):
        if l1[char] != l2[char]:
            #the below line your code appending index of char , i am appending char
            r.append(l1[char])
    return r

def search(a, b):
    found = []
    elim = remove(a, b)
    print elim
      #the below line your code iterating through all chars of elim , i am looping through only unique ones using set
    for char in set(elim):
        if char in b:
            find = 'y'
            found.append(find)
    return found

A: Change your second function to this:
def search(a, b):
    found = []
    elim = remove(a, b)
    for char in elim:
        if a[char] in b:
            find = 'y'
            found.append(find)
            b.remove(a[char])
    return found

This takes into account that elim contains indexes rather than characters.  It will remove one 'V' from b every time a 'V' is indexed by elim.  But if both lists contains two 'V's you will get two 'y's.  I don't know if that's what you want.  Your statement of the problem isn't clear.  But I am pretty sure that you are a Python beginner and aren't ready to use the advanced concepts from the other answers.


text:
Q: Why is the pointer location of shared memory across two blocks identical? I thought that shared memory of a cuda-device is private to a block. However, it seems to me that the pointer of shared memory across two blocks is identical:
#include <stdio.h>

__global__ void foo() {
    __shared__ int ar[8];
    printf("shared memory pointer %p at blockidx %i\n", ar, blockIdx.x);
}

int main() {
    dim3 blockDim(1);
    dim3 gridDim(2);
    foo<<<gridDim, blockDim>>>();
    cudaDeviceSynchronize();
}

Running to code above produces:
shared memory pointer 0x7f88f5000000 at blockidx 0
shared memory pointer 0x7f88f5000000 at blockidx 1

With this program, I expected to create two different blocks, initialize shared memory on each block and obtain two different locations for the memory. Am I misunderstanding something? Or do these pointer indeed have a different physical location but within a block the addresses seem to be the same?

A: Shared memory is block-private, i.e. threads from one block cannot access another block's shared memory.
... for this very reason, it's actually to be expected that the address range for shared memory will be the same for all blocks - but in each block, loading from or storing to these addresses affects the block-local shared memory.
For intuition: This is somewhat similar to how, on the CPU, code in two processes may use identical pointer addresses but they will actually access different physical locations in memory (usually).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I l reshape data that has multiple related binary "observations" so that works nicely with ggplot? I have a data-wrangling problem.
Per observation, I have data that has a number of exhibited "features", and they result in an outcome as well as the duration of time spent.
So, for example, we have this data.
participantID   observation treatment   duration    outcome feature.A   feature.B   feature.C   feature.D   feature.other
1   1   A   3.1 Successful  TRUE    FALSE   TRUE    FALSE   FALSE
1   2   A   2.1 Successful  TRUE    TRUE    FALSE   TRUE    FALSE
1   3   A   1.0 Unsuccessful    FALSE   FALSE   FALSE   FALSE   TRUE
1   4   A   5.1 Successful  TRUE    FALSE   TRUE    TRUE    FALSE
2   1   B   2.5 Unsuccessful    FALSE   FALSE   FALSE   FALSE   TRUE
2   2   B   3.1 Unsuccessful    TRUE    FALSE   TRUE    FALSE   FALSE
2   3   B   2.6 Successful  TRUE    TRUE    FALSE   FALSE   FALSE
2   4   B   2.8 Successful  TRUE    FALSE   TRUE    FALSE   FALSE
2   5   B   2   Unsuccessful    TRUE    TRUE    TRUE    TRUE    FALSE
2   6   B   3.6 Successful  TRUE    FALSE   TRUE    FALSE   FALSE
3   1   A   3.4 Successful  FALSE   FALSE   FALSE   FALSE   TRUE
3   2   A   3.5 Unsuccessful    TRUE    FALSE   TRUE    FALSE   FALSE

The idea is that we have participants who have tried different attempts (observations). These participants were in treatment groups A, or B. Based on their attempts, we identified if they were successful or unsuccessful, as well as the duration of their attempt. We also identify if they used particular features, which are not mutually-exclusive with each other, with the exception of feature.other, which is TRUE only when every other feature is FALSE.
I would like to be able to plot this data in ggplot with a command similar to the following:
ggplot(test, aes(x=observation, y=duration, fill=outcome)) + geom_bar(position="dodge", stat="identity") + facet_grid(participantID ~ feature.A + feature.B + feature.C + feature.D + feature.other)

This command would print a gridded plot of features and participants, and looks something like this:

I'm not sure, however, that this is the right "way" to use the data. One thing I want to be able to do is to somehow collapse the different "feature" variables into one, so I can easily use it (for example, if I want to build stacked bar charts I can just add it as a "feature" column in ggplot).
From what I understand, I should be melting it down to long format, right? But if I do that incorrectly, the feature variables end up duplicating the number of observations because each "TRUE" ends up appearing as an ID and then it ends up that there are problems counting the observations (especially if I do cumsums and similar to do additions).
Attempt:
    reshape(test, direction="long", varying=c("feature.A", "feature.B", "feature.C", "feature.D", "feature.other")) # This gives me some odd output, including "time" as the old feature variable A/B/C/D/other
But then when I plot it gives me output that doesn't make sense (for example, all of the bars end up being the same height).
So my question is:
How can I format related binary factors (like the features) in such a way that it plays nicely with reshape and ggplot, without duplicating the variable output values?
I ask this because if I want to (later) plot a cumulative sum of the durations at each observation, using reshape gets in the way: for example, if I have a reshaped data frame:
ddply(test_long, .(participantID), summarize,cumsum(duration))

will give me incorrect results. I suppose one way to get around this is to simply do the calculation before the melt, but doing things in an order-dependent way is somewhat less than idea.
Maybe this also stems from an understanding of what exactly "long" format and "wide" format are and how they interact with ggplot as well, if someone can briefly point me to explanatory resources to further my understanding I would appreciate it.
dput data below:
test <- structure(list(participantID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L), observation = c(1L, 2L, 3L, 4L, 1L, 2L,
3L, 4L, 5L, 6L, 1L, 2L), treatment = structure(c(1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L), .Label = c("A", "B"), class = "factor"),
    duration = c(3.1, 2.1, 1, 5.1, 2.5, 3.1, 2.6, 2.8, 2, 3.6,
    3.4, 3.5), outcome = structure(c(1L, 1L, 2L, 1L, 2L, 2L,
    1L, 1L, 2L, 1L, 1L, 2L), .Label = c("Successful", "Unsuccessful"
    ), class = "factor"), feature.A = c(TRUE, TRUE, FALSE, TRUE,
    FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE), feature.B = c(FALSE,
    TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE,
    FALSE, FALSE), feature.C = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE), feature.D = c(FALSE,
    TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE,
    FALSE, FALSE), feature.other = c(FALSE, FALSE, TRUE, FALSE,
    TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE)), .Names = c("participantID",
"observation", "treatment", "duration", "outcome", "feature.A",
"feature.B", "feature.C", "feature.D", "feature.other"), class = "data.frame", row.names = c(NA,
-12L))

A: test_long = reshape(test, direction = 'long',
  idvar = 1:5, varying = 6:10, sep = ".",
)

rownames(test_long) = NULL

library(ggplot2)
ggplot(test_long, aes(x = observation, y = duration, fill = outcome)) +
  geom_bar(position="dodge", stat="identity") +
  facet_grid(participantID ~ time)


text:
Q: PHP regexp to surround numbers with html tags in strings I have some strings they are combinations of numbers and letters both like:
A555D1E , 452AE, now i want to set a different color for numbers and letters.
So I need to surround numbers in string with html tags like span or b and result should be like this:
html:

A555D1E

css:
spec-text{
    color:red;
}

spec-text .n{
    color:green;
}

if there is some function like:
function surroundNumbersByTag($string, $tag, $classes){
    // codes that return this string:
    // 'A555D1E'
}

is there anyway ?

A: Try
function surroundNumbersByTag ($string, $tag, $classes)
{
    return preg_replace("~([0-9]+)~", "<$tag class='$classes'>$1</$tag>", $string);
}

echo surroundNumbersByTag('A555D1E', 'span', 'n');


text:
Q: how to uninstall power designer 16 plugin from eclipse ide juno release I've been trying to uninstall the plugin of power designer 16 (sybase product) from my Eclipse IDE but couldn't find a way to do that. I've checked the about-eclipse > installation details stuff, but power-designer ins't listed in the installed plugins list though all its components are shown in the installed software category (though no option to uninstall them).
I'm also looking for a solution that will remove the power designer perspective that got added as well.
Thanks in advance

A: Uninstalling/disabling plugins in Eclipse is a bit tricky. I described it once in my blog: http://www.asgarli.net/2011/05/uninstalling-eclipse-plugins-from.html

A: Try to check in the Eclipse's install folder manually for the plugin's files :
Eclipse > plugins or Eclipse > features

A: In Juno:
Windows>Preferences>Install/Update>Uninstall or Update.
Click on plugins you want to remove and click on uninstall


text:
Q: Change background-color upon click (using map function in javascript) I have a menu of buttons and upon hover over, they change in background-color. Below is a toy version. (Context: I use a map function because the number, names, and colors of buttons are dependent on the elements in "myList" and "myColors" which can be different in other cases.)
However, when the user clicks on a button, I'd like the button to stay that color. All clicked button should remain colored, so multiple buttons can stay colored at the same time. But when the user clicks "done", all the buttons should return to white/transparent. Does anyone know how to do this?
I'm having trouble making this edit since I create the button ids with a mapping function, which means I can't directly edit the background colors in my css file.
Many thanks in advance!

    <meta charset="utf-8" />

done

A: I would suggest to add an additional class to buttons once they are clicked to keep the hover functionality.
let $buttons = $('
');
      let myList = ["A", "B", "C", "D"];
      let myColors = ["red", "green", "blue", "red"];

      myList.map(function (letter, index) {
        let $button = $("

")
          .addClass("buttons")
          .attr("id", "button_" + letter)
          .html("
" + letter + "
")
          .on("mouseenter", function () {
            $(this).css("background", myColors[index]);
          })
          .on("mouseleave", function () {
                    if(!$(this).hasClass('clicked')){
            $(this).css("background", "transparent");
            }
          })
          .on("click", function () {
            $(this).css("background", myColors[index]);
            $(this).addClass('clicked');
          })
        $buttons.append($button);
      });

      $("body").append($buttons);

      $("#done").on("click", clearColor);

      function clearColor() {
         $(".buttons").css({backgroundColor:'transparent'});
         $(".buttons").removeClass('clicked');
      }


text:
Q: How to receive multiple object parameters in GET Action in ASP.NET Core 2.2 REST API? I have common scenario where I want to list some items in web client app (I am using vue.js and axios) that are fetched from the backend (asp.net core 2.2 REST application). The client should pass some filtering and pagination options to the backend in order to get items it needs to display on the current page.
However, the problem I have is that GET action defined on server Controller can't deserialize parameters passed to it from HTTP request.
Here is the backend code:
// these are classes that represent parameters sent in HTTP Get request
public class Filter
{
    public bool IsActive { get; set; }
    public string Name { get; set; }
}

public class Pagination
{
    public string Page { get; set; }
    public string ItemsPerPage { get; set; }
}

This is the action in controller:
[HttpGet]
public IActionResult GetItems([FromQuery]Filter filter, [FromQuery]Pagination pagination)
{
    // ... get items from db with specified filter and pagination
    return Ok();
}

Here is the axios get request from the client:
axios.get('https://localhost:44336/api/items', {
  params: {
    filter: {
      isLive: true,
      name: 'test123'
    },
    pagination: {
      page: 5,
      itemsPerPage: 10
    }
  }
})

Notice that I use axios params to specify two nested objects, one filter and other pagination. This doesn't work and parameters passed to GetItems() action are objects with default values (eg. isLive=false, name=null, page=0, itemsPerPage=0...)
Is there a way to make this work and have two separate objects passed and properly deserialized by GetItems() action?

A: View Model:
public class ViewModel
{
    public Filter Filter{ get; set; }
    public Pagination Pagination  { get; set; }
}

Action method:
public IActionResult GetItems([FromQuery] ViewModel model)

Client:
params: {
    filter.isActive: true,
    filter.name: 'test123',
    pagination.page: 5,
    pagination.itemsPerPage: 10,
}

A: For your current request from axios, the request will be https://localhost:44320/api/SampleData/GetItems?filter={"isActive":true,"name":"test123"}&pagination={"page":5,"itemsPerPage":10} which will not be able to bind by default modelbinder.
You could implement your own model binder like
public class NestedModelBinder<T> : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var modelName = bindingContext.ModelName;
        var request = bindingContext.HttpContext.Request.Query.TryGetValue(modelName, out var modelValue);
        if (modelValue.Count ==0)
        {
            return Task.CompletedTask;
        }
        try
        {
            var model = JsonConvert.DeserializeObject<T>(modelValue);
            if (model == null)
            {
                return Task.CompletedTask;
            }
            bindingContext.Result = ModelBindingResult.Success(model);
            return Task.CompletedTask;
        }
        catch (Exception ex)
        {
            return Task.CompletedTask;
        }
    }
}

Useage
[HttpGet("[action]")]
public IActionResult GetItems([ModelBinder(typeof(NestedModelBinder<Filter>))]Filter filter, [ModelBinder(typeof(NestedModelBinder<Pagination>))]Pagination pagination)
{
    var request = HttpContext.Request.Query;
    // ... get items from db with specified filter and pagination
    return Ok();
}

One more note: keep Filter.IsActive at server side and filter.isLive at client side the same.


text:
Q: Optimize memory usage of a collection of Strings in Java I have a large number of name - value pairs (approx 100k) that I need to store in some sort of cache (say a hash map) where the value is a string with an average of about 30k bytes in size.
Now I know for a fact that a large number of the values have exactly the same string data.  In order to avoid having to allocate the identical string data several times, I would like to somehow reuse a previously allocated string thus consuming less memory.  In addition this needs to be reasonably fast. i.e. scanning through all the previously allocated values one-by-one is not an option.
Any recommendations on how I could solve this problem?

A: String.intern() will help you here (most likely). It will resolve multiple instances of the same string down to one copy.
EDIT: I suggested this would 'most likely' help. In what scenarios will it not ? Interning strings will have the effect of storing those interned string representations permanently. If the problem domain is a one-shot process, this may not be an issue. If it's a long running process (such as a web app) then you may well have a problem.
I would hesitate to say never use interning (I would hesistate to say never do anything). However there are scenarios where it's not ideal.

A: String.intern is the obvious choice as Brian says. But if you don't want to intern across all the String in memory, you can use a Set to first see if the value is present. Here's untested code. You will have to work out removing from reverse map when removing from main
  class Map2<K, V> implements Map<K, V>
  {
    Map<K, V> _map = Maps.newHashMap();
    Set<V, V> _rev = Maps.newHashMap();

    V put(K k, V v) {
      if (_rev.containsKey(v)) {
        V prev = _rev.get(v);
        return _map.put(k, prev);
      } else {
        _rev.put(v, v);
        return _map.put(k,v);
      }
   }

A: Do not use String.intern (there have been various memory issues related to this through the years).  instead, create your own cache, similar to String.intern.  basically, you want a Map, where each key maps to itself.  then, before caching any string, you "intern" it:
private Map<String,WeakReference<String>> myInternMap = new WeakHashMap<String,,WeakReference<String>>();
public String intern(String value) {
  synchronized(myInternMap) {
    WeakReference<String> curRef = myInternMap.get(value);
    String curValue = ((curRef != null) ? curRef.get() : null);
    if(curValue != null) {
      return curValue;
    }

    myInternMap.put(value, new WeakReference<String>(value));
    return value;
  }
}

note, you use weakreferences for the keys and values so that you don't keep references for strings which you are no longer using.

A: It somewhat depends upon how you are creating the String.
One possible way is to use TreeSet that uses a Comparator that can compare existing Strings and the source of your new String. Use SortedSet.tailSet and an Iterator to find an existing String. Or alternatively NavigableSet.ceiling/floor or a TreeMap with a similar setup.
String.intern has performance problems.

A: Agreed with others on not using String.intern(): once you've put a string there, it will never go away. Look to early revisions of Xerces for why this is a bad idea.
A better solution is to use a WeakHashMap, wrapping the value in a WeakReference:
private Map<String,WeakReference<String>> _map
    = new WeakHashMap<String,WeakReference<String>>();

public synchronized String intern(String str)
{
    WeakReference<String> ref = _map.get(str);
    String s2 = (ref != null) ? ref.get() : null;
    if (s2 != null)
        return s2;
    str = new String(str);
    _map.put(str, new WeakReference(str));
    return str;
}

This code is from an article that I wrote on the Java reference objects. You'll find the explanation there.
EDIT: need to create a new string here (and I'll update the article) because the original might be a substring of a far larger character array. I thought that was fixed around JDK 1.3, but apparently not (at least not in 1.5).

A: You could compress the strings. A 30K string should get a good compression ratio.  I wrote a hack to compress large String as an exercise, but you could use a byte[] of the compressed data to store the String.
A 30K character string will use about 60KB (2 bytes per character) so even using getBytes() is likely to be an improvement.

A: Do you actually need Strings, or do you just need any old CharSequence? If not, then consider implementing a "compact" CharSequence such as the one I suggest in the link.


text:
Q: "Обнаружены символы за пределами инструкции SQL" почему-то не получается добавить данные в базу, пишет "Обнаружены символы за пределами инструкции SQL"

Вот сам синтаксис запроса:
SELECT abonent.ID, abonent.[FIO abonenta], abonent.tarif, abonent.uslugi, abonent.balans, abonent.[data plateja], abonent.status

FROM abonent;

INSERT INTO abonent (ID, [FIO abonenta], tarif, uslugi, balans, [data plateja], status) VALUES ('6', 'Кузьмин Е.О.', 'Стандарт', 'тв+телефония', '-11', '25.08.2016', 'выкл')

A: Попробуйте так, как в документации: запрос на добавление нескольких записей
    INSERT INTO target [( field1 [, field2
    [, …]])] [IN externaldatabase ] SELECT
    [ source .] field1 [, field2 [, …] FROM
    табличное выражение


text:
Q: How to clean Maven snapshots deployed on the server? On the snapshot server, Maven keeps all the generated snapshots. I want to clean all but the latest ones that are deployed on the server.
How can I tell Maven to only keep the N latest snapshot versions and to remove the rest?

A: I believe this is not controlled by Maven.  Instead, it is more to do with the repository manager.
For example, in Nexus, you can setup scheduled task to remove snapshots from hosted repositories.

A: The best is to use a Repository Manager like Artifactory, Nexus or Archiva which have tasks for such purposes or in case of releases the according SNAPSHOT's will automatically be deleted.


text:
Q: Excel - auto-fill blank cells or 0 in B:B to a dummy e-mail address which changes sequentially I am creating a database in Excel that requires an e-mail address to be assigned to each row or user. While some users have an e-mail address in the original CSV file the majority do not. Each e-mail address will need to be unique. Is there any way to auto-fill all blank cells with an e-mail address which starts with a higher number each time it's used for example 1example@example.com, 2example@example.com etc etc...

A: If the email address you are going to autofill wouldn't have any significance, and you just want them to be unique, you can use the row number to make up an email address. One possible formula you can use is as follows,
=ROW()&"example@example.com"

If the above formula is used in 10th row, it would produce 10example@example.com.


text:
Q: Canonical Topology Let $V$ be an n-dimensional vector space over $\mathbb{R}$.
Of course $V \cong \mathbb{R^n}$ since we can define an isomorphism
$$f:V\longrightarrow \mathbb{R^n}$$
by mapping basis elements to basis elements.
But such isomorphism requires a choice of basis.
I can define a topology $\tau = \{f^{-1}(V); V \ $is open in$\ \mathbb{R^n}\}$
But is $\tau$ a canonical topology?
An isomorphism is canonical if it is defined without having to choose a basis.
But what does canonical mean in terms topology?
In my case, I had to "choose" a basis to define an isomorphism, then use that isomorphism to define open sets. So I'm not sure if it works...

A: It is a canonical topology in the following two senses:

*

*A priori, the topology $\tau$ depends on the choice of an isomorphism $f \colon V \rightarrow \mathbb{R}^n$ so let's denote $\tau$ by $\tau_f$. However, if you pick a different linear isomorphism $g \colon V \rightarrow \mathbb{R}^n$ then you have $\tau_f = \tau_g$ so in fact, the topology doesn't depend on the choice of an isomorphism. To see that, note that we can find a linear isomorphism $T \colon \mathbb{R}^n \rightarrow \mathbb{R}^n$ such that $T \circ f = g$. Since $T$ is a linear isomorphism, it is, in particular, a homeomorphism of $\mathbb{R}^n$ (with the standard topology) and so a set $U$ is open in $\mathbb{R}^n$ iff $T^{-1}(U)$ is open in $\mathbb{R}^n$. But since $g^{-1}(U) = f^{-1}(T^{-1}(U))$, the resulting topologies are the same.

*You can characterize $\tau$ without any choice by saying that $\tau$ is the weakest topology on $V$ with respect to which, any linear map $T \colon V \rightarrow \mathbb{R}^n$ (or even any linear map $T \colon V \rightarrow \mathbb{R}^m$) is continuous (where the right hand side gets the usual topology). Thus
$$ \tau = \{ T^{-1}(U) \, | U \subseteq \mathbb{R}^n \textrm{ is open}, T \colon V \rightarrow \mathbb{R}^n \textrm{ is a linear isomorphism}\} \\
= \{ T^{-1}(U) \, | \, U \subseteq \mathbb{R}^n \textrm{ is open}, T \colon V \rightarrow \mathbb{R}^n \textrm{ is linear} \} \\
= \{ T^{-1}(U) \, | \, U \subseteq \mathbb{R}^m \textrm{ is open}, T \colon V \rightarrow \mathbb{R}^m \textrm{ is linear} \} $$
and you eliminate any "choice" by taking "all the possible choices".
To see that the three definitions for $\tau$ coincide, let $T \colon V \rightarrow \mathbb{R}^m$ be a linear map and let $U \subseteq \mathbb{R}^m$ be an open set. We need to show that we can find an open $\tilde{U} \subseteq \mathbb{R}^n$ and a linear isomorphism $\phi \colon V \rightarrow \mathbb{R}^n$ such that $T^{-1}(U) = \phi^{-1}(\tilde{U})$. Choose some linear isomorphism $\phi \colon V \rightarrow \mathbb{R}^n$ and write $T = (T \circ \phi^{-1}) \circ \phi$ where $T \circ \phi^{-1} \colon \mathbb{R}^n \rightarrow \mathbb{R}^m$ is linear, hence continuous. Then
$$ T^{-1}(U) = \phi^{-1} \left( \underbrace{\left( T \circ \phi^{-1} \right)^{-1} (U)}_{\tilde{U}} \right). $$

A: You may check that your topology does not depend on the choice of $f$: if you pick another basis, the open subsets will be the same.
This topology is canonical in the following sense. First, note that it makes $V$ into a topological vector space: the addition of vectors $V\times V\to V$ and the action $\mathbb{R}\times V\to V$ are continuous with respect to this topology. Then, any finite dimensional Hausdorff topological vector space necessarily has the topology that you described.
See an exposition in the blog of Terence Tao.


text:
Q: PHP: global variable not being stored? It turns out this has nothing to do with global variables (sorry discussed in another post).
I was trying to keep all the code on one page (self-processing), but I'm pretty sure it's not possible. Arranging the following code outlined in the answer below, on the same page, does not work. Figures.
*edited to add the whole script minus the CSS (unnecessary).
<!DOCTYPE html>

        <title>Inventory Tables</title>

<?php //IRCinventoryhome.php
    require("IRCpage.inc");
    require_once 'IRCinventoryconfig.php';

    $homepage = new IRCtemplate();

    $homepage->Display();

    session_start();
?>

        <?php //Menu for table selection
        ini_set('display_errors',1);  error_reporting(E_ALL);

        $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
            if ($connection->connect_error) die($connection->connect_error);

        $result = $connection->query("SHOW TABLES");

        $table = array();
            while ($row = $result->fetch_row()){
            $table[] = $row[0];
            }
        $count = count($table);
        ?>

        <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
            <select name="value">
                <?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
                    echo <<<_END

                            <option value="$table[$pointer]">$table[$pointer]</option>

_END;
                }
?>
            </select>
        <input type="submit" value="go">
        </form>

<?php //inventory mysql tables
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['value'])) {

$thisTable = $_POST['value'];

global $thisTable;

ini_set('display_errors',1);  error_reporting(E_ALL);

$queryColumns  = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
    if (!$resultColumns) die ("Database access failed: " . $connection->error);

$columns = array();
    while ($column = $resultColumns->fetch_row()){
        $columns[] = $column[0];
     }

echo "

\n";
$count = count($columns);

$insertColumns = array();
for ($pointer = 1 ; $pointer < $count ; ++$pointer) {
    $insertColumns[] = $columns[$pointer];
    }

for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
    echo "";
    echo $columns[$pointer];
    echo "	";
    }
    echo "ACTIONS	";
$queryRows  = "SELECT * FROM $thisTable";
    $resultRows = $connection->query($queryRows);
    if (!$resultRows) die ("Database access failed: " . $connection->error);

$rows = $resultRows->num_rows;

for ($j = 0 ; $j < $rows ; ++$j)
    {
        $resultRows->data_seek($j);
        $row = $resultRows->fetch_array(MYSQLI_NUM);

        $count = count($row);

        echo "
";
        for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
            echo "";
            echo $row[$pointer];
            echo "	";
        }
?>

            <input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="edit" name="edit">
            <input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="delete" name="delete">

<?php
    }
echo "

"; //end table, end content

$connection->close();
}
?>

        <form name="addRow" action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
                <input type="hidden" name="control">

                Add row?

        <?php for ($pointer = 1 ; $pointer < $count ; ++$pointer) { ?>

                <input type="text" name="<?php echo $columns[$pointer];?>">

        <?php } ?>

                <input type="submit" value="go">

        </form>

<?php

global $thisTable;
echo $thisTable;

if (isset($_POST['control'])) {

global $thisTable;
echo $thisTable;

$valuesArray = array();
if (isset($_POST)) {
    $valuesArray = $_POST;
    }

$columnsArray = array_keys($valuesArray);
//array_splice($columnsArray, 0, 1);

$columnsString = implode(", ", $columnsArray);

print_r($columnsString);

$insertValues = array();
foreach($valuesArray as $values) {
     $insertValues[] = $values;
    }

$valuesString = implode(" ", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = str_replace(" ", "', '", $valuesString);
$valuesString = substr($valuesString, 3);

print_r($valuesString);
/*
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
            if ($connection->connect_error) die($connection->connect_error);

    $queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
    $result      = $connection->query($queryInsert);

    if (!$result) echo "INSERT failed: $query
" .
      $connection->error . "

";

$connection->close();
*/
}
?>

A: After 20 hours or so I'm still not sure if this possible to do all on the same page. But this solution works...
Page one:
<!DOCTYPE html>

        <title>Interactive Resource Center Inventory</title>
        <meta charset="UTF-8">

<?php //IRCinventoryhome.php
require("IRCpage.inc");
require("IRCinventoryfunctions.php");
require_once 'IRCinventoryconfig.php';

$homepage = new IRCtemplate();

$homepage->Display();

session_start();
    $_SESSION['value'] = $_POST['value'];
    $thisTable = $_SESSION['value'];
    var_dump($_SESSION);

$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
    if ($connection->connect_error) die($connection->connect_error);
    global $connection;

$result = $connection->query("SHOW TABLES");

$table = array();
    while ($row = $result->fetch_row()){
    $table[] = $row[0];
    }
$count = count($table);

?>

        <form action="http://localhost:8888/IRC/IRCinventoryhometest.php" method="POST">
            <select name="value">
                <?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
                    echo <<<_END

                            <option value="$table[$pointer]">$table[$pointer]</option>

_END;
                }
                ?>
            </select>
            <input type="submit" name="go">
        </form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$thisTable = "OUTGOING";

$queryColumns  = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
    if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;

$queryRows  = "SELECT * FROM $thisTable";
    $resultRows = $connection->query($queryRows);
    if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;

$rows = $resultRows->num_rows;
global $rows;

global $connection;

drawTable();

$connection->close();
} else {

if(isset($_POST['value'])) {
    $thisTable = $_POST['value'];
    }

$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
    if ($connection->connect_error) die($connection->connect_error);
    global $connection;

$queryColumns  = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
    if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;

$queryRows  = "SELECT * FROM $thisTable";
    $resultRows = $connection->query($queryRows);
    if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;

$rows = $resultRows->num_rows;
global $rows;

global $connection;

drawTable();

?>

        <form name="addRow" action="http://localhost:8888/IRC/IRCprocessinventory.php" method="POST">
                <input type="hidden" name="control">

                Add row?

        <?php for ($pointer = 2 ; $pointer < $countColumnsGlobal ; ++$pointer) { ?>

                <input type="text" name="<?php echo $columns[$pointer];?>">

        <?php } ?>

                <input type="submit" value="submit">

        </form>

<?php
}

?>

Page 2:
<?php
require_once 'IRCinventoryconfig.php';

ini_set('display_errors',1);  error_reporting(E_ALL);
session_start();

if(isset($_SESSION['value'])) {
    $thisTable = $_SESSION['value'];

    $valuesArray = array();
    if (isset($_POST)) {
        $valuesArray = $_POST;
        }

    $columnsArray = array_keys($valuesArray);
    array_splice($columnsArray, 0, 1);

    $columnsString = implode(", ", $columnsArray);

    $insertValues = array();
    foreach($valuesArray as $values) {
        $insertValues[] = $values;
        }

    $valuesString = implode("','", $insertValues);
    $valuesString = "'".$valuesString."'";
    $valuesString = substr($valuesString, 3);

    $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
        if ($connection->connect_error) die($connection->connect_error);

    $queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
    $result      = $connection->query($queryInsert);

    if (!$result) echo "INSERT failed: $query
" .
        $connection->error . "

";
    else echo "Successful entry";

    $connection->close();

}
?>


text:
Q: How can I create a loop in my Graphviz flowchart? I am trying to create a flowchart with nodes in set positions. I am using invisible nodes to try and force the direction of edges. My diagram is below.
Its not quite right as I am wanting the lines coming out from node d , and around to the edge from c to d to be continuous (and straight).
How can I make it so that the lines all join? Thanks

My code to reproduce
digraph g1 {

  graph [splines=false];

  // invisible nodes
  node[fontsize=15, shape = box, width=3, height=0] ;
  i1 [ style="invis"];
  i2 [ style="invis"];
  i3 [ style="invis"];
  i4 [ style="invis"];

  node[fontsize=15, color = black, shape = box, width=3, height=1] ;
  a[color=blue, label="a"];
  b[color=green, label="b"];
  c[color=orange, label="c"];
  d[color=red, label="d"] ;

  {rank=same; a -> b -> c};

  {rankdir = TB;    c -> i1[arrowhead=none];
        i1 -> d[label="  FOR EACH\n\n"];
        d -> i2[arrowhead=none];
  };

  {rank=same; i3 -> i2[arrowhead=none] };

  {rankdir = TB;
    b -> i4[style="invis"];
    i4 -> i3[arrowhead=none];
  };

  {rank=same; i4 -> i1};

}

Following Paul's comment I tried using node[fontsize=15, shape = box, label="", width=0, height=0, fixedsize=true] which resulted in

A: Using shape = points and minlen comes to the rescue:
digraph g1 {

  graph [splines=false];

  // invisible nodes
  node[ shape = point, width=0, height=0] ;
  i1 [ style="invis"];
  i2 [ style="invis"];
  i3 [ style="invis"];
  i4 [ style="invis"];

  node[fontsize=15, color = black, shape = box, width=3, height=1] ;
  a[color=blue, label="a"];
  b[color=green, label="b"];
  c[color=orange, label="c"];
  d[color=red, label="d"] ;

  {rank=same; a -> b -> c};

  c -> i1[arrowhead=none];
  i1 -> d[label="  FOR EACH\n\n"];
  d -> i2[arrowhead=none];

  {rank=same; i3 -> i2[arrowhead=none, minlen = 7 ] };

  b -> i4[style="invis"];
  i4 -> i3[arrowhead=none];

  {rank=same; i4 -> i1};

}

yields


text:
Q: Hashtable key within integer interval I don't know if this is possible but i'm trying to make an Hashtable of  where Interval is a class with 2 integer / long values, a start and an end and i wanted to make something like this:
Hashtable<Interval, WhateverObject> test = new Hashtable<Interval, WhateverObject>();
test.put(new Interval(100, 200), new WhateverObject());
test.get(new Interval(150, 150)) // returns the new WhateverObject i created above because 150 is betwwen 100 and 200
test.get(new Interval(250, 250)) // doesn't find the value because there is no key that contains 250 in it's interval

So basically what i want is that a key between a range of values in an Interval object give the correspondent WhateverObject. I know i have to override equals() and hashcode() in the interval object, the main problem i think is to somehow have all the values between 100 and 200 (in this specific example) to give the same hash.
Any ideias if this is possible?
Thanks

A: You could use an IntervalTree. Here's one I made earlier.
public class IntervalTree<T extends IntervalTree.Interval> {
  // My intervals.

  private final List<T> intervals;
  // My center value. All my intervals contain this center.
  private final long center;
  // My interval range.
  private final long lBound;
  private final long uBound;
  // My left tree. All intervals that end below my center.
  private final IntervalTree<T> left;
  // My right tree. All intervals that start above my center.
  private final IntervalTree<T> right;

  public IntervalTree(List<T> intervals) {
    if (intervals == null) {
      throw new NullPointerException();
    }

    // Initially, my root contains all intervals.
    this.intervals = intervals;

    // Find my center.
    center = findCenter();

    /*
     * Builds lefts out of all intervals that end below my center.
     * Builds rights out of all intervals that start above my center.
     * What remains contains all the intervals that contain my center.
     */

    // Lefts contains all intervals that end below my center point.
    final List<T> lefts = new ArrayList<T>();
    // Rights contains all intervals that start above my center point.
    final List<T> rights = new ArrayList<T>();

    long uB = Long.MIN_VALUE;
    long lB = Long.MAX_VALUE;
    for (T i : intervals) {
      long start = i.getStart();
      long end = i.getEnd();
      if (end < center) {
        lefts.add(i);
      } else if (start > center) {
        rights.add(i);
      } else {
        // One of mine.
        lB = Math.min(lB, start);
        uB = Math.max(uB, end);
      }
    }

    // Remove all those not mine.
    intervals.removeAll(lefts);
    intervals.removeAll(rights);
    uBound = uB;
    lBound = lB;

    // Build the subtrees.
    left = lefts.size() > 0 ? new IntervalTree<T>(lefts) : null;
    right = rights.size() > 0 ? new IntervalTree<T>(rights) : null;

    // Build my ascending and descending arrays.
    /** @todo Build my ascending and descending arrays. */
  }

  /*
   * Returns a list of all intervals containing the point.
   */
  List<T> query(long point) {
    // Check my range.
    if (point >= lBound) {
      if (point <= uBound) {
        // In my range but remember, there may also be contributors from left or right.
        List<T> found = new ArrayList<T>();
        // Gather all intersecting ones.
        // Could be made faster (perhaps) by holding two sorted lists by start and end.
        for (T i : intervals) {
          if (i.getStart() <= point && point <= i.getEnd()) {
            found.add(i);
          }
        }

        // Gather others.
        if (point < center && left != null) {
          found.addAll(left.query(point));
        }
        if (point > center && right != null) {
          found.addAll(right.query(point));
        }

        return found;
      } else {
        // To right.
        return right != null ? right.query(point) : Collections.<T>emptyList();
      }
    } else {
      // To left.
      return left != null ? left.query(point) : Collections.<T>emptyList();
    }

  }

  private long findCenter() {
    //return average();
    return median();
  }

  protected long median() {
    // Choose the median of all centers. Could choose just ends etc or anything.
    long[] points = new long[intervals.size()];
    int x = 0;
    for (T i : intervals) {
      // Take the mid point.
      points[x++] = (i.getStart() + i.getEnd()) / 2;
    }
    Arrays.sort(points);
    return points[points.length / 2];
  }

  /*
   * What an interval looks like.
   */
  public interface Interval {

    public long getStart();

    public long getEnd();
  }

  /*
   * A simple implemementation of an interval.
   */
  public static class SimpleInterval implements Interval {

    private final long start;
    private final long end;

    public SimpleInterval(long start, long end) {
      this.start = start;
      this.end = end;
    }

    public long getStart() {
      return start;
    }

    public long getEnd() {
      return end;
    }

    @Override
    public String toString() {
      return "{" + start + "," + end + "}";
    }
  }

}

A: A naive HashTable is the wrong solution here.  Overriding the equals() method doesn't do you any good because the HashTable compares a key entry by the hash code first, NOT the equals() method.  The equals() method is only checked AFTER the hash code is matched.
It's easy to make a hash function on your interval object, but it's much more difficult to make one that would yield the same hashcode for all possible intervals that would be within another interval.  Overriding the get() method (such as here https://stackoverflow.com/a/11189075/1261844) for a HashTable completely negates the advantages of a HashTable, which is very fast lookup times.  At the point where you are scanning through each member of a HashTable, then you know you are using the HashTable incorrectly.
I'd say that Using java map for range searches and https://stackoverflow.com/a/11189080/1261844 are better solutions, but a HashTable is simply not the way to go about this.

A: No need to reinvent the wheel, use a NavigableMap. Example Code:
final NavigableMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(0, "Cry Baby");
map.put(6, "School Time");
map.put(16, "Got a car yet?");
map.put(21, "Tequila anyone?");
map.put(45, "Time to buy a corvette");

System.out.println(map.floorEntry(3).getValue());
System.out.println(map.floorEntry(10).getValue());
System.out.println(map.floorEntry(18).getValue());

Output:

Cry Baby
  School Time
  Got a car yet?

A: I think implementing a specialized get-method would be much easier.
The new method can be part of a map-wrapper-class.
The key-class: (interval is [lower;upper[ )
public class Interval {
    private int upper;
    private int lower;

    public Interval(int upper, int lower) {
        this.upper = upper;
        this.lower = lower;
    }

    public boolean contains(int i) {
        return i < upper && i >= lower;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Interval other = (Interval) obj;
        if (this.upper != other.upper) {
            return false;
        }
        if (this.lower != other.lower) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 61 * hash + this.upper;
        hash = 61 * hash + this.lower;
        return hash;
    }
}

The Map-class:
public class IntervalMap<T> extends HashMap<Interval, T> {

    public T get(int key) {
        for (Interval iv : keySet()) {
            if (iv.contains(key)) {
                return super.get(iv);
            }
        }
        return null;
    }
}

This is just an example and can surely be optimized, and there are a few flaws as well:
For Example if Intervals overlap, there's no garantee to know which Interval will be used for lookup and Intervals are not garanteed to not overlap!

A: OldCurmudgeon's solution works perfectly for me, but is very slow to initialise (took 20 mins for 70k entries).
If you know your incoming list of items is already ordered (ascending) and has only non overlapping intervals, you can make it initialise in milliseconds by adding and using the following constructor:
public IntervalTree(List<T> intervals, boolean constructorFlagToIndicateOrderedNonOverlappingIntervals) {
    if (intervals == null) throw new NullPointerException();

    int centerPoint = intervals.size() / 2;
    T centerInterval = intervals.get(centerPoint);
    this.intervals = new ArrayList<T>();
    this.intervals.add(centerInterval);
    this.uBound = centerInterval.getEnd();
    this.lBound = centerInterval.getStart();
    this.center = (this.uBound + this.lBound) / 2;
    List<T> toTheLeft = centerPoint < 1 ? Collections.<T>emptyList() : intervals.subList(0, centerPoint);
    this.left = toTheLeft.isEmpty() ? null : new IntervalTree<T>(toTheLeft, true);
    List<T> toTheRight = centerPoint >= intervals.size() ? Collections.<T>emptyList() : intervals.subList(centerPoint+1, intervals.size());
    this.right = toTheRight.isEmpty() ? null : new IntervalTree<T>(toTheRight, true);
}

A: This depends on your hashCode implementation. You may have two Objects with the same hashCode value.
Please use eclipse to generate a hashCode method for your class (no point to re-invent the wheel

A: For Hastable or HashMap to work as expected it's not only a equal hashcode, but also the equals method must return true. What you are requesting is that Interval(x, y).equals(Interval(m, n)) for m, n within x,y. As this must be true for any overlapping living instance of Interval, the class has to record all of them and needs to implement what you are trying to achieve, indeed.
So in short the answer is no.
The Google guava library is planning to offer a RangeSet and Map: guava RangeSet
For reasonable small ranges an easy approach would be to specialize HashMap by putting and getting the indivual values of the intervals.


text:
Q: URLs contain double slash in path for all links within the 'X people chatting' container I noticed the container that holds the 'X people chatting' content, <div class="s-sidebarwidget mb16 module"> contains links that all have a double slash // in the URL after the authority where the path begins.
Each of the chat room categories like HTML / CSS / WebDesign links show the double slash in the HTML (ie when you hover your mouse over the link) it shows chat.stackoverflow.com//rooms/29074. After clicking the link and navigating to the chat room the URL is updated and the // goes away so its chat.stackoverflow.com/rooms/29074/html-css-webdesign like expected.
When hovering any of the users links they also show the // in the HTML but after clicking a link in the container, the // persists in the URL and we end up with chat.stackoverflow.com//users/1140368. I understand from this question and the RFC spec that URLs with a // in the path after the authority are considered "valid" and servers might ignore it but browsers do not. I wasn't sure if this warranted a fix, but wanted to bring attention to it.


text:
Q: How to compare two values in generic method? I need to create generic method which returns greater of two params. Operators > and < don't work. Here is signature of my method:
public static T Greater<T>(ref T a, ref T b)
{
    if (a > b)
    {
       return a;
    }
    else
    {
       return b;
    }
}

I'm quite rookie in C# and totally new in generic types.

A: Since the T can be any type there is no guarantee that T will overload > or < operators. Adding a IComparable<T> constraint you are saying that T must implement IComparable<T> which contains a method named CompareTo, then you can use that method to compare your objects instead:
public static T Greater<T>(ref T a, ref T b) where T : IComparable<T>
{
    if(a.CompareTo(b) > 0) return a;
    else return b;
}


text:
Q: macro problems with loop if I have in cell "A1" any value like " my name " i have to separate tis value to many cells to be shown at cell "A2" (M) , cell"A3" (y), etc. . after that i have to look up for every cell value from cell "A2" to last cell which have last character on another range to get value which met this character .
the loop is done till separating cell "A1" value to many cells but only making lookup for cell "A2" only and not making loop for the next cells .
Sub Macro1() LENGHTH = Len(Range("A1")) CELL_START = ("2") WORD_LEN = 1

  Do While LENGHTH <> 0
    Range("A" & CELL_START).VALUE = mid(Range("A1"), WORD_LEN, 1)
    CELL_START = CELL_START + 1
    LENGHTH = LENGHTH - 1
    WORD_LEN = WORD_LEN + 1
  Loop

  If ActiveWorkbook.Sheets("SHEET1").Range("A2") <> "" Then
     ***Do While ("a2" & " LENGHTH") = ""
       Range("B2").VALUE = WorksheetFunction.VLookup(Range("A2"), Sheet1.Range("G3:H15"), 2, False)
     Loop***

  Else
  End If

End Sub

A: Here is the code for taking the "name" entered in A1 and spreading the letters across the cells to the right of the "name".  The code shown will allow you to list a bunch of names in column A, and the macro will spread the letters for all names listed.
Dim LENGHTH As Integer
Dim zWord As String

Sub Macro1()
    Range("A1").Select
    zWord = Range("A1").Value
    Do While zWord <> ""
        LENGHTH = Len(zWord)
        For i = 1 To LENGHTH
            ActiveCell.Offset(0, 1).Select
            ActiveCell.Value = Mid(zWord, i, 1)
        Next i
        ActiveCell.Offset(1, -LENGHTH).Select
        zWord = ActiveCell.Value
    Loop
End Sub

I'm not sure what you are trying to accomplish in the second section of the macro, but you may want to use "hlookup" rather than "vloopup".


text:
Q: Printing out double quote in Python have space print('"',*x,'"')

Gives out
" Hello world "

I desire
"Hello world"

What should I do?

A: print put spaces(' ') between each arguments. You can change that with sep= keyword argument, but then you can't have space for between x's elements. So you can add spaces manually.
x = ['Hello', 'world']

print(f'"{" ".join(x)}"')  # Python 3.6 or later only
print('"' + " ".join(x) + '"')
print('"{}"'.format(' '.join(x)))

output:
"Hello world"
"Hello world"
"Hello world"

A: You may try the sep parameter.
print('"', *x, '"', sep = '')


text:
Q: How to pass an arraylist from an innerclass to another class that has already been started? I am trying to retrieve an ArrayList from an async task. This async task is an inner class of another activity(OfflineBookingsFragment).
Calling the BackgroundTask2 from class TodaysBookingsActivity :-
OfflineBookingsFragment offlineBookingsFragment = new OfflineBookingsFragment();
            OfflineBookingsFragment.BackGroundTask2 backGroundTask2 = offlineBookingsFragment.new BackGroundTask2(getContext());
            backGroundTask2.execute();

To get the arraylist back to TodaysBookingsActivity I have made a method named setarraylist in class TodaysBookingsActivity:-
public void setarraylist(ArrayList<VendorBookingsSummary> SummaryArrayList) {
     summaryAdapter = new SummaryBookingsAdapter(getContext(), SummaryArrayList);
        bookinglv1.setAdapter(summaryAdapter);
        summaryAdapter.notifyDataSetChanged();
        }

The bookinglv is initialized in the class  TodaysBookingsActivity in onCreate. But it shows a null pointer exception in the method.
If we use an intent to send arraylist using Parcelable as:-
 Intent intent = new Intent(mContext, TodaysBookingsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("Birds", VendorBookingsSummaryArrayList);
                    intent.putExtras(bundle);
                    startActivity(intent);

This error is received.
java.lang.IllegalStateException: Fragment OfflineBookingsFragment{987d75c} not attached to Activity


text:
Q: Accepting a parameter either as individual object or as array of objects I have a bunch of functions that take in either an array of objects, or a single object designed to be treated as an array containing one object, and I am looking for a cleaner way to accomplish this. Basically, I want to know how I could make the unless part in the following function more concise:
def foo(bar_or_bars)
  unless bar_or_bars.is_a?(Array)
    bar_or_bars = [bar_or_bars]
  end
  bar_or_bars.each { |baz| ... }
end

Any help will be appreciated! Thanks.

A: The simplest solution is to use Kernel method Array:
Array(5) #=> [5]
Array([1, 2, 3]) #=> [1,2,3]

so
def foo(bar_or_bars)
  Array(bar_or_bars).each { |bar| ... }

This will even work on nested arrays that have arrays as elements (they wont be flattened out).
One case this won't work for is Hashes:
Array(a: 1, b: 2) #=> [[:a, 1], [:b, 2]]

If you want to iterate through unchanged Hash objects, best use Array.wrap from ActiveSupport.

A: I am currently using this:
bars = [bar_or_bars].flatten

A: First thing you could do is to write the unless logic in a single line:
bars = bar_or_bars.is_a?(Array) ? bar_or_bars : [bar_or_bars]

As you see, I give it a new name here, as it's no longer a bar or bars, it's now definitely a collection.
The problem with this and your original approach is that although your function could work on any Enumerable, you will force your users to give you an argument of a specific type, which breaks duck typing.
A neat trick to partially solve that issue is the following:
def foo(bar_or_bars)
  bars = [*bar_or_bars]
  bars.each { |baz| ... }
end

I wouldn't exactly call that readable, though. It actually smells a lot like bad API design. Probably you should better take multiple arguments like this:
def foo(*bars)
  bars.each { |baz| ... }
end

And let the caller decide whether he wants to pass a single object or an array:
foo("XYZ")
ary = ["abc", "def"]
foo(*ary)


text:
Q: Alluding to already Narrated Past Simple events in Past Perfect Please, read the following quote:

I finally finished tidying about 3 a.m. (after I moved the furniture) and a few minutes later I
  was fast asleep. I woke up suddenly at 8 a.m.  I had arranged to meet my parents at the airport at 8.30 a.m. but I hadn't set the alarm!

If moving the furniture which was already narrated in the story was one of the causes of the current distressing state, can I still refer to it using the past perfect tense? i.e something like "I hadn't set the alarm and had moved the furniture"? or it is a choice because it's already mentioned in the story in clear order?
This was a comment on my previous post "Reference Time, Coordinating Conjunctions and Past Simple/Perfect Tense" which was answered gratefully by @StoneyB, but it is a different question.

A: If you feel a need to bring up the furniture-moving at the 8 am RT, yeah, ya gotta use a past perfect if you're going to use a tensed verb:

I finally finished tidying about 3 a.m., and a few minutes later I was fast asleep. I woke up suddenly at 8 a.m. I had arranged to meet my parents at the airport at 8.30 a.m. but I'd moved all the furniture and tired myself out, so I hadn't set the alarm.

But FumbleFingers' Perfect Truism tells us "Don't use the past perfect unless you have to" There are better ways of skinning this cat—participles and gerunds, for instance:

I finally finished tidying about 3 a.m., and a few minutes later I was fast asleep. I woke up suddenly at 8 a.m. I had arranged to meet my parents at the airport at 8.30 a.m., but tired out from moving all the furniture, I hadn't set the alarm—and now I was late.

A:
I finally finished tidying about 3 a.m. (after I moved the furniture)
  and a few minutes later I was fast asleep. I woke up suddenly at 8
  a.m. I had arranged to meet my parents at the airport at 8.30 a.m. but
  I hadn't set the alarm!

There is really nothing wrong with the quote. I would prefer "had moved the furniture", but "moved" is fine, too. In an anecdote, generally, the rules are more relaxed. StoneyB's examples are much clearer, but they really change the tone.


text:
Q: XPath predicate must be preceded by node test I have read all I could find but just wanted to confirm that the following is NOT a valid XPath expression because of the reason mentioned in the title.
//trip/[@trainID]

I already found that the expression
//trip[@trainID]

Selects all trip elements with the attribute called trainID,
and that the expression
//trip/@trainID

Selects all trainID attributes on trip elements.
I also had referred to this answer.

Reason for the Question:
I knew that the part in brackets (i.e. predicate) creates a filter.
  I thought perhaps the expression in question would function like in the third expression above in the absence of any test on the attribute. But it did not work in my test and it was confirmed below the expression is simply not valid.

A: No, //trip/[@trainID] is not a valid XPath.
Like you said in the title, a predicate must be proceeded by a node test.
From the 1.0 spec:

[4]       Step       ::=      AxisSpecifier NodeTest Predicate*
                             | AbbreviatedStep

With NodeTest defined as:

[7]       NodeTest       ::=      NameTest
                                 | NodeType '(' ')'
                                 | 'processing-instruction' '(' Literal ')'


text:
Q: Sign Of Derivatives and Local Extremum Consider a differentiable function $f(x)$ on the interval $[a, b]$, such that it has no local Extremum on this interval then prove that $f(x)$ is monotonic on the interval $[a, b]$.
$$$$If $f'(x)$ is entirely non-negative or non-positive then we are done and if not then there exists $$a \leq c < d \leq b$$ such that $f'(c)$ and $f'(d)$ are of opposite signs. Now if $f'(x)$ takes the value $0$ at a finite number of points in $[c, d]$ say at $x_1, x_2, .... x_n$ then divide the interval $[c, d]$ into $$[c, x_1]; [x_1, x_2]; ..... ; [x_{n-1}, x_n]; [x_n, b]$$. Now consider any arbitrary subinterval say $[x_k, x_{k+1}]$ then in the open interval $(x_k, x_{k+1})$ $f'(x)$ is entirely positive or negative as derivatives have the intermediate value property. And hence there is a point $x_{k_0}$ passing through which $f'(x)$ must change it's sign because if it would have not changed its sign passing through any of the $x_k$ then $f'(c)$ and $f'(d)$ would have same sign. And hence there is a local Extremum at some point in $[a, b]$ which contradicts the given hypothesis, and hence $f'(x)$ is either entirely non-negative or non-positive.
$$$$I want to know that is the Theorem Correct even when $f'(x)$ takes the value $0$ at infinite number of points or is there a counterexample.


text:
Q: how to add identity user from another project in .net I have .net web api project which uses identity to store users. I have another admin web application project seperate from api. My question is how can I add users from my admin project. Probably I need to add user with UserManager instead of adding user via Entity Framework. But how to do that? How can I use another project's UserManager from my admin web project? or what is proper way to add user from another project?

A: You may try adding your first project to other like multi layer project. If i were you, i would create a new layer and add it to my second project. Also i suggest  you can check identity framework.


text:
Q: Django FileField Model that doesn't upload but returns path of the file I am using Django to build an app where I ask the user to choose some files from his/her computer and the app will process them and write an output file in the same directory.
If I use the FileField model in Django, it uploads the file to the MEDIA_ROOT directory. That's not what I want. I would like the file to remain where it is and I need the path to the file where it is instead. I have been looking at the FileField code:
https://docs.djangoproject.com/en/1.11/_modules/django/db/models/fields/files/#FieldFile
Does anyone know of a hack around this where the upload_to is disabled and the storage method that is being used returns the path instead? From what I could make out, the storage method reads the file and writes it into the upload_to directory. The FileField class uses the FieldFile class and the FileDescriptor class. Does anyone know which method actually performs the read and therefore has the actual path of the file? Been trying to read the code but I am not at an advanced stage yet and I can't understand all of it.
Thanks in advance.


text:
Q: Admob native advance Ads repeating in recycler view I ran this(Google Codelab Native Ads) code and the native ads in the list are sometimes working fine but most of the time they are like the bottom two screenshots.
They are not in order and repeating themselves.
Can anyone please check whats wrong in this demo code?
Tried on different devices but no luck :(

Screenshot1.

Screenshot2

A: Only two things in your RecyclerView adapter
  @Override
    public long getItemId(int position) {
    return position;
  }

and in constructor of adapter

 setHasStableIds(true);

I tried this on same demo and git it working correctly.


text:
Q: Solving a scalar equation using matrix algebra I need to solve the following equation to find $x$ in $\mathbf{x}^T=[1,-x]$
$$(E[\mathbf{x^TAZ}])^2= \alpha^2Var[\mathbf{x^TAZ}]$$
where $\mathbf{Z} \sim N(\mathbf{m},\mathbf{\Sigma})$ is a vector of independent normal random variables, i.e $\mathbf{\Sigma}$ is a diagonal matrix.
One way of doing this is to express everything as scalars and to solve a quadratic qaution, but is there a way to do it with vector algebra? Maybe using a Moore-Penrose inverse? I only got to
$$(\mathbf{x^TA}E[\mathbf{Z}])^2= \alpha^2\mathbf{x^TA \Sigma A^Tx}$$
or by setting $\mathbf{x^TA} = \mathbf{c^T}$
$$(\mathbf{c}^T \mathbf{m})^2= \alpha^2 \mathbf{c}^T \mathbf{\Sigma c}$$
and not sure how to proceed from here (if it is even possible to do so).


text:
Q: Create a Border with Different Edges / Sides
How to create a Border with different edges. Do not have to be the exact the same. Just want to know how to set four different styles to border.

A: I don't think there is a way to control border style of each side. You can however put 4 borders on top of each other (or within each other) each having corresponding side with desired style and other sides with width 0

A: You cant do it with border but you can create a content control with same style some thing like.
<Style x:Key="DiffBorderStyle" TargetType="{x:Type ContentControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ContentControl}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Rectangle
                        Fill="Black" Width="1"
                        Grid.RowSpan="3"/>

                        <Rectangle
                        Fill="Blue" Width="1"
                        Grid.Column="2"
                        Grid.RowSpan="3"/>

                        <Rectangle
                        Fill="Red" Height="1"
                        Grid.ColumnSpan="3"/>

                        <Rectangle
                        Fill="Black"  Height="1"
                        Grid.Row="2"
                        Grid.ColumnSpan="3"/>

                        <ContentPresenter Grid.Column="1" Grid.Row="1"/>
                    </Grid>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

You can stylized each rectangle in style and also you can use Line in place of rectangle.
Hope it helps..


text:
Q: Can I create an index on User-defined Table variables? Just wanted to check, if we will be able to create indexes on User-defined Table variables.  I know that we can create PK on an UDT.  Does it imply that PK creates an (clustered) index internally?  If an index is possible on a column on UDT, where does the indexed data get stored?

A: To define an index on a table variable use a primary key or unique constraint. You can nominate one as clustered.

*

*If you need an index on a non-unique field, simply add the unique key to the end of the index column list, to make it unique.

*If the table variable has not got a unique field, add a dummy unique field using an identity column.
Something like this:
declare @t table (
    dummy identity primary key nonclustered,
    val1 nvarchar(50),
    val2 nvarchar(50),
    unique clustered (val1, dummy)
)

Now you have a table variable with a clustered index on non-unique field val1.

A: With table variables, you can define primary key and unique constraints, but you are unable to define
any clustering behaviour. The indexes for these are stored alongside the actual data in the table variable - hopefully in memory within tempdb, but if necessary, spilled to disk, if memory pressure is high.
You're unable to define arbitrary indexes on such tables.

A: You can however define whatever indexes you want on temp tables.


text:
Q: Can I use cmder for Git Bash and other command line functions like dotnet, ng, etc at the same time? I use cmder for dotnet and ng commands and for Git operations I use Git Bash command line. I think it it also possible to use cmder for Git operations on another tab. Is it possible to use the same cmder window with 4 tabs and run these 4 commands at the same time?
git checkout development

dotnet build

ng serve --port 4200

ipconfig
... (other command line operations)

I look at Combine Git Bash and opening in current folder in CMDER but I am not sure if it let me use these commands at the same time.

A: Short answer : Yes.

Cmder comes pre-packed with git-bash, which in turn brings with it a lot of unix programs in the form of mingw. Cmder allows you to use in the same terminal session all your windows command line tools + the ones from Mingw. It even allows you to get powerful command line editing features through clink.
Also, you do not install cmder (at least the default way) you just grab the archive you want to work with, unarchive it, then run it. Your PATH will stay safe and only you can make the decision to either add it to your path or not.


text:
Q: Search bar built using React that queries Firebase Relatively new to React and attempting to incorporate a search bar that queries a 'businesses' node in my Firebase database. Could use some guidance/input on the flow of my components.
My initial instinct told me it should go something like 'router > SearchBarLogic > SearchBar > BusinessIndexLogic > BusinessIndex' with a term being passed down from my SearchBar to my BusinessIndexLogic for aid in generating my query.
Going to paste the relevant code from the components I mentioned above below. Any insight would be much appreciated.
router.js
const router = (
  <Router history={browserHistory} >
    <Route path='/' component={App} >
       <IndexRoute component={HomeLogic} />
       <Route path='businesses' >
         <IndexRoute component={SearchBarLogic} />
         <Route path='addbusiness' component={AddBusinessFormLogic} />
         <Route path=':id' >
           <IndexRoute component={BusinessesProfileLogic} />
           <Route path='deletebusiness' component={DeleteBusinessPageLogic} />
         </Route>
       </Route>
   </Router>
);

SearchBarLogic.js
import React, {Component} from 'react';
import SearchBar from '../layouts/SearchBar';

class SearchBarLogic extends Component {
  constructor(props){
    super(props);
    this.state = {
      term: "",
    };
  }

  search(term) {
    this.setState({ term });
  }

  render(){
    let term = this.state.term

    return (

        <SearchBar
          term={term}
          onSearchTermChange={(term) => {this.search(term)}}
        />

    )
  }
}

export default SearchBarLogic;

SearchBar.js
import React, {Component} from 'react';
import BusinessIndexLogic from '../logic/businesses/BusinessIndexLogic';

class SearchBar extends Component {
  render(){
  return (

        <form>

            <input
              id="search"
              type="search"
              value={this.props.term}
              onChange={(event) => {this.props.onSearchTermChange(event.target.value)}}
            />

        </form>

        <BusinessIndexLogic
          value={this.props.term}
        />

  );
  }
}

export default SearchBar;

BusinessIndexLogic.js
import React, { Component } from 'react';
import { BusinessStorage } from '../../../config/FirebaseConstants';
import BusinessIndex from '../../pages/businesses/BusinessIndex';

class BusinessIndexLogic extends Component {
  constructor(props){
    super(props);
    this.state = {
      allBusinesses: [],
    }
  }

  componentDidMount() {
    let _this = this;
    let businesses = {};

    if (this.props.value === ""){
      BusinessStorage.ref('users/').once('value', function(allData) {
        allData.forEach(function(data) {
          data.forEach(function(userNode) {
            if (userNode.val().type === 'businesses') {
              if (userNode.val().deletedAt !== true) {
                let companyName = userNode.val().companyName;
                let idNumber = data.key;
                businesses[companyName] = {name: companyName, id: idNumber}
              }
            }
          })
        })
      }).then(function(user) {
        let keys = Object.keys(businesses).sort();
        let sortedHash = {};
        let sortedArray = [];

        for (let i = 0; i < keys.length; i++) {
          let key = keys[i];
          sortedArray.push(sortedHash[key] = businesses[key]);
        }

        _this.setState({allBusinesses: sortedArray}, function afterBusinessSet() {

        });
      })
  } else {
    BusinessStorage.ref('users/').startAt(`${this.props.value}`).once('value', function(allData) {
      allData.forEach(function(data) {
        data.forEach(function(userNode) {
          if (userNode.val().type === 'business') {
            if (userNode.val().deletedAt !== true) {
              let companyName = userNode.val().companyName;
              let idNumber = data.key;
              businesses[companyName] = {name: companyName, id: idNumber}
            }
          }
        })
      })
    }).then(function(user) {
      let keys = Object.keys(businesses).sort();
      let sortedHash = {};
      let sortedArray = [];

      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        sortedArray.push(sortedHash[key] = businesses[key]);
  }

      _this.setState({allBusinesses: sortedArray}, function afterBusinessSet() {

      });
    })
  }
  }

  render() {
    let allBusinesses = this.state.allBusinesses;
    let pathName = this.props.location.pathname;

    return (
      <BusinessIndex
        allBusinesses={allBusinesses}
        pathName={pathName}
      />
    )
  }
}

export default BusinessIndexLogic;

And the error I'm currently getting in my console is Uncaught TypeError: Cannot read property '_currentElement' of null which isn't helping much. Like I said, any insight or suggestions would be appreciated. Thanks.

A: According to this, that error means that your code is throwing a different error that's preventing your components from rendering. Is there an error above that one in the console? If not, add some error handling with console.logs. It's probably something in your Promise chain (Firebase call); add .catch(err => console.log(err)) to the end of the chain, but in general do some error handling throughout.


text:
Q: Designer error: frameworkName cannot be an empty string I am trying to make a imageview but when running I find this problemme (Error:. (7, 17) Resource id can not Be an empty string (at 'id' with value '@ + id /')) in this line: android: id = "@ + id /">

A: *

*There are whitespaces which are not allowed! Not sure if its just a copy and paste error. Here with underscroe to show you the white spaces.
android: id = "@_+id/"

*you dont define any id. you have to add an name after @+id/ like:
android:id="@+id/my_id"


text:
Q: Testing memory limit of Python in Windows I was trying to probe the Python 32bit memory limit. So I wrote the little program
a=[]
while 1:
    a.append(chr(65))

and watched the Windows task manager for the memory consumption of python.exe.
Firstly, I was surprised that it is occationally reduced (almost halved sometimes). Second, the amount only goes up to about 500MB (I believe on another 64bit machine it rose endlessly).
The computer has 4GB memory, windows boot>3GB is supposingly active and I patched the python.exe with imagecfg.exe -l. No other relevant processes are running and total memory does not exceed 40%. I believe the very same procedure worked on another computer though.
Any suggestions how I can check if my python can go up to 3GB now?


text:
Q: Jordan-Schönflies Curve Theorem - Multiple Curves Jordan-Schönflies Curve Theorem states:

For any simple closed curve in the plane, there is a homeomorphism of the plane which takes that curve into the standard circle.

Question: Is there a similar theorem for finitely many non-intersecting simple closed curves?
For example, given two non-intersecting simple closed curves, is there a homeomorphism of the plane which takes the curves into two non-intersecting circles? There could be two cases:

*

*One circle lies inside another circle;

*No circle is contained in another circle.

I am trying to prove that if $U$ is a bounded open set whose topology boundary is a union $B$ of ranges of multiple non-intersecting simple closed curves, then $\overline{U}$ is a manifold with boundary whose manifold boundary is exactly $B$.


text:
Q: RichEdit not respecting PlainText with pasted content I create a new application, drop on a TRichedit and set the PlainText property to true. I then run the application and paste some rich formatted text into the RichEdit.
I would expect it to display as plain text however it shows the content with the formatting.
Anyone know how to use a TRichedit just as plain text (and not using a memo :))

A: You'll need to do the paste manually ensuring that the formatting is ignored.
if Clipboard.HasFormat(CF_TEXT) then
  RichEdit.SelText := Clipboard.AsText;

Run this code from a message handler for WM_PASTE.
I currently do not know how to intercept the CTRL+V keypress and replace it with this code. The WM_PASTE message is not sent to rich edit controls.

As Cody suggests in the comment, one solution is as follows:

*

*Make sure that all the text in the edit control is marked as protected.

*Subclass TRichEdit and override CNNotify.

*Handle the EN_PROTECTED message, and if msg=WM_PASTE then use the paste as text code above and return 1 from the message handler to indicate that the requested operation (a rich paste) is rejected.


text:
Q: DropWizard Serving Assets help needed Help! I've been trying for hours, googling anything I could think of. I have a problem, that I would like to show my static content instead of my application on my site.
I modified a simple hello-world application:
public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");
    new HelloWorldApplication().run(args);
}

@Override
public String getName() {
    return "hello-world";
}

@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
    bootstrap.addBundle(new AssetsBundle("/assets/*", "/"));
}

@Override
public void run(HelloWorldConfiguration configuration, Environment environment) {
    final HelloWorldResource resource = new HelloWorldResource(
            configuration.getTemplate(),
            configuration.getDefaultName()
        );
    final AddResource addResource = new AddResource();
    final DeleteResource deleteResource = new DeleteResource();
    final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);
    environment.jersey().register(resource);
    environment.jersey().register(addResource);
    environment.jersey().register(deleteResource);
}

Here's my hello-world.yml:
server:
  type: simple
  applicationContextPath: /application/hello-world

template: Hello, %s!
defaultName: Stranger

I applied everything, what the DropWizard docs (http://dropwizard.readthedocs.org/en/latest/manual/core.html#serving-assets) said. But I just cannot manage to reach the index.html

A: I have not seen an actual example that proves that the documented way actually works.
And when looking in the Dropwizard source, I conclude that this is in fact not possible: the Jetty application context is set by the configuration parameter applicationContextPath in SimpleServerFactory:103:
environment.getApplicationContext().setContextPath(applicationContextPath);

And after that, the AssetBundles are registered into this applicationContext upon run() (AssetBundle:109):
environment.servlets().addServlet(assetsName, createServlet()).addMapping(uriPath + '*');

So, assetbundles are always served within the applicationContextPath that is set in the application's YAML file, so serving them outside this applicationContextPath is not possible (despite the docs saying so)
A better way to get this working, is to configure the application to use the / path:
applicationContextPath: /

And then, in your application's code, in the bootstrap() and run() methods, explicitly override the path for Jersey resources and add AssetBundles to your liking:
bootstrap.addBundle(new AssetsBundle("/static", "/"));

environment.jersey().setUrlPattern("/application/*");

A: I got it working by using the default constructor for the AssetsBundle() class.
With the default constructor your resources will gets looked up in a directory on the java classpath e.g.
/src/main/resources/assets/

and your have to name your applicationContextPath only /application
Point your browser to the folling location for static content
localhost:8080/application/assets/index.htm

A: For Dropwizard 0.8.0 and newer this is achieved from this configuration:
applicationContextPath: /
rootPath: /application

Where applicationContextPath is Jetty's Context path, and rootPath is Jersey's.

A: As Geert mentioned, the asset bundle needs to be served from within the applicationContextPath.  However, if you add the AssetsBundle in the bootstrap method, and set the contextPath from the run method, the AssetServlet gets added after the contextPath is set.
My fix is to avoid using the AssetsBundle and add the AssetsServlet directly in the run method (after contextPath is set):
environment.getApplicationContext().setContextPath("/");
environment.servlets().addServlet("assets", new AssetServlet("/assets", "/", "index.html", StandardCharsets.UTF_8)).addMapping("/*");


text:
Q: hosting multiple websites on multiple servers with a single outside IP address I have a single outside, static IP address. I have a domain registered (abc123xyz.com) that points to this IP address. I would like to be able to set up multiple servers (Microsoft and Linux) on the inside of my network that are available as subdomains. For example, if someone browses to s1.abc123xyz.com, they'll go to a website that is hosted on my internal server1. s2.abc123xyz.com will go to a website hosted on server2, and so on. I'm not talking about virtual hosts because virtual hosts are on a single server. I'm talking about sites on separate servers.
I'd like to forward web traffic to a single inside IP and then control the redirection from that device. Is this what a (reverse) proxy server would be used for?

A: Exactly. You need one http endpoint that takes the requests and then forwards the requests to the appropiate server on the inside. This is the very definition of a reverse proxy.
Note that this means you need to introduce either specialized hardware (i.e. a more capable router or firewall appliance), OR you use one of your backend computers. Instead of having
Reverse proxy -> server W and L
you could have
Server W -> forwarding specific domains to Server L


text:
Q: Select ID based on row Number This is my table
|  | Id                                 |
|1 |07A83EA7-6E00-4265-906C-FF187FE18EB3|
|2 |B6C10F47-7DEE-4D2B-AA3D-FF27B8FC105C|
|3 |10F56030-0803-4133-B57B-FF3F941A0D60|

Is it possible to select the Id based off of the row number?
I've tried:
SELECT [Id],ROW_NUMBER() OVER(Order by Id ASC) AS RowLol, Id

But that isn't really functional for what i have intended as it generates a temporary field.
Desired functionality:
being able to iterate through all entries, and use that as a parameter for my UPDATE in the loop
--DECLARE @json NVARCHAR(MAX) = (SELECT Data FROM ProcessEventMessages WHERE Id='AEF11F7B-06C1-4C40-9806-0004CAC6A042')
-- This will only work for ONE instance. Hence why i need an iterative ID, to pass along here^

SELECT * FROM OPENJSON(@json)
WITH (
    message varchar(200) '$.message',
    machineId varchar(200) '$.machineId',
    machineName int '$.machineName',
    ipAddress varchar(200) '$.ipAddress',
    LocalTime datetime2(7) '$.time'
 )  AS ChangeTime;

--loop on id
DECLARE @loopCounter INT = 0;

WHILE @loopCounter < (SELECT count(Id) FROM ProcessEventMessages)
BEGIN
PRINT 'changing values...';

UPDATE ProcessEventMessages SET Data = JSON_MODIFY(@json,'$.time', FORMAT(DATEADD(hour,-2,JSON_VALUE(@json,'$.time')),'yyyy-MM-ddTHH:mm:ss.fff')) WHERE ROWNUMBER = @loopCounter)
SET @loopCounter = @loopCounter + 1;
END;

PRINT 'done';
GO

Suggestion:
DECLARE @json NVARCHAR(MAX)
DECLARE @loopCounter INT = 0;
WHILE @loopCounter < (SELECT count(Id) FROM ProcessEventMessages)
BEGIN
    PRINT 'Changing...';
SELECT * FROM OPENJSON(@json)
WITH (
    message varchar(200) '$.message',
    machineId varchar(200) '$.machineId',
    machineName int '$.machineName',
    ipAddress varchar(200) '$.ipAddress',
    LocalTime datetime2(7) '$.time'
 )  AS ChangeTime;

   ;WITH CTE AS(
    SELECT *,ROW_NUMBER() OVER(Order by Id ASC) AS RowNo
    FROM ProcessEventMessages
    )
    UPDATE CTE

    SET Data = JSON_MODIFY(@json,'$.time', FORMAT(DATEADD(hour,-2,JSON_VALUE(@json,'$.time')),'yyyy-MM-ddTHH:mm:ss.fff'))
    WHERE RowNo = @loopCounter

   SET @loopCounter = @loopCounter + 1;
END;

PRINT 'Done';
GO

Attempt that crashed:
DECLARE @loopCounter INT = 0;

WHILE @loopCounter < (SELECT count(Id) FROM ProcessEventMessages)
BEGIN
    PRINT 'Changing...';
    DECLARE @json NVARCHAR(MAX) = (SELECT Data FROM ProcessEventMessages WHERE RowNo = @loopCounter) -- RowNo isn't declared here. Where would i move it?
    SELECT * FROM OPENJSON(@json)
    WITH (
        message varchar(200) '$.message',
        machineId varchar(200) '$.machineId',
        machineName int '$.machineName',
        ipAddress varchar(200) '$.ipAddress',
        LocalTime datetime2(7) '$.time'
     )  AS ChangeTime;

   ;WITH CTE AS(
    SELECT *,ROW_NUMBER() OVER(Order by Id ASC) AS RowNo
    FROM ProcessEventMessages
    )
    UPDATE CTE

    SET Data = JSON_MODIFY(@json,'$.time', FORMAT(DATEADD(hour,-2,JSON_VALUE(@json,'$.time')),'yyyy-MM-ddTHH:mm:ss.fff'))
    WHERE RowNo = @loopCounter
    SET @loopCounter = @loopCounter + 1;
END;

PRINT 'Done';
GO

Example:
DECLARE @RowNrr int = (SELECT *,ROW_NUMBER() OVER(Order by Id ASC) AS RowNrr FROM ProcessEventMessages)
SET @json = (SELECT Data FROM ProcessEventMessages WHERE @RowNrr = @loopCounter)
...
and then
...

;WITH CTE AS(
    SELECT @RowNrr
)

but it doesn't work :/

A: Assuming that you are using sql server as dbms, now if I understood your requirement correctly then you may looking for CTE,
;WITH CTE AS(
   SELECT [Id],
          ROW_NUMBER() OVER(Order by Id ASC) AS RowNo
   FROM TableName
)
SELECT ID
FROM CTE
WHERE RowNo IN(1,2,3)

UPDATED
If you try to integrate your update command with cte form, then this may be looks like this.
;WITH CTE AS(
    SELECT *,ROW_NUMBER() OVER(Order by Id ASC) AS RowNo
    FROM ProcessEventMessages
)
UPDATE CTE
SET Data = JSON_MODIFY(@json,'$.time', FORMAT(DATEADD(hour,-2,JSON_VALUE(@json,'$.time')),'yyyy-MM-ddTHH:mm:ss.fff'))
WHERE RowNo = @loopCounter

Note : I am not sure that row number on id will be consistent. since if new ID get inserted then there may be chance of change in row numbers.

A: select foo.*
from (
select ROW_NUMBER() OVER () as rownum, * from mytable ) as foo
where rownum=5


text:
Q: findig and storing the video file path in iphone I am trying to find the video file path and get store that path into my sqlite  I getting video from the photo lib For that use the code like that
-(IBAction)showVideoLibraryPicker
{
    picker.delegate = self;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        picker.mediaTypes = [NSArray arrayWithObjects:(NSString *) kUTTypeMovie, nil];
        [self presentModalViewController:picker animated:YES];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Error" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

}

And for taking video i use this code
- (IBAction)showVideoPicker {

    //picker = [[UIImagePickerController alloc] init];
    //
    //  picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //  picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    //  picker.delegate = self; picker.editing = NO; [self presentModalViewController:picker animated:YES];

    //picker = [[[UIImagePickerController alloc] init] autorelease];
    picker.delegate = self;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes = [NSArray arrayWithObject:(id)kUTTypeMovie];
        [self presentModalViewController:picker animated:YES];
        //[picker setCameraOverlayView:cameraOverlay];
        //      picker.navigationBarHidden = YES;
        //      picker.toolbarHidden = YES;
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Camera is not available" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

    // [self presentModalViewController:picker animated:YES];
}

I am confused how can get the path for storing that video path  into sqlite  .
I find the photo path but didn't get the video path .
For finding the photo path I use the code like this
NSData *imageData = UIImagePNGRepresentation(self.imageView.image);
NSData *myImage=[[NSData alloc]initWithData:imageData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"%@",documentsDirectory);

NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",camtitle.text]];
[myImage writeToFile:fullPathToFile atomically:YES];
NSLog(@"%@",fullPathToFile);
[myImage release];

How can I do for the video also .I need help to solve it out problem
Thanks in advance

A: Pl. go thru this doc.
Importantly, Implementing a Delegate for the Camera Interface , Listing 2 in that link.
Read the video file data from the obtained path and store that to documents folder.


text:
Q: How to disable dot replacement in bash? I want to run MySQL query from bash script to create new user:
mysql -u root -p$dbpass -e "GRANT ALL PRIVILEGES ON appdb_${BUILD}.* TO appuser@localhost IDENTIFIED BY 'somepass'"

Where $BUILD variable is set to a number, for example 15, so final query should look like this:
mysql -u root -p$dbpass -e "GRANT ALL PRIVILEGES ON appdb_15.* TO appuser@localhost IDENTIFIED BY 'somepass'"

But... in directory where script is and is run there is a tar archive with same name as database, so query becomes like this:
mysql -u root -p$dbpass -e "GRANT ALL PRIVILEGES ON appdb_15.tar.gz TO appuser@localhost IDENTIFIED BY 'somepass'"

I guess this happens because there is a match, but changing file name is not an option. Moving script to other directory is not allowed too.
I tried to escape dot with backslashes (appdb_${BUILD}\.*) - nothing changed.
How I can fix this?

A: There is nothing wrong with your approach and it is working in my case. See below. Can you tell us what is the error that you are getting so that we can help you?
[root@cloud mysql]# ls
appdb_15.tar.gz  test.sh

[root@cloud mysql]# cat test.sh
#!/bin/bash

BUILD=15
# First Method
mysql -u root -ptest -e "GRANT ALL PRIVILEGES ON appdb_${BUILD}.* TO appuser@localhost IDENTIFIED BY 'somepass';"

# Second Method
mysql -u root -ptest <<EOF
GRANT ALL PRIVILEGES ON appdb_${BUILD}.* TO appuser1@localhost IDENTIFIED BY 'somepass';
select user, host from mysql.user where user like 'appuser%';
EOF

[root@cloud mysql]# ./test.sh
user    host
appuser localhost
appuser1        localhost

EDIT 1:
 I forgot to mention that this is definitely not a bash issue.
EDIT 2: Changed the build variable to 15 from 5.


text:
Q: Persistence of variables in a service using Perspective Broker in Python Twisted? I'm having a problem using the Perspective Broker feature of Twisted Python. The structure of my code is like this:
class DBService(service.Service):
    def databaseOperation(self, input):
        # insert input into DB

class PerspectiveRoot(pb.Root):
    def __init__(self, service):
        self.service = service

    def remote_databaseOperation(self, input):
        return self.service.databaseOperation(input)

db_service = DBService()
pb_factory = pb.PBServerFactory(PerspectiveRoot(db_service))

I hook up the factory to a TCP server and then multiple clients connect, who are able to insert records into the database via the remote_databaseOperation function.
This works fine until the number of requests gets big, then I end up with duplicate inputs and missing inputs. I assume this is because DBService's 'input' variable persists and gets overwritten during simultaneous requests. Is this correct? And, if so, what's the best way to rewrite my code so it can deal with simultaneous requests?
My first thought is to have DBService maintain a list of DB additions and loop through it, while clients are able to append to the list. Is this the most 'Twisted' way to do it?
Alternatively, is there a separate pb.Root instance for every client? In which case, I could move the database operation into there since its variables won't get overwritten.


text:
Q: Angular/Breeze: Hanging on save - how to troubleshoot? Since a couple of days, I'm struggling with this problem. When I try to save changes (very small change, only one property changed) it got stuck. In Chrome, when I hit break, I got following call stack:
(anonymous function) (breeze.debug.js:8113)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:168)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:175)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187)
__toJSONSafe (breeze.debug.js:187) (anonymous function) (breeze.debug.js:13975) unwrapInstance (breeze.debug.js:13963) (anonymous function) (breeze.debug.js:15394) ctor._prepareSaveBundle (breeze.debug.js:15393) breeze.AbstractDataServiceAdapter.ctor.saveChanges (breeze.debug.js:14704) proto.saveChanges (breeze.debug.js:12793) SaveQueuing.innerSaveChanges (breeze.savequeuing.js:98) saveChangesWithQueuing (breeze.savequeuing.js:81)
_saveEntity (commonContext.js:220)
_save (commonContext.js:295) (anonymous function) (angular.js:10294) isolateScope.(anonymous function) (angular.js:6243) (anonymous function) (angular.js:10294) (anonymous function) (angular.js:18229) Scope.$eval (angular.js:12075) Scope.$apply (angular.js:12173) (anonymous function) (angular.js:18228) jQuery.event.dispatch (jquery-2.0.3.js:4676) elemData.handle (jquery-2.0.3.js:4360)

How do I troubleshoot this kind of problem? What could possibly be the problem?
This page has quite a lot of bindings. Did I hit the limit of Angular binding? What's the limit?
UPDATE:
When I keep hitting break button, I often see it stopped at line 8113 of breeze.debug.js, where it throws new error.
proto.addProperty = function (dataProperty) {
    assertParam(dataProperty, "dataProperty").isInstanceOf(DataProperty).check();
    if (this.metadataStore && ! dataProperty.isUnmapped) {
        throw new Error("The '" + this.name + "' ComplexType has already been added to a MetadataStore and therefore no additional properties may be added to it.");
    }
    if (dataProperty.parentType) {
        if (dataProperty.parentType !== this) {
            throw new Error("This dataProperty has already been added to " + property.parentType.name);
        } else {
            return this;
        }
    }
    this._addDataProperty(dataProperty);

    return this;
};

So, is there something wrong with my data structure?


text:
Q: Django ORM and hitting DB When I do something like
I. objects = Model.objects.all()
and then
II. objects.filter(field_1=some_condition)
I hit db every time when on the step 2 with various conditions. Is there any way to get all data in first action and then just take care of the result?

A: Of course you will hit db every time. filter() transforms to SQL statement which is executed by your db, you can't filter without hitting it. So you can retrieve all the objects you need with values() or list(Model.objects.all()) and, as zeekay suggested, use Python expressions (like list comprehensions) for additional filtering.

A: You actually don't hit the db until you evaluate the qs, queries are lazy.
Read more here.
edit:
After re-reading your question it becomes apparent you were asking how to prevent db hits when filtering for different conditions.
qs = SomeModel.objects.all()

qs1 = qs.filter(some_field='some_value')
qs2 = qs.filter(some_field='some_other_value')

Usually you would want the database to do the filtering for you.
You could force an evaluation of the qs by converting it to a list. This would prevent further db hits, however it would likely be worse than having your db return you results.
qs_l = list(qs)
qs1_l = [element for element in qs_l if element.some_field='some_value']
qs2_l = [element for element in qs_l if element.some_field='some_other_value']

A: Why don't you just do objs = Model.objects.filter(field=condition)? That said, once the SQL query is executed you can use Python expressions to do further filtering/processing without incurring additional database hits.