text:
Q: Decent way to disallow virtual functions due to placement new usage What would be a decent approach to check at compile/run-time that a particular struct/class does not have any virtual functions. This check is required in order to ensure the proper byte alignment when doing placement new.
Having so much as a single virtual function will shift the entire data by a vtable pointer size, which will completely mess things up in conjunction with the placement new operator.

Some more details: I need something that works across all major compiler and platforms, e.g. VS2005, VC++10, GCC 4.5, and Sun Studio 12.1 on top of Windows, Linux, and Solaris.
Something that is guaranteed to work with the following scenario should suffice:
struct A { char c; void m(); };
struct B : A { void m(); };

Should someone decide to make this change:
struct A { char c; virtual void m(); };
struct B : A { void m(); };

It would be great to see a compile-time error that says struct A must not contain virtual functions.

A: There are facilities and tricks (depending on the version of C++ you are using) to get the proper alignment for a class.
In C++0x, the alignof command is similar to sizeof but returns the required alignment instead.
In C++03, the first thing to note is that the size is a multiple of the alignment, because elements need be contiguous in an array. This means that using the size as the alignment is over-zealous (and may waste space) but works fine. With some trickery you can get a better value:
template <typename T>
struct AlignHelper
{
  T t;
  char c;
};

template <typename T>
struct Alignment
{
  static size_t const diff = sizeof(AlignHelper<T>) - sizeof(T);
  static size_t const value = (diff != 0) ? diff : sizeof(T);
};

This little helper gives a correct alignment as a compile-time constant (suitable for template programming therefore). It may be larger than the minimal alignment required (*).
Normally though it should be fine to use placement new, unless you are actually using it on a "raw buffer". In this case, the size of the buffer should be determined with the following formula:
// C++03
char buffer[sizeof(T) + alignof(T) - 1];

Or you should make use of C++0x facilities:
// C++0x
std::aligned_storage<sizeof(T), alignof(T)> buffer;

Another trick to ensure a "right" alignment for virtual tables it to make use of the union:
// C++03 and C++0x
union { char raw[sizeof(T)]; void* aligner; } buffer;

The aligner parameter guarantees that the buffer is correctly aligned for pointers, and thus for virtual tables pointers as well.
EDIT: Additional explanations as suggested by @Tony.
(*) How does this work ?
To understand it we need to delve into the memory representation of a class. Each subelement of a class has its own alignment requirement, so for example:
struct A { int a; char b; int c; };

+----+-+---+----+
| a  |b|xxx| c  |
+----+-+---+----+

Where xxx denotes padding added so that c is suitably aligned.
What is the alignment of A ? Generally speaking, it is the stricter alignment of the subelements, so here, the alignment of int (which is often 4 since int is often a 32 bits integral).
To "guess" the alignment of an arbitrary type, we thus "trick" the compiler by using the AlignHelper template. Remember that sizeof(AlignHelper<T>) must be a multiple of the alignment because types should be laid out contiguously in an array, thus we hope our type will be padded after the c attribute, and the alignment will be the size of c (1 by definition) plus the size of the padding.
// AlignHelper<T>
+----------------+-+---+
|        t       |c|xxx|
+----------------+-+---+

// T
+----------------+
|        t       |
+----------------+

When we do sizeof(AlignHelper<T>) - sizeof(T) we get this difference. Surprisingly though, it could be 0.
The issue comes from the fact that if there is some padding (unused bytes) at the end of T, then a smart compiler could decide to stash c there, and thus the difference of size would be 0.
We could, obviously, try to recursively increase the size of c attribute (using a char array), until we finally get a non-zero difference. In which case we would get a "tight" alignment, but the simplest thing to do is to bail out and use sizeof(T), since we already know it is a multiple of the alignment.
Finally, there is no guarantee that the alignment we get with this method is the alignment of T, we get a multiple of it, but it could be bigger, since sizeof is implementation dependent and a compiler could decide to align all types on power of 2 boundaries, for example.

A:
What would be a decent approach to
  check at compile/run-time that a
  particular struct/class does not have
  any virtual functions

template<typename T>
struct Is_Polymorphic
{
  struct Test : T { virtual ~Test() = 0; };
  static const bool value = (sizeof(T) == sizeof(Test));
};

Above class can help you to check if the given class is polymorphic or not at compile time. [Note: virtual inheritance also have a vtable included]

A: dynamic_cast is only allowed for polymorphic classes, so you can utilize that for a compile time check.

A: You are almost certainly doing something wrong.
However, given that you have decided to do something wrong, you don't want to know if your tpe has no virtual functions.  You want to know if it is okay to treat your type as an array of bytes.
In C++03, is your type POD?  As luck would have it, there's a trait for that, aptly named is_pod<T>.  This is provided by Boost/TR1 in C++03, although it requires a relatively modern compiler [gcc > 4.3, MSVC > 8, others I don't know].
In C++11, you can ease up your requirements by asking if your type is trivially copiable. Again, there's a trait for that: is_trivially_copyable<T>.
In either case, there is also is_polymorphic<T>, but as I said, that's really not what you want anyhow.  If you are using an older compiler, it does have the advantage of working out of the box if you get it from Boost; it performs the sizeof test mentioned elsewhere, rather than simply reporting false for all user defined types as is the case with is_pod.
No matter what, you'd better be 120% sure your constructor is a noop; that's not something that can be verified.

I just saw your edit.  Of what you listed, Sun Studio is the only one that might not have the necessary intrinsics for these traits to work.  gcc and MSVC have both had them for several years now.

A: Use is_pod type trait from tr1?

A: There is no feature for you to determine whether a class has virtual functions are not.


text:
Q: Converting Lat / long to PointClass IPoint pPoint = new ESRI.ArcGIS.Geometry.PointClass();
pPoint.PutCoords(-92.96000, 44.9227); //This should be near Minneapolis
mapControl.CenterAt(pPoint); //mapControl is a AxMapControl

When I run this code the point always ends up near Kansas. Can anyone help me convert lat / longs to an PointClass that will work properly?
I'm using VS2010 ArcEngine 10 C#

A: There is a lot more to this than you have currently given. Both a lat/long point and your map have a specific spatial reference. If they do not match, it is likely your point will plot in an unexpected way.
The point you are showing is a standard Latitude/Longitude point. Which is likely Nad83 (North American), or WGS84 (World). These are Spatial References with a Geographical Coordinate System. You are likely trying to plot the point on a Projected Coordinate System.
You need to make your MapControl's Spatial Reference match the types of points you are trying to plot.
Since I do not know the Spatial Reference of your Map, I can only give you an example of translating a Lat/Lon into what the MapControl's current spatial reference is.
ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();

IGeographicCoordinateSystem gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
ISpatialReference sr1 = gcs;

IPoint point = new PointClass() as IPoint;
point.PutCoords(-92.96000, 44.9227);

IGeometry geometryShape;
geometryShape = point;
geometryShape.SpatialReference = sr1;

geometryShape.Project(mapControl.SpatialReference);

mapControl.DrawShape(geometryShape);

This takes your point and projects it to the MapControls current spatial reference, then plots the point.
Good Luck.

A: Here is the code to zoom and center on a lat / long, the above poster was helpful but his solution did not work for me.
mapControl.MapScale = mapControl.MapScale / 2; //for zooming
ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass(); //move up top later
IGeographicCoordinateSystem gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //World lat / long format
ISpatialReference sr1 = gcs;
IPoint point = new PointClass();
point.SpatialReference = gcs;
point.PutCoords(-92.96000, 44.9227);
point.Project(mapControl.SpatialReference);
mapControl.CenterAt(point);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Measurable function on the Cantor Set with the Product Topology I am new to measure theory and I have worked out that the cantor set can be represented as $C = \{ 0,1 \}^N$ with the product topology metric. But I don't know how to show that for $\phi : N \to N $ , the map $ \sigma_{\phi} : (C, B_{C}) \to (C, B_{C})$  such that $\sigma_{\phi} = (x_1,x_2,x_3,...)$ = $\{x_{ \phi (1)}, x_{\phi (2)}, x_{\phi (3)}\}$ is measurable.
Do I have to make sure it works in the definition of measure?
Any help would be appreciated.

A: For any "index set" $I$ and any collection $\{S_i:i\in I\}$ of spaces, the (Tychonoff) product topology $T$ on $P=\prod_{i\in I}S_i$ is defined as the weakest (i.e. $\subset$-smallest) topology such that every projection $p_j: P\to S_j$ is continuous. [ If $x=(x_i)_{i\in I}\in P$ then $p_j(x)=x_j.$ ]
For each $j\in I$ let $B_j$ be the collection of all sets of the form $\prod_{i\in I}U_i,$ where $U_i=S_i$ if $i\ne j,$ and $U_j$ is some (any) open subset of $S_j.$
Then $B=\cup_{j\in I}B_j$ is a sub-base (sub-basis) for the topology $T$ on $P$.
Therefore any $\sigma: P\to P$ is continuous iff $\sigma^{-1}b\in T$ whenever $b\in B.$
In your Q:
We have $I=\Bbb N$ and every $S_i=\{0,1\}$ has the discrete topology. And $P=\{0,1\}^{\Bbb N}.$
Now for $j\in \Bbb N$ the only members of $B_j$ other than $P$ and $\emptyset$ are $B_j(0)=\{(x_i)_{i\in \Bbb N}: x_j=0\}$ and $B_j(1)=\{(x_i)_{i\in \Bbb N}: x_j=1\}.$
For $x=(x_i)_{i\in\Bbb N}\in P,$ and for $j\in \Bbb N,$ and for $y\in \{0,1\},$ we have $$(\sigma_{\phi})^{-1} B_j(y)=\{ x\in P: x_{\phi (j)}=y\}=  B_{\phi(j)}(y)\in T.$$ Therefore $\sigma_{\phi}$ is continuous.
This might suspiciously easy. But that's all there is.


text:
Q: how does the training routine and test routine work when applying spatial transform network I'm just starting a new project and I'm having some problems understanding how the training and testing routine works in a neural network.
So first i started with this tutorial provided by pytorch.
STN pytorch tutorial
I copied the same layers and all the parameters I didn't really change anything. I was able to understand the tutorial, but I wanted to go further, so I wanted to create my own dataset and apply it in the same convolutional neural network. My idea was as follows: I take an image of the FashionMNSIT dataset instead of the number MNSIT dataset. let's take this example:
item-1
item-2
then i think about rotating the images with random rotation angles and create for example 100 images per item.
After that, my idea was to create a dataset with these rotated images, and I want to assign index 0 for item-1 and index 1 for item-2 as classification ID. Because I found that this method torch.utils.data.DataLoader needs the images and the classification index for the training and testing part. After creating the dataset, I want to split the 200 images into two parts. The first part is the training dataset, which contains 160 images, and the rest of the images (40 images) is the test dataset. My expectation is that the stn layers will give me an image that is aligned, ie not rotated, once I use the visualize_stn method as in the tutorial. Can anyone tell me if my ideas are correct or I am thinking wrong.
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np

plt.ion()   # interactive mode

# Training dataset
train_loader = torch.utils.data.DataLoader(
datasets.FashionMNIST(root='.', train=True, download=True,
               transform=transforms.Compose([
                   transforms.ToTensor(),
                   transforms.Normalize((0.1307,), (0.3081,))
               ])), batch_size=64, shuffle=True, num_workers=4)
# Test dataset
test_loader = torch.utils.data.DataLoader(
datasets.FashionMNIST(root='.', train=False,
transform=transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])), batch_size=64, shuffle=True, num_workers=4)

class Net(nn.Module):
def __init__(self):
    super(Net, self).__init__()
    self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
    self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
    self.conv2_drop = nn.Dropout2d()
    self.fc1 = nn.Linear(320, 50)
    self.fc2 = nn.Linear(50, 10)

    # Spatial transformer localization-network
    self.localization = nn.Sequential(
        nn.Conv2d(1, 8, kernel_size=7),
        nn.MaxPool2d(2, stride=2),
        nn.ReLU(True),
        nn.Conv2d(8, 10, kernel_size=5),
        nn.MaxPool2d(2, stride=2),
        nn.ReLU(True)
    )

    # Regressor for the 3 * 2 affine matrix
    self.fc_loc = nn.Sequential(
        nn.Linear(10 * 3 * 3, 32),
        nn.ReLU(True),
        nn.Linear(32, 3 * 2)
    )

    # Initialize the weights/bias with identity transformation
    self.fc_loc[2].weight.data.zero_()
    self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))

# Spatial transformer network forward function
def stn(self, x):
    xs = self.localization(x)
    xs = xs.view(-1, 10 * 3 * 3)
    theta = self.fc_loc(xs)
    theta = theta.view(-1, 2, 3)

    grid = F.affine_grid(theta, x.size())
    x = F.grid_sample(x, grid)

    return x

def forward(self, x):
    # transform the input
    x = self.stn(x)

    # Perform the usual forward pass
    x = F.relu(F.max_pool2d(self.conv1(x), 2))
    x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
    x = x.view(-1, 320)
    x = F.relu(self.fc1(x))
    x = F.dropout(x, training=self.training)
    x = self.fc2(x)
    return F.log_softmax(x, dim=1)

  model = Net().to(device)
  optimizer = optim.SGD(model.parameters(), lr=0.01)

  def train(epoch):
     model.train()
     for batch_idx, (data, target) in enumerate(train_loader):
          data, target = data.to(device), target.to(device)

     optimizer.zero_grad()
     output = model(data)
     loss = F.nll_loss(output, target)
     loss.backward()
     optimizer.step()
     if batch_idx % 500 == 0:
        print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss:
        {:.6f}'.format(epoch, batch_idx * len(data),
         len(train_loader.dataset),
            100. * batch_idx / len(train_loader), loss.item()))

  def test():
     with torch.no_grad():
        model.eval()
        test_loss = 0
        correct = 0
        for data, target in test_loader:
             data, target = data.to(device), target.to(device)
        output = model(data)

        # sum up batch loss
        test_loss += F.nll_loss(output, target,
        size_average=False).item()
        # get the index of the max log-probability
        pred = output.max(1, keepdim=True)[1]
        correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{}
       ({:.0f}%)\n'
          .format(test_loss, correct, len(test_loader.dataset),
                  100. * correct / len(test_loader.dataset)))
   def convert_image_np(inp):
"""Convert a Tensor to numpy image."""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
return inp

def visualize_stn():
   with torch.no_grad():
    # Get a batch of training data
    data = next(iter(test_loader))[0].to(device)

    input_tensor = data.cpu()
    transformed_input_tensor = model.stn(data).cpu()

    in_grid = convert_image_np(
        torchvision.utils.make_grid(input_tensor))

    out_grid = convert_image_np(
        torchvision.utils.make_grid(transformed_input_tensor))

    # Plot the results side-by-side
    f, axarr = plt.subplots(1, 2)
    axarr[0].imshow(in_grid)
    axarr[0].set_title('Dataset Images')

    axarr[1].imshow(out_grid)
    axarr[1].set_title('Transformed Images')

for epoch in range(1, 20 + 1):
  train(epoch)
  test()

 # Visualize the STN transformation on some input batch
  visualize_stn()

  plt.ioff()
  plt.show()


text:
Q: Are Anita and Arutha related? In the books of the Riftwar cycle (by Raymond E. Feist), Anita and Arutha refer to each other as "cousins", however it is unclear how close of cousins they are (first cousins? second cousins?).

 Nevertheless, they marry and nobody seems to have any issue with this.

Furthermore, it is implied earlier that when speaking about royalty, the word "cousin" may actually refer to the fact that the royal families often intermarry, so everyone is kind of related to everyone else, even if the actual relation might be distant and difficult to trace.
So - has it ever been specified in the books (or interviews or whatever) just how closely or distantly Anita and Arutha are related by blood? I tried looking up on the Internet, but the closest I got was that their fathers had also been considered "cousins", which doesn't really say much.

A: From my reading of this, official family tree, their exact familial relationship is "Unknown", but the tree goes back at least 4 generations before they have a shared ancestor.
I've pasted the relevant section for posterity


text:
Q: Finding the accuracy of an accelerometer I would like to measure and compare the accuracy of different accelerometers.
Obviously I must choose a reference, therefore I compare all the accelerometer with this reference and then decide which is the most precise.
How can I select this reference ?

A: You can achieve this in two distinct ways:
1) use a reference (I'll give an example below)
2) measure other quantities that can be converted into an acceleration.
Here are some possibilities:
1a) Gravity. At rest, the accelerometer should measure the local g.
2a) Put it on a rotating platform. Knowing the rotational speed and distance to the pivot, you can calculate the acceleration.
2b) Put in on a swing
2c) Shoot it with a catapult
2d) Put it on a subwoofer
2e) ...
The list goes on and on. Practical methods depend on the type of accelerometer.


text:
Q: Difference between two Backbone.Router definitions I to try create my first javascript app with backbone.js
And I found strange behaviour, don't understand difference between 2 piece of code
One works well and second seems not work.
That show alert on homepage and '#test' url
var AppRouter = Backbone.Router.extend({
    routes:{
        "": 'index',
       "test": 'test'
    },
    index: function(){
        alert('index');
    },
    test: function(){
        alert('test');
    }
});
var app = new AppRouter();
Backbone.history.start();

And that not work, but Backbone.history.hanlers looks identical
var router = new Backbone.Router({
    routes:{
        "": 'index',
       "test": 'test'
    },
    index: function(){
         alert('index');
    },
    test: function(){
         alert('test');
    }
});
Backbone.history.start();

A: The difference between the two bits of code is that in the first one you are creating a new class called AppRouter whereas in the second one you are just creating a plain Backbone.Router class.
I may be misunderstanding, but it seems you are saying that the first example works, and the second one doesn't?
The reason the second example does not work is because Backbone.Router only accepts the routes hash as an argument to it's constructor.  The index and test functions you have passed are not created as functions on the object.
If you want to pass the routes hash to the constructor you still need to extend Backbone.Router with the actual routing functions.  For example:
var AppRouter = Backbone.Router.extend({
    index: function(){
        alert('index');
    },
    test: function(){
        alert('test');
    }
});
var app = new AppRouter({
    routes:{
        "": 'index',
       "test": 'test'
    }});
Backbone.history.start();


text:
Q: What exactly is a read/write operation in cloud storage? Is it possible to combine several write requests into one single requests? Hello guys I am new to web development and related technologies. I would like to know whether each get request is a read operation and post, put and delete are write operations?
Is it possible to combine several write requests and do it as a single write request? For example, if someone likes a post, instead of writing that directly to database, is it possible to hold the request somewhere temporarily before writing it together with other similar requests? and if you do like that, does it save costs?
Thanks

A: Your question is very broad and open-ended and probably not well suited to Stackoverflow. I encourage you to Google tutorials that explain how HTTP and REST work (e.g. link).
HTTP is a protocol that underpins the Web and, essentially involves (HTTP) clients (e.g. your browser) making (HTTP) requests to some (HTTP) server that provides a response.
Every HTTP request includes a 'verb' (GET, POST, PUT, UPDATE) and each has a reasonably well-defined intent. E.g. GET is what we commonly think of a browsing the web. Your browser requests e.g. https://stackoverflow.com/questions/65832394 and the Stackoverflow server provides the HTML that renders as this page. Other verbs are used to send data to a server.
It is often (but not always) true that GETs involve reading from and e.g. POSTs involve writing to some form of 'backend' (e.g. database).
HTTP is a stateless protocol. There's no intrinsic correlation between any requests and responses. If you make e.g. 2 POSTs (e.g. Here's this thing, And here's another thing) from the same machine to the same URL, the only way that the server would be able to correlate these is if you were to include some form of identifying data (usually in the form of a header), e.g. {"user":"prehistoricbeast", "message": "First thing"}, {"user":"prehistoricbeast", "message": "Second thing"}. And, then the server would have to manage some state, i.e. 2 messages from prehistoricbeast for you.
Even if you manage state like this in one server, you will have problems if you wish to scale out and add other servers. If server #x received {"user":"prehistoricbeast", "message": "First thing"} and server #y received {"user":"prehistoricbeast", "message": "Another thing"}, you'd need to share state across these machines too...
It is common (as @civfan suggests) to cache data in a server and there are many other useful mechanisms including queuing (pub/sub) etc. etc. to help with efficiency (throughput, cost etc) but these are all highly-dependent on your use-case, the services you have available etc.


text:
Q: stooped or kicked in "He laughed and stooped them all into the river."? In the movie "little mouse who was a princess",
https://www.youtube.com/watch?v=kv1CFTWdofk.

at the time of 10 minutes 52 seconds,i saw a sentence

He laughed and stooped them all into the river.

stoop means "to bend (a part of the body) forward and downward",when i watch the movie ,it seems that mouse princess and its coachmen are all kicked into a river nearby by a man passing by.
Maybe it is better to write it as :

He laughed and kicked them all into the river.

A: To my ears, the spoken dialogue says 'he laughed and shoot them all into the river". I guess this may be American rural dialect (in some region) for 'shot' (you can shoot something [somewhere] with your foot). The narrator's girlish voice has a heavy American accent. You should be aware that the captions on YouTube are often computer generated, or hastily created by people, and not always by native speakers. They do not always correctly match what is being spoken. You are correct that 'kicked them all into the river' is correct and appropriate standard English for what happened.

A: To my ear, it sounds like scooped, which makes much more sense.
The makers of the video probably took it from the page A Little Mouse Who Was A Princess:

Walking through the jungle, they came near a town. There was a river flowing in between. They had to cross the bridge over the river. As they were crossing it, a man came from nowhere in the opposite direction. He saw a bunch of mice coming on his way. He laughed and stooped them all into the river. Veikko was very sad for the mouse. But the man laughed loudly and went away. He looked down into the river but he found nowhere.

This very paragraph contains clues that confirm @BillyKerr's view:

He saw a bunch of mice coming on his way.
He laughed and stooped them into the river. Veikko was very sad for the mouse (-> logically 'mice').
He looked down into the river but he found nowhere (-> found them nowhere).

My best guess is that the original word must have been scooped (or possibly shot) which was then mistyped/corrupted through translation/appropriation.

A: I think the grammar and syntax of the piece are so bad in places that it really is of no import whether that one word is stooped or scooped, or anything else for that matter.
I would theorise that the script is written by a non-native, under no supervision. It contains a lot of instances where, even if the grammar is technically fine, the idiom is missing a clue.
For the narration they found American voice-over artists whose job it is to read what's written, not to make suggestions on grammar or syntax.
They did the job, anonymously, took the money & ran, thank you very much. There are no credits, beginning or end. Comments are off - probably to avoid people pointing out how bad it is.
If not already crystal clear from my comments so far - don't use this source to learn English.


text:
Q: Install gitlab library to docker-compose based interpreter environment in PyCharm project I need to install one package to the docker-compose based environment of the application.
The package is not downloaded on pip, therefore, I install it via GitLab URL. I can successfully install it on venvs I created for test the package, but when I try to install it on the docker-compose app I start to get mistakes.
That's how it looks in the requirments.txt file:
git+https://git.somerepo.com/smth/smth/package-name.git#egg=package_name

When I try to install I receive an error message:
Running command git clone -q +https://git.somerepo.com/smth/smth/package-name.git /tmp/pip-install-kqlwiux8/package-name_2ba6c558a2e14343acef3f3e34d49f18
fatal: could not read Username for 'https://git.somerepo.com': No such device or address

If i change the requirement to git@git.somerepo.com/smth/smth/package-name.git#egg=package_name  it doesn't recognized as a requirement.
When I try to install it from the terminal with the command:
docker-compose --project-name=some_backend_api -f docker/dev/docker-compose.yml run core /bin/bash -c 'pip install git+https://git.somerepo.com/smth/smth/package-name.git#egg=package_name'

I receive the result that the package is successfully installed:
Successfully built package-name
Installing collected packages: pandas, package-name
Successfully installed pandas-1.3.4 package-name-0.1.0

But when i check pip list:
docker-compose --project-name=some_backend_api -f docker/dev/docker-compose.yml run core /bin/bash -c 'pip list
I couldn't find the package-name and couldn't access it
When I rebuild the containers, I once again encounter the git fatal error. What might be the reason for this git fatal error, and why I couldn't find the package inside the pip list, after successfully installing it via terminal?
Warning after install-requirements command
errors after running the command


text:
Q: http://localhost:3000/getalldata/undefined 404 (Not Found) again am getting an error while fetching data from backend to frontend , don't know where am wrong please try to fix my error, if you have any query please free feel to ask.

Note :: My adddata Opeartion is working fine
Userdata.js

This is my react js part where i want to fetch data from backend , and am using axios to fetch data
import React, { useEffect, useState } from "react";
import { Link,useParams } from "react-router-dom";
import Axios from 'axios';

const UserData = () => {
  const [users, setUser] = useState([{
    title : "",
    description : ""
  }]);

  const {id} = useParams();

  useEffect(() => {
    AllUsers();
  }, []);

  const AllUsers = async (id) => {
    const res = await Axios.get(`http://localhost:3000/getalldata/${id}`);
    console.log(res.data);
    setUser(res.data)
  };

  return (

              {/* No	 */}
              Title
              Details
              Action

            {users.map((user, index) => (

                {user.id}
                {user.title}
                {user.description}

            ))}

  );
};

export default UserData;

Userdata/Route

This is my route file
const express = require("express");
const route = express.Router();

const {
  getallData,
  addData,
  getDataById,
  deleteData,
  editData,
} = require('../controller/userdata');

route.get("/getalldata", getallData);
route.post("/adddata", addData);
route.get("/:id", getDataById);
route.delete("/:id", deleteData);
route.put("/editData/:id", editData);

module.exports = route;

App.js

I have added App.js file which is link to each other.
import "./App.css";
import Home from "./components/Home";
import Login from "./components/Login";
import Navbar from "./components/Navbar";
import Register from "./components/Register";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import UserData from "./components/UserData";
import AddData from "./components/AddData";

function App() {
  return (
    <BrowserRouter>
      <Navbar />

        <Routes>
          <Route exact path="/" element={<Home />} />
          <Route exact path="/signup" element={<Register />} />
          <Route exact path="/signin" element={<Login />} />
          <Route exact path="/getalldata" element={<UserData />} />
          <Route exact path="/adddata" element={<AddData/>} />
        </Routes>

    </BrowserRouter>
  );
}

export default App;

A: When you are not passing any params, you wont get any value while using getParams() so it will return undefined and which will be stored to id variable.
localhost:3000/getalldata

if your end point for all data looks like this , then you can avoid /${id} from url get request as you did in example code.


text:
Q: Removing & adding strings from a vector I'm new to C++ and I was just wondering how would I go about removing and adding strings from a vector. I have tried several implementations and the program does not seem to work has intended.
//allows the user to list thier top 10 video games
cout << "Please list your Top 10 favourite video games below.\n";
string gameTitle;
vector<string> gameList(10);
cin >> gameTitle;
gameList.insert(gameList.begin(), gameTitle);

//prints out the game list
vector<string>::iterator iterGameList;
cout << "Your Top 10 video games are:\n";
for (iterGameList = gameList.begin(); iterGameList != gameList.end() ++iterGameList)
{
    cout << *iterGameList << endl;
}

//allows the use to remove a game title from the list

Any help on this would be greatly appreciated.
P.S. Would I have to pass find() to erase() via an iterator.

A: By far the most common way to add items to a vector is with push_back, something like:
vector<string> gameList;

for (int i=0; i<10; i++) {
    std::string game;

    std::cin >> game;
    gameList.push_back(game);
}

To remove an item you use erase. For example, to remove all the items currently in your vector, you could use:
gameList.erase(gameList.begin(), gameList.end());

...though erasing all the contents is a common enough operation that there's a clear() to do exactly that.

A: Instead of gameList.insert(gameList.begin(), gameTitle);
use gameList.push_back(gameTitle);
Check out the article for information on push_back:
http://www.cplusplus.com/reference/vector/vector/push_back/


text:
Q: Getting data using Regular Expressions - PHP I have html text stored in one of the columns of a database. the column name is mailbody and the table name is inbox_master.
Some the cells of column mailbody has divs like below

2802

or

6894

or

6894

what is common here is a div with the id "uid-g-uid". I want to be able to read the html of this div. I know this could be done using regular expressions however, not sure how to do it.
Below is the regex that i have tried but doesnt work all the time
/(?<=\<div\ id\=\"uid\-g\-uid\").*?(?=\<\/div\>)/gim

A: Thanks to @sikfire and @dave, i got the solution using DOM. below is my working which helped me
$doc = new DOMDocument();
@$doc->loadHTML('The HTML Content Goes here');
$d = $doc->getElementById('uid-g-uid');
echo 'Value is ' . $d['textContent'];

Didnt knew this could be this simple! Thanks Guys!

A: you can also look at the project here. PHP DomParser
This might help!


text:
Q: Using 'else np.nan' in list comprehension I have a list of websites, and I want to extract social media profiles only (let's say facebook, linkedin and pinterest)
import numpy as np

mylist = ['linkedin.com/profilexyz','facebook.com/profile374','bbcnews.com/USA_news','stackoverflow.com']

I have used list comprehension to get the urls, returning nan if it's not found:
facebook = [x for x in mylist if 'facebook' in x else np.nan for x in mylist]
linkedin = [x for x in mylist if 'linkedin' in x else np.nan for x in mylist]
pinterest = [x for x in mylist if 'pinterest' in x else np.nan for x in mylist]

However I get the error:
File "<ipython-input-329-578130619ae7>", line 1
facebook = [x for x in mylist if 'facebook' in x else np.nan for x in mylist]
                                                        ^
SyntaxError: invalid syntax

I have checked the suggested duplicates such as this one: if/else in a list comprehension? but can't get my comprehension to work.

A: you have the order messed up and an extra for
fb = [x if 'facebook' in x else np.nan for x in mylist]

A: This is one approach using collections.defaultdict and str.split
Ex:
from collections import defaultdict

result = defaultdict(list)
mylist = ['linkedin.com/profilexyz','facebook.com/profile374','bbcnews.com/USA_news','stackoverflow.com']

for url in mylist:
    result[url.split('/')[0]].append(url)
print(result)

Output:
defaultdict(<class 'list'>, {'linkedin.com': ['linkedin.com/profilexyz'], 'facebook.com': ['facebook.com/profile374'], 'bbcnews.com': ['bbcnews.com/USA_news'], 'stackoverflow.com': ['stackoverflow.com']})

FYI in your method
facebook = [x for x in mylist if 'facebook' in x]
print(facebook)

A: Remove extra for loop from list comprehension.
Ex.
import numpy as np

mylist = ['linkedin.com/profilexyz','facebook.com/profile374','bbcnews.com/USA_news','stackoverflow.com']
facebook = [x if 'facebook' in x else np.nan for x in mylist]
linkedin = [x if 'linkedin' in x else np.nan for x in mylist]
pinterest = [x if 'pinterest' in x else np.nan for x in mylist]
print(facebook)
print(linkedin)
print(pinterest)

O/P:
[nan, 'facebook.com/profile374', nan, nan]
['linkedin.com/profilexyz', nan, nan, nan]
[nan, nan, nan, nan]

Remove duplicate nan value from list using set()
print(list(set(facebook)))
print(list(set(linkedin)))
print(list(set(pinterest)))

O/P:
[nan, 'facebook.com/profile374']
[nan, 'linkedin.com/profilexyz']
[nan]

A: Just use parentheses:
facebook = [(x for x in mylist) if 'facebook' in x else np.nan for x in mylist]
linkedin = [(x for x in mylist) if 'linkedin' in x else np.nan for x in mylist]
pinterest = [(x for x in mylist) if 'pinterest' in x else np.nan for x in mylist]


text:
Q: How to get 2 unrelated Swift objects to know how to do the same sets of function Before anyone says inheritance.. hear me out first.
I have 2 totally unrelated view controllers. They each have an MKMapView. I would like both of them to conform to and implement the same delegate methods.
For example, I want both to implement:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polyline = overlay as! MKPolyline
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4
        return renderer
    }

Again, these 2 view controllers aren't related at all, so I don't want to make a base class. As a matter of fact, these 2 view controllers are already inheriting from their respective inheritance hierarchy.

A: Use a protocol and a default implementation.
protocol SomeMapFunctions {
    var mapView : MKMapView? { get }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
}

extension SomeMapFunctions {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polyline = overlay as! MKPolyline
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4
        return renderer
    }
}

class VC1 : UIViewController, SomeMapFunctions {
    var mapView : MKMapView?
}

class VC2 : UIViewController, SomeMapFunctions {
    var mapView : MKMapView?
}

As shown, any common properties that are necessary for the default implementations can be put into the protocol as well.

A: One solution could be:
protocol CommonStuff {
   func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
}

extension CommonStuff where Self: UIViewController {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polyline = overlay as! MKPolyline
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4
        return renderer
    }
}

Then, adopting the protocol by both view controllers would provide them the same behaviour.


text:
Q: PHP Regex specify multiple paths using glob() glob("aaafolder/*php")
glob("bbbfolder/*php")
glob("cccfolder/*php")

Is it possible to simplify this?
glob("(?=aaafolder/*php)(?=bbbfolder/*php)(?=cccfolder/*php)")

The above returns nothing.

A: As the PHP manual said, its the GLOB_BRACE flag.
glob("{aaafolder/*php,bbbfolder/*php,cccfolder/*php}", GLOB_BRACE)

A: This note on the manual page of glob() seems to answer your question, saying that glob is not limited to a single directory : using GLOB_BRACE, you can specify several directories.

I'm quoting the example that @Ultimater gives there :
$results=glob("{includes/*.php,core/*.php}",GLOB_BRACE);

User-notes on the manual pages often contain useful informations and examples ;-)


text:
Q: How to Request Location permission before showing map set up in Xaml. Xamarin.Forms I recently updated sdk level to 6.0 in Xamarin.forms.
I used Xaml to place a map on a page. Since I updated to 6.0 permission is required to show the map. My problem now is I can't figure out how to request permission to show the map before the app attempts to show it. As a result I get an unhandled exception.
 public MapPage()
        {
            Init();
            InitializeComponent();

            azureService = AzureService.defaultManager;

        }
        private async Task Init()
        {
            await RequestLocationPermission();
        }
        protected async override void OnAppearing()
        {
            base.OnAppearing();

            MyMap.MoveToRegion(
               MapSpan.FromCenterAndRadius(
                   new Position(0, 0),
                   Distance.FromMiles(10.0)));

        }

private async Task RequestLocationPermission()
        {
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
                if (status != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
                    {
                        await DisplayAlert("Need location", "Gunna need that location", "OK");
                    }

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
                    status = results[Permission.Location];
                }

                if (status == PermissionStatus.Granted)
                {
                                        }
                else if (status != PermissionStatus.Unknown)
                {
                    await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                }
            }
            catch (Exception ex)
            {

            }
        }

If the map is set up in Xaml, how can I request permission before showing it?

A: The way your constructor is set up right now, you are starting the permission request in a task which will run in a separate thread. That means that InitializeComponent() will probably run before the user can grant permission. The problem is you can't make the constructor an async method so there isn't an easy way to get around this.
To make this work without to much effort, you can move the InitializeComponent() from your constructor into your "if (status == PermissionStatus.Granted)" block. It would probably look something like this:
if (status == PermissionStatus.Granted)
{
     Device.BeginInvokeOnMainThread(() =>
     {
         InitializeComponent()
     });
}

With this approach you will have to be careful what you do in OnAppearing() as it will probably be called before InitializeComponent(). If you try to access any of your UI components at that point it will fail.
However I think the better way to handle this is to move your permission request code one level up. In other words put it in the class where you are instantiating this page from. Then you can show this page if access is granted, or another page that does not have the map if access is denied. It would make for a better user experience.


text:
Q: Find specific TEXT between Small brackets using FIND with wildcard I need to find specific Text say " PL" between small brackets () i.e
Text Criteria:

*

*text " PL" - both letters are Capital and there is a space before "PL"

*text should be bold

*text should be in between small brackets ie. ()

Example Text:

*

*Portugues SA (BCP PL, Buy): (Target Price: €0.22) Bank

*Jeronimo Martins SGPS SA (JMT PL, Buy): (Target Price: €19.60) 2Q21 Review

*Ibersol SGPS SA (IBS PL, Neutral): (Target Price: €6.50) Cinven acquires controlling

VBA Code:
    With Selection.Find
        .Text = "\((.*?)\)" ' WhildCard
        .Forward = True
        .Wrap = wdFindStop
        .MatchWildcards = True
        .Execute
    End With
    If Selection.Find.Found Then

    'if found then need to select the paragraph and do something with it.

    End If

If it is possible using Wildcard, please help

A: Try this code:
Sub test1()
    With ActiveDocument.Range.Find 'or Selection.Range.Find
        .Text = "\(?*\)"
        .MatchWildcards = True
        Do While .Execute
            If InStr(.Parent.Text, " PL") And .Parent.Font.Bold Then
                'do something with it
                .Parent.Paragraphs(1).Range.Delete
            End If
        Loop
    End With
End Sub

Edit2 pattern without parentheses
Sub test2()
    Dim rng As Range
    With ActiveDocument.Range.Find
        .Text = " PL"
        .MatchWildcards = True
        Do While .Execute
            If .Parent.Font.Bold Then
                .Parent.Paragraphs(1).Range.Delete
            End If
        Loop
    End With
End Sub


text:
Q: what is the correct way "brought" or "brang"? My son uses the word brang all the time and my wife saying that it is ok.
I was taught that the proper past of "bring" is brought.
Who is right here?

A: Brang is a common (in the US, at least), but marked, past tense of bring. It is associated with less educated speakers in disadvantaged social groups. It is very uncommon among educated or high-social-standing speakers.

A: While there are present/imperfect/perfect participle constructions like sing/sang/sung and ring/rang/rung, bring/brang/brung is not one of them.
From the Germanic origins of English we can see that for those verbs like sing the participles of sing/sang/sung correlate with the German singen/sang/gesungen, and that bring correlates with the German verb bringen - the English participles bring/brought/brought correlate with the German bringen/brachte/gebracht.
So no, brang is not correct (nor is brung). As noted it is a usage more common among less educated speakers.


text:
Q: Excel - How do I find the index/position of the nth word of a string? I have a cell with a long paragraph, and I'm trying to create a formula to find the index of the first or last letter of the nth word.
For example, if my string is: This is sentence 1. This is sentence 2. and I wanted the position of the 3rd word, the formula should return 9 (position of the "s" in "sentence" of) or 16 (position of the final "e" in sentence).
Further to the example, if I wanted the position of the 4th word, the formula should return 18 (position of the "1") or 19 (position of the period).
Any help would be greatly appreciated! Thank you!

A: Take the third word.
The third word will occur after the second space.  Will will find the second space amd them add one:
=FIND(CHAR(1),SUBSTITUTE(A1," ",CHAR(1),2))+1

So in the above example, the third word begins at string position #8.
NOTE
To get the position of the 12th word, we would use:
=FIND(CHAR(1),SUBSTITUTE(A1," ",CHAR(1),11))+1

etc.

A: To extract the nth word of a string, it seems logical to turn the sentence into an array and then extract the nth element of that array.
if you have a Windows version of Excel 2013+, you can create an XML where each node is a word, and then use the  FILTERXML to extract the appropriate node:
=FILTERXML("<t><s>" & SUBSTITUTE(TRIM(A2)," ","</s><s>") & "</s></t>","//s[" & WordNum & "]")

If you have a MAC version, or earlier version, the formula is more complicated. You create an Array where each element is a word, and then use the INDEX function to return the appropriate element.
=INDEX(TRIM(MID(SUBSTITUTE(TRIM(A2)," ",REPT(" ",99)),seq_99,99)),WordNum)

where seq_99 is a Named Formula that refers to:
=IF(ROW(INDEX($A:$A,1,1):INDEX($A:$A,255,1))=1,1,(ROW(INDEX($A:$A,1,1):INDEX($A:$A,255,1))-1)*99)


text:
Q: PulseAudio sink missing for GSP670 headset I just got a Sennheiser GSP 670 gaming headset and I had some issues with the device being detected correctly by PulseAudio.
The headset is wireless and it has a dongle.
The headset has a main stereo output for games and music. Apart from that, there is one more mono input and output that is dedicated to communication.
Essentially there are two audio devices registered by ALSA (and on Windows as well), one which can be used for stereo playback and another one which can be used for mono playback and capture at the same time.
The dongle is registered as follows
hw:S60,0
hw:S60,1

The hedset is registered as follows when it's plugged in via USB
hw:G670,0
hw:G670,1

I have no trouble using the devices with ALSA, however PulseAudio only detects the first device, which is for communication and not the other one.
The way I solved it for now is by telling PulseAudio to ignore the device and creating the sinks manually.
Here is how I make PulseAudio ignore the device with an udev rule:
ATTRS{idVendor}=="1395", ATTRS{idProduct}=="0089", ENV{PULSE_IGNORE}="1"

And this is the script I am using to create the sinks and sources:
#!/usr/bin/sh

pacmd load-module module-alsa-sink device=hw:S70,0 name=gsa70_comm_output
pacmd 'update-sink-proplist alsa_output.gsa70_comm_output device.description="GSA70 Communication" '

pacmd load-module module-alsa-sink device=hw:S70,1 name=gsa70_main
pacmd 'update-sink-proplist alsa_output.gsa70_main device.description="GSA70 Main" '

pacmd load-module module-alsa-source device=hw:S70,0 name=gsa70_comm_input
pacmd 'update-source-proplist alsa_input.gsa70_comm_input device.description="GSA70 Communication" '

This is working so far but it's not optimal. It's not plug and play, meaning the sinks are still there after the dongle is disconnected.
I could use udev to run this script when the the dongle is connected, and then run a cleanup script when the dongle is disconnected, but I'm wondering if there is a better way to do this.


text:
Q: Run the libspotify examples I am trying to run the spotify examples. I have sucecsfully compiled them but I cannot run anything. When i.e. do ./jukebox.o it just says "cannot execute binary file". How do I run the examples?
This is what I got when i did make:
libspotify/examples$ make LIBSPOTIFY_PATH=../../../..
for a in jukebox spshell localfiles; do make -C $a LIBSPOTIFY_PATH="/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release" all; done
make[1]: Entering directory /home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/share/doc/libspotify/examples/jukebox'
cc -I/usr/include/alsa   -I/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/include -Wall   -Wl,-rpath,/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/lib -L/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/lib jukebox.o appkey.o alsa-audio.o audio.o -o jukebox -lasound   -lspotify
/usr/bin/ld: alsa-audio.o: undefined reference to symbol 'pthread_create@@GLIBC_2.2.5'
/lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make[1]: *** [jukebox] Error 1
make[1]: Leaving directory/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/share/doc/libspotify/examples/jukebox'
make[1]: Entering directory /home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/share/doc/libspotify/examples/spshell'
cc -I/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/include -Wall -Wl,-rpath,/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/lib -L/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/lib spshell.o spshell_posix.o appkey.o cmd.o browse.o search.o toplist.o inbox.o star.o playlist.o test.o -lreadline -lspotify -o spshell
/usr/bin/ld: spshell_posix.o: undefined reference to symbol 'pthread_create@@GLIBC_2.2.5'
/lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make[1]: *** [spshell] Error 1
make[1]: Leaving directory/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/share/doc/libspotify/examples/spshell'
make[1]: Entering directory /home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/share/doc/libspotify/examples/localfiles'
make[1]: Leaving directory/home/alexander/slask/libspotify-12.1.51-Linux-x86_64-release/share/doc/libspotify/examples/localfiles'

A: I had a similar problem on 64-Bit Ubuntu. Edit the LDLIBS line in examples/common.mk to read as follows
LDLIBS  += -lspotify -lpthread -ldl

A: You have to make the file executable.
Try chmod u+x jukebox.o and if that doesn't work, you should try compiling it like gcc jukebox.c -o jukebox

A: On Linux, after you've successfully run the makefile, your share/doc/libspotify/examples/jukebox directory should look like this:
weeble@mylaptop:~/prj/libspotify/libspotify-12.1.51-Linux-i686-release/share/doc/libspotify/examples$ ls -l jukebox/
total 140
-rw-r--r-- 1 weeble weeble  5588 Jun 13  2012 alsa-audio.c
-rw-r--r-- 1 weeble weeble  5392 Feb 26 09:25 alsa-audio.o
-rw-r--r-- 1 weeble weeble   856 Feb 26 09:26 appkey.o
-rw-r--r-- 1 weeble weeble  1840 Jun 13  2012 audio.c
-rw-r--r-- 1 weeble weeble  1828 Jun 13  2012 audio.h
-rw-r--r-- 1 weeble weeble  1400 Feb 26 09:25 audio.o
-rw-r--r-- 1 weeble weeble  1718 Jun 13  2012 dummy-audio.c
-rwxr-xr-x 1 weeble weeble 21865 Feb 26 09:26 jukebox
-rw-r--r-- 1 weeble weeble 15156 Jun 13  2012 jukebox.c
-rw-r--r-- 1 weeble weeble  9116 Feb 26 09:19 jukebox.o
-rw-r--r-- 1 weeble weeble  1051 Jun 13  2012 Makefile
-rw-r--r-- 1 weeble weeble  4469 Jun 13  2012 openal-audio.c
drwxr-xr-x 3 weeble weeble  4096 Jun 13  2012 osx
-rw-r--r-- 1 weeble weeble  3378 Jun 13  2012 osx-audio.c
-rw-r--r-- 1 weeble weeble  8860 Jun 13  2012 playtrack.c
-rw-r--r-- 1 weeble weeble 18990 Jun 13  2012 queue.h

The executable file is the one called "jukebox". So run "./jukebox/jukebox". If that file isn't there, perhaps the build process failed. Were there any messages or warnings when you ran "make"?


text:
Q: R: Put Child Elements of an XML node into a data frame, based on the attribute let's say I have a XML-File and i want to write a R Function which takes the attributes I am looking for and searches through an XML-File. The content of the child nodes of these attributes then should be given to a data frame.
    <?xml version="1.0"?>
    <catalog>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
       <book id="bk102">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies,
          an evil sorceress, and her own childhood to become queen
          of the world.</description>
       </book>
       <book id="bk103">
          <author>Corets, Eva</author>
          <title>Maeve Ascendant</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-11-17</publish_date>
          <description>After the collapse of a nanotechnology
          society in England, the young survivors lay the
          foundation for a new society.</description>
       </book>
       <book id="bk104">
          <author>Corets, Eva</author>
          <title>Oberon's Legacy</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2001-03-10</publish_date>
          <description>In post-apocalypse England, the mysterious
          agent known only as Oberon helps to create a new life
          for the inhabitants of London. Sequel to Maeve
          Ascendant.</description>
       </book>
       <book id="bk105">
          <author>Corets, Eva</author>
          <title>The Sundered Grail</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2001-09-10</publish_date>
          <description>The two daughters of Maeve, half-sisters,
          battle one another for control of England. Sequel to
          Oberon's Legacy.</description>
       </book>
       <book id="bk106">
          <author>Randall, Cynthia</author>
          <title>Lover Birds</title>
          <genre>Romance</genre>
          <price>4.95</price>
          <publish_date>2000-09-02</publish_date>
          <description>When Carla meets Paul at an ornithology
          conference, tempers fly as feathers get ruffled.</description>
       </book>
       <book id="bk107">
          <author>Thurman, Paula</author>
          <title>Splish Splash</title>
          <genre>Romance</genre>
          <price>4.95</price>
          <publish_date>2000-11-02</publish_date>
          <description>A deep sea diver finds true love twenty
          thousand leagues beneath the sea.</description>
       </book>
       <book id="bk108">
          <author>Knorr, Stefan</author>
          <title>Creepy Crawlies</title>
          <genre>Horror</genre>
          <price>4.95</price>
          <publish_date>2000-12-06</publish_date>
          <description>An anthology of horror stories about roaches,
          centipedes, scorpions  and other insects.</description>
       </book>
       <book id="bk109">
          <author>Kress, Peter</author>
          <title>Paradox Lost</title>
          <genre>Science Fiction</genre>
          <price>6.95</price>
          <publish_date>2000-11-02</publish_date>
          <description>After an inadvertant trip through a Heisenberg
          Uncertainty Device, James Salway discovers the problems
          of being quantum.</description>
       </book>
       <book id="bk110">
          <author>O'Brien, Tim</author>
          <title>Microsoft .NET: The Programming Bible</title>
          <genre>Computer</genre>
          <price>36.95</price>
          <publish_date>2000-12-09</publish_date>
          <description>Microsoft's .NET initiative is explored in
          detail in this deep programmer's reference.</description>
       </book>
       <book id="bk111">
          <author>O'Brien, Tim</author>
          <title>MSXML3: A Comprehensive Guide</title>
          <genre>Computer</genre>
          <price>36.95</price>
          <publish_date>2000-12-01</publish_date>
          <description>The Microsoft MSXML3 parser is covered in
          detail, with attention to XML DOM interfaces, XSLT processing,
          SAX and more.</description>
       </book>
       <book id="bk112">
          <author>Galos, Mike</author>
          <title>Visual Studio 7: A Comprehensive Guide</title>
          <genre>Computer</genre>
          <price>49.95</price>
          <publish_date>2001-04-16</publish_date>
          <description>Microsoft Visual Studio 7 is explored in depth,
          looking at how Visual Basic, Visual C++, C#, and ASP+ are
          integrated into a comprehensive development
          environment.</description>
       </book>
    </catalog>

so for example if I put in my function bk107, bk111, bk112 i want the subchild nodes with a headline and the attribute as a row description in a data frame.
            author           title                 genre      price   publish_date   description
    bk107   Thurman, Paula   Splish Splash         Romance    4.95    2000-11-02     A deep sea diver fin...
    bk111   O'Brien, Tim     MSXML3: A Compr...    Computer   36.95   2000-12-01     The Microsoft MSX...
    bk112   Galos, Mike      Visual St...          Computer   49.95   2001-04-16     Microsoft Visual Stu...

I looked up in an book how the XML package for R works, but this right now is way over my head.
Appreciate any help. <3

A: Here is a possibility, if you already know the tags you want to retrieve:
# Define the XML text
xml.str <- '<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer\'s Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
</catalog>'

# Parse the XML
xml <- XML::xmlInternalTreeParse(xml.str, asText = TRUE)

# Get the book IDs
ids <- XML::xpathSApply(xml, '//book', XML::xmlGetAttr, 'id')

# Retrieve values for each book
books <- data.frame()
for (id in ids) {
    book <- list(id = id)
    for (field in c('author', 'title', 'genre', 'price', 'publish_date')) {
        value <- XML::xpathSApply(xml, paste0('//book[@id="', id, '"]/', field), XML::xmlValue)
        book[[field]] <- value
    }
    books <- rbind(books, book, stringsAsFactors = FALSE)
}

# Result
books


text:
Q: Documenting Internal Structures of v4 CTree Database.. parsing binary? I have a very old (circa 1993, v4 Faircom CTree Database) that was used by a now defunct test equipment manufacturer. I have no access to original configuration but there only appear to be two tables (two files) and then two other matching files which I assume are their sibling index files.
Im attempting to parse out these old files in a newer C# program to load the data for other purposes so Im looking at the binary.... I see how they are structured, there is a header and a variety of pointers (this was written and compiled with Turbo C) and I even see my data in there as text.
binary snapshot picture #1
Taking what is shown above, you can see that the offset to the record data is the second word it the main file header. Now we get into the record specific structure...
binary snapshot picture #2
4 Records shown here - each a different color
1st Word - two matching bytes signifying the record type? (FA,FB,FC,FD,FE,FF=end)
2nd Word - IS the length of the record (after 6 header bytes).
3rd Word - Unknown (sometimes matches the 2nd word, sometimes zero, somtimes something else)
Actual questions for this post:

*

*It appears that I will need to ascertain the fields for the records myself by parsing through a handful of different data files to figure out lengths. Does anyone know if there are free tools out there that can 'understand' Faircom database structures? I have contacted Faircom and they will help me if I buy a support contract, but I wasn't totally expecting to spend money on this, but I may have to.

*I tried to find C headers to get to the binary emitted in these old versions, but I just can't find the stuff this low. Anyone have any pointers or knowledge around Faircom DB internals or super low level reference info. Understanding what those 0xFA-0xFF enums would be handy too.

A: Okay, just to sorta wrap this up, here is where I landed.. in the end, I just parsed the binary myself into relevant records because I did not have the original schema files which would have been needed to use any of the Faircom stuff. The task of recreating the files would have taken just as much time as parsing the binary in C# since that is pretty straightforward.
I did see that the 0xFA records appeared to be 'real' records while the 0xFD records signified that they were 'deleted'. The original program did have the ability to 'revert' a file if you have changed it and not yet saved, so the faircom database structures allowed that to be pretty turnkey back in 1994.
Other general observations which may or may not be specific to my schema... I had the following data types... String, StringArray, ByteArray, Number
I created a little SchemaDefinition that looks like this..
schema = new CTreeSchema();
schema.Columns.Add(new CTreeColumn("Ordinal", CTreeColumnType.Number, 4));
schema.Columns.Add(new CTreeColumn("Unknown3", CTreeColumnType.Number, 4));
schema.Columns.Add(new CTreeColumn("Unknown4", CTreeColumnType.Number, 4));
schema.Columns.Add(new CTreeColumn("Name", CTreeColumnType.String, 0));
schema.Columns.Add(new CTreeColumn("ExtendedData", CTreeColumnType.StringArray, 0));

and then I parsed it using something like this...
public CTreeRecord(CTreeSchema schema, byte[] bytes)
    {
        _internalBytes = bytes;
        RecordTypeId = bytes[0];
        int byteIndex = 6;
        foreach(var i in schema.Columns)
        {
            int endIndex = 0;
            switch (i.Type)
            {
                case CTreeColumn.CTreeColumnType.String:
                    if (i.Length == 0)
                    {
                        //null terminated
                        endIndex = Array.IndexOf<byte>(bytes, 0x00, byteIndex);
                        i.Value = Encoding.ASCII.GetString(bytes.Skip(byteIndex).Take(endIndex - byteIndex).ToArray());
                        byteIndex += (1+ endIndex - byteIndex);
                    }
                    if (i.Length > 0)
                    {
                        //specific length
                        throw new NotSupportedException("Static Length String columns not supported.");
                        //byteIndex += i.Length;
                    }
                    break;
                case CTreeColumn.CTreeColumnType.StringArray:
                    List<string> headerStrings = new List<string>();
                    endIndex = Array.IndexOf<byte>(bytes, 0x00, byteIndex);
                    byte[] arrayBytes = bytes.Skip(byteIndex).Take(endIndex - byteIndex).ToArray();
                    byteIndex += (1 + endIndex - byteIndex);
                    List<byte[]> headerBytes = SplitByteString(arrayBytes, 0x01, false);
                    foreach (byte[] b in headerBytes)
                    {
                        headerStrings.Add(Encoding.ASCII.GetString(b));
                    }
                    i.Value = headerStrings;
                    break;
                case CTreeColumn.CTreeColumnType.ByteArray:
                    List<byte[]> byteArray = new List<byte[]>();
                    for (int a = 0; a < i.Length; a++)
                    {
                        endIndex = Array.IndexOf<byte>(bytes, 0x00, byteIndex);
                        byteArray.Add(bytes.Skip(byteIndex).Take(endIndex - byteIndex).ToArray());
                        byteIndex += (1 + endIndex - byteIndex);
                    }
                    i.Value = byteArray;
                    break;
                case CTreeColumn.CTreeColumnType.Number:
                    switch (i.Length)
                    {
                        case 2:
                            i.Value = BitConverter.ToUInt16(bytes, byteIndex);
                            break;
                        case 4:
                            i.Value = BitConverter.ToUInt32(bytes, byteIndex);
                            break;
                    }
                    byteIndex += i.Length;
                    break;
                case CTreeColumn.CTreeColumnType.Date:
                    throw new NotSupportedException("Date columns not supported.");
                    break;
            }
            Columns.Add(i);
        }
    }

    private List<byte[]> SplitByteString(byte[] bytes, byte splitValue, bool removeEmptyEntries)
    {
        List<byte[]> splitBytes = new List<byte[]>();
        int currentIndex = 0;
        while (currentIndex < bytes.Length)
        {
            int splitIndex = Array.IndexOf<byte>(bytes, splitValue, currentIndex);
            if (splitIndex >= 0)
            {
                //found one
                int currentLength = splitIndex - currentIndex;
                if (!(currentLength == 0 && removeEmptyEntries))
                {
                    splitBytes.Add(bytes.Skip(currentIndex).Take(currentLength).ToArray());
                    currentIndex += (1 + currentLength);
                }
                else
                {
                    currentIndex++;
                }
            }
            else
            {
                //not found, just take until end now..
                splitBytes.Add(bytes.Skip(currentIndex).Take(bytes.Length - currentIndex).ToArray());
                currentIndex += (bytes.Length - currentIndex);
            }

        }
        return splitBytes;
    }

All in all, it is pretty ugly and very specific to this application, but if someone has to deal with C Faircom database files, this might provide some sanity.


text:
Q: How to apply spark.sql into worker nodes combining with df.createOrReplaceTempView() When I executed the following codes,
df6.createOrReplaceTempView("table2")
def func(partition_id, r):
    flmgd=str(r.FNAME)+str(r.LNAME)+str(r.MNAME)+str(r.GENDER)+str(r.DOB)
    query="""
    SELECT PID, FNAMELNAMEMNAMEGENDERDOB
    FROM table2
    WHERE FNAMELNAMEMNAMEGENDERDOB=\"%s\"
    """%flmgd
    df=spark.sql(query)
    list1=df.select('FNAMELNAMEMNAMEGENDERDOB').rdd.collect()
    if list1 ==[]:
        ID=None
    else:
        ID=df.select(['PID']).collect()
    yield Row(**r.asDict(),PIDF=ID)
df3=df2.rdd.mapPartitionsWithIndex(func).toDF()

then I received the warning message

PicklingError: Could not serialize object: Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.

It looks like that the main issue is SparkContext is unable to be run in worker nodes. I googled but failed to find solutions. Would you mind helping me getting around this issue? Thank you.


text:
Q: When I try to implement appium-flutter-driver in java, the appium-flutter-finder dependency does not work someone knows how to fix it? I'm trying to implement appium-flutter-driver in an automation project, I'm trying to make a POC with the example that is in the repo https://github.com/truongsinh/appium-flutter-driver
When I made an mvn clean install the appium-flutter-finder dependency does not work with the next error message
Could not transfer artifact pro.truongsinh:appium-flutter-finder:pom:0.0.4 from/to saucelabs-repository (https://repository-saucelabs.forge.cloudbees.com/release): repository-saucelabs.forge.cloudbees.com: nodename nor servname provided, or not known

Does someone know which is my error? or if someone has some example with java I appreciated

A: I think pro.truongsinh:appium-flutter-finder is not in the Maven Repository because of that we can not use this one.
I have created an automation project to test a flutter app using the Appium Flutter Driver.
https://www.youtube.com/watch?v=v0IHGIFlIFQ&ab_channel=GihanWijesekara
You can download the project which I have created using https://github.com/gihanchandana46/AppiumFlutterDriver


text:
Q: How to create rtsp for multiple video by same port python? Is it possible to create rtsp for multiple videos by same port like rtsp://12.0.0.1:8554/test will hold one video and rtsp://12.0.0.1:8554/test2 will hold another video, and both ports will be same?
I've tried the code below by threading, but it create the rtsp for first thread second thread and rtsp doesn't get generated.  How do I create rtsp for multiple video by same port?
This is the code:
import cv2
import gi
import threading
gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import Gst, GstRtspServer, GObject

class SensorFactory(GstRtspServer.RTSPMediaFactory):
  def __init__(self, video,**properties):
    super(SensorFactory, self).__init__(**properties)
    self.cap = cv2.VideoCapture(video)
    self.number_frames = 0
    self.fps = 30
    self.duration = 1 / self.fps * Gst.SECOND  # duration of a frame in nanoseconds
    self.launch_string = 'appsrc name=source block=true format=GST_FORMAT_TIME ' \
                         'caps=video/x-raw,format=BGR,width=600,height=600,framerate={}/1 ' \
                         '! videoconvert ! video/x-raw,format=I420 ' \
                         '! x264enc speed-preset=ultrafast tune=zerolatency ' \
                         '! rtph264pay config-interval=1 name=pay0 pt=96'.format(self.fps)

def on_need_data(self, src, lenght):
    if self.cap.isOpened():
        ret, frame = self.cap.read()
        frame = cv2.resize(frame, (600, 600))
        if ret:
            data = frame.tostring()
            buf = Gst.Buffer.new_allocate(None, len(data), None)
            buf.fill(0, data)
            buf.duration = self.duration
            timestamp = self.number_frames * self.duration
            buf.pts = buf.dts = int(timestamp)
            buf.offset = timestamp
            self.number_frames += 1
            retval = src.emit('push-buffer', buf)
            print('pushed buffer, frame {}, duration {} ns, durations {} s'.format(self.number_frames,
                                                                                self.duration,
                                                                                self.duration / Gst.SECOND))
            if retval != Gst.FlowReturn.OK:
                print(retval)

def do_create_element(self, url):
    return Gst.parse_launch(self.launch_string)

def do_configure(self, rtsp_media):
    self.number_frames = 0
    appsrc = rtsp_media.get_element().get_child_by_name('source')
    appsrc.connect('need-data', self.on_need_data)

class GstServer(GstRtspServer.RTSPServer):
  def __init__(self,video,stream,**properties):
    super(GstServer, self).__init__(**properties)
    self.set_service("8012")
    self.factory = SensorFactory(video )
    self.factory.set_shared(True)
    self.get_mount_points().add_factory("/"+stream, self.factory)
    self.attach(None)

video ='/home/root1/Documents/test_videos/videoplayback.mp4'
stream = 'test'
stream1 = 'test1'

GObject.threads_init()
Gst.init(None)

server = threading.Thread(target=GstServer, args=(video,stream,)).start()
server1 = threading.Thread(target=GstServer, args=(video,stream1,)).start()
loop = GObject.MainLoop()
loop.run()


text:
Q: Is there an API to read Inbox including mail in subfolders in Microsoft Graph? Right now I can use these APIs to get or track mails in Inbox root folder.
GET /me/mailfolders/Inbox/messages
GET /me/mailFolders/Inbox/messages/delta

Is there an API that I can read all mails in Inbox including mail in subfolders in Inbox? Thanks

A: The approach I've taken is to do a sequence of requests:

*

*Find all descendant folders of the Inbox. To do this I list all Mail Folders then user parentFolderId to figure out which ones are descendants.

*Sync each descendant folder (/$batch is helpful here).
Hope that helps!


text:
Q: vectorized matrix list application in numpy the problem i am trying to solve is as follows. I am given a matrix of arbitrary dimension representing indices of a list, and then a list. I would like to get back a matrix with the list elements swapped for the indices. I can't figure out how to do that in a vectorized way:
i.e if z = [[0,1], [1,0]] and list = [20,10], i'd want [[20,10], [10,20]] returned.

A: When they both are np.array, you can do indexing in a natural way:
import numpy as np

z = np.array([[0, 1], [1, 0]])
a = np.array([20, 10])

output = a[z]
print(output)
# [[20 10]
#  [10 20]]


text:
Q: How to fix bad Double-Buffering I tried following a double buffering tutorial, and I really don't know what I did wrong. It works before then before I did the tutorial, but there is still and occasional flicker here and there. I have two files Game and gameLoop
Game:
import java.awt.Graphics;
public class Game extends gameLoop
{
    public void init()
    {
        setSize(854,480);
        Thread th = new Thread(this);
        th.start();
        offscreen = createImage(854,480);
        d = offscreen.getGraphics();
    }
    public void paint(Graphics g)
    {
        d.clearRect(0, 0, 854, 480);
        d.drawImage(disk, x, y, this);
        g.drawImage(offscreen , 0, 0, this);
    }
    public void Update(Graphics gfx)
    {
        paint(gfx);
    }
}

gameLoop
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class gameLoop extends Applet implements Runnable, MouseListener, MouseMotionListener
{
    public int x, y, counter, mouseX, mouseY;
    public Image offscreen;
    public Graphics d;
    public boolean up, down, left, right, pressed;
    public BufferedImage disk1, disk2, disk3, disk4, disk;
    public int ballSpeedX = -6;
    public int ballSpeedY = -3;

    public void run()
    {
        x = 400;
        y = 200;
        try {
            disk1 = ImageIO.read(new File("disk1.png"));
            disk2 = ImageIO.read(new File("disk2.png"));
            disk3 = ImageIO.read(new File("disk3.png"));
            disk4 = ImageIO.read(new File("disk4.png"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        while(true)
        {
            if(x >= (854 - 150))
            {
                    ballSpeedX = ballSpeedX * -1;
            }
            if(y >= (480 - 140))
            {
                    ballSpeedY = ballSpeedY * -1;
            }
            if(y < (0 - 10))
            {
                    ballSpeedY = ballSpeedY * -1;
            }
            if(x < (0- 10))
            {
                    ballSpeedX = ballSpeedX * -1;
            }

            x = x + ballSpeedX;
            y = y + ballSpeedY;

            counter ++;
            if(counter >= 4)
                counter = 0;

            if(counter == 0)
                disk = disk1;
            if(counter == 1)
                disk = disk2;
            if(counter == 2)
                disk = disk3;
            if(counter == 3)
                disk = disk4;

            System.out.println(counter);

            repaint();

            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseMoved(MouseEvent m) {}

    public void mousePressed(MouseEvent m)
    {

    }

    public void mouseReleased(MouseEvent m)
    {
        pressed = false;
    }

    public void mouseDragged(MouseEvent e) {
        PointerInfo a = MouseInfo.getPointerInfo();
        Point b  = a.getLocation();
        mouseX = (int)b.getX();
        mouseY = (int)b.getY();
        ballSpeedX = mouseX;
        ballSpeedY = mouseY;
    }
}

A: public void Update(Graphics gfx)
{
    paint(gfx);
}

Should be lower case, as you're trying to override the update(Graphics g) method in the Applet.
So it should be
@Override
public void update(Graphics gfx)
{
    paint(gfx);
}

As for changing the background, a background is simply a big rectangle that covers the screen and makes it a certain color. In your paint, you're doing clearRect, which clears the screen. Instead just switch that to fillRect after setting the color.
It might look something like
public void paint(Graphics g)
{
    //setColor to whatever you want
    //fillRect to cover the screen
}

When you're doing this though, one thing you have to remember is to not confuse your two graphics objects. As a concept, double buffering works by drawing to memory first (drawing it on an offscreen image) and then to the screen. You want to always draw onto this offscreen image, as it is much faster (and we lose the flicker).
So make sure you're doing imageGraphicsObject.setColor not screenGraphicsObject.setColor or imageGraphicsObject.fillRectnotscreenGraphicsObject.fillRect`. Otherwise you're no longer double-buffering.

A: There are a number of different types "double buffers".  The basic is a simple off screen image that you update and this gets painted to the screen instead.  If done right, painting the image is often faster then drawing graphics to the screen.
Another type is page flipping.  That is, you have an active buffer which is always rendered to the screen and a off screen/scratch buffer which is what you actually render to.  You then flip these buffers when you are ready to render the updates to the screen (this is closer to how film animation works).
The following example is a REALLY basic example of page flipping.

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Panel;
import java.awt.image.BufferedImage;
import static testdoublebuffer.TestDoubleBuffer.UPDATE;

public class AppletDoubleBuffer extends Applet {

    private BufferedPane pane;

    @Override
    public void init() {
        pane = new BufferedPane();
        setLayout(new BorderLayout());
        add(pane);
    }

    @Override
    public void start() {
        pane.start();
    }

    @Override
    public void stop() {
        pane.stop();
    }

    public class BufferedPane extends Panel {

        private BufferedImage activeBuffer;
        private BufferedImage scratch;
        private boolean running = false;

        public BufferedPane() {
        }

        public void start() {
            if (!running) {
                running = true;
                Thread thread = new Thread(new MainLoop());
                thread.setDaemon(true);
                thread.start();
            }
        }

        public void stop() {
            running = false;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        public void invalidate() {
            synchronized (UPDATE) {
                activeBuffer = null;
                scratch = null;
            }
            super.invalidate();
        }

        @Override
        public void update(Graphics g) {
            if (activeBuffer != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.drawImage(activeBuffer, 0, 0, this);
                g2d.dispose();
            }
        }

        public class MainLoop implements Runnable {

            private int delay = 1000 / 25;
            private int x = 0;
            private int velocity = 5;
            private int size = 10;

            public void update() {

                x += velocity;
                if (x + size >= getWidth()) {
                    x = getWidth() - size;
                    velocity *= -1;
                } else if (x <= 0) {
                    x = 0;
                    velocity *= -1;
                }

                if (getWidth() > 0 && getHeight() > 0) {
                    synchronized (UPDATE) {
                        if (scratch == null) {
                            scratch = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
                        }
                        Graphics2D g2d = scratch.createGraphics();
                        int y = (getHeight() - size) / 2;
                        g2d.setBackground(Color.BLUE);
                        g2d.clearRect(0, 0, getWidth(), getHeight());
                        g2d.setColor(Color.RED);
                        g2d.fillOval(x, y, size, size);
                        g2d.dispose();

                        // Flip the buffers...
                        BufferedImage tmp = activeBuffer;
                        activeBuffer = scratch;
                        scratch = tmp;
                    }
                }

            }

            @Override
            public void run() {
                while (running) {

                    long startTime = System.currentTimeMillis();

                    update();
                    repaint();

                    long duration = System.currentTimeMillis() - startTime;
                    if (duration < delay) {
                        try {
                            Thread.sleep(delay);
                        } catch (InterruptedException ex) {
                        }
                    }

                }
            }
        }
    }
}

I personally, would just skip using AWT and move to Swing which provides better/built in functionality for this type of thing.


text:
Q: object undefined javascript handlebars This works fine and returns the string which I pass to the function
    Handlebars.registerHelper('date', function (strng) {
    return strng;
    });

This tells me strng is undefined..
    Handlebars.registerHelper('date', function (strng) {
    return strng.substring(1,7);
    });

What am I doing wrong?
More context:
I am adding this to handlebars.js file.
I am invoking it with the following template:
Date Added: {{{date TriageRecord.DateAdded}}}

The first piece of code I added returns the string back to the template just fine.  When I add strng.substring(1,7) it errors out.
Documentation: Here


text:
Q: Stable homotopy of exceptional Lie groups Using Bott periodicity, we know the stable homotopy of all classical compact lie group. So I am wondering if a similar pattern exists for exceptional Lie groups.
Unfortunately, I couldn't find a result online. Is it because it is too easy or too difficult?
A relevant paper I found is "Homotopy Groups of Compact Lie Groups E6, E7, and E8" https://projecteuclid.org/download/pdf_1/euclid.nmj/1118797372, which we don't see a period yet.


text:
Q: I need to find the day of a date, i.e. monday, in python I need a programme which can find out the day of any date.
all I know is that: (4/4, 6/6, 8/8, 10/10, 12/12, and the last day of February) fall on. in 2012 all these dates fell on a wednesday

A: you want date.weekday()
date(2002, 12, 4).weekday() == 2
That shows that December 4th, 2002 was a Wednesday.
The date of the week is an integer where Monday is 0 and Sunday is 6.
http://docs.python.org/2/library/datetime.html

A: One liner:
date(2012, 4, 4).strftime('%A')
>>> Wednesday


text:
Q: Height issues in website I am creating a site for which I have created a structure but I am facing height issue in that. here is what I am expecting

but this is what I am getting

Below is the CSS:
html {height:100%!important;}
body {
    margin:0;
    font:12px/15px "Lucida Sans Unicode", "Lucida Grande", sans-serif;
    color:#8a8a8a;
    min-width:1000px;
    background:#fff;
    min-height:100%!important;
}

#wrapper {
    position:relative;
    min-height:100%;
    overflow:hidden;
    background:url(../images/wrapper.jpeg) repeat-y;
}
#content {
    float:left;
    width:100%;
    min-height:100%;
}

A: 100% is just getting set to 100% of the content in it , try using a pixel height instead
#content {
    float:left;
    width:100%;
    min-height:500px;
}

A: I would put a min-height in pixels on your wrapper. Since the #content is set to 100% height, it will fill all of the wrapper.
This way, if there is less content than needed to fill the full height of the browser, the page will add whitespace below your content to fill the browser height. I do this often when first building out a new page, since I don't have any content, but want to get an idea of how it will look when filling the browser window.
I would suggest doing something like this:
#wrapper {
    position: relative;
    min-height: 600px;
    overflow: hidden;
    background: url(../images/wrapper.jpeg) repeat-y;
}

You might want to adjust the min-height in pixels to fit your site- whatever it takes to make it fill the browser window.


text:
Q: DD-WRT DNSMasq DNS Caching, Forwarding, and Local Resolution I just flashed DD-WRT to my Linksys e4200 and I'm exceptionally pleased with it. I would like to use DNSMasq to cache DNS resolutions, forward results it does not have in its cache to Google's public DNS, and resolve local lookups. I have ensured that both of the Use DNSMasq for DHCP and Use DNSMasq for DNS options are checked and I have ensured a large cache-size with cache-size=10000.
However I need to set up forwarding to Google's public DNS and also set up local name resolution:

*

*To set up forwarding to Google, I can specify IP addresses in the three Static DNS fields in the DHCP section of the basic setup.

*

*If I choose this process than do I need to specify my own router as the first Static DNS with 192.168.1.1 or 127.0.0.1, or not?

*If I don't have to list my own router as a Static DNS then what do I put in the last field? Another DNS provider like OpenDNS?

*I think I can also specify DNS with a server=8.8.8.8 and server=8.8.4.4 option in the Additional DNSMasq Options box in the Services tab.

*

*Again do I have to specify my own router first as a server in order for it to use the local cache with server=192.168.1.1 or server=127.0.0.1?

Does it matter which of these methods I use?
Now concerning host names and local DNS.  I am having issues getting names to resolve to local IP addresses. I have seen really simple tutorials instructing that all one has to do is to enable local resolution with the Use DNSMasq for DNS option, and then specify names/IP addresses in the /etc/hosts/ file or by adding lines in the  address=/hostname/192.168.1.150 format to the configuration options box in the Services tab. Apparently the Local DNS option in the DNSMasq options section in the Services tab actually does not have anything to do with DNSMasq, at least according to this post. Does it matter if I either specify IP to host name mappings in the /etc/hosts file or with the address=/hostname/192.168.1.150 option in the Additional DNSMasq Options box? I cannot at this point get even the two entries already present in the host file to resolve let alone any other's I specify in the options box. This tutorial makes it sound very easy, should it work just like that? Is there something I am missing?
Thanks so much for your assistance! Please let me know if there is more information that you need!

A: So the stumbling block for me was the domain being used. It was set to WAN, which would force all of the machines into the WAN domain, and not a local LAN/WLAN domain, preventing lookups like hostname.local from working. Simple as that!

A: You needn't supply more than one DNS server if you don't wish.   As well, you ought not to enter your own server; if the name is cached, the server will hand it out; if it doesn't have the name cached, then it will go to one of the servers you've configured, if all's as you say.
Your DHCP server, however, should provide your internal DNS server's IP (not 127.0.0.1) so that your LAN's clients can take advantage of your local name server.


text:
Q: Javascript - LocalStorage para éste script...? ¿Es posible crear un LocalStorage para el siguiente script, teniendo en cuenta que debería guardar los parámetros del script-1 y script-2 aún cuando se recargue la página...?

NOTA:
Estoy aprendiendo JS, por cuanto no sé implementar un LocalStorage, aunque he mirado Este CodePen pero así y todo no logré implementarlo en mi script de práctica...

El script-1 suma y resta los clicks.
El script-2 clona los divs (ocultos) y los pega en el div "derecha".
Ver demo 100% funcional AQUI
Muchas gracias !!!...
// Script-1
var clicks=0;function clickME(){clicks += 1;document.getElementById("clicks").innerHTML=clicks}
var clicksdos=0;function clickME2(){clicksdos += 1;document.getElementById("clicksdos").innerHTML=clicksdos;

if (clicksdos === 1) {
document.getElementById("mostrar").style.display = "block";
  }
}
if (clicksdos === 0) {
document.getElementById("mostrar").style.display = "none";
  }
function restar() {
if (clicks>0) clicks -= 1;
document.getElementById("clicks").innerHTML=clicks;
  }
function restardos() {
if (clicksdos>0) clicksdos -= 1;
document.getElementById("clicksdos").innerHTML=clicksdos;
if(clicksdos === 0){
document.getElementById("mostrar").style.display = "none";
  }
};

// Script-2
$(document).ready(function() {
$("#comp-p1").click(function(){
$("#cont-p1").clone().appendTo(".derecha");
  });
// =============
$("#comp-p2").click(function(){
$("#cont-p2").clone().appendTo(".derecha");
  });
// =============
$("#comp-p3").click(function(){
$("#cont-p3").clone().appendTo(".derecha");
  });
});

A: La API de localStorage permite almacenar cadenas de texo.
Puedes almacenar los valores de click y clickdos en formato texto mediante el siguiente código:
localStorage.setItem('click', click);
localStorage.setItem('clickdos', clickdos);

Despues los podras obtener de vuelta y convertirlos a números enteros con
if ((localStorage.getItem("click")!=null) && (localStorage.getItem("clickdos")!=null))
{
click=parseInt(localStorage.getItem("click"));
clickdos=parseInt(localStorage.getItem("clickdos"));
}

Respecto al contenido del div .derecha, lo puedes almacenar mediante
localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML);

y obtenerlo de vuelta con
document.getElementsByClassName("derecha")[0].innerHTML=localStorage.getItem("html")

A: Tu código añadiendo localStorage sería el siguiente:
// Script-1
var clicks=0;function clickME(){clicks += 1;localStorage.setItem('clicks', clicks);document.getElementById("clicks").innerHTML=clicks}
var clicksdos=0;function clickME2(){clicksdos += 1;localStorage.setItem('clicksdos', clicksdos);document.getElementById("clicksdos").innerHTML=clicksdos;

if (clicksdos === 1) {
document.getElementById("mostrar").style.display = "block";
    }
}
if (clicksdos === 0) {
document.getElementById("mostrar").style.display = "none";
    }
function restar() {
if (clicks>0) clicks -= 1;
localStorage.setItem('clicks', clicks);
document.getElementById("clicks").innerHTML=clicks;
    }
function restardos() {
if (clicksdos>0) clicksdos -= 1;
localStorage.setItem('clicksdos', clicksdos);
document.getElementById("clicksdos").innerHTML=clicksdos;
if(clicksdos === 0){
document.getElementById("mostrar").style.display = "none";
    }
};

// Script-2
$(document).ready(function() {
  $("#comp-p1").click(function(){
    $("#cont-p1").clone().appendTo(".derecha");
    localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML);
  });
  // =============
  $("#comp-p2").click(function(){
    $("#cont-p2").clone().appendTo(".derecha");
    localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML);
  });
  // =============
  $("#comp-p3").click(function(){
    $("#cont-p3").clone().appendTo(".derecha");
    localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML);
  });

  if ((localStorage.getItem("clicks")!=null) && (localStorage.getItem("clicksdos")!=null))
  {
    clicks=parseInt(localStorage.getItem("clicks"));
    clicksdos=parseInt(localStorage.getItem("clicksdos"));
    document.getElementById("clicks").innerHTML=clicks;
    document.getElementById("clicksdos").innerHTML=clicksdos;
  }

  if (localStorage.getItem("html")!=null)
  {
    document.getElementsByClassName("derecha")[0].innerHTML=localStorage.getItem("html")
  }

});

Saludos


text:
Q: do I need to install plotly even though I am calling cdn in html? I am using flask to build online app. I am grabbing user input using d3.js then send it off to app.py which will use this input to make an api call and grab appropriate data then it will return jsonfied data back to javascript for rendering plot in correct html tag however it keeps on giving me error: Error: DOM element provided is null or undefined
app.py:
import os
from flask import Flask, render_template, jsonify, request, redirect, url_for
from alpha_vantage.timeseries import TimeSeries
import plotly
# import plotly.plotly as py
# import plotly.graph_objs as go

app = Flask(__name__)

api_key = "ssdqwjhwq"

# This will run upon entrance
@app.route("/")
def home():
    return render_template("index.html")

@app.route("/stockchart/")
def stock_data(label):
    ts = TimeSeries(key=api_key, output_format='pandas')
    df, meta_deta = ts.get_daily(label, outputsize="full")
    df.columns = ["open", "high", "low", "close", "volume"]
    data = [{"dates":list(df.index.values)},
            {"close": list(df.close)}]
    return jsonify(data)

if __name__ == "__main__":
    app.run()

my html code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Stock Screener</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Stock Screener

Interactive chart with predictions using machine learning

        <form>
            Enter stock label

            <input type="text" id="stockInput" name="stock_label" placeholder="Label">

            <input type="submit" value="submit" id="stocklabelsubmit">
        </form>

And my javascript
// give reference to submit button
// Upon click, submitted function will run

d3.select("#stocklabelsubmit").on("click", submitted);

function submitted(){
    d3.event.preventDefault();

    // grab label inputted.
    var inputted_label = d3.select("#stockInput").node().value;
    // refresh input box
    d3.select("#stockInput").node().value = "";
    // pass inputted_label to plot function
    Plot(inputted_label);
};

function Plot(input){
    var url = `/stockchart/${input}`
    // when this function is called call /stock_data function!!
    // data is what is returned from python
    d3.json(url).then(function(data){
        console.log(data);
        console.log(data[0]);
        console.log(data[0].dates);
        var trace = {
            x:data[0].dates,
            y:data[1].close,
            type: "scatter"
        };

        var layout {
            title:"Stock chart",
            xaxis:{
                title:"dates"
            },
            yaxis:{
                title:"closing price"
            }
        };
        var data = [trace];
        // var loc_plot = document.getElementById("chart");

        Plotly.newPlot("chart", data, layout);
    });
};

Error tells me that there is an error in js line 33 = Plotly.newPlot("chart", data,layout); I am not sure how I can fix this everything seems to work fine until plotting as it console logs properly. Any help? Thanks!

A: According to the documentation, the graphDiv argument of Plotly.newPlot() refers to either a DOM node or string ID of a DOM node.
In your code above, it looks like you are providing neither. You are providing the class of a DOM node, but not an actual DOM node or ID of a DOM node. This probably explains the error you're getting regarding the null or undefined DOM node.
Try changing
 to
 (or some other ID), or get the node using Element.querySelector() and pass that in for the DOM node instead and see if that works.


text:
Q: Create a Shared Object in Red5 Server with Java but without Actionscript or Flex technology I'm looking for a way to create a Remote Shared Object in Red5 Server (installed on a server machine) only using Java technology. The shared object can be any thing (simpler is better) because my purpose is just a feasibility study. The problem is that I am a novice in Java and I'm having a hard time .. On Internet there are in fact many tutorials that build applications on Red5, but using Actionscript etc..
Can anyone give me some advice to realize a mini project in Eclipse to create and modify the shared object? Thank you very much and sorry for my English :)

A: I've build a RTMPClient for doing some load tests recently:
https://svn.apache.org/repos/asf/incubator/openmeetings/trunk/singlewebapp/src/org/apache/openmeetings/test/rtmp/LoadTestRtmpClient.java
It will only establish the RTMP connection and do some remote calls. For ceating a shared object you will probably need to extend the RTMPClient library.
Sebastian