text:
Q: What is the 2 W resistance in the regulator input for?
What is the purpose of R1 (120 Ω, 2W)?

*

*When the voltage drops from 24 V to 5 V, a lot of heat is generated in the 78L05.

*Put a resister on the 78L05's input. Say we need 5 V, 100 mA output from the 78L05.

*What is the resistor for?

*

*limit current

*limit voltage

A: It performs two functions. If an input transient comes along it will be clamped by the TVS with excessive voltage dropped across the resistor.
It also reduces the maximum dissipation by dropping voltage.
However it should be noted that this is a rather marginal design. The TVS doesn't really start to clamp until the input voltage is well over 30V which is the stated maximum input and also the absolute maximum input voltage for the L78L05.
At the stated maximum output current of 100mA there will be about 105mA through the resistor and it will drop 12.6V and dissipate 1.3W (acceptably within the 2W rating for many purposes).
The regulator, with 30V in, will dissipate about 1.8W so the junction will be about 100°C hotter than ambient with 6cm^2 of copper heatsink. Chance are the junction will be hotter than absolute maximum even in a cool office environment, and if Ta gets much hotter than that, and there's an enclosure keeping in the 1.3W from the resistor and the 1.8W from the regulator the semiconductor will be well into danger territory.
So there's two ways for this circuit to die catastrophically.


text:
Q: How to give the user options to create new columns in the database Is there a by the book way of allowing a user to add columns to a sites database table. For example, if the site was about animals, one user might want to have stats like, 'walks per week' and 'type of food' about their breed of dog. but another user might want to keep track of how much milk their goat is producing.
So if i have an 'Animal' class with come basic info. like, 'breed', 'animal name', 'DOB', 'DOD'. But then, in the front end have a form that will allow the users to add all the other columns they would like.
Is this possible? hope I've explained it well enough.

A: @WillemVanOnsem already mentioned some good options in the comments. I'm going to chime in to say that modifying your schema's structure based on user input is an extremely bad idea and opens another avenue for abuse... for Django in particular, it means you either can't use the ORM's migration facilities for some of your models, or you probably have to do some really awful automation.
If your animal types are well-defined and consistent, you can consider (carefully) making them subclasses of the Animal model. Otherwise, this would be the simplest way to handle it (note that the following isn't valid code, it needs required arguments for the field types):
class AnimalAttribute(models.Model):
    animal = models.ForeignKey(Animal)
    name = models.CharField()
    value = models.CharField()

This works best if attributes aren't shared, e.g. users are directly inputting their animals' names and attributes, not picking from an existing list.
If you need to provide a normalized list of attributes users can pick from (actual EAV, which is something you should avoid if possible, since it moves some of your data structure from code into the data persistence layer), doing that in your models is a little more complex. For example:
class Species(models.Model):
    name = models.CharField()

class SpeciesAttribute(models.Model):
    species = models.ForeignKey(Species)
    name = models.CharField()

class Animal(models.Model):
    name = models.CharField()
    species = models.ForeignKey(Species)

class AnimalAttributeValue(models.Model):
    animal = models.ForeignKey(Animal)
    attribute = models.ForeignKey(SpeciesAttribute)
    value = models.CharField()

redpajama_set_name: RedPajamaStackExchange


text:
Q: 2D Camera using OpengGl I am coding a little game in 2D and I want to implement a camera that follow the characacter when he moves.
Unfortunately with my implementation my result when I move the character is a black screen ...  Can you help me if you know where my mistake is ? I am new to openGl.
Here is my code with the main code :
int main(int argc, char** argv) {

glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(300, 350);

glutCreateWindow("Map");
init();
glutDisplayFunc(drawMap);
glutSpecialFunc(specialkeyboard);

glutIdleFunc(moveObjects);
glutMainLoop();
return 0;
}

The function to draw the map :
    void drawMap()
    {
//int x=0;
//Initialisation
glClear (GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluOrtho2D(0.0,500.0,0.0,500.0);
glViewport(0,0,1000,700);

// drawing the rest of the map //

And here the camera code, I think the problem come from the camera function.
void camera() {

float left = C.x - (300/2.0);
float  bottom = C.y - (350/2.0);

float  right = left + 300;
float  top = bottom + 350;

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(left, right, bottom, top);
glMatrixMode(GL_MODELVIEW);

}

And the function specialkeyboard :
void specialkeyboard(int key, int x, int y)
{
switch (key) {
    case GLUT_KEY_UP:
        C.y += 2;
        camera();
        break;
    case GLUT_KEY_DOWN:
        C.y -= 2;
        camera();
        break;
    case GLUT_KEY_RIGHT:
        C.x += 2;
        camera();
        break;
    case GLUT_KEY_LEFT:
        C.x -= 2;
        camera();
        break;
}
glutPostRedisplay();
}

Thank you very much for your help :)
EDIT
So now the problem is that the map move on the wrong direction, it is moving with the character but not following him. (The red circle is the character)
Main code :
int main(int argc, char** argv) {

glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 700);
glutCreateWindow("Map");
init();
glutDisplayFunc(drawMap);
glutSpecialFunc(specialkeyboard);

glutIdleFunc(moveObjects);
glutMainLoop();
return 0;
}

Drawing the map :
void drawMap()
{
std::cout << "Debut Drawmap " << std::endl;
//TRY
glClear (GL_COLOR_BUFFER_BIT);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D(0.0,500.0,0.0,500.0);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}

//drawing the map//

// Red circle
C.DrawCircle();
camera();
glutSwapBuffers ();
std::cout << "Fin drawmap " << std::endl;
}

And the camera :
  void camera(){
  glViewport(C.x,0,1000,700);
  }

A: As soon as your camera() function is called, you are applying two glOrtho() matrices, which is certainly not what you want.
The fixed fuinction GL will apply the product Projection * ModelView to each vertex that you draw. Initially, Projection will be identity, so it will have no effect, and you are setting ModelView to Ortho2D(0.0,500.0,0.0,500.0).
When you draw in that state, a vertex coordinate of x=0 will be mapped to the left edge of the viewport, and x=500 will be mapped to the right one. However, that is only the case because the GL will always apply the viewport transform after the matrices have been applied. What Ortho2D actually does is create scale and translation  so that the viewing voulme in eye space is transformed to a cube from -1 to 1 along all dimensions in NDC space.
Now when you also set the projection matrix to ortho, you will have the following effect:
ModelView will transform x=0 to -1 and x=500 to 1. And then, the projection is applied which will map your camera-based left to -1 and left + 300 to 1. If your C.x and C.y where both zero at that time, you would have the effect that you image would be scaled down to 1/300 and 1/350 of the original size. But since you at least increase or decrease your camera position by two units - which is now exactly the size of your original image region due to the first Ortho2D - you guarantee that that point is not on the screen any more at all.
Having said all that, there ae several advices I can give:

*

*Do never put an ortho matrix onto the ModelView stack. It is not meant to be used that way.

*Just keep a single ortho call, on the projection matrix, and dependent on your camera location.

*Forget everything about glMatrixMode, gluOrtho2D and so on. These are deprecated in the GL since a decade. Modern core profiles of OpenGL do not support that functions at all. If you start learning OpenGL nowadays, don't ever bother with that old cruft which last time made sense in the previous millenia. Learn the proper way by using the programmable pipeline.


text:
Q: How would caching with this GET request work? I recently heard that my GET requests would be cached and im having questions about what that would mean to my case.
I send a GET request using javascript:
var ajax = new XMLHtpprequest();
ajax.open("GET", "https://my-website.com/somepage.php");
ajax.onload = function () {
    // do something depending on the echoed response
}
ajax.send();

And in my somepage.php :
$wp_user_id = get_current_user_id();
// echo something depending on the $wp_user_id back

My understanding is that when different logged in users open the ajax-call they get the last cached ajax call, which could be incoherent with their individual wp_user_id.
I use wordpress without plugins on my webserver.
My questions:

*

*Am i right with this or have i understand something wrong about caching?

*If im wrong whats the best way to stop this behaviour?
Thanks for any answers in advance!

A: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response
you just need to write a response handler. (and listen for onreadystatechange)
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    responseHandlerCallback(xhr.response);
  }
}

to prevent caching of requests, use a cachebuster
https://yourdomain.com/web-api/handler.php?cb=ej0d293dj


text:
Q: Probability - exponential distribution question I got the following question:
There are two cashiers in a supermarket, the waiting time for each is of exponential distribution with parameters $\lambda_1$ and $\lambda_2$ accordingly.
Person 1 arrives at cashier 1 at 9:00.
Person 2 arrives at cashier 2 at 9:01.
Person 3 arrives at 9:03 with both cashiers still being occupied, and flips a fair coin by which he decides to wait for cashier 1 or 2 (after choosing a cashier, he is only waiting for that one).
If it is known that at 9:06, his turn still hasn't arrived yet, what is the probability that at 9:08 it still wouldn't be his turn?
I tried to solve it this way:
Y = overall waiting time for person 3
X = 1 if cashier 1 was chosen, 0 else
$P(Y > 3+2 | Y > 3) = P(Y > 2) = P(Y > 2 | X = 1) \cdot P(X = 1) + P(Y > 2 | X = 0) \cdot P(X = 0 ) = e^{-2\lambda_1} \cdot 0.5 + e^{-2\lambda_2} \cdot 0.5$
Apparently my solution is wrong but I don't understand why. If you could please point to where I'm mistaken and how could it be solved correctly that would be great.

A: When you write $P(Y>3+2 \mid Y>3) = P(Y>2)$, you assume that $Y$ is a memoryless distribution: an exponential. But $Y$ is not an exponential: $Y$ is the mixture of two exponentials with different rates! So we can't make this simplification yet.
Instead, consider the following four cases:

*

*$X=1$ and $3 < Y < 5$: this happens with probability $\frac12(e^{-3\lambda_1} - e^{-5\lambda_1})$.

*$X=1$ and $Y > 5$: this happens with probability $\frac12 e^{-5 \lambda_1}$.

*$X=2$ and $3 < Y < 5$: this happens with probability $\frac12(e^{-3\lambda_2} - e^{-5\lambda_2})$.

*$X=2$ and $Y > 5$: this happens with probability $\frac12 e^{-5 \lambda_2}$.

These are the probabilities before we are told that $Y>3$. But when we are given that $Y>3$, we know that exactly one of these four cases happens. So we should scale up these four probabilities so that they add up to $1$. They become, respectively:
$$
   \frac{e^{-3\lambda_1} - e^{-5\lambda_1}}{e^{-3\lambda_1} + e^{-3\lambda_2}},\;
   \frac{e^{-5\lambda_1}}{e^{-3\lambda_1} + e^{-3\lambda_2}},\;
   \frac{e^{-3\lambda_2} - e^{-5\lambda_2}}{e^{-3\lambda_1} + e^{-3\lambda_2}},\;
   \frac{e^{-5\lambda_2}}{e^{-3\lambda_1} + e^{-3\lambda_2}}.\;
$$
To get the probability that $Y>5$, we just want to add up the second and fourth case, getting
$$
   \frac{e^{-5\lambda_1} + e^{-5\lambda_2}}{e^{-3\lambda_1} + e^{-3\lambda_2}}.
$$

A: Firstly, I'd like to point out that the exponential distribution is not totally realistic for the time $1$ person takes to check out. It is memoryless, meaning that after a person waits $x$ minutes, the remaining time $y$ they'll need to wait is independent of $x$. $y$ will be the same whether $x$ is $1$ minute or $10$ minutes. So the "If it is known that" clause should be jumping out at you. At the outset, the exponential distribution can be used to forecast the time it will take for something to happen, but once some time has passed, the forecast changes.
If it is known that at 9:06, his turn still hasn't arrived yet, then that is $t=0$ for our equations. The probability that at 9:08 it still wouldn't be his turn is the inverse of the probability that it would be, which is the $\text{OR}$ junction of the two exponential distributions. (The $\text{OR}$ of two probabilities is their sum minus the probability of both occuring.)
$$Pr(X \leq 2 \text{ min}) = 1- e^{-(2/(\lambda_1 \text{in minutes}))} + 1- e^{-(2/(\lambda_2 \text{in minutes}))} - [(1- e^{-(2/(\lambda_1 \text{in minutes}))}) \cdot (1- e^{-(2/(\lambda_2 \text{in minutes}))})]$$


text:
Q: Google Analytics Android SDK V4 confusion I have been using Google Analytics SDK for Android V3 in my apps so far, and it has been working fine (My Apps are supported on Android 3.0 and above). Now the V3 has been deprecated, and the latest one is Google Analytics SDK v4 for Android.
I was able to get it to work by reading the official documentation along with this blog post. But I still have a few questions:
1) What is a Global Tracker and an App Tracker? What is the concept behind it? If I have more than one Android Apps, then whats the difference. Should all my apps have the same Global Tracker? is it 'global' in that sense? I am a little clueless here.
2) The V4 uses Google Play Services V4.3 and above, and does not have a Standalone Library like V3 had. So, is it safe to remove the V3 library jar file and the code? The Google Developers page does say this:

The SDK can be used and will work on devices that do not have Google
  Play Services. In this case the SDK will will automatically fall back
  to local dispatching.

Also

In general, devices running Android 2.3 (Gingerbread) or later and
  have the Google Play Store app installed receive updates within a few
  days. This allows you to use the newest APIs in Google Play services
  and reach most of the devices in the Android ecosystem (devices older
  than Android 2.3 or devices without the Google Play Store app are not
  supported).

So with V4, will my app tracking still work on all the devices which may not have the Google Play Services V4.3 or above? If not, then will the app crash on account of not finding a particular class needed by the analytics code? Or, Is it safe to assume that all devices with Android 2.3+ will be compatible with Analytics V4?
Note: The Google Play Services documentation page does show how to check if Google Play Services are available. But I don't want to prompt the user unnecessarily as the analytics does not affect the functionality of my app. Also, I can put a check, but I don't want to miss on any analytics information.

A:
1) What is a Global Tracker and an App Tracker? What is the concept
  behind it? If I have more than one Android Apps, then whats the
  difference. Should all my apps have the same Global Tracker? is it
  'global' in that sense? I am a little clueless here.

They are pretty much the same thing. Just configured in different ways to serve as example. You might want to use both if you have several apps, so that you have each app tracked to it's own Google Analytics Property and also to a global property that rolls up all data. But the tracker objects are exactly the same. Most of the time you just use one or the other. So ignore that part from the docs, and read them as examples only on how to setup trackers. Choose one and stick to it. I would recommend the xml configuration method, which is cleaner.

2) The V4 uses Google Play Services V4.3 and above, and does not have
  a Standalone Library like V3 had. So, is it safe to remove the V3
  library jar file and the code? The Google Developers page does say
  this

Yes. Safe to remove. Any Android device above 2.2 will have Play Services installed. You might want to check if it's not available to just skip tracking altogether in your app.

A:
1) What is a Global Tracker and an App Tracker? What is the concept
  behind it? If I have more than one Android Apps, then whats the
  difference. Should all my apps have the same Global Tracker? is it
  'global' in that sense? I am a little clueless here.

Global tracker is meant to track things that you'd like to track across different apps of yours whether they're different apps altogether or same app for different platforms. You could just keep an app tracker and not use any global tracker if you don't need it.

2) The V4 uses Google Play Services V4.3 and above, and does not have
  a Standalone Library like V3 had. So, is it safe to remove the V3
  library jar file and the code?

Yes, V3 library jar is not needed anymore. Instead of using the Analytics V3 library you're using the Play Services library now. The main difference is that instead of your app dispatching the data (via the Analytics V3 library), the dispatch will happen via Play Services APK to which the Play services library present in your app will pass the data. In case, the required Play Services APK is not available on the device, the Play services library will fall back to local dispatching meaning instead of Play Services APK dispatching the data your app will directly dispatch the data like it used to do in V3 and before.
What Analytics becoming part of Play services 4.3 means to me is:

*

*Google Analytics becomes first class citizen on Android. Play services is more popular than the standalone Analytics library and I expect more people start using GA with this change.

*Dispatching becoming a part of Play Services APK will be able to get faster improvements because of automatic updating of the APK.

There are other enhancements in the API itself (Global tracker, etc.) but they don't have anything to do with Analytics becoming part of the Play services.


text:
Q: How to join two lists? (Full code available at:  https://dotnetfiddle.net/tdKNgH)
I have two lists that are associated by ParentName and I would like to join them in a specific way.
class Parent
{
    public string ParentName { get; set; }
    public IEnumerable<string> ChildNames { get; set; }
}

class Child
{
    public string ParentName { get; set; }
    public string ChildName { get; set; }
}

var parents = new List<Parent>()
{
    new Parent() {ParentName = "Lee"},
    new Parent() {ParentName = "Bob"},
    new Parent() {ParentName = "Tom"}
};

var children = new List<Child>()
{
    new Child() {ParentName = "Lee", ChildName = "A"},
    new Child() {ParentName = "Tom", ChildName = "B"},
    new Child() {ParentName = "Tom", ChildName = "C"}
};

I'm using a foreach loop to join, and it works, but is there a more succinct way to do it?
foreach (var parent in parents)
{
    var p = parent; // to avoid foreach closure side-effects
    p.ChildNames = children.Where(c => c.ParentName == p.ParentName)
                           .Select(c => c.ChildName);
}

Here's what the resulting parents list would look like:
Parent Children
------ --------
Lee    A
Bob    (empty)
Tom    B,C

A: You can add an extension method for enumerables:
public static void Each<T>(this IEnumerable<T> source, Action<T> action)
{
    if (action == null)
        return;
    foreach (T obj in source)
        action(obj);
}

And then do:
parents.Each(p => p.ChildNames = children.Where(c => c.ParentName == p.ParentName)
                                         .Select(c => c.ChildName));

A: You could do a group join. LINQ isn't meant to update, though. So I'm not sure whether this would actually get you anywhere useful.
IEnumerable<Parent> parents = ...;

var parentsWithChildren = parents.GroupJoin(children,
                                            c => c.ParentName,
                                            c => c.ParentName,
                                            (a, b) => new
                                                      {
                                                          Parent = a,
                                                          ChildNames = b.Select(x => x.ChildName)
                                                      });

foreach (var v in parentsWithChildren)
{
    v.Parent.ChildNames = v.ChildNames;
}

This would certainly help if all you were given were parent names and children, rather than full Parent objects, since then you could just group join that collection to the child names, and create instances of parents where I create an anonymous type ((a, b) => new { ... }). But since I'm assuming your Parent objects would realistically hold more than just a name and that this is just an example, this seems like your best bet.

A: Consider calling the name of a parent as Parent.Name instead of Parent.ParentName(a parent's parent?), Child has the same problem...
class Parent
{
    public string Name { get; set; }
    public IEnumerable<string> ChildrenNames { get; set; }
}

class Child
{
    public string ParentName { get; set; }
    public string Name { get; set; }
}

You can completely avoid foreach by creating parentNames array first:
var parentNames = new[] { "Lee", "Bob", "Tom" };
var allChildren = new List<Child>()
{
    new Child() {ParentName = "Lee", Name = "A"},
    new Child() {ParentName = "Tom", Name = "B"},
    new Child() {ParentName = "Tom", Name = "C"}
};

Such that the parents are constructed entirely by LINQ without any side-effects (no updates to any variables), and it should be very simple:
var parents =
    from parentName in parentNames
    join child in allChildren on parentName equals child.ParentName into children
    select new Parent { Name = parentName, ChildrenNames = children.Select(c => c.Name) };

A: Given that LINQ is based on functional principles, side effects are generally a big no-no (and also the reason for why there's no foreach method).
I therefore suggest the following solution:
var parents = new List<Parent>()
{
    new Parent() { ParentName = "Lee" },
    new Parent() { ParentName = "Bob" },
    new Parent() { ParentName = "Tom" }
};

var children = new List<Child>()
{
    new Child() { ParentName = "Lee", ChildName = "A" },
    new Child() { ParentName = "Tom", ChildName = "B" },
    new Child() { ParentName = "Tom", ChildName = "C" }
};

var parentsWithChildren = parents.Select(x => new Parent
{
    ParentName = x.ParentName,
    ChildNames = children
        .Where(c => c.ParentName == x.ParentName)
        .Select(c => c.ChildName)
});

foreach (var parent in parentsWithChildren)
{
    var childNamesConcentrated = string.Join(",", parent.ChildNames);

    var childNames = string.IsNullOrWhiteSpace(childNamesConcentrated)
        ? "(empty)" : childNamesConcentrated;

    Console.WriteLine("Parent = {0}, Children = {1}", parent.ParentName, childNames);
}

The solution above, do not modify the Parent objects of the collection parents by setting their ChildNames. Instead it creates a new set of Parents with their respective ChildNames.

A: You can use ToLookup for best performance with a little memory penalty:
 var clu = children.ToLookup(x => x.ParentName, x => x.ChildName);
 parents.ForEach(p => p.ChildNames = clu[p.ParentName]);


text:
Q: Usage of sentence after "as" Can i use a sentence after "as" or "in the way" as is the case with sentences below.
1) This sentence can be translated as "they will never come again" .
2) This sentence can be translated in the way that "they will never come".

A: The most natural use is

This sentence can be translated as "they will never come again"

Your alternative

This sentence can be translated in the way that "they will never come".

would be better as

A way that this sentence can be translated is "they will never come".


text:
Q: Is it possible to add a button in " google maps activity" to pass control to another activity? I am new to android, i want to add the Google map for displaying users current location, i have done it with Google maps  activity,.Now what i need is, i have to enable an option to input a destination ,so i want to add a button in that map layout.Is it possible?if possible how can i add this.I selected this layout.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"
tools:layout="@layout/abc_list_menu_item_radio" />

A: yes for that take one relative layout and put the fragment and your button in the relative layout.
Try this code may be it will help you..
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

   <fragment xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/map"
     android:name="com.google.android.gms.maps.SupportMapFragment"
     android:layout_width="match_parent"
     android:layout_height="500dp"
     tools:context=".MapsActivity"
     tools:layout="@layout/abc_list_menu_item_radio" />

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />
</RelativeLayout>


text:
Q: HashCode for a class in class diagram I am trying to create class diagrams through code. Since CD files are XML files, it should be straight way to generate the files from classes. But the problem is I don't know how to get the hash code to embed in the type identifier.
Below is the XML generated by VS for a class.
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
  <Class Name="NVTest.Program" Collapsed="true">
    <Position X="0.5" Y="0.5" Width="1.5" />
    <TypeIdentifier>
      <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAA=</HashCode>
      <FileName>Program.cs</FileName>
    </TypeIdentifier>
  </Class>
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>

Assuming that the hashcode is a base64 string, I tried to generate it from class def. as
Convert.ToBase64String((BitConverter.GetBytes(typeof(Program).GetHashCode())))

but the result is:  nJ4uAA==
So, how to generate the HashCode?
Thanks

A: While I don't know how that hashcode is generated, not having the HashCode element in .cd files doesn't seem to make a difference to the Class Diagram viewer. So you may try generating those files without any HashCode.

A: Just uninstall Class Designer from Visual Studio\Invidual components\Code tools then you can get hashcode from you class file.


text:
Q: How to define unicode ranges by properties/identifiers in c++ for PEGTL With PEGTL (https://github.com/taocpp/PEGTL), which is a template based C++11 header-only PEG library, I can define ranges for unicode characters like this:

*

*utf8::range<0x0, 0x10FF> //All UTF8 Characters

*utf8::range<0x41, 0x5A, 0x61, 0x7A> //UTF8 0x41-0x5A[A-Z] and 0x61-0x7A[a-z]

Now with UTF8 there is this properties categorisation (https://en.wikipedia.org/wiki/Unicode_character_property#General_Category) with which I could do something like [:Lu:] or [:ID_Start:] and get a set/range of characters.
Now, since I'm working with c++ templates, I need those ranges at compile time. In my opinion I have the following options:

*

*Discover that PEGTL has itself the possibility to look up [:ID_Start:] or [:Lu:]

*Find a c++ preprocessor library, that allows such queries at compile time

*Get an Application/Online Service, where I can perform those queries and get ranges (as shown above), which I can then paste in my code.

This also represents the order of the solutions I prefer.

A: The PEGTL uses rules to match characters, not return sets of characters. If you'd like to match characters with certain Unicode character properties, you could create a custom rule and implement it with the help of some Unicode library, e.g. ICU. It provides methods to test codepoints for various properties, see this link.
Here's a complete example program:
#include <iomanip>
#include <iostream>

#include <unicode/uchar.h>

#include <tao/pegtl.hpp>

using namespace tao::TAO_PEGTL_NAMESPACE;  // NOLINT

namespace test
{
   template< UProperty P >
   struct icu_has_binary_property
   {
      using analyze_t = analysis::generic< analysis::rule_type::ANY >;

      template< typename Input >
      static bool match( Input& in )
      {
         // this assumes the input is UTF8, adapt as necessary
         const auto r = internal::peek_utf8::peek( in );
         // if a code point is available, the size is >0
         if( r.size != 0 ) {
            // check the property
            if( u_hasBinaryProperty( r.data, P ) ) {
               // if it matches, consume the character
               in.bump( r.size );
               return true;
            }
         }
         return false;
      }
   };

   using icu_lower = icu_has_binary_property< UCHAR_LOWERCASE >;
   using icu_upper = icu_has_binary_property< UCHAR_UPPERCASE >;

   // clang-format off
   struct grammar : seq< icu_upper, plus< icu_lower >, eof > {};
   // clang-format on
}

int main( int argc, char** argv )
{
   for( int i = 1; i < argc; ++i ) {
      argv_input<> in( argv, i );
      std::cout << argv[ i ] << " matches: " << std::boolalpha << parse< test::grammar >( in ) << std::endl;
   }
}

Now I can compile and run it:
$ g++ -std=c++11 -pedantic -Wall -Wextra -Werror -O3 -Ipegtl/include icu.cpp -licuuc -licudata -o icu
$ ./icu Ďánîel DánÎel
Ďánîel matches: true
DánÎel matches: false
$

EDIT: I've added the ICU rules (lots of them) to the PEGTL. As they require ICU, an external dependency, I've put them in the contrib-section.


text:
Q: Error closing frame by clicking "x" close icon on selenium webdriver I am struggling to click on "x" close icon displayed on a frame. I am able perform all other operations on the frame but once i save the data on frame i need to close the frame by "x" close icon at the top of the frame. below is the html code from the frame along with the code I am trying to write to close the frame which fails with the error
Error
====
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: The given selector //*[contains(concat(' ', normalize-space(@class), ' '),' x-tool-close '] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //*[contains(concat(' ', normalize-space(@class), ' '),' x-tool-close '] because of the following error:
SyntaxError: The expression is not a legal expression.

HTML Code
=========

Webdriver Code
===========

    Driver.switchTo().frame(0); // works
    Driver.findElement(By.id("serviceButton_bottom")).click(); //// works
    Driver.findElement(By.xpath("//*[contains(concat(' ', normalize-space(@class), ' '),' x-tool-close ']")); //Fails

Selenium finds the close icon with above mentioned xpath

A:  Driver.findElement(By.className('x-tool-close')).click()

A: I'd the same kind of issue..
Sometimes iframe close button will have a reference in main DOM.
try switching back to main window and close.
    driver.switchTo().defaultContent();
//then write your code to close that iframe


text:
Q: Help with exercise.sty counter not shown incremented I'm using exercise.sty and have two Exercise counters I'm trying to use, one for Examples with in a chapter, and one for Problems for the chapter.  Here's an example:
\documentclass[]{scrreprt}
\usepackage[]{exercise}
\usepackage[svgnames]{xcolor}
\usepackage[]{chngcntr}
\newcounter{Example}
\counterwithin{Example}{chapter}
\counterwithin{Exercise}{chapter}

\newcommand{\makeproblem}[3]{%
\begin{Exercise}[ title={#1}, label={#2} ]%
#3%
\end{Exercise}%
}

\newcommand{\makeexample}[3]{%
\begin{Exercise}[ title={#1}, label={#2}, name={Example}, counter={Example} ]%
#3%
\end{Exercise}%
}

\begin{document}

\chapter{Ch1.}

   \makeexample{blah}{ch1:ex1}{
   Given $b=e$, compute $foo(b)$...
   }

   \makeexample{another}{ch1:ex2}{
   Given $b=f$, compute $foo(b)$...
   }

   \makeproblem{compute foo}{ch1:problem:foo}{
   Given $b=a$, compute $foo(b)$.
   }

   \makeproblem{compute bar}{ch1:problem:bar}{
   Given $b=a$, compute $bar(b)$.
   }

\end{document}

However, in the output:

notice how the counters for the Examples are not shown incrementing (even within one chapter).
EDIT: noticed only after the fact that my example without any change to the formatting also didn't show incrementing Example numbers.  Deleted all parts of the question about my formatting modifications.
EDIT2: This issue appears to be due to a mis-interaction of the chngcntr package with the exercise package once a non-default counter is used.  Is there any way to deal with this?

A: You could use \renewcounter, provided by the same package, and redefine \theExercise:
\renewcounter{Exercise}[chapter]
\makeatletter
\renewcommand{\theExercise}{\if@ExeStared\else\thechapter.\arabic{\@ExerciseCounter}\fi}
\makeatother
\newcounter{Example}
\renewcounter{Example}[chapter]

Internally, the package uses \@ExerciseCounter (initialized with Exercise) with \theExercise, that's why just redefining \theExample doesn't work.


text:
Q: How to use cache with queries on different fields/keys? I am implementing a Spring MVC based web application where I have added caching, but now face a problem in terms of how to operate on the cache when changes are applied to underlying database.
I have been studying the documentation from available at Ehcache (http://ehcache.org/documentation), but failed to find any good examples to solve my problem.
Let's say I have a DAO class where I have chosen to apply a cache on two methods that return a list of objects (non-compileable pseudocode):
@Repository
public class MyEntityDao {

   @Autowired
   DataSource ds;

   @Autowired
   EhCacheCacheManager cacheManager;

   @Autowired
   CacheKeyGenerator keyGenerator;

   @Cacheable("myEntityCache")
   public List<MyEntity> findByFieldAlpha(String fieldAlpha) {
       return ds.query("select * from MyEntity where fieldAlpha = #fieldAlpha").execute();
   }

   @Cacheable("myEntityCache")
   public List<MyEntity> findByFieldBeta(String fieldBeta) {
       return ds.query("select * from MyEntity where fieldBeta = #fieldBeta").execute();
   }

   public void deleteByFieldAlpha(String fieldAlpha) {
      ds.query("delete from MyEntity where fieldAlpha = #fieldAlpha").execute();
   }

   public void deleteByFieldBeta(String fieldBeta) {
      ds.query("delete from MyEntity where fieldBeta = #fieldBeta").execute();
   }

   public void store(MyEntity myEntity) {
      ds.insert(myEntity).execute();
   }
}

I am using a custom KeyGenerator, so I know how keys when calling a method are generated:
public class CacheKeyGenerator implements KeyGenerator {

   @Override
   public Object generate(final Object target, final Method method, final Object... params) {
       return generateCacheKey(method.getName(), params);
   }

   public String generateCacheKey(final String methodName, final Object... params) {
       StringBuilder key = new StringBuilder();
       key.append(methodName);
       for (Object o : params) {
          key.append("_").append(o.toString());
       }
       return key.toString();
   }
}

The obvious problem I need to solve is how I should implement the cache modification policy when data is added or removed to the underlying database.
For the store method I find the problem quite trivial to solve:
 ...

 public void store(MyEntity myEntity) {
    boolean success = ds.insert(myEntity).execute();
    if (success) {
       Cache cache = cacheManager.getCache("myEntityCache")

       String keyFieldAlpha = keyGenerator.generateCacheKey("findByFieldAlpha", myEntity.getFieldAlpha());
       List cacheListFieldAlpha = (List) cache.get(keyFieldAlpha).getObjectValue();
       cacheListFieldAlpha.add(myEntity);

       String keyFieldBeta = keyGenerator.generateCacheKey("findByFieldBeta", myEntity.getFieldBeta());
       List cacheListFieldBeta = (List) cache.get(keyFieldBeta).getObjectValue();
       cacheListFieldBeta.add(myEntity);
    }
 }

But for the delete-methods things get much more complicated.
This is one implementation I have come up with so far, but it seems to be far more complicated (costly) than it should be. Anyone have any valuable input if my design patterns are correct, or if should solve my problem in any other way?
public void deleteByFieldAlpha(String fieldAlpha) {
  List<MyEntity> myEntititesToBeDeleted = this.findByFieldAlpha(fieldAlpha);
  boolean success = ds.query("delete from MyEntity where fieldAlpha = #fieldAlpha").execute();
  if (success) {
     Cache cache = cacheManager.getCache("myEntityCache")

     String keyFieldAlpha = keyGenerator.generateCacheKey("findByFieldAlpha", fieldAlpha);
     cache.remove(keyFieldAlpha);

     for (MyEntity myEntity : myEntititesToBeDeleted) {
        String keyFieldBeta = keyGenerator.generateCacheKey("findByFieldBeta", myEntity.getFieldBeta());
        List cacheListFieldBeta = (List) cache.get(keyFieldBeta).getObjectValue();
        cacheListFieldBeta.remove(myEntity);
     }
  }
}

Perhaps this is the correct way of solving it? I haven't stumbled upon any recipes that solves these problems so I am at my best guess here.

A: I'll give you my opinion. It seems to be (almost) the correct aproach. I think that after delete operation you should empty all the cache and start again. Usualy, after data changing operations the cache is reset. That's done because of the table joins. Doesn't seem to be your case because you have only two queries and no joins, but usualy the cache is cleaned and restarted. Doing this way you don't need to scan over the cache that refers to "fieldBeta" after changes in "fieldAlfa". Hope somethig from this could help you.
BTW, MyBatis works that way.

A: Use Ehcache search API, probably in operator would be useful in you case.


text:
Q: С# WinForms SelectedIndexChanged Буду конкретным: при клике на toolstripComboBox, выбирая  строку из выпадающего списка, на dataGridView должна открываться таблица соответствующая названию выбранной строки. Таблицы из базы данных .mdf считываются нормально, фото 1 - это видно при открытии выпадающего списка, но на dataGridView ничего не появляется. Не понимаю в чём проблема.
Фото 1

Код:
  private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (connection = new SqlConnection(connectionString))
        {
            string sTable = toolStripComboBox1.SelectedItem.ToString();
            sqlDataAdapter = new SqlDataAdapter("SELECT * FROM " + sTable, connection);
            dat = new DataTable(sTable);
            bs = new BindingSource();

            connection.Open();

            sqlDataAdapter.Fill(dat);
            bs.DataSource = dat;
            bindingNavigator1.BindingSource = bs;
            dataGridView1.DataSource = bs;

            connection.Close();
        }
    }

Если использовать редактор справа, то всё прекрасно работает, фото 2.
Код редактора на всякий случай тоже приложу.
Фото 2

Код:
 private void button1_Click(object sender, EventArgs e)
    {
        using (connection = new SqlConnection(connectionString))
        {
            try
            {
                sqlDataAdapter = new SqlDataAdapter(textBox1.Text, connection);
                dat = new DataTable();
                bs = new BindingSource();

                connection.Open();

                sqlDataAdapter.Fill(dat);
                bs.DataSource = dat;
                bindingNavigator1.BindingSource = bs;
                dataGridView1.DataSource = bs;

                connection.Close();
            }
            catch
            {
                MessageBox.Show("Неправильно написан запрос. Попробуйте снова.");
            }
        }
    }

Код функции, загружающий названия таблиц в Items:
private void Form1_Load(object sender, EventArgs e)
    {
        using (connection)
        {
            connection.Open();
            DataTable tables = connection.GetSchema("Tables");
            foreach (DataRow row in tables.Rows)
            {
                string TableName = row["TABLE_NAME"].ToString();
                toolStripComboBox1.Items.Add(TableName);
            }
            connection.Close();
        }
    }


text:
Q: Laravel Vapoor on aws codepipeline Laravel vapor is completely developed on aws platform but not used aws code pipeline to deploy codes. Has anyone tried aws code pipeline to deploy vapor codes?
I can deploy ubuntu server and install required PHP extensions and run vapor deploy staging command in aws codedeploy. Wondering is there any better way to deploy laravel vapor.

A: Finally, I made the below changes in the buildspec.yml file and used the ubuntu instance.
install:
    commands:
       - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2 &
       - timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
       #- command
      #- echo Logging in to Amazon ECR
  pre_build:
    commands:
       - docker run --name myvapor -d -e VAPOR_API_TOKEN=MY_VAPOR_API_TOKEN  --volume $(pwd):/~   --workdir /~ teamnovu/laravel-vapor
       - docker exec myvapor  vapor deploy staging


text:
Q: How can I remove argument redundancy with lists of similar arguments? I'm having trouble removing some redundancy in a series of C++ logging functions. They are each variants that alter on the first parameter, and the form of the final parameters.  I'm thinking somehow a variant with a variadic template might help.
The two basic functions:
void error( util::source_provider const & where, std::string const & reason )
void error( util::source_location const & where, std::string const & reason )

The first argument differs between a source_provider and source_location. These are basic structs, no virtuals.  After the reason I have several functions that look like these (with both the location and provider version):
void error( util::source_provider const & where, std::string const & reason,
    std::vector<item> const & itemsA,
    std::vector<item> const & itemsB,
    boost::optional<item> item0 = boost::optional<item>(),
    boost::optional<item> item1 = boost::optional<item>() )
void error( util::source_provider const & where, std::string const & reason,
    std::vector<item> const & itemsA,
    boost::optional<item> item0 = boost::optional<item>(),
    boost::optional<item> item1 = boost::optional<item>() )
void error( util::source_provider const & where, std::string const & reason,
    boost::optional<item> item0 = boost::optional<item>(),
    boost::optional<item> item1 = boost::optional<item>() )

I'm trying to make it convenient for the caller to provide lists of these item entries in whatever form they have. The information comes from a variety of places and it'd be an explosion of syntax at the call site if they needed to assemble into a single list. Some of this is also added via macros calling the logger.
What combination of features do I use to reduce this? I'm guessing I need a vardiac template with a variant somehow, to accept either a vector or item.
For clarity, these functions all ultimately call this function, combining all the item args into one vector first:
virtual void error_impl( boost::optional<util::source_location> where, std::string const & reason,
        std::vector<item> const & items ) = 0;

C++14 is okay. I'm using GCC 5.4 so I don't think all of C++17 is available yet.


text:
Q: loop to create a dictionary, D, which looks like: {1:100, 2:99,3:98,…,100:1} I need to create a dictionary that comes out as {1:100, 2:99,3:98,…,100:1}
I was messing around and got this
D = { }
keys = range(101)
i = 0
values = [100]
for i in keys:
    for x in values:
        x = i
        D[x] = i
        pass
print D

this has a output of
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 32: 32, 33: 33, 34: 34, 35: 35, 36: 36, 37: 37, 38: 38, 39: 39, 40: 40, 41: 41, 42: 42, 43: 43, 44: 44, 45: 45, 46: 46, 47: 47, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 58: 58, 59: 59, 60: 60, 61: 61, 62: 62, 63: 63, 64: 64, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 91: 91, 92: 92, 93: 93, 94: 94, 95: 95, 96: 96, 97: 97, 98: 98, 99: 99, 100: 100}

so I need to find a way to inverse it and get rid of the 0, I know .reverse() wont work on a dictionary and
list(reversed(sorted(a.keys())))

just made it a list that got rid of the 1:...100:

A: You can do:
# Save the range object for efficiency
In [30]: nums = range(1, 101)

# Dict comprehension to with zip to produce the desired dict
In [31]: {f: r for f, r in zip(nums, nums[::-1])}
Out[31]:
{1: 100,
 2: 99,
...
100: 1}

# Or use the dict constructor directly on the iterator returned by zip
In [32]: dict(zip(nums, nums[::-1]))
Out[32]:
{1: 100,
 2: 99,
...
100: 1}

A: While other answers are correct I think this is a good case for a dict comprehension. It makes the code easier to read and more pythonic
result = { i: 101 - i for i in range(1, 101)}

To make it even better you can make the code reusable using a variable instead of harcoding the 101, so:
num = 101
result = { i: num - i for i in range(1, num)}

A: You can use a dict comprehension with enumerate and range to create the dictionary.
print( {k:v for k,v in enumerate(range(100,0,-1),1)})
#{1: 100, 2: 99, 3: 98, 4: 97, 5: 96, 6: 95, 7: 94, 8: 93, 9: 92, 10: 91, 11: 90, 12: 89, 13: 88, 14: 87, 15: 86, 16: 85, 17: 84, 18: 83, 19: 82, 20: 81, 21: 80, 22: 79, 23: 78, 24: 77, 25: 76, 26: 75, 27: 74, 28: 73, 29: 72, 30: 71, 31: 70, 32: 69, 33: 68, 34: 67, 35: 66, 36: 65, 37: 64, 38: 63, 39: 62, 40: 61, 41: 60, 42: 59, 43: 58, 44: 57, 45: 56, 46: 55, 47: 54, 48: 53, 49: 52, 50: 51, 51: 50, 52: 49, 53: 48, 54: 47, 55: 46, 56: 45, 57: 44, 58: 43, 59: 42, 60: 41, 61: 40, 62: 39, 63: 38, 64: 37, 65: 36, 66: 35, 67: 34, 68: 33, 69: 32, 70: 31, 71: 30, 72: 29, 73: 28, 74: 27, 75: 26, 76: 25, 77: 24, 78: 23, 79: 22, 80: 21, 81: 20, 82: 19, 83: 18, 84: 17, 85: 16, 86: 15, 87: 14, 88: 13, 89: 12, 90: 11, 91: 10, 92: 9, 93: 8, 94: 7, 95: 6, 96: 5, 97: 4, 98: 3, 99: 2, 100: 1}

Enumerate takes a secondary optional parameter to start at that number (1 in this case) and range accepts 3 parameter (start, stop, steps)
Edit: it seems you don't need a dict comprehension like Pault pointed out:
dict(enumerate(range(100,0,-1),1))

would work.

A: Best possible answers have been given.
If you still want a simpler approach, this helps. :)
D = {}
for i in range(1,101):
    D[i]=101-i
print(D)

A: Try this:
dict(zip(range(1,101),range(100,0,-1)))

What you are doing in this code is first generating a list with all the numbers from 1-100 range(1,101) and from 100-1 range(100,0,-1) using the range command. You set the start and end points (the final sequence does not include the end, which is why you put 101 or 0) and the spacing (-1 when counting down).
Next you make a list with these two lists zipped together zip() which gives you [(1,100),(2,99),...(100,1)]
Finally the dict function makes a dictionary out of this list of tuples, where the first entry is the key and the second is the value. So, your final outcome is
{1:100, 2:99, 3:98...100:1}
Hope that helps!


text:
Q: Are the absolute values of random variables iid if the random variables are iid? If $X$ and $Y$ are independent and identically distributed (iid) random variables, does it imply that $|X|$ and $|Y|$ are iid? How would you go about proving this?

A: $X,Y$ are independent if and only if $$P\left\{ X\in A\wedge Y\in B\right\} =P\left\{ X\in A\right\} P\left\{ Y\in B\right\} $$
is true for measurable sets $A,B$.
If this is the case and $f,g:\mathbb{R}\rightarrow\mathbb{R}$ are
measurable functions then:
$$P\left\{ f\left(X\right)\in A\wedge g\left(Y\right)\in B\right\} =P\left\{ X\in f^{-1}\left(A\right)\wedge Y\in g^{-1}\left(B\right)\right\} =P\left\{ X\in f^{-1}\left(A\right)\right\} P\left\{ Y\in g^{-1}\left(B\right)\right\} =P\left\{ f\left(X\right)\in A\right\} P\left\{ g\left(Y\right)\in B\right\} $$
showing that $f\left(X\right)$ and $g\left(Y\right)$ are independent.

A: Yes. In fact one can show that $X$ and $Y$ are independent if and only if $f(X)$ and $g(Y)$ are independent for every measurable  function $f, g$
I don't know how you introduced independence, but X and Y independent means that the $\sigma$-algebrae generated by them are independent; it is easy to see that the $\sigma$-algebra generated by $f(X)$ is smaller that the one generated by $X$, hence independence is preserved

A: Evidently so. See this link
Are functions of independent variables also independent?
which addresses independence. It's clear they are identically distributed, isn't it?


text:
Q: Testing a component with dependencies using karma & jasmine I'm new to angular 2 and I have some problems testing my code. I use the jasmine testing framework and the karma test runner to test my app.
I have a component (called GroupDetailsComponent) that I want to test. This component uses two services (GroupService & TagelerServie, both have CRUD methods to talk to an API) and some pipes in the html file. My component looks like this:
import 'rxjs/add/operator/switchMap';
import { Component, Input, OnInit } from '@angular/core';
import { Tageler } from '../../tagelers/tageler';
import { TagelerService } from '../../tagelers/tageler.service';
import { Params, ActivatedRoute } from '@angular/router';
import { GroupService} from "../group.service";
import { Group } from '../group';

@Component({
  selector: 'app-group-details',
  templateUrl: 'group-details.component.html',
  styleUrls: ['group-details.component.css'],
})

export class GroupDetailsComponent implements OnInit {
  @Input()
  tageler: Tageler;
  tagelers: Tageler[];
  group: Group;

  constructor(
    private route: ActivatedRoute,
    private groupService: GroupService,
    private tagelerService: TagelerService) {
  }

  ngOnInit() {
    console.log("Init Details");
    this.route.params
      .switchMap((params: Params) => this.groupService.getGroup(params['id']))
      .subscribe(group => this.group = group);

    this.tagelerService
      .getTagelers()
      .then((tagelers: Tageler[]) => {
        // some code
          }
          return tageler;
        });
      });
  }
}

And the test file looks like this:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { GroupDetailsComponent } from './group-details.component';
import { FilterTagelerByGroupPipe } from '../../pipes/filterTagelerByGroup.pipe';
import { SameDateTagelerPipe } from '../../pipes/sameDateTageler.pipe';
import { CurrentTagelerPipe } from '../../pipes/currentTageler.pipe';
import { NextTagelerPipe } from '../../pipes/nextTageler.pipe';
import { RouterTestingModule } from '@angular/router/testing';
import { GroupService } from '../group.service';
import { TagelerService } from '../../tagelers/tageler.service';

describe('GroupDetailsComponent', () => {

  let component: GroupDetailsComponent;
  let fixture: ComponentFixture<GroupDetailsComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        GroupDetailsComponent,
        FilterTagelerByGroupPipe,
        SameDateTagelerPipe,
        CurrentTagelerPipe,
        NextTagelerPipe, ],
      imports: [ RouterTestingModule ],
      providers: [{provide: GroupService}, {provide: TagelerService}],
    })

    fixture = TestBed.createComponent(GroupDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  class MockGroupService {
    getGroups(): Array<Group> {
      let toReturn: Array<Group> = [];
        toReturn.push(new Group('Trupp', 'Gruppe 1'));
      return toReturn;
    };
  }

  it('should create component', () => {
    expect(component).toBeDefined();
  });
});

I read the angular 2 documentation about testing and a lot of blogs, but I still don't really understand how to test a component that uses services and pipes. When I start the test runner, the test 'should create component' fails and I get the message that my component is not defined (but I don't understand why). I also don't understand how I have to inject the services and pipes. How do I mock them the right way?
I hope that someone can give me helpful advice!
Ramona

A: You can use spyOn to fake the call in jasmine.
spyOn(yourService, 'method').and.returnValue($q.resolve(yourState));


text:
Q: Rails 4: How to set cookies in redirect? I have a controller that attempts takes form inputs, set values in a cookie and then redirect to a page that will pull from that cookie.
The problem is that the cookie is never set in the redirect headers.
Notes: I've tested in Chrome and FF.  Rails version is 4.0.13. Setting cookies w/o a redirect works as expected.
Here's the controller code:
def create
  request.cookies[:foo] = "bar"

  # also tried:
  #   cookies[:foo]="bar"
  #   cookies.signed[:foo]="bar"
  #   cookies[:foo] = {
  #     value: "bar",
  #     expires: 1.month.from_now,
  #     domain: ".myapplicationhostname.com"
  #   }

  redirect_to root_url
end

The response header on the redirect doesn't contain a Set-Cookie attribute and as such, the cookie values aren't available in the controller/action in the redirected-to path.
I've found some contradictory evidence that some browsers don't accept cookies in redirects, but it appears that that's not the case anymore? And anyways, neither FF or Chrome are showing a Set-Cookie in the response header, so it doesn't appear this is a browser issue.
Here's the header response from cURL, note the lack of Set-Cookie:
HTTP/1.1 302 Moved Temporarily
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-UA-Compatible: chrome=1
Location: http://app.mydomain.com:3000/
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
X-Request-Id: 1fc1c7e5-7489-4720-bb70-28588f3abcb6
X-Runtime: 4.688166
Connection: close
Server: thin 1.6.2 codename Doc Brown

How do I get rails to set cookies (or at least set the header) on redirects?

A: It appears that the cause of this is actually CSRF protection kicking in.  The controller had instantiated a NullCookieJar which prevents the writing of cookies when there's a potentially forged POST.
This is because my controller was being set up to respond to an off-site form, thus no access to the CSRF token.
So, if you're running into this when submitting an off-site form to your Rails app, you'll need to disable the CSRF check or write your own verification method as described in the answer to the SO question: "Receive POST from External Form".
Summarized here:
Disabling Check
skip_before_filter :verify_authenticity_token, only: :my_action

Custom Check
skip_before_filter :verify_authenticity_token, :only => :my_action
before_filter :verify_custom_authenticity_token, :only => :my_action

def verify_custom_authenticity_token
  # checks whether the request comes from a trusted source
end


text:
Q: TYPO3 Extbase soap client How can I integrate a soap client in TYPO3 Extbase?
I have installed php_soap on the webserver. Can I use the normal http://php.net/manual/de/soapclient.soapclient.php implementation?
$client = new SoapClient("my.wsdl", array('login'          => "my_name",
                                       'password'       => "my_passwort"));

Maybe there are some extbase implementations available?
Thanks for a quick tipp. I dint' find good extbase documentation for this purpose.
Just found this:
Create object in extbase extension from a PHP standard class
How to make a PHP SOAP call using the SoapClient class

A: I would create a SoapService class and inject it in an extbase controller.
The SoapService class can be easily injected in the Controller the service would look like this :
<?php

namespace Vendor\Name\Service;

class SoapService
{
    /**
     * @var \SoapClient
     */
    protected $client;

    /**
     * SoapService constructor.
     */
    public function __construct()
    {
        $this->client = new \SoapClient('my.wsdl', ['login' => 'my_name', 'password' => 'my_passwort']);
    }

    /**
     * Fetch data on webservice.
     *
     * @return mixed
     */
    public function fetchWhateverData() {
        $arguments = [];
        return $this->client->__soapCall("getWhateverOnSoapService", $arguments);
    }
}


text:
Q: _vm.arr[0] is undefined Vue.js, Nuxt I've got a website. There's a main page with a navbar. Navbar contains of 2 links. There's a link (main-link) as well and it goes on other page. When I click on the main-link it opens a new page with the same navbar. I should click on any link and it will redirect me on them.
The issue:
If I click on the navbar on the main page and click on the main-link it works well. If go on the page by click the main-link I can use navbar. But if I refresh the page it doesnt work.
Here is the error from console:
_vm.arr[0] is undefined

components specialty.vue html section:

...

...

components specialty.vue script section:
export default defineComponent({
  props: {
    arr: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  components: {
    ...
  },
  setup () {
    return {
      ...
    }
  }
})

I guess that it broke because when I refresh the page the data about arr isn't recieved yet. But why other data is OK?

A: In Vue 3 templates, you could use optional chaining on arr[0] so that arr[0] is only dereferenced when truthy:

...

...

demo
Or you could check arr[0] beforehand:

...

...


text:
Q: Collections - Filtering multiple multi-select attribute values That's not a typo.
I am aware that I need to use 'finset' to filter my multi-select attributes; however, I am trying to filter multiple values at once and getting:
Incorrect parameter count in the call to native function 'FIND_IN_SET.
Here's some sample code:
foreach ($options as $option) {
    // $option[0] contains an attribute ID as a string
    $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($option[0]);

    if ($attribute->getFrontendInput() == 'multiselect') {
        $collection->addAttributeToFilter($attribute->getAttributeCode(), array('finset' => $option[1]));
    } else {
        $collection->addAttributeToFilter($attribute->getAttributeCode(), array('in' => $option[1]));
    }
}

What I have on the frontend is a set of fields, each set corresponds to a specific attribute and contains checkboxes for each attribute value. Based on these submissions, the collection should filter out what has been selected.
Everything works great except for the single case where I attempt to filter two of the multi-select options at the same time. If I only choose one of them, the search works properly. If I choose two or more, I get the MySQL error mentioned above.
Any ideas? Or am I forced to use custom SQL statements to build this filter?

A: From what I understand you want to send 2 or more values and filter by them using OR.
Something like this:
...
WHERE
    FIND_IN_SET($v1, `some_field`) OR
    FIND_IN_SET($v2, `some_field`) OR
...

$v1 & $v2 are the values of your checkboxes
For that you need to pass to the addAttributeToFilter and array of arrays.
->addAttributeToFilter(
    array(
          array('attribute'=>'some_attribute', 'finset'=>$v1),
          array('attribute'=>'some_attribute', 'finset'=>$v2),
    )
);

Here is a possible implementation.
$data = THE ARRAY OF THE CHECKBOX VALUES;

$filter = array();
foreach ($data as $value) {
    $filter[] = array(
        'attribute' => $attribute->getAttributeCode(),
        'finset'    => $value
    );
}

if (count($filter) > 0) {
    $collection->addAttributeToFilter($filter);
}

A: This code will combine two finset conditions with OR:
->addAttributeToFilter(
    array(
          array('attribute'=>'some_attribute', 'finset'=>$v1),
          array('attribute'=>'some_attribute', 'finset'=>$v2),
    )
);


text:
Q: Listen to events without knowing sender in C#? I'm currently diving into the more advanced C# topics and have a questions about events:
If I understood that right, I need to know the object (instance) that raises an event in order to listen to it:
class IWantToListen {
    public IWantToListen(IAmSending s) {
        s.OnTrigger += HandleTrigger;
    }

    public void HandleTrigger(object sender, EventArgs e) {
        // react to event
    }
}

public class IAmSending {
    public event EventHandler OnTrigger;

    public void TriggerEvent(EventArgs e) {
        OnTrigger(this, e);
    }
}

In order to have my IWantToListen instance listen to events from my IAmSending instance, I have to pass at some point the reference to that specific instance.
But what if I want my IWantToListen instances to listen to events from all instances of IAmSending and those instances are dynamically created. I would have to manually let IWantToListen know that there is a new IAmSending instance that it has to subscribe to. Is there no other possibility? I think I'm looking for something that would work like this:
public class IWantToListen {
    public IWantToListen() {
        EventDistributionSystem.AddListener("OnTrigger", HandleTrigger);
    }

    public void HandleTrigger(object sender, EventArgs e) {
        // react to event
    }
}

public class IAmSending {
    public void TriggerEvent(EventArgs e) {
        EventDistributionSystem.Send("OnTrigger", this, e);
    }
}

Of course that's only a rough sketch with room for improvement, but I think you get the idea. Anyway, I couldn't for the life mine find anything doing this or even somebody asking for it. I could probably build a singleton EventDistributionSystem class on my own, but the fact that it doesn't prominently exist already raises the question if there is a reason for that. Is this considered bad design? If yes, why?


text:
Q: Why do we need to use target "PROJECT_NAME" do from what version of cocoapods / xcode Recently in my new MACI've installed cocoa pods 1.2.1 i ran "pod update" in my projects Folder to update to the newest Version.
The result of the update is:
The dependencyFlurrySDKis not used in any concrete target.
I've fixed the problem by adding pod like this
target "PROJECT_NAME" do

    pod 'FlurrySDK'

end

But Just for curiasity...
I want to know from which version of XCode / Cocoapods we need to add this line
target "PROJECT_NAME" do
and Why
Can some one please clarify on this

A: Your pod file will be like this,
it is necessary to add your project name as "target".
Consider this code:
 # Uncomment this line to define a global platform for your project
   platform :ios, '8.0'
 # Uncomment this line if you're using Swift
 # use_frameworks!

 target 'PROJECT_NAME' do
 pod 'FlurrySDK'
 end

I hope it will help you, because i always add this for adding pods.
i think it is not XCode version based.


text:
Q: WPF 4.0 EdgeMode.Aliased drawing inexplicably slow to display on canvas I'm drawing some vector data, slightly under 9000 polygon objects, using FrameworkElement:DrawingVisual which in turn is a child of a Canvas object. My tree of objects would look something like this:
WPF Window
-Canvas
--FrameworkElement
---DrawingVisual -> DrawingContext.DrawGeometry

So far so good. I'm timing all the rendering methods and it is pretty much as expected, 0.32 seconds for the DrawingContext to do its stuff and 0.5 seconds total. With EdgeMode set to default (anti-aliased) the completed drawing appears on my canvas barely half a second later.
However, because I need all lines to be aliased I use RenderingOptions.SetEdgeMode to EdgeMode.Aliased on the canvas object.
After doing this there is no discernible difference in rendering time, 0.5 seconds total time. But - the completed drawing now takes over 4 seconds before it appears in my window. This compared to under 0.5 seconds for the anti-aliased version. The only difference is this single line of code:
 RenderOptions.SetEdgeMode(myCanvas, EdgeMode.Aliased);

If I resize the window same thing happens, it takes much longer for the aliased version to resize compared to the anti-aliased one. Obviously, in this case my drawing code isn't even invoked so the problem must lie elsewhere.
It seems that something external to my code is slowing things down drastically when in aliased rendering mode, quite opposite of what I would have expected. So what am I missing here?


text:
Q: Updating a set number of progress bars in one JFrame(preferably) Looked around and there were a few similar questions, but none seemed to show how to run more than one progress bar in a single JFrame while updating it from 3 other threads.
Preferably I plan to have a progressbar class of its own, a lot of the examples I saw people doing all the progressbar work inside a main thread which I didn't really like. If that's how you're meant to do it I'm sorry I've never used a progressbar before.
I want to monitor the progress of the robot threads. I was going to send an update directly from the Robot class to my progress bar and have a progressbar object in my main if that's possible.
my main thread is sort of like this
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
Motor m = new Motor();

Robot xRob = new Robot(cyclicBarrier, m);
Robot yRob = new Robot(cyclicBarrier, m);
Robot zRob = new Robot(cyclicBarrier, m);

Thread xRobThread = new Thread(xRob);
Thread yRobThread = new Thread(new Robot(cyclicBarrier, m));
Thread zRobThread = new Thread(zRob);

boolean clockwise = true, counterClockwise = false;

m.setMotor(clockwise, 14400000, xRob);
m.setMotor(clockwise, 0, yRob);
m.setMotor(counterClockwise, 36000000, zRob);

xRobThread.start();
yRobThread.start();
zRobThread.start();

This is the important parts of my robot class.
public class Robot implements Runnable{
public void run(){
    System.out.println("Running: ");
    m.Engage(this);
    try {
        System.out.println("Sleeping: ");
        Thread.sleep(3000);
        cyclicBarrier.await();

    } catch (Exception e){
        e.printStackTrace();
    }
    System.out.println("Engaging: ");
}

public void Rotate(){
        if ((opcode & clockwise) > 0){
            rotation++;
            if(rotation == 360){
                rotation = 0;
                moveCount++;
            }
        }
        if ((opcode & counter) > 0){
            rotation--;
            if(rotation == -360){
                rotation = 0;
                moveCount --;
            }
        }

}
}

Here is the progress bar I have so far
public class ProgressBar {

final int MAX = 100;
final JFrame frame = new JFrame("JProgress ");
final JProgressBar pbOne = new JProgressBar();
final JProgressBar pbTwo = new JProgressBar();
final JProgressBar pbThree = new JProgressBar();

    ProgressBar(){

        pbOne.setMinimum(0);
        pbOne.setMaximum(MAX);
        pbOne.setStringPainted(true);

        pbTwo.setMinimum(0);
        pbTwo.setMaximum(MAX);
        pbTwo.setStringPainted(true);

        pbThree.setMinimum(0);
        pbThree.setMaximum(MAX);
        pbThree.setStringPainted(true);

        frame.setLayout(new FlowLayout());
        frame.getContentPane().add(pbOne);
        frame.getContentPane().add(pbTwo);
        frame.getContentPane().add(pbThree);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }

    public void setProgress(int progress){
        try {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    pb.setValue(progress); //HERE IS where I get lost. How do I differentiate between PBs and Threads
                                           // As in which thread the code is coming from and which progress bar it's updating.
                }
            });
            java.lang.Thread.sleep(100);
        } catch (InterruptedException e) {
        JOptionPane.showMessageDialog(frame, e.getMessage());
        }
    }
}

I was going to update the progress everytime it went through a rotation in my robot class, but I haven't implemented that yet since I wanted to first get the design down.


text:
Q: Writing to the console using Task.Run() fails A colleague of mine found an issue with our code and it took a while to hunt down exactly what was happening, but it can be best demonstrated by this simple example:
// Fails
class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => Console.WriteLine("Hello World"));
        Console.ReadKey();
    }
}

// Works fine
class Program
{
    static void Main(string[] args)
    {
        Console.Write(String.Empty);
        Task.Run(() => Console.WriteLine("Hello World"));
        Console.ReadKey();
    }
}

It's clear from playing around with this that writing to the console anywhere from the main thread will allow the background thread to write to the console also, but we are struggling to understand why this is happening.  Can anyone explain what writing to the console from the main thread achieves that the first snippet does not?

A: I have a suspicion as to what's going on. What I've observed:

*

*If you do anything with the console's output before starting the ReadKey, it's fine. This includes fetching Console.Out but not using it

*If you put a delay in so that the Console.WriteLine call starts before the Console.ReadKey call, it's fine (and you can have multiple WriteLine calls while ReadKey is waiting

I suspect that the first operation to use the console acquires a lock for initialization (to avoid it being initialized twice) and that the ReadKey method keeps hold of the lock until a key has been read. That would certainly explain every program I've run so far.
The operations which perform the hypothesized initialization are interesting though - reading Console.Out "fixes" the issue, but reading from Console.In doesn't.
I suspect that ReadKey initializes the output because the value is still echoed to the console... but I wouldn't like to swear to it.
Interestingly, using Console.ReadLine() instead of Console.ReadKey() doesn't cause the problem in the first place.

A: Actually, the first case doesn't fail. "Hello World" appears just before the Application ends. This is a classical Race Condition. In the first case,Console.ReadKey() from the main thread beats the task, and in the second case, the task wins. Unfortunately, I cannot tell you Exactly why writing the empty string makes the task win.


text:
Q: How do I execute this command (curl) in rails? That is, what library contains a tool that allows me to pass an API key this way? Here's the command I need to execute: (using the example API key)
curl -v -u 1971800d4d82861d8f2c1651fea4d212:api_token \
-X GET https://www.toggl.com/api/v8/workspaces/777/tasks

I am writing a dashing/sinatra based dashboard that shows a summary of the information from our Toggl account. My question is, how to I open this url in sinatra using something like
open('http://...) do |f|
A successful curl returns an array (json) that I can parse for the info I need.
I'm not entirely sure how to tackle this. I have some ideas but they aren't well formed enough to properly comment on them. I though I'd bounce this off of you all for inspiration and information.
I'm all ears.

A: Check out HTTParty. The example in the README shows basically exactly what you're looking to do using auth headers:
https://github.com/jnunemaker/httparty


text:
Q: What is -moz-border-radius? -CSS What is
-moz-border-radius:

I really have no idea what it is, and I can't find answers on stackoverflow, google, or anywhere. I'm new to web dev and I tried using this and opened up firefox, and there is no real difference. Nor if I open anything else. Also what about
-webkit-border-radius or anything that begins with -webkit

A: They are vendor prefixed properties, a type of vendor specific extension
They are used to implement experimental versions of features before they are standardised.

An initial dash or underscore is guaranteed never to be used in a
  property or keyword by any current or future level of CSS. Thus
  typical CSS implementations may not recognize such properties and may
  ignore them according to the rules for handling parsing errors.
  However, because the initial dash or underscore is part of the
  grammar, CSS 2.1 implementers should always be able to use a
  CSS-conforming parser, whether or not they support any vendor-specific
  extensions.
Authors should avoid vendor-specific extensions

A: Well anything starting with a - prefix is for a specific browser.

*

*-moz is for firefox

*-webkit is for chrome and safari

*-o is for opera

*-ms is for internet explorer

Border radius is simply just to round the corners of an element. You can set the value to 5px and you will see the difference. Here is a fiddle to show the property: http://jsfiddle.net/Ps4mN/
border-radius: 5px;

A: It is important to realize browser compatibility, and most import backwards compatibility. Mozilla, in it's past used it's own unique methods of parsing CSS. They also, because of this, were a little behind on new standards in CSS and had to add them later down the road. Adding prefix's to these attributes gave them a way to highlight their 'new' implementation of already released CSS as a 'new and improved' vision of whats already out. See branding.
Because of this, however, it caused a lot of issues with compatibility between developers. Deciding what browsers to develop for, or how to optimize for one specific brand. Which furthered it notoriety as well as it's revenues.
Only recently has some browsers caved into following standards of CSS, such as border-radius:
However, do to this war, which is still being raged, you need to keep in mind a lot of people don't use the browsers you are using. In fact some 25% of all computers online still run Windows XP as well as Internet Exploder (I'm sorry, Internet Explorer or something like that)! And there is no easy way of supporting rounded corners there besides fun workarounds.
Take a look at this article about cross compatible borders for new and old browsers right here. Mind you border-radius: will work in newer version of Mozilla, but not older ones. It will also run on current version of most web standard browsers. Just it's always good to keep some legacy code in for older browsers.


text:
Q: Process terminates when function is called I'm trying to write a function that will read and print the contents of a file. I gave the filename as a parameter for my function. I used FILE *testfile to create a file handle and then I use fread to read the file. block_t is a struct and nreserved are the reserved segments of the block. Each block has records. I don't think that it is necessary to tell you how block_t is created.
My problem is that even though the function runs and I can see in the console the results that I want to see the process terminates. This happens even if I comment out the if else parts. I get this message Process terminated with status -1073741510
Here is my code:
#include "dbtproj.h"
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>

using namespace std;

void showEntriesOfBlock(char *filename){
    FILE *testfile;
    block_t block;
    int nreserved;

    //open file and print contents
    testfile = fopen(filename,"r");

    if(testfile==NULL)
        cout << "Error";
    else{
        while(!feof(testfile)){
            fread(&block, 1, sizeof(block_t), testfile);
            nreserved = block.nreserved;

    //print block contents
    for (int i=0; i<nreserved; ++i) {
        printf("this is block id: %d, record id: %d, num: %d, str: %s\n",
                block.blockid, block.entries[i].recid, block.entries[i].num,
                block.entries[i].str);
        }
    }
}
fclose(testfile);
};

In my main file I create a file by using outfile = fopen("file.bin", "w"); then I write random data to the file. Then I close the file with fclose(outfile); and in the next line I call my function like this showEntriesOfBlock("file.bin");
Can anybody help? I think that I might have messed up my pointers of did something wrong with the file handlers.
This is how I give data to my blocks and records.
for (int b=0; b<nblocks; ++b) { // for each block

    block.blockid = b;
    for (int r=0; r<MAX_RECORDS_PER_BLOCK; ++r) { // for each record

        // prepare a record
        record.recid = recid++;
        record.num = rand() % 1000;
        strcpy(record.str,"hello");   // put the same string to all records
        record.valid = true;

        memcpy(&block.entries[r], &record, sizeof(record_t)); // copy record to block
    }

    block.nreserved = MAX_RECORDS_PER_BLOCK;
    block.valid = true;

    fwrite(&block, 1, sizeof(block_t), outfile);    // write the block to the file
}

fclose(outfile);

And here are the definitions of my structs:
// This is the definition of a record of the input file. Contains three fields, recid,           num and str
typedef struct {
    unsigned int recid;
    unsigned int num;
    char str[STR_LENGTH];
    bool valid;  // if set, then this record is valid
 } record_t;

// This is the definition of a block, which contains a number of fixed-sized records
typedef struct {
    unsigned int blockid;
    unsigned int nreserved; // how many reserved entries
    record_t entries[MAX_RECORDS_PER_BLOCK]; // array of records
    bool valid;  // if set, then this block is valid
    unsigned char misc;
    unsigned int next_blockid;
    unsigned int dummy;
} block_t;

A: Here's a working version using FILE* (which I wouldn't recommend if you're learning...)
NOTE: open your files in binary mode : fopen(filename, "wb") or fopen(filename, "rb")
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <cassert>
#include <fstream>

const int STR_LENGTH = 10;
const int MAX_RECORDS_PER_BLOCK = 5;

//! For my test I assumed the following definitions.
//! (i.e. that block_t is a POD.)
// This is the definition of a record of the input file. Contains three fields, recid,           num and str
typedef struct
{
    unsigned int recid;
    unsigned int num;
    char str[STR_LENGTH];
    bool valid;  // if set, then this record is valid
} record_t;

// This is the definition of a block, which contains a number of fixed-sized records
typedef struct
{
    unsigned int blockid;
    unsigned int nreserved; // how many reserved entries
    record_t entries[MAX_RECORDS_PER_BLOCK]; // array of records
    bool valid;  // if set, then this block is valid
    unsigned char misc;
    unsigned int next_blockid;
    unsigned int dummy;
} block_t;

void showEntriesOfBlock(const char *filename)
{
    FILE* testfile = fopen(filename, "rb");
    assert(testfile);

    if (!testfile)
    {
        perror("Error");
        return;
    }

    block_t block;
    while(fread(reinterpret_cast<char*>(&block), sizeof(block_t), 1, testfile))
    {
        if (ferror(testfile))
        {
            perror("Error while reading");
            return;
        }

        //print block contents
        for (int i = 0; i < block.nreserved; ++i)
        {
            printf("this is block id: %d, record id: %d, num: %d, str: %s\n",
                block.blockid, block.entries[i].recid, block.entries[i].num,
                block.entries[i].str);
        }
    }

    fclose(testfile);
};

int main(int argc, const char *argv[])
{
    std::string filename = "g:/test.dat";
    FILE* outfile;
    outfile = fopen(filename.c_str(), "wb");
    int nblocks = 10;
    int recid = 0;

    for (int b = 0; b < nblocks; ++b)
    {
        block_t block;
        block.blockid = b;
        for (int r = 0; r < MAX_RECORDS_PER_BLOCK; ++r)
        {
            // for each record
            // prepare a record
            record_t record;
            record.recid = recid++;
            record.num = rand() % 1000;
            strcpy(record.str, "hello");   // put the same string to all records
            record.valid = true;

            memcpy(&block.entries[r], &record, sizeof(record_t)); // copy record to block
        }

        block.nreserved = MAX_RECORDS_PER_BLOCK;
        block.valid = true;

        fwrite(&block, sizeof(block_t), 1, outfile);    // write the block to the file
    }

    fclose(outfile);

    showEntriesOfBlock(filename.c_str());

    return 0;
}

A: Try this:
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <cassert>
#include <fstream>
#include <type_traits>

void showEntriesOfBlock(char *filename)
{
    std::ifstream testfile(filename, std::ios_base::binary);
    assert(testfile);

    if (!testfile)
    {
        std::cout << "Error";
        return;
    }

    block_t block;
    int nreserved;

    while (testfile)
    {
        //! This assumes block is a POD.
        static_assert(std::is_pod<block_t>::value, "block_t is not a POD.");
        testfile.read(reinterpret_cast<char*>(&block), sizeof(block_t));
        nreserved = block.nreserved;

        //print block contents
        for (int i = 0; i < nreserved; ++i)
        {
            printf("this is block id: %d, record id: %d, num: %d, str: %s\n",
                    block.blockid, block.entries[i].recid, block.entries[i].num,
                    block.entries[i].str);
        }
    }

    testfile.close();
};


text:
Q: Why have solutions to the obstacles for the Philospher's Stone? While I'm not debating the difficulty of the obstacles presented in the Philospher's Stone, it would seem to me that it would make more sense to just guard it.
In the cases of the potions, the keys, and the chess, why present solutions to the user?  Why not simply present a wall of fire, an enchanted door that's nigh on impossible to unlock, and some stone guardians one has to fight?

A: I think the most likely answer is that the obstacles are meant to delay people, not to stop them. Providing a solution means that people will take the time to try to figure out how to solve them, and potentially proceed undetected, rather than to brute force the obstacles in a smash-and-grab that might succeed before help could arrive.


text:
Q: How to create a Bash script to copy files from a bucket on one S3 account to a bucket on another S3 account I am trying to do accomplish the task in subject.
Till now I tried to simply copy files from place to place on the same account like this:
#!/bin/bash

aws s3 cp s3://my-bucket/my-prefix s3://another-bucket/temp1/ --recursive

This is using my default s3 account. No problem at all!
But what are the steps to perform if my-bucket is on a seperate s3 account than another-bucket?


text:
Q: What does a dot (.) means after a numeric value in Oracle? This is my first time using an ORACLE SQL.
I came across with a query like this :
SELECT *
FROM TABLE_A
WHERE COLUMN_A = 1.
AND COLUMN_B <> 0.

Can anyone explain me what does a dot (.) after those integers means? Will it make any difference if I don't put a dot (.)?
Thanks in advance :)

A: It will just add 0 after the decimal point. It has no effect. It is equivalent to
1. = 1.0
0. = 0.0

If the datatype COLUMN_A is decimal then based on scale of COLUMN_A number of zero's after the decimal point will vary.

A: I've never seen numbers represented without the decimal 0 (zero) afterward, but it looks like that's what's happening here.
SELECT *
FROM TABLE_A
WHERE COLUMN_A = 1.0
AND COLUMN_B <> 0.0

which is the same as
SELECT *
FROM TABLE_A
WHERE COLUMN_A = 1
AND COLUMN_B <> 0


text:
Q: prelink-rtld: command not found Getting Prelink-rtld: command not found error, when trying to build my project using yocto.
Complete error:
work/aarch64-oe-linux/gstreamer1.0/1.12.2-r0/recipe-sysroot/usr/bin/g-ir-scanner-lddwrapper: line 2: prelink-rtld: command not found

| ==6485==LeakSanitizer has encountered a fatal error.

| If the above error message is about missing .so libraries, then setting up GIR_EXTRA_LIBS_PATH in the recipe should help.

| (typically like this: GIR_EXTRA_LIBS_PATH="${B}/something/.libs" )

Tried adding DEPENDS += "prelink"
But this didn't solve the problem.
Started getting this error after enablink gcc-sanitizer.
i.e
+DEPENDS += "gcc-sanitizers"
+CFLAGS += "-fsanitize=address"
+CPPFLAGS += "-fsanitize=address"
+LDFLAGS += "-fsanitize=address"

in gstreamer1.0_1.12.2.bbappend file.

A: You probably need the native prelink version, because it is executed at build time.
Try using
DEPENDS += "prelink-native"


text:
Q: AngularJS API call inside getter function I've inherited a project in AngularJS with some structural issues. It uses an API call to fetch some settings from an endpoint but sometimes the application attempts to use these settings before they're loaded resulting in an 'undefined' error.
I attempted to solve this by using a getter. The idea was that when some method accesses the settings object, it would check if they were already loaded in and if not, fetch them from the API.
I've got it working after a while but there's a problem with this idea. When multiple methods access the settings at the same time (when loading the page) the API is being called multiple times because the first call hasn't come back to override the internal _settings yet.
    vm._settings  = null;
    Object.defineProperty(vm,'settings',{get: function(){
      if(vm._settings == null){
        settings_service.get().$promise.then(function success(response) {
          vm._settings = response;
          console.log(vm._settings);
          console.log("returning in");
          return vm._settings;
        }, function error(err) {
          handle_api_error(ngNotify, err);
        });
      }
      else return vm._settings;
    }});

I can't figure out a way to let the other attempts to execute the getter wait until the first call returns and use that result instead. I'm not sure if I should use await, promises or something else. Thanks in advance

A: You want to debounce these requests. You could use an existing library or just implement your own.
app.factory('debounce', function($timeout) {
    return function(callback, interval) {
        var timeout = null;
        return function() {
            $timeout.cancel(timeout);
            timeout = $timeout(function () {
                callback.apply(this, args);
            }, interval);
        };
    };
});


text:
Q: jQuery DataTable PDF export table cells has no borders I'm using jQuery DataTable to display a table. This table includes a "PDF Export" button. The export displays a PDF form but this form has no borders around the cells. It's just a text form (versus a table like Excel).
I want something like:  for each cell but I can't seem to find a way to do this. Can anyone help?
My javascript code to set up this DataTable looks like the following:
$("table[id$='jQueryDataTable']").dataTable(
            {
                aLengthMenu: [
                    [10, 25, 50, 100, 200, -1],
                    [10, 25, 50, 100, 200, "All"]
                ],
                iDisplayLength: -1,
                dom: 'Blrftip',
                buttons: [
                    {
                        extend: 'pdf',
                        title: 'Non Desctructive Inspection ' +
                            '   DATE: ' + d,
                        pageSize: 'A2',
                        orentation: 'landscape',
                        exportOptions: {  // This is IMPORTANT --- Monty
                            orthogonal: 'sort'
                        }//,
                        //function(){}
                    }
                ],
                aoColumnDefs: [{
                    "aTargets": [0, 1, 2, 3, 4, 5, 6],
                    "defaultContent": "",
                    "ordering": true
                }

});
Thanks in advance.
Steve

A: Add this to customize function:
var objLayout = {};
objLayout['hLineWidth'] = function(i) { return .8; };
objLayout['vLineWidth'] = function(i) { return .5; };
objLayout['hLineColor'] = function(i) { return '#aaa'; };
objLayout['vLineColor'] = function(i) { return '#aaa'; };
objLayout['paddingLeft'] = function(i) { return 8; };
objLayout['paddingRight'] = function(i) { return 8; };
doc.content[0].layout = objLayout;

Complete datatable implementation is:
$('#datatable').DataTable({
        lengthMenu: [
            [4, 7, 10, 15, 20, -1],
            [4, 7, 10, 15, 20, "Todo"]
        ],
        responsive: true,
        paging: true,
        pagingType: "full_numbers",
        stateSave: true,
        processing: true,
        dom: 'Blftirp',
        buttons: [
            {
                extend: 'copyHtml5',
                text: '',
                titleAttr: 'Copy',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                text: '',
                titleAttr: 'PDF',
                extension: ".pdf",
                filename: "name",
                title: "",
                orientation: 'landscape',
                customize: function (doc) {

                    doc.styles.tableHeader = {
                        color: 'black',
                        background: 'grey',
                        alignment: 'center'
                    }

                    doc.styles = {
                        subheader: {
                            fontSize: 10,
                            bold: true,
                            color: 'black'
                        },
                        tableHeader: {
                            bold: true,
                            fontSize: 10.5,
                            color: 'black'
                        },
                        lastLine: {
                            bold: true,
                            fontSize: 11,
                            color: 'blue'
                        },
                        defaultStyle: {
                            fontSize: 10,
                            color: 'black'
                        }
                    }

                    var objLayout = {};
                    objLayout['hLineWidth'] = function(i) { return .8; };
                    objLayout['vLineWidth'] = function(i) { return .5; };
                    objLayout['hLineColor'] = function(i) { return '#aaa'; };
                    objLayout['vLineColor'] = function(i) { return '#aaa'; };
                    objLayout['paddingLeft'] = function(i) { return 8; };
                    objLayout['paddingRight'] = function(i) { return 8; };
                    doc.content[0].layout = objLayout;

                    // margin: [left, top, right, bottom]

                    doc.content.splice(0, 0, {
                        text: [
                            {text: 'Texto 0', italics: true, fontSize: 12}
                        ],
                        margin: [0, 0, 0, 12],
                        alignment: 'center'
                    });

                    doc.content.splice(0, 0, {

                        table: {
                            widths: [300, '*', '*'],
                            body: [
                                [
                                    {text: 'Texto 1', bold: true, fontSize: 10}
                                    , {text: 'Texto 2', bold: true, fontSize: 10}
                                    , {text: 'Texto 3', bold: true, fontSize: 10}]
                            ]
                        },

                        margin: [0, 0, 0, 12],
                        alignment: 'center'
                    });

                    doc.content.splice(0, 0, {

                        table: {
                            widths: [300, '*'],
                            body: [
                                [
                                    {
                                        text: [
                                            {text: 'Texto 4', fontSize: 10},
                                            {
                                                text: 'Texto 5',
                                                bold: true,
                                                fontSize: 10
                                            }

                                        ]
                                    }
                                    , {
                                    text: [
                                        {
                                            text: 'Texto 6',
                                            bold: true, fontSize: 18
                                        },
                                        {
                                            text: 'Texto 7',
                                            fontSize: 10
                                        }

                                    ]
                                }]
                            ]
                        },

                        margin: [0, 0, 0, 22],
                        alignment: 'center'
                    });

                },
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'csvHtml5',
                text: '',
                titleAttr: 'CSV',
                fieldSeparator: ';',
                fieldBoundary: '"',
                exportOptions: {
                    columns: ':visible'
                }
            },

            {
                extend: 'print',
                text: '',
                exportOptions: {
                    columns: ':visible',
                }
            },

            {
                extend: 'colvis',
                postfixButtons: ['colvisRestore'],
                collectionLayout: 'fixed four-column'
            }

        ]

    });


text:
Q: how does uploading a file through input type = file open the windows dialog window When we click on choose file. It opens dialog window to choose a file to upload, but I want to know what really happens when we click on choose file and how does that diolog window appears.
Thanks in advance.

A:
there should be some event which gets trigger when we click on choose
  file. I need to know what that event is.

See GlobalEventHandlers.onchange , Using files from web applications , 4.10.5.1.18 File Upload state (type=file)

var input = document.querySelector("input[type=file]");
input.onchange = function(event) {
  console.log(event.target.files)
}
<input type="file" />

A: HTML5 defines a files property for all  controls. This collection is a FileList, which is an array-like structure called FileList containing File objects for each selected file in the control (remember, HTML5 allows multiple file selection in these controls). So at any point in time, you can get access to the files a user has selected using code similar to this:
<input type="file" id="your-files" multiple>
<script>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {

    // When the control has changed, there are new files

    var i = 0,
        files = control.files,
        len = files.length;

    for (; i < len; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }

}, false);
</script></code>

This relatively simple code listens for the change event on the file control. When the event fires, it signifies that the file selection has changed, and the code iterates through each File object and outputs its information. Keep in mind that the files property is always accessible from JavaScript, so you don't have to wait for change to try to read it.
For more information please check the below URLs.
https://www.nczonline.net/blog/2012/05/08/working-with-files-in-javascript-part-1/
https://en.wikipedia.org/wiki/File_select