text:
Q: MockMVC @PathVariable not work when using String Mockmvc test not work when Pathvariable is a String but work on int.
Here is my code:
@Controller
@RequestMapping("/etablissement/{typeEtablissement}")
public class EtablissementController{
    @RequestMapping(method = RequestMethod.GET)
    public String accueil(@PathVariable("typeEtablissement") String typeEtablissement) {
        return "/test";
    }
}

// somewhere in my test
mockMvc.perform(get("/etablissement/{typeEtablissement}", "test")).andExpect(status().isOk()); // Error 400

But, if I use int instead of String it works
@RequestMapping(method = RequestMethod.GET)
public String accueil(@PathVariable("typeEtablissement") int typeEtablissement) {
    return "/test";
}

// somewhere in my test
mockMvc.perform(get("/etablissement/{typeEtablissement}", 123)).andExpect(status().isOk()); // Works

Using Object also work
public String accueil(@PathVariable("typeEtablissement") Object typeEtablissement) {}

Thanks for your help !

A: Here is an example of a GetMapping who should help you :
@GetMapping("/{typeEtablissement}/{something2}/{something3}")
    public List<Object> extract(
            @PathVariable String typeEtablissement,
            @PathVariable String something2,
            @PathVariable String something3) {

List<Object> object = objectService.extractDatas(typeEtablissement, something2, something3);

return object;
}

A: Strange cause it means typeEtablissement is an int. You can also create a new variable after with valueOf:
@GetMapping("/{typeEtablissement}/{something2}/{something3}")
    public List<Object> extract(
            @PathVariable String typeEtablissement,
            @PathVariable String something2,
            @PathVariable String something3) {

String typeEtablissementConverted = String.valueOf(typeEtablissement );

List<Object> object = objectService.extractDatas(typeEtablissementConverted, something2, something3);

return object;
}


text:
Q: Constant Strings? I am writing a workbook to compute double integrals, and in order to graph the function in polar/cylindrical form, I have to make a substitution in the original formula. How can I have the original output in a string, and then changed. Below is a snippet of essentially what is want to do.
Input["Input the function f(r,theta)", function];
r = Sqrt[x^2 + y^2];
function (*this would output as r*)
Plot3D[function,{x,-10,10},{y,-10,10}] (*this would have the substitution made*)

Or, If a function could be defined (a topic I am hopelessly lost on) that would graph in Cylindrical Coordinates (r,theta,z) , something in the form below, to eliminate my above problem, that would be just as welcome
 PolarPlot3D[F[r_,theta_],{r,rmin,rmax},{theta,thetamin,thetamax}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confusion with the principles of Redux I was learning Redux and came across the three principles of it:

*

*single source of truth,

*state is read-only,

*changes are made with pure functions.

I understood the idea behind the first principle but still find myself in confusion with the other two.
Concerning state is read-only, I got that we can update state only via actions and is it true that the reason for using actions to update state is predictability which ensures that there is no unexpected and sudden changes and thanks to actions it is clear when and how state is changed(action is kinda like protection of state being changed unexpectedly)? Right?
Lastly, about changes are made with pure functions yeah I understood that it also gives predictability but cannot get the actual and clear reason behind that. \
Thus I really need your kind help


text:
Q: How to configure JS/TS debugger on PhpStorm like on VSCode with attach option? I am moving from VSCode to PhpStorm. In VSCode I could configure debugger with attach mode.
What is attach mode? It allows you to debug your app in existing browser window. In launch mode new instance of browser is started.
In PhpStorm I can't see that option in docs. Do I search in wrong way? Or there is a trick to do that?
Thank you for response.

A: You can use the Attach to Node.js/Chrome run configuration to attach the debugger to a running Node.js process/Chrome browser started with --remote-debugging-port option. See https://www.jetbrains.com/help/phpstorm/2021.3/running-and-debugging-node-js.html#node_debugging_running_application for more info.


text:
Q: Ошибка сегментации при размерности двумерного массива. Метод Дейкстры (C++) Программа для поиска кратчайшего пути в графе методом Дейкстры. При выполнении максимально возможное число ребер 100х100, при дальнейшем увеличении этого числа программа выдает ошибку сегментации.
При запуске вводим количество вершин и количество ребер, создается квадратная матрица и заполняется случайными данными.
Компилирую на университетском кластере при помощи следующей команды:
mpicxx -o test1.out Lab1.cpp -std=c++11
Код программы:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <climits>
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <chrono>
using namespace std;

class Timer
{
private:
    using clock_t = std::chrono::high_resolution_clock;
    using second_t = std::chrono::duration<double, std::ratio<1> >;

    chrono::time_point<clock_t> m_beg;

public:
    Timer() : m_beg(clock_t::now())
    {
    }

    double elapsed() const
    {
        return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
    }
};

int main()
{
    int a,c;
    cout << "Enter the number of vertices: ";
    cin >> a;
    cout << "Enter the number of ribs : ";
    cin >> c;
    long int **v = (long int **) malloc(c * sizeof(long int*));
        for (int i = 0; i < c; i++) {
            v[i] = (long int *) malloc(c * sizeof(long int));
    }
    srand(static_cast<unsigned int>(time(0)));
    for (int i = 0; i < c; i++) {
        for (int j = 0; j < c; j++) {
            v[i][j] = v[j][i] = rand() % 10 + 1;
        }
        v[i][0] = v[0][i] = 0;
    }

    bool visit[100];
    int distance[100];
    string path[100];

    Timer t;

    for (int i = 0; i < c; i++) {
        visit[i] = false;
        distance[i] = INT_MAX;
    }

    distance[1] = 0;
    visit[1] = true;

    queue<int>q;

    q.push(1);
    path[1] = to_string(1);

    while (!q.empty()) {
        int vert = q.front();
        q.pop();
        for (int j = 1; j < sizeof(v[vert]); j++) {
            if (!visit[j] && v[vert][j] && v[vert][j] + distance[vert] < distance[j]) {
                distance[j] = v[vert][j] + distance[vert];
                path[j] = path[vert] + "-" + to_string(j);
                q.push(j);
            }
        }
    }

    cout << "Shortest Path Output: \n" << endl;

    for (int j = 2; j < a + 1; j++) {
        cout << "Distance to " << j << " vertex = " << distance[j] << endl;
        cout << "Path to " << j << " vertex: " << path[j] << "\n\n";
    }

    cout << "Time elapsed: " << t.elapsed() << '\n';
    return 0;
}

A: Логично, что программа падает. У Вас есть такие массивы
bool visit[100];
int distance[100];
string path[100];

как раз 100:) я увеличил до 1000 все три числа и теперь при 200 работает как нужно (я надеюсь).
Также, освобождайте память или используйте обычный vector<vector<long int>>


text:
Q: Swap keys for unique values in a dictionary in Python a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = {}
for key, val in a.items():
    b[val] = key
print b

What I am trying to do is to swap value of the dictionary for key. But using this code, I lose some information of the dictionary, getting this output:
{'LinMotion': 10, 'PtpMotion': 9, 'Wait': 11}

Why does it happen?

A: Each key can only occur once in a dictionary.  You could store a list of indices for each key:
import collections
b = collections.defaultdict(list)
for key, val in a.iteritems():
    b[val].append(key)
print b
# {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 'PtpMotion': [0, 1, 9], 'Wait': [11]}

Edit: As pointed out by ecik in the comments, you could also use a defaultdict(set) (and use .add() instead of .append() in the loop).

A: When you say
b[val] = key

and val already exists,it overrides the setting, getting what you see. To get all values, you must map the original values to lists of keys, such as
from collections import defaultdict

b = defaultdict(list)
for key, val in a.items():
    b[val].append(key)
print b

When I do it (python 2.5.1), I get
defaultdict(<type 'list'>, {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10],
                            'PtpMotion': [0, 1, 9],
                            'Wait': [11]})

A: Dictionary keys must be unique.  If you wanted to keep them all you'd have to make each value for b[val] a list and add the values to those lists.

A: Perhaps you want lists in the output dictionary:
from collections import defaultdict
a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = defaultdict(list)
for key, val in a.items():
    b[val].append(key)
print b

yields:
defaultdict(<type 'list'>, {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 'PtpMotion': [0, 1, 9], 'Wait': [11]})


text:
Q: Javascript doesn't execute in Safari when placed in HEAD I'm having a problem with Javascript not executing when placed in the HEAD section of an HTML page in the Safari browser. It works fine in IE, Chrome and Firefox, but with Safari I have to move it down to between the  and  tags.
Anyone know if this is a known issue?
PS. The HTML and Javascript is contained in .PHP files, if that makes a difference.
Update:
Code I'm using to test:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <link href="style.css" rel="stylesheet" type="text/css">

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>

<script type="text/javascript">
    alert("In HEAD Tag");
</script>

</head>
<body>
    <div id="innerthumbcontainer">
    Test
    </div>
</body>
</html>

If I open the page containing this directly it seems to work. But as soon as I load this into a DIV from another page it does not fire in Safari. In all the other browsers it does work though.

A: I think I would have heard about it if that was a general problem, you probably have a syntax error in your HTML or something, which for some reason makes Safari give up. Post your code, preferably the HTML output, and we'll have a chance of telling you what is wrong.
Edit: As far as I understand you are trying to use a complete HTML page as content for a div, you really can't do that. Depending on what exactly you are trying to achieve you could either use an iframe, or you could cut out the html, header and body tags.


text:
Q: How to check if array shares elements with another array in Ruby? I'm currently trying to see if an array of records shares elements with another array.
I'm using the splat operator for a conditional like this:
if @user.tags.include?(*current_tags)
    # code
end

This works when tags are present, but returns this error when current_tags are empty.

wrong number of arguments (given 0, expected 1)

This happens a lot in my app so I was wondering if there are any alternatives to achieving this same functionality but in other way that won't blow up if current_tags is an empty array.

A: Another trick to do the same is:
if current_tags.any? { |tag| @user.tags.include?(tag) }
  ...
end

if you want to be sure that at least one of the current_tags is in the array of @user.tags, or
if current_tags.all? { |tag| @user.tags.include?(tag) }
  ...
end

in case all tags should be there.
Works fine with empty current_tags as well.

A: You can use an intersection to solve this problem instead. The intersection of two arrays is an array containing only the elements present in both. If the intersection is empty, the arrays had nothing in common, else the arrays had the elements from the result in common:
if (current_tags & @user.tags).any?
  # ok
end

A: Add one more condition if current_tags.present?
if current_tags.present? && @user.tags.include?(*current_tags)
    # code
end

As
2.3.1 :002 > [].present?
 => false


text:
Q: In Cocoa how to scale a NSImage with no transparency I'm using this code to scale an image, everything works fine but the resulting image has a transparency in its properties and I just need an image with no transparencies and no alpha channels at all... Anyone knows how could I modify my code to obtain an image with no transparencies?
Here my code:
- (void)scalePreviews:(NSString *)outputPath :(NSURL *)nomeImmagine :(CGFloat)size1   :(CGFloat)size2 :(NSString *)nomeIcona
{
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[nomeImmagine path]];
if (!image)
    image = [[NSWorkspace sharedWorkspace] iconForFile:[nomeImmagine path]];

NSSize outputSize = NSMakeSize(size1,size2);
NSImage *anImage  = [self scaleImagePreviews:image toSize:outputSize];

NSString *finalPath = [outputPath stringByAppendingString:[NSString stringWithFormat:@"/image-previews/%@",nomeIcona]];

//questo serve a creare la directory delle icone se gia' non esiste
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:[outputPath stringByAppendingString:@"/image-previews"] isDirectory:nil])
    if(![fileManager createDirectoryAtPath:[outputPath stringByAppendingString:@"/image-previews"] withIntermediateDirectories:YES attributes:nil error:NULL])
        NSLog(@"Error: Create folder failed %@", [outputPath stringByAppendingString:@"/image-previews"]);

//  NSLog(@"finalPath: %@",finalPath);
NSData *imageData = [anImage TIFFRepresentation];

NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];

NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];

[dataToWrite writeToFile:finalPath atomically:NO];

}

- (NSImage *)scaleImagePreviews:(NSImage *)image toSize:(NSSize)targetSize
 {
       if ([image isValid])
        {

          NSSize imageSize = [image size];
         float width  = imageSize.width;
         float height = imageSize.height;
         float targetWidth  = targetSize.width;
        float targetHeight = targetSize.height;
        float scaleFactor  = 0.0;
        float scaledWidth  = targetWidth;
        float scaledHeight = targetHeight;

        NSPoint thumbnailPoint = NSZeroPoint;

        if (!NSEqualSizes(imageSize, targetSize))
        {
            float widthFactor  = targetWidth / width;
            float heightFactor = targetHeight / height;

            if (widthFactor < heightFactor)
            {
                scaleFactor = widthFactor;
            }
            else
            {
                scaleFactor = heightFactor;
            }

            scaledWidth  = width  * scaleFactor;
            scaledHeight = height * scaleFactor;

            newImage = [[NSImage alloc] initWithSize:targetSize];

            [newImage lockFocus];

            NSRect thumbnailRect;
            thumbnailRect.origin = thumbnailPoint;
            thumbnailRect.size.width = targetSize.width;  //scaledWidth;
            thumbnailRect.size.height = targetSize.height; //scaledHeight;

            [image drawInRect:thumbnailRect
                     fromRect:NSZeroRect
                    operation:NSCompositeSourceOver
                     fraction:1.0];

            [newImage unlockFocus];
        }

 }

 return newImage;

}

A: I found a solution... I changed the representationUsingType... I used JPEGFileType so the image has no transparencies at all...
here the changed code:

NSData *dataToWrite = [rep representationUsingType:NSJPEGFileType properties:nil];


text:
Q: Setting a price cap for AWS Free Tier I'd like to setup a website on the Amazon AWS free tier but I'd like to be sure I won't lose any money if I see a sudden spike in traffic. Is there any way to set a cap on traffic or stop the server after a certain level of cost is reached?
Thanks.

A: Simple answer: No way to do this via the AWS control panel.
The only "solution" I know is to check your account regularly or to implement a check directly on your EC2 instance (see How to cap bandwidth usage on AWS EC2? )

A: I talked to someone from Amazon last night and they said that they definitely get requests for this kind of thing and they are planning to open an API soon that will allow you to write a script to check the amount of money you have spent.
Also, there is a company in Portland ( I forget the name) that offers a interface similar to Mint.com that will report your $$$ usage.


text:
Q: FluentFtp validate server cert against fingerprint I have a powershell script using WinScp that allows me to authenticate the server cert against a fingerprint stored as a string "a1:ec:72:18:8b:c3:dc:12:9b:77:b0:6d:f4:c1:a6:cf:db:47:8f:66:66:15:14:39:c4:62:85:a7:b2:73:f7:93"
I am attempting to implement FluentFtp inside the main data processing app so we no longer need the script.  _ftpsOptions is an object containing various ftps relevant settings from Configuration.  I've read that I need to implement a callback handler to ValidateCertificate so, in my ftps method:
client.Config.ValidateAnyCertificate = _ftpsOptions.IgnoreCertificateErrors;
client.ValidateCertificate += new FtpSslValidation(OnValidateCertificate); //this is ignored if ValidateAnyCertificate is true

and then.
/// <summary>
/// Callback handler for FtpSslValidation
/// </summary>
/// <param name="control"><see cref="BaseFtpClient"/> A base Ftp Client</param>
/// <param name="e"><see cref="FtpSslValidationEventArgs"/> options</param>
private void OnValidateCertificate(BaseFtpClient control, FtpSslValidationEventArgs e)
{

    X509Certificate2 serverCert = (X509Certificate2)e.Certificate;
    if (serverCert.Thumbprint == _ftpsOptions.FingerPrint)
    {
        e.PolicyErrors = SslPolicyErrors.None;
    }
    else
    {
        e.PolicyErrors = SslPolicyErrors.RemoteCertificateNameMismatch;
    }

    if (e.PolicyErrors != System.Net.Security.SslPolicyErrors.None)
    {
        // invalid cert, do you want to accept it?
        e.Accept = false;
    }
    else
    {
        e.Accept = true;
    }
}

To access the Thumbprint property I have to cast to X509Certificate2 as mentioned in several blog posts. There is no 'bad server cert' option in the SslPolicyErrors enum, so picking the closest.
Problem is: check is failing.  I can't see the Thumbprint value in VS because its being optimized away.  Tried adding [MethodImpl(MethodImplOptions.NoOptimization] to the method, but it didn't help. I think it would need adding to the X509Certificate2 class.  Added a Log.Debug and that worked.
[10:50:49 DBG] [FtpsFluent.OnValidateCertificate] Server Thumbprint: 679B8B251C541FA0CCF3734B25A7C523635B9360
[10:50:49 DBG] [FtpsFluent.OnValidateCertificate] Validate Against:  a1:ec:72:18:8b:c3:dc:12:9b:77:b0:6d:f4:c1:a6:cf:db:47:8f:66:66:15:14:39:c4:62:85:a7:b2:73:f7:93

These look different enough that I don't think I'm comparing the same thing.  Should I change my config to store the 679B... value?  Should I be going about this differently?


text:
Q: How to come up with different ways to find the same solution?
A coin has probability $p$ of heads. Adam flips it first, then Becca, then Adam, etc., and the winner is the first to flip heads. Compute the probability that Adam wins.

So I saw this problem this afternoon and I tried solving it on my own. I used the following reasoning to get to the solution:
If $n$ denotes the number of tosses done in total. Then the only way Adam can win is if the head appears at an "odd" trial ($2n-1$). For the head to occur at the $2n - 1$ trial the first $(2n-1) - 1$ tosses must be equal to tails, so I expressed this as
$$p\sum_{n=1}^\infty (1-p)^{2n - 2}$$
I then realized that this is a geometric series, which converges to the following value
$$\frac{p}{1 - (1-p)^2} = \frac{1}{2 - p}$$
From my perspective I thought this was the only way you can get to this result, but the paper from which I got the question from used a very different approach (recursion). So I guess my question is, how can you train yourself to think about problems like this in more than one way?

A: Think about different ways the problem can be represented. The more math you know, the more tools from which you'll have to choose. Also don't try to judge ahead of time which methods will be useful, because you never know what you may discover with a given approach.
For this particular problem, what about drawing out a tree, like this? Let's see...Adam's probability of winning is $0.5 + (0.5)^{3} + (0.5)^{5} + \ ... = 0.5 + 0.125 + 0.03125 + \ ...$, it's not too tough to see that this is steadily going to get closer and closer to a limit of $\frac{2}{3}$.
Are you familiar with Markov chains? That might be a bit quicker. We define 4 states, which are applied to the horizontal and vertical a with the same labels: Adam's flip, Adam wins, Becca's flip, Becca wins. The initial state distribution matrix, then, looks like this:
$$\begin{pmatrix}
0 &0.5  &0.5  &0 \\
0 &1  &0  &0 \\
0.5 &0  &0  &0.5 \\
0 &0  &0  &1
\end{pmatrix}$$
Translation:
First row says: there's no chance of going from Adam's flip to Adam's flip, a 50% chance of moving from Adam's flip to Adam's win, a 50% chance of moving from Adam's flip to Becca's flip, and no chance of moving from Adam's flip to Becca's win.
Second row says: There's a 100% chance of moving from Adam's win to Adam's win (absorbing state).
Third row says: there's a 50% chance of moving from Becca's flip to Adam's flip, no chance of moving from Becca's flip to Adam's win, no chance of moving from Becca's flip to Becca's flip, and a 50% chance of moving from Becca's flip to Becca's win.
Fourth row says: There's a 100% chance of moving from Becca's win to Becca's win (absorbing state).
To find out how this plays over the long run, we raise this to infinity (or, more realistically, an arbitrarily high power), to get the stability distribution.
Overall, I would recommend 3 things to help learn to vary your mathematical perspective:

*

*Read Martin Gardner's books, especially his 15 collections of Scientific American columns. Persi Diaconis put it best when he said, "Martin Gardner has turned thousands of children into mathematicians, and has turned thousands of mathematicians into children." Martin Gardner's 2 books, Aha! Gotcha! and Aha! Insight! are also great lessons in changing your mathematical perspective.

*Study James Tanton's Curriculum Inspirations material closely.

*Learn that you will never be stumped if you change your point of view.

A: It's not really a different approach.   Demonstrating recursion is a method by which the closed form of a geometric series can be obtained.
$$\begin{align}S & = \sum_{k=0}^\infty r^k  \\ &= 1+r\sum_{k-1=0}^\infty r^{k-1} \\[1ex] &= 1+ rS \tag{Recurrence} \\[2ex] \therefore \quad S &= \frac{1}{1-r}\end{align}$$
So if a geometric series is involved in evaluating the probability, there will be a recurrence in the set-up.   If you can spot the recursion, you can use it to directly evaluate the probability.   It may be easier to find one or the other depending on how you look at it.
You just need to be familiar with the proofs of the results you use and have practice spotting patterns.
Practice, practice, practice.
Also practice some more.
And when you are not practicing, practice.

A: Let $A$ be Adam's win probability.
He has a probability  $p$ of winning on the first flip, and a $(1-p)^2$ probability of surviving the second - at which point his probability of winning would be $A$, because it's the same game.
So, $A = p + (1-p)^2A$, which reduces to the answer in the paper.
Even more tersely, the probability of Adam winning when it's not his flip is $1-A$.
So, $A = p + (1-p)(1-A)$; that gives $A(2-p) = 1$ directly.


text:
Q: Как автоматически создать таблицу на основе сущности с помощью Hibernate? Я тренируюсь использовать JPA, для понимания работы сущностей, аннотаций, менеджера сущностей описываю достаточно сложные или новые сущности. Чтобы использовать EntityManager у меня должны быть созданы таблицы. Руками через SQL со всеми зависимостями их не очень легко создавать. Я знаю, что можно настроить hibernate что бы он сам создавал таблицы на основе сущностей. Я искал в интернете, на киберфоруме, на стэковерлоф, на туториалах от хибернейта, но все равно не понял до конца как это сделать. Единственное, что я понял - что в persistence.xml надо указать строку  <property name="hbm2ddl.auto" value="create"/>. Я указал, но ничего не происходит при запуске хибернейта, таблиц не появляются в бд. Что мне сделать, что бы у меня создались таблицы на основе сущностей которые я описал? Может кто то пошагово описать все шаги которые я должен сделать чтобы получить бд на основе сущности?
Вот логи которые идут после подключения хибернейта к пользователю бд:
апр. 05, 2019 3:29:12 ПП org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
апр. 05, 2019 3:29:12 ПП org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
апр. 05, 2019 3:29:12 ПП org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
апр. 05, 2019 3:29:13 ПП org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

UPD Теперь другая ошибка при создании таблицы. Вот логи:
Hibernate:

    create table User (
       id int4 not null,
        name varchar(255) not null,
        password varchar(255) not null,
        primary key (id)
    )
апр. 05, 2019 3:45:41 ПП org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "
    create table User (
       id int4 not null,
        name varchar(255) not null,
        password varchar(255) not null,
        primary key (id)
    )" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "
    create table User (
       id int4 not null,
        name varchar(255) not null,
        password varchar(255) not null,
        primary key (id)
    )" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:156)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:56)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at Main.main(Main.java:10)
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "User"
  Позиция: 20

Вот класс User, на позиции 20 там ничего такого нет:
@Entity
public class User {
    private int id;
    private String name;
    private String password;

    public User() {
    }

    public User(String name, String password, int id) {
        this.name = name;
        this.password = password;
        this.id = id;
    }

    @Id @GeneratedValue
    @Column(nullable = false)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Size(max = 255)
    @Column(nullable = false)
    @Access(AccessType.PROPERTY)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Size(max = 255)
    @Column(nullable = false)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Users{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (!Objects.equals(name, user.name)) return false;
        return Objects.equals(password, user.password);

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (password != null ? password.hashCode() : 0);
        return result;
    }
}

A: Если изначально следовать туториалу по настройки проекта, то есть использую Spring-Boot
Достаточно в src/main/resources/application.properties прописать
// Для автоматического создание таблиц на основание сущностей
spring.jpa.hibernate.ddl-auto=create

Позже после создание, таблиц рекомендуются перевести данную настройку в
spring.jpa.hibernate.ddl-auto=validate

A: Вы пропустили ключевое слово hibernate в названии свойства
<property name="hibernate.hbm2ddl.auto">create</property>

Ответ на второй вопрос: hibernate запрещает создавать таблицы с именем User.

A: Вот пример persistence unit для соединения с H2 (in-memory) базой данных:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="com.example">
        <!-- Ваши сущности -->
        <class>com.example.Event</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MVCC=TRUE" />
            <property name="javax.persistence.jdbc.user" value="sa" />
            <property name="javax.persistence.jdbc.password" value="" />

            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
        </properties>
    </persistence-unit>

</persistence>

Когда Persistence Provider (Hibernate) создает таблицы из сущностей? Если говорить просто и не вдаваться во внутреннюю реализацию, то при создании EntityManagerFactory, то есть, грубо говоря, после строки
EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.example");

все таблицы будут созданы.

A: Если Вы очень хотите разобраться, что происходит, когда Вы пытаетесь построить таблицы на основе entity, то посмотрите на класс org.hibernate.tool.hbm2ddl.SchemaExport (пакет находится в hibernate-core.jar). У класса имеется метод main, который можно запустить с передачей параметров (например в eclipse откройте этот класс и по правой клавише вызовите Run as > run configuration и на закладке Arguments допустим такие параметры --target=SCRIPT --config=my_hibernate.cfg.xml --output=script.txt  --implicit-naming=legacy-hbm  --physical-naming= com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy ). Полный список параметров см. в методе parseCommandLineArgs().
Кроме того, имеется класс  org.hibernate.tool.hbm2ddl.SchemaUpdate, который используется когда надо получить изменеия в БД, после изменения entity.

A: Необходимо задать следующий параметр
<property name="hbm2ddl.auto">update</property>


text:
Q: Error importing Typescript-compiled modules with System.js I am recently learning to use system.js to import modules which compiled by Typescript. The modules were previously compiled for require.js, and works fine.
However, when merging to system.js, the modules cannot be imported when applying system-production.js. The console says
Uncaught (in promise) Error: Module instantiation did not call an anonymous or correctly named System.register.
   Instantiating https://www.star.com/libs/js/klondike.js
   Loading ./libs/js/klondike.js
    at register-loader.js:203
t           @ common.js:83
(anonymous) @ loader-polyfill.js:70

I don't quite understand what causes the error message. And when I applying system.src.js, there won't be error message, but I cannot use functions in the imported modules. Any call will return undefined. So did I operate in a wrong way?
Below is the source code.
test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
</body>

<!-- sys import -->
<script src="libs/js/system-production.js"></script>

<!--<script src="libs/js/system.src.js"></script>-->

<script>
    System.import("./libs/js/klondike.js");
</script>

</html>

tsconfig.json
{
  "compilerOptions": {
    "module": "System",
    "outFile": "../../js/klondike.js",
    "target": "es5",
    "sourceMap": true,
    "removeComments": true
  },
    "include": [
    "./*"
  ]
}

Main module: CardMoves.ts
//sys import
import * as DBJSN from "./debugJson";
import PokerCard from "./Cards";

let suits: string[] = ["spade", "heart", "club", "diamond"];
let cards: string[] = [, "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

//sys export
export function createDeck() {
    let playCards: PokerCard[] = new Array(DBJSN.settings.decks*52);

    console.log(playCards);

    for (let i=0; i<playCards.length; i++) {
        playCards[i] = new PokerCard();
        playCards[i].suit = suits[Math.floor(i % 52 / 13)];
        playCards[i].card = i % 52 % 13 + 1;
    }

    return playCards;
}

Dependency1: Cards.ts
//sys export
export default class PokerCard {
    private _suit: string;
    private _card: number;

    constructor() {}

    //Suit getter and setter
    get suit(): string {
        return this._suit;
    }

    set suit(newSuit: string) {
        try {
            if (this._suit === undefined)
                this._suit = newSuit;
            else
                throw "Suit value has been set.";
        }
        catch(e) {
            console.log(e);
        }
    }

    //Card getter and setter
    get card(): number {
        return this._card;
    }

    set card(newCard: number) {
        try {
            if (this._card === undefined)
                this._card = newCard;
            else
                throw "Card value has been set.";
        }
        catch(e) {
            console.log(e);
        }
    }
}

Dependency2: debugJson.ts
//sys export
export let settings = {
    decks: 1,
    cardsPerClick: 1,
    timer: true
};

A: I had the same issue. The problem was I tried to use bundle as regular module. According to documentation bundle should have several System.register calls. Then you have to add this bundle via script tag as regular js file. And after that call your start point module (createDeck in your case I assume).
Please follow https://github.com/systemjs/systemjs/blob/master/docs/production-workflows.md for more information.
Hope this helps!


text:
Q: Uncaught TypeError: Cannot read property 'removeClass' of undefined i've got a problem with my jquery code i feel the solution is quite simple but i just can't get it, it's a simple .on click function on an element with a class But when i click on the element  it gives me this error "Uncaught TypeError: Cannot read property 'removeClass' of undefined" does anyone know what i'm doing wrong here?
$("body").on( "click", ".fa-caret-right", function(e) {
    e.trigger.removeClass("fa-caret-right");             // <--- right here
    e.trigger.addClass("fa-caret-down");
    e.trigger.parent().next().css("display", "block");
});
$("body").on( "click", ".fa-caret-down", function(e) {
    e.trigger.removeClass("fa-caret-down");             // <--- and probably here
    e.trigger.addClass("fa-caret-right");
    e.trigger.parent().next().css("display", "none");
});

thanks in advance!

A: e is the Event object, which doesn't have a property called trigger.  Since trigger doesn't exist, you can't call functions on it.
What are you trying to do here?:
e.trigger.removeClass("fa-caret-right");

If you want to remove the class from the element which invoked the handler (the element which was clicked), you can reference that element with this:
$(this).removeClass("fa-caret-right");

Or, if you want to use the Event object, you may be looking for the target property:
e.target.removeClass("fa-caret-right");


text:
Q: Traversing json using with square brackets with jsx I need some help with my syntax please in trying to get thevalue from a key. Given the following json object:
{
"records": [
    {
        "id": "recD17v5uIGpA7jYU",
        "fields": {
            "header h1": "Clouds",
            "Email": 1,
            "header figure": [
                {
                    "id": "attmeLF6GWqLF3iOS",
                    "url": "https://dl.airtable.com/.attachments/d6c5f674aeb427dd533cd2c60ab2b29f/f2f99dc0/80__clouds.jpg",
                    "filename": "80__clouds.jpg",
                    "size": 2334688,
                    "type": "image/jpeg",
                    "thumbnails": {
                        "small": {
                            "url": "https://dl.airtable.com/.attachmentThumbnails/7c3dc033b1a7f77fcdeddb2f594a1feb/9a93ab8d",
                            "width": 36,
                            "height": 36
                        },
                        "large": {
                            "url": "https://dl.airtable.com/.attachmentThumbnails/6145b560b5c807787814fcf9b39e6130/0f7d0049",
                            "width": 519,
                            "height": 512
                        },
                        "full": {
                            "url": "https://dl.airtable.com/.attachmentThumbnails/ecebeb4705ba5531744d556242ddc081/20e10b2a",
                            "width": 2121,
                            "height": 2094
                        }
                    }
                }
            ]
        },
        "createdTime": "2019-02-12T09:53:52.000Z"
    },
    {
        "id": "recXiwDKIMSiGd2fn",
        "fields": {
            "header h1": "People",
            "Email": 2,
            "header figure": [
                {
                    "id": "attr1iy10UnygtRx0",
                    "url": "https://dl.airtable.com/.attachments/67484295777d866d6610ef9f84f8bc53/81ae8e6b/A07.jpg",
                    "filename": "A07.jpg",
                    "size": 1014718,
                    "type": "image/jpeg",
                    "thumbnails": {
                        "small": {
                            "url": "https://dl.airtable.com/.attachmentThumbnails/786cc58d3f5b82f4a8414d89b5ea48fb/4a214afc",
                            "width": 14,
                            "height": 36
                        },
                        "large": {
                            "url": "https://dl.airtable.com/.attachmentThumbnails/3cb6be2be2b42be2c240f4f2bb9b7901/3bf2b62b",
                            "width": 512,
                            "height": 1288
                        },
                        "full": {
                            "url": "https://dl.airtable.com/.attachmentThumbnails/4e56dafdcf39da1f35c1e2f9e96fda6c/07d91945",
                            "width": 800,
                            "height": 2013
                        }
                    }
                }
            ]
        },
        "createdTime": "2019-02-12T09:53:52.000Z"
    },
    {
        "id": "recvSJHL3EkSBprs9",
        "fields": {
            "Email": 3
        },
        "createdTime": "2019-02-12T09:53:52.000Z"
    }
],
"offset": "recvSJHL3EkSBprs9"

}
I'm able to extract the value for "header h1" key with the following jsx

{record.fields["header h1"]}

I'm now trying to extract the value from the "url" key. I've tried the following.

and

I'm getting TypeError: Cannot read property "url" of undefined.Need some help with my syntax please

*

*List item

A: your records is an array, also you must specify wich position you want to read:
I tested your json with jq:
jq '.records[0].fields["header figure"][0]["url"]'

delivers
"https://dl.airtable.com/.attachments/d6c5f674aeb427dd533cd2c60ab2b29f/f2f99dc0/80__clouds.jpg"

and
jq '.records[1].fields["header figure"][0]["url"]'

delivers
"https://dl.airtable.com/.attachments/67484295777d866d6610ef9f84f8bc53/81ae8e6b/A07.jpg"


text:
Q: How to specify the websocket connect timer in CPPRest SDK I'm trying to connect an websocket server with CPPRest SDK.
But as per their documentation there is no timeout in websocket_client_config compared to http_client_config.
So how do I correctly specify the timeout so that the connect pplx::task will exit after the mentioned timeout?

A: You can't. Actually CPPRest SDK seems to be abandoned. The websocket part was changed last time 3 years ago. Don't use in new projects. Consider using Boost.Beast or WebSocket++ by Zaphoyd.


text:
Q: can't upgrade from google chrome 45 to 50. Says, Unable to find expected entry i have looked at some of the solutions here, but nothing worked:
Unable to find expected entry 'main/binary-i386/Packages - Chrome and No more updates for Google Chrome | apt-get update error.
i'm currently running Chrome 45.0.2454 (64-bit) on my Ubuntu 14.04 64-bit box.
I have been trying to upgrade chrom to version 50 for several hours, but nothing seems to work.Tried doing it using Software Centre as well but to no avail (nothing happens when I click "Install" as mentioned in the first answer here as well). When i try to upgrade Chrome to 50, using sudo apt-get update i get,
W: Failed to fetch http://dl.google.com/linux/chrome/deb/dists/stable/Release  Unable to find expected entry 'main/binary-i386/Packages' in Release file (Wrong sources.list entry or malformed file).

i have added [arch=amd64] into /etc/apt/sources.list.d/google-chrome.list, but when i do sudo apt-get update i get the same error message.
my google-chrome.list file looks as below now:
cat /etc/apt/sources.list.d/google-chrome.list
deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main

How do i upgrade my chrome 45 to 50?
few more information to help someone help me:
sudo apt-get install google-chrome-stable
Reading package lists... Done
Building dependency tree
Reading state information... Done
google-chrome-stable is already the newest version.
The following packages were automatically installed and are no longer required:
  libkactivities-models1 mysql-server-core-5.5
Use 'apt-get autoremove' to remove them.
0 to upgrade, 0 to newly install, 0 to remove and 51 not to upgrade.
W: Duplicate sources.list entry http://dl.google.com/linux/chrome/deb/ stable/main amd64 Packages (/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-amd64_Packages)
W: Duplicate sources.list entry http://dl.google.com/linux/chrome/deb/ stable/main amd64 Packages (/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-amd64_Packages)
W: You may want to run apt-get update to correct these problems

A: One possible workaround is downloading and installing latest chrome (.deb) from Google manually.
After having downloading it you have to either installing it by doubleclicking the .deb file or executing
sudo dpkg -i /path/to/local/chrome.deb

Manually installing the deb should as well add a new entry to your sources for later upgrades.

A: My chrome said that google will not support anymore old kernels with updates
Maybe thats why it doesn't work!
Try to get the latest kernel version and than try again.


text:
Q: GCM egistration_ids field deprecation? Can someone clarify the status of the registration_ids field?  From my interpretation it is at risk of becoming unsupported.  What is meant by "for general purposes"?
"Though for general purposes it is deprecated, you can use registration_ids as a target for multicast messages to more than one device (up to 1000)."[1]
[1] https://developers.google.com/cloud-messaging/server

A: As I understand it, if you are using the registration_ids field to send messages to one device at a time, you should use the to field instead. Only if you are using registration_ids to send a message to multiple devices you should keep using it.
It's not marked as deprecated in Table 1 here, while another parameter (notification_key) is marked as deprecated.
That said, there's a long way from deprecated to not supported. The old C2DM service that was deprecated and replaced by GCM about 3 years ago is still supported.


text:
Q: AOP on Spring Managed JSF beans I am trying to apply AOP on Spring managed JSF Beans, but for some reason as soon as I apply AOP JSF is throwing MethodNotFoundException.
here is my code :
Web.xml
<application>
<default-render-kit-id>org.apache.myfaces.trinidad.core</default-render-kit-id>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>

applicationContext.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:security="http://www.springframework.org/schema/security"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<aop:aspectj-autoproxy/>
 <bean id="loginAuditAspect" class="com.test.mobile.service.LoginAuditManagementAspect">
 <constructor-arg index="0">
<list>
<bean class="com.test.mobile.service.LoginAuditableResourceResolver" />
<bean class="com.test.mobile.service.LoggedInAuditableResourceResolver" />
<bean class="com.test.mobile.service.NavigationAuditableResourceResolver" />
</list>
</constructor-arg>
</bean>

   <bean id="loginService" class="com.test.mobile.service.MLoginServiceImpl" />
   <bean id="memberService" class="com.test.mobile.service.MMemberServiceImpl"
         scope="session">
    <property name="thpContext" ref="thpContext"></property>
    </bean>

  <bean id="mMemberProfileBean" class="com.test.mobile.service.MMemberProfileBean"
        scope="session">
  <property name="memberService" ref="memberService"></property>
  </bean>

  <bean id="testBean" class="com.test.mobile.service.TestBean" scope="session">
  </bean>
  </beans>

Backing Bean:
 public class TestBean extends BaseBackingBean {
   private static final long serialVersionUID = 1L;

   @Auditable(resourceName="LoggedIn",
 resourceResolverClass=com.test.mobile.service.LoggedInAuditableResourceResolver.class)
public String getXxx() {

    return null;
}

}
Can someone help me in applying AOP logic on spring managed JSF beans

A: You should post at least some info about the stack trace and the aspect.  But if you are losing methods just only applying the aspetct try with:
<aop:aspectj-autoproxy proxy-target-class="true"/>

That uses CGLIB to proxy classes instead jdk proxies (that only proxy interfaces).


text:
Q: Import library into xamarin How do you import a library into Xamarin?
For instance, how would i import json.net into xamarin for my project?
Thanks

A: Json.NET is available as a nicely packaged free Xamarin-compatible Component from the Component Store.  You can also install from NuGet, but it is generally more difficult to determine which NuGet packages are Xamarin (or PCL) compatible.

A: Go to
Project=>Add Packages..
Should see Json.NET, just check it.

A: What's your IDE?
if Xamarin Studio:
   (your project root node) => Add Packages..., then type in the search box.
if Visual Studio:
   right click on References of your project, and click Manage NuGet Packages..., then type in the search box.

A: In xamarin studio Go to Project  -> Add Packages
Search Json.NE and added.

A:
Adding packages is really easy. Just click the settings cog on the Xamarin Packages folder in the solution explorer to add packages.
Also I am not sure why your question was downvoted. Seems like a good one to me (Upvoted)!

A: Go to solution window and check your project.
Right click on component->click on "get more component" -> search for required package and Click on "Add"
thus, you can get your required package.


text:
Q: JavaScript micro library for Ext JS style layouts? I've been developing with Ext JS for a while but a new project has me getting up to speed on the world of JS micro frameworks/libraries. Are there any JS layout libraries that provide an abstraction layer to do things that come close to Ext JS container style layouts (hboxes, vboxes, anchor layouts, etc)?
I didn't seen anything on microjs.com but thought I'd ask here to double-check.

A: MochaUI springs to mind (not a micro framework, but smaller than Ext).
Others that might interest you are uki and Moolego UI.

A: After doing some more research the CSS3 Flexible Box Model is everything I'm looking for.
http://www.html5rocks.com/en/tutorials/flexbox/quick/
http://www.css3.info/introducing-the-flexible-box-layout-module/
http://www.the-haystack.com/2010/01/23/css3-flexbox-part-1/


text:
Q: Undefined reference to `PyString_FromString' I have this C code:
... [SNIP] ...
for(Node = Plugin.Head; Node != NULL; Node = Node->Next) {
    //Create new python sub-interpreter
    Node->Interpreter = Py_NewInterpreter();
    if(Node->Interpreter == NULL) {
        Die("Py_NewInterpreter() failed");
    }

    //Create path to plugins main source file
    snprintf(Filename, FILENAME_MAX, "%s/main.py", Node->File);

    //Convert filename to python string
    PFilename = PyString_FromString(Filename);
    if(PFilename == NULL) {
        Die("PyString_FromString(%s) failed", Filename);
    }

    //Import plugin main source file
    PModule = PyImport_Import(PFilename);
    if(PModule == NULL) {
        Die("PyImport_Import(%s) failed", Filename);
    }

    //Deallocate filename
    Py_DECREF(PFilename);

    //Get reference to onLoad function from module
    PFunction = PyObject_GetAttrString(PModule, "onLoad");
    if(PFunction == NULL) {
        Die("PyObject_GetAttrString() failed");
    }
}
... [SNIP] ...

Which gives this error when compiled:
/tmp/ccXNmyPy.o: In function `LoadPlugins':
/home/alex/Code/Scribe/Scribe.c:693: undefined reference to `PyString_FromString'
collect2: error: ld returned 1 exit status

Python.h is included at the top of the source file.
I'm compiling with:
gcc -funwind-tables -rdynamic -I /usr/include/python2.7/ -g -o Scribe Scribe.c -lcurses `python-config --cflags` `python-config --ldflags` -Wall

I'm basing the code on the Python C-Api docs, from here:
http://docs.python.org/2/c-api/
Specifically:
http://docs.python.org/2/c-api/string.html?highlight=pystring_fromstring#PyString_FromString
I have no idea why this is happening, halp? =c

A: Solved it, thanks to some help from martineau.
Turns out the python-config --cflags and python-config --ldflags lines generated flags that included the python3.3 include directory in the search path and linked the python3.3 lib.
Naturally python3.3 doesn't work so well with python2.7 C-API, which is what caused this problem.
My solution was to copy the output of python-config --cflags and python-config --ldflags and edit it so it included python2.7 instead of python3.3m:
-I/usr/include/python2.7 -I/usr/include/python2.7 -Wno-unused-result -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2

-lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic

Instead of:
-I/usr/include/python3.3m -I/usr/include/python3.3m -Wno-unused-result -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2

-lpthread -ldl -lutil -lm -lpython3.3m -Xlinker -export-dynamic

A: The order of the libraries is important. Try compiling with -lpython2.7 appearing last in the library list.


text:
Q: (for) any longer Is 'for' necessary before 'any longer', or at all?
I won't be able to talk (for) any longer.
I can't talk (for) any longer.
I can't workout (for) any longer.

A: From my understanding of the intended meaning of these sentences, for is not required in these sentences.
In your example, "I won't be able to talk any longer" the words "talk any longer" is what you won't be able to do. There is no need to have a for in the sentence as the meaning is clear without it.
For is a word that can be used in many ways. In Mirriam Webster's online dictionary we see that one of the meanings of for is listed as:

9 -- used as a function word to indicate duration of time or extent of space

In your example sentences, the prase 'any longer' does not require the use of the word for as it is not indicating a duration in time, even though it may appear to be. Instead it is indicating the cessation (stopping) of the activity.
You would need to use for in these alternative sentences, which do refer to a duration of time:
"I won't be able to talk for two days after the operation."
"I can't talk for longer than 20 minutes."
"I can't workout for more than 30 minutes."


text:
Q: Trying to create method that will return ArrayList using SQL statement and key I am trying to write a generic method that will take an SQL string and a key value, and return an ArrayList, where T is the appropriate type for the rows in the result set. I keep running into type erasure issues. My latest attempt looks like:
    public static <T extends CMObject> void populateCMObjectsByKey(int key, String SQL, ArrayList<T> list) throws SQLException, ObjectNotFoundException {

        Connection connection = null;
        PreparedStatement pstatement = null;
        ResultSet rs = null;

        try {
            connection = TomcatConnectionManager.getInstance().getConnection(ClientManagerConstants.dbName);
            pstatement = connection.prepareStatement(SQL);
            pstatement.setInt(1, key);
            rs = pstatement.executeQuery();
            while (rs.next()) {
                T.createFromResultSet(rs, list);
            }
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstatement != null) {
                pstatement.close();
            }
            //
            connection.close();
            TomcatConnectionManager.getInstance().freeConnection(ClientManagerConstants.dbName, connection);
        }
        return;
    }

The compiler indicates an an error on "T.createFromResultSet(rs, list);", which reads "The method createFromResultSet(ResultSet, ArrayList) in the type CMObject is not applicable for the arguments (ResultSet, ArrayList)". Is what I'm trying to do not possible?

A: The problem is that static methods are not available from a generic type reference -- only non-static methods from any upper bound (here, CMObject).  Also, static methods cannot be overridden.
For both of those reasons, making createFromResultSet non-static in CMObject and its subclasses is the only way to make this work.  But then you'll need an instance to work on.
// Add an instance as another parameter.
public static <T extends CMObject> void populateCMObjectsByKey(
    int key, String SQL, ArrayList<T> list, T populator)
    throws SQLException, ObjectNotFoundException {

Then you'll be able to call the method on the instance:
populator.createFromResultSet(rs, list);


text:
Q: Decoding JSON with invalid characters I have a service that is receiving data from an outside service (through a redis list used as a queue). The data is just a flat JSON-encoded dictionary, an example may look like this:
{
  "type": "visit",
  "referer": "http://www.google.com/",
  "session_referer": "http://www.google.com/\x0e",
  "uuid": "48e8ea41-420d-021c-be16-7ac5b7c6fb97",
  "user_ip": "1.2.3.4",
  "user_agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36",
  "user_locale": "en_US",
}

The problem is that, as you can see in the above example, sometimes the referrer or session_referrer has invalid data (that can't be decoded using any of the encodings I expect such as UTF-8, ISO-8859-1, etc.).
My issue is that I can't access any of the other data. I can live with the fact that the referrer is messed up, but I still need the other data. Is there any way to do a "raw" decode without turning the data into any specific encoding and then letting me handle it from there?

A: Given a text file containing your JSON-like "string" with

*

*a hex 0E byte in the "session_referer" value, and

*a spurious comma following the last key/value pair:

the following Python code removes the troublesome values ...
# -*- coding: iso-8859-1 -*-
import json
import re

# retrieve the JSON data into a string
f = open(r'C:\Users\Gord\Desktop\jsonData.txt', 'r')
s = f.read()
f.close()
print '~> raw JSON string'
print s
print

# remove "characters" below \x20 except \n
s = re.sub(r'[\000-\011\013-\037]', '', s)
# remove (extraneous) last comma
s = re.sub(',\n}$', '\n}', s)
print '~> tweaked JSON string'
print s
print

# decode tweaked JSON string
j = json.loads(s)

# see what we got
print '~> decoded result "pretty printed"'
print json.dumps(j, sort_keys=True, indent=4, separators=(',', ': '))
print

# extract just one element
print '~> print just j["user_ip"]'
print j["user_ip"]

... and produces the following results in the Python IDLE shell:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
~> raw JSON string
{
  "type": "visit",
  "referer": "http://www.google.com/",
  "session_referer": "http://www.google.com/♫",
  "uuid": "48e8ea41-420d-021c-be16-7ac5b7c6fb97",
  "user_ip": "1.2.3.4",
  "user_agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36",
  "user_locale": "en_US",
}

~> tweaked JSON string
{
  "type": "visit",
  "referer": "http://www.google.com/",
  "session_referer": "http://www.google.com/",
  "uuid": "48e8ea41-420d-021c-be16-7ac5b7c6fb97",
  "user_ip": "1.2.3.4",
  "user_agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36",
  "user_locale": "en_US"
}

~> decoded result "pretty printed"
{
    "referer": "http://www.google.com/",
    "session_referer": "http://www.google.com/",
    "type": "visit",
    "user_agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36",
    "user_ip": "1.2.3.4",
    "user_locale": "en_US",
    "uuid": "48e8ea41-420d-021c-be16-7ac5b7c6fb97"
}

~> print just j["user_ip"]
1.2.3.4
>>>

A: You can try by setting strict = false which allows control characters within string.
https://docs.python.org/2/library/json.html


text:
Q: C# NUnit unit test not using correct method return to compare I have the following class
public static class MyClass
{
    public static double Converter(int mpg)
    {
       return Math.Round((double)mpg / ((double)36 / 12.74), 2);
    }
}

And NUnit unit test
[TestFixture]
public class ConverterTests
{
    [Test]
    public void Basic_Tests()
        Assert.AreEqual(8.50, MyClass.Converter(24));
    }
}

My Unit tests fails with
Expected: 8.5d
But was:  8.4900000000000002d

When I debug the method return 8.49 so where does the unit test get the long number from with a 2 at the end?

A: The unit test shows the same result as I see when executing the code. Here's a short but complete program to show the exact result retrieved, using my DoubleConverter class.
using System;

class Test
{
    static void Main()
    {
        double x = Convert(24);
        Console.WriteLine(DoubleConverter.ToExactString(x));
    }

    static double Convert(int mpg)
    {
        return Math.Round((double) mpg / ((double) 36 / 12.74), 2);
    }
}

Result:
8.4900000000000002131628207280300557613372802734375

Using a calculator, I'd expect the unrounded result to be 8.4933333 - which would indeed round to "about 8.49" when rounded to two decimal places.
So really, the question is more why you're seeing 8.5 in the debugger than why the unit test fails. I'm not seeing that myself, so you might want to look into exactly how you're debugging. When you debug, you may be seeing different results because:

*

*In debug you may be using different floating point operations, e.g. "pure" 64-bit instead of the 80-bit intermediate operations which are permitted by .NET

*You may be debugging other code which sets the floating point mode of the processor to 32-bit; I've seen this happen when using DirectX, but I'd expect you to be aware that you're doing it

*The debugger may be displaying the results in a truncated form, although I wouldn't expect it to truncate that number to 8.5

A: 'double' is a dirty trick to manipulate fractions... :-)
You should NEVER test for equality when talking about doubles.
The correct way to test is: Math.Abs(8.50 - MyClass.Converter(24)) < TOLERANCE
Where 'TOLERANCE' is how much variance is accepted.
Ex.
for TOLERANCE == 0.001
8.5004 == 8.50
8.4995 == 8.50

for TOLERANCE == 0.01
8.504 == 8.50
8.495 == 8.50


text:
Q: Decreasing refresh time for Skim app (macOS High Sierra)? Is there any way to decrease the interval between compilation and the point when Skim refreshes its display of the corresponding PDF?  It seems to take quite a bit longer than on my old Windows Vista machine with MiKTeX and Sumatra PDF.
For reference, I am using macOS High Sierra and Aquamacs with AucTeX and TeXLive.


text:
Q: System.Net.Http.HttpClient cannot connect to web API via NSwag client (Windows Universal Platform) I wrote a simple .Net Core 3.0 API using Swashbuckle Swagger and generated an api client via NSwag Studio, then I put a generated Api Client to a .Net Standard 2.0 project.
I have a Universal Windows Platform application, which is meant to be connecting to the Web Api and send/receive data etc.
I put a simple code in MainPage.xaml.cs class with System.Net.Http.HttpClient inside
public MainPage()
    {
        this.InitializeComponent();
        var httpClient = new HttpClient();
        var apiClient = new ApiClient(ProjectConstants.API_URL, httpClient);
        var deviceService = new DeviceService(apiClient);
    }

When API is called later in deviceService my program throws an exception on SendAsync method in generated Api Client

"An error occurred while sending the request."

var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
I tested API Client and HttpClient on .Net Core console app and it worked fine.
I read about Http Client for UWP https://learn.microsoft.com/en-us/windows/uwp/networking/httpclient but it seems UWP should support System.Net.Http.HttpClient too, which I would love to stick to.
Is this a Universal Windows Platform bug or do I forgot about adding something necessary to a project?

A: The System.Net.Http.HttpClient API can be used across platforms, but we do recommend using APIs from Windows.Web.Http.HttpClient NameSpace which is easy to use. So you could use Windows.Web.Http.HttpClient API in UWP,and use GetAsync(PostAsync) to send a request, for example:
Uri requestUri = new Uri("http://www.contoso.com");
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
httpResponse = await httpClient.GetAsync(requestUri);

For more information about the differences between Windows.Web.Http and System.Net.Http.HttpClient, you can refer to this article

A: Does it have the same api as the portable HttpClient?


text:
Q: Book recommendation for masters student with no maths background I have been accepted for a masters course in computational finance that is largely mathematical, and is most suited for students who have studied either mathematics or physics in their bachelor's degree. I however, have done business/finance. I believe the reason why I have been offered a place is because I studied lots of maths in my free time (I really regret not doing maths as my degree, and I am trying to compensate for that by doing it on my own). I would solve STEP questions whenever I had free time off work. I am already week 5 into my course and it has been OK so far. But stochastic processes starts to become a bit too much for me (and it is a core module).
To give you an idea of what I have done so far: for our quantitative module, we derived kolmogorov equation, used similarity methods to solve it; we defined brownian motion; we then learned quickly about stochastic processes; Ito's lemmas and most recently we have derived the Black-Scholes equation. Lecturer mentioned about parabolic and hyperbolic PDEs (I know what a PDE is, but not heard about those classifications).
For linear algebra, I think I am coping, but if you have a nice quick intro book for that, would be awesome; we have "done" (rushed through) SVD and PCA so far (no examples were provided). Even though I understand the concepts of both, I really need to do a few examples (not sure whether they can be manual for PCA?).
And finally, stochastic processes for finance. This is really a disaster. But this is mostly because of the lecturing style than anything else. I have learned chapters 2 to 7 inclusive of Ross's "First Course in Probability". Thus, I have learned about the marginal density functions, convolution etc. To be honest, so far it was basic probability. The last lecture however, started going into Fourier transforms, and I lost the plot at that point.
I am certain it is doable to pass the course, but I want more, I want a somewhat better understanding of what is going on. I study every day from very early until very late, so I hope I can at least partially catch up with other students. Not sure whether this question is appropriate here, and whoever is still reading, I appreciate it. If you have any book recommendations that really are useful for my purposes, please let me know.

A: I recommend checking out the recent book An Introduction to Stochastic Differential Equations by Evans, who is the author of a very popular PDEs textbook.  An Introduction to Stochastic Differential Equations is a short, intuitive, friendly book.  Here's the amazon description:

This short book provides a quick, but very readable introduction to
  stochastic differential equations, that is, to differential equations
  subject to additive "white noise" and related random disturbances. The
  exposition is concise and strongly focused upon the interplay between
  probabilistic intuition and mathematical rigor. Topics include a quick
  survey of measure theoretic probability theory, followed by an
  introduction to Brownian motion and the Itô stochastic calculus, and
  finally the theory of stochastic differential equations. The text also
  includes applications to partial differential equations, optimal
  stopping problems and options pricing. This book can be used as a text
  for senior undergraduates or beginning graduate students in
  mathematics, applied mathematics, physics, financial mathematics,
  etc., who want to learn the basics of stochastic differential
  equations. The reader is assumed to be fairly familiar with measure
  theoretic mathematical analysis, but is not assumed to have any
  particular knowledge of probability theory (which is rapidly developed
  in Chapter 2 of the book).

For linear algebra, I recommend Gilbert Strang's book Linear Algebra and its Applications, which makes the subject seem easy and provides good intuition.

A: I recommend An Elementary Introduction to Mathematical Finance by Sheldon M. Ross.
From the Amazon review:

This textbook on the basics of option pricing is accessible to readers with limited mathematical training. It is for both professional traders and undergraduates studying the basics of finance. Assuming no prior knowledge of probability, Sheldon M. Ross offers clear, simple explanations of arbitrage, the Black-Scholes option pricing formula, and other topics such as utility functions, optimal portfolio selections, and the capital assets pricing model. Among the many new features of this third edition are new chapters on Brownian motion and geometric Brownian motion, stochastic order relations, and stochastic dynamic programming, along with expanded sets of exercises and references for all the chapters.

For partial differential equations, I recommend The mathematics of financial derivatives: a student introduction by P. Wilmott, S. Howison, and J. Dewynne.

This book avoids almost all discussion of diffusion processes associated with option pricing, focusing instead as much as possible on the associated PDE's. Relatively easy to read; it goes much further on numerical approximation schemes, American options, and some other PDE-related topics.

For linear algebra, I can suggest Schaum's Outline of Linear Algebra.

A: Hi I am currently a Mathematics Masters student having come in from a course with only moderate mathematical content. I use Walter Rudin's 'Principles of Mathematical Analysis' as my first stop to check anything related to analysis .i.e. Fourier Transform. It may not be the best choice of book for linear algebra etc but I thought I would share and recommend having a look!

A: I recommend those books
Satish Shirali,_Harkrishan Lal Vasudeva. "Multivariable Analysis",
Derek J. S. Robinson "A COURSE IN LINEAR ALGEBRA WITH APPLICATIONS (2nd Edition),
ROBERT B. ASH, MELVIN F. GARDNER, "Topics in Stochastic Processes"

may be are usefull,


text:
Q: Reasource Dictionary's and Storyboards Having an issue moving a storybord to a resource dictionary for use across my enitre application.
basically want to use the same story board on multiple user control's.
Resource Dicitionary
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Storyboard RepeatBehavior="Forever" x:Key="AnimateWidth">
<DoubleAnimation Storyboard.TargetProperty="Width" From="1" To="250" Duration="0:0:2" BeginTime="0:0:0" FillBehavior="Stop" />
</Storyboard>
</ResourceDictionary>

UserControl
<UserControl x:Class="Toolset.WMIControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:View="clr-namespace:Toolset"
             Name="WmiControl_UserControl"
             Loaded="UserControl_Loaded"

             mc:Ignorable="d"
             >
<UserControl.Resources>
        <ResourceDictionary x:Key="Animations">
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="AnimationStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </UserControl.Resources>

 <DockPanel Name="DockPanel1" Style="{StaticResource Animations}">
            <DockPanel.Triggers>
            <EventTrigger RoutedEvent="Loaded">

                <BeginStoryboard Storyboard="{Binding AnimateWidth, Source={StaticResource Animations}}"/>
            </EventTrigger>
        </DockPanel.Triggers>
    </DockPanel>

Not really sure where i have gone wrong here. Any help would be appreciated.
Getting error "Must have a Storyboard object referenced before this trigger action can execute.

A:   <UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="AnimationStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

<DockPanel Name="DockPanel1">
    <DockPanel.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard Storyboard="{StaticResource AnimateWidth}"/>
        </EventTrigger>
    </DockPanel.Triggers>
</DockPanel>

A: Answered my own question..
This is how you use animations from a ResourceDictionary that is in another file.
Without using C#, since your not styling the view keep it in the view
 <ResourceDictionary x:Key="Animations">
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="AnimationStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>

       <DockPanel x:Name="Simple_Mode" DockPanel.Dock="Top"
                  HorizontalAlignment="Left"
                  ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                       Resources="{StaticResource Animations}"
                       >
                <DockPanel.Triggers>
                    <EventTrigger RoutedEvent="Loaded">
                        <BeginStoryboard Storyboard="{StaticResource AnimateWidth}"/>
                    </EventTrigger>
                </DockPanel.Triggers>
        </DockPanel>


text:
Q: According to canon, what is the primary style of hand to hand combat utilized by Kirk in Star Trek TOS? The hand to hand combat prowess of STNG Starfleet's security personnel is lauded by Tasha Yar in the accepted answer to this question.

Tasha: I think you should know that there is no physical training
  anywhere that matches Starfleet, especially its security people.

It is likely combat training evolved during the time elapsed between TOS and STNG, but Kirk definitely had specific moves which he seemed to be trained in and repeatedly used during his 5 year mission.
While some of the moves are identifiable, I find it difficult to pin a label on the double handed, flying hip check, style William Shatner utilized in his portrayal of James Kirk. According to canon, is Kirk practicing a known fighting style, and if so, what is it?

A: Captain Kirk is shown to be practicing Judo (TOS 1x07, 'Charlie X') but his actual 'fighting style' seems to be made up on the fly with no resemblance to an actual organized form or style.

In the Next Generation Lt. Yar conjures up a holodeck Aikido opponent to demonstrate Starfleet Security force training to visiting Dignitaries in (TNG: 1x04 'Code of Honor').

There have been no other mentions of any 'modern day' form of martial art training, but there has been a couple of made-up (in universe) martial art forms briefly shown in TNG:

Anbo-jyutsu — (TNG: 2x14, "The Icarus Factor") involves wearing helmets that do not allow a combatant to see and using large, electrified pugil sticks that signal when aimed at the opponent. Practitioners of this art include Cmdr. William Riker and his father Kyle.

Worf teaches some of the Enterprise crew an art called "Mok'bara" that Thomas Riker identifies as having similar moves as human T'ai chi ch'uan (TNG: 6x24, "Second Chances").


text:
Q: flutter: Putting a FlatButton with Column as child in an AppBar breaks layout I have the following code for creating an BottomAppBar in my app, which works fine.
class MyBottomAppBar extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final List<Widget> rowContents = <Widget> [
      new FlatButton(
          onPressed: () {

          },
          padding: EdgeInsets.all(10.0),
          child: new Row(
            children: <Widget>[
              new Icon(Icons.menu),
              new Text("Feed")
            ],
          ),
      ),
      const Expanded(child: const SizedBox()),
      new FlatButton(
        onPressed: () {

        },
        padding: EdgeInsets.all(10.0),
        child: new Row(
          children: <Widget>[
            new Icon(Icons.people),
            new Text("Profile")
          ],
        ),
      ),
    ];

    return new BottomAppBar(
      hasNotch: true,
      child: new Row(children: rowContents),
    );
  }
}

I want to use a Column() as a child of the FlatButton(), so that the Text() is shown below the Icon() and not next to it.
When I change Row() to Column(), I get the following result:

What am I doing wrong here?

A: By default the Column widget fills in all the space possible. You can pass it a mainAxisSize of mainAxisSize.min to tell the widget to take up as little space as possible.
This is a revised version of your code that works as you want it:
class MyBottomAppBar extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final List<Widget> rowContents = <Widget> [
      new FlatButton(
        onPressed: () {

        },
        padding: EdgeInsets.all(10.0),
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new Icon(Icons.menu),
            new Text("Feed")
          ],
        ),
      ),
      const Expanded(child: const SizedBox()),
      new FlatButton(
        onPressed: () {

        },
        padding: EdgeInsets.all(10.0),
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new Icon(Icons.people),
            new Text("Profile")
          ],
        ),
      ),
    ];

    return new BottomAppBar(
      hasNotch: true,
      child: new Row(children: rowContents),
    );
  }
}


text:
Q: If $x\geqslant e^3$, why $\frac{\ln{\ln{x}}}{2\ln{x}}\geqslant \frac{1}{2x}$? How to get this inequality?
If $x\geqslant e^3$
$\frac{\ln{(\ln{x}})}{2\ln{x}}\geqslant \frac{1}{2x}$

A: From:
$$x\ge e^3$$
$$\ln \left(x\right)\ge \ln \left(e^3\right)$$
$$\ln \left(x\right)\ge 3$$
$$\ln \left(\ln \left(x\right)\right)\ge \ln \left(3\right)$$
$$\frac{\ln \left(\ln \left(x\right)\right)}{2\ln \left(x\right)}\ge \frac{\ln \left(3\right)}{2\ln \left(x\right)}$$
$$$$
Compare:
$$\frac{\ln \left(3\right)}{2\ln \left(x\right)}$$
with :
$$\frac{1}{2x}$$
$$$$
We have that :
$$\ln \left(3\right)\ge 1$$
and
$$2\ln \left(x\right)\le 2x$$
$$$$
Hence :
$$\frac{\ln \left(3\right)}{2\ln \left(x\right)}\ge \frac{1}{2x}\:$$
Then :
$$\frac{\ln \left(\ln \left(x\right)\right)}{2\ln \left(x\right)}\ge \frac{\ln \left(3\right)}{2\ln \left(x\right)}\ge \frac{1}{2x}\:$$
$$\frac{\ln \left(\ln \left(x\right)\right)}{2\ln \left(x\right)}\ge \frac{1}{2x}\:$$


text:
Q: How to synchronize two runways so planes can land using java? I seem to have a small problem. I have an Air Traffic Control Application, with two runways which I am to synchronize in java. This is to be done because, if there is a plane two that lands while plane one is in the process of landing, it(plane two) does not have to wait but can quickly move to the runway two to land.
I have successfully synchronized one runway and I use one ArrayList to store the plane details and the landing works, however landing of plane two will have to wait(about 5 seconds). Any ideas as to, how to synchronize two runways ?
My present idea was to have two ArrayLists(one ArrayList(Even) stores even numbered planes, eg. plane two, plane four) and another ArrayList(Odd) stores odd numbered planes, e.g. plane one, plane three. Then I can make ArrayList (Even) to work with runway one and ArrayList (Odd) to work with runway two(using the individual synchronizaion technique I have done for runway one). The Downside is that, if I add 2 odd numbered planes in ArrayList Odd and 20 even numbered planes in ArrayList, when runway two becomes free, it would not be used. Instead only runway one would be used and the even numbered planes would have to wait.
Side note: I do understand that if both runways are occupied, the third plane will have to wait, but this is acceptable according to the markscheme.
Any suggestions ?
Thank you

A: To do this properly you need to have only one queue that you put the incoming aircraft into. Java provides a queue implementation and I suggest you use it rather than rolling your own.
Once you have the queue set up you need two runway objects and an 'air traffic controller'. The air traffic controller is responsible for checking the runways and if one is available popping a plane off the queue and telling it to land.

A: You need a counting semaphore with a value of 2. When someone wishes to land, they consume 1 from the semaphore. When they have the semaphore, they can then choose which runway to land on (simply check the status of the runway and pick a free one).
If the semaphore has a 0 value, then folks will have to wait. They need not even look at the runways.
When a plane leaves the runway, they free up the semaphore.
The Java docs on Semaphore has the details.

A: What you want to do is have each airplane obtain a permit to use a runway when it needs it for landing/taking off. There are two ways to do this.
If knowing the Runway is important:
Make the Runway an object and place it into a pool of Runways. For instance, place all Runways for an Airport into a BlockingQueue that belongs to the Airport. When a Plane needs a Runway, it can call BlockingQueue.take() to acquire one. When the plane is done with the Runway, it should call BlockingQueue.put() to release it for use by another Plane.
If you don't care about which Runway:
Use a Semaphore to keep track of the number of runways available. Each Plane will need to acquire and release the Semaphore.

A: Why not just have a single Tower object with methods requestLand() and reportClear(), then just store the runway status as an array inside Tower.
Is there another requirement I'm missing?
Don't understand the purpose of the two ArrayLists?


text:
Q: How can I restrict record creation in access based on a field value? I have a small access database I use to let students sign up for my afterschool classes (electronics, programming etc), I can only accept 30 people in each session.
At the moment they create their record and receive a message to learn how many people have already signed up (which I time-stamp in case of dropouts, first come first served).
However what I would like to do is prevent the record being created unless there is a slot available.
I've added a field on the form which says how many places are left, how can I stop access creating a new record when this value is <= 0?
Thanks in advance everyone

A: In the OnCurrent event of the form, insert this code line:
Me.AllowAdditions = (Me!PlacesLeft.Value > 0)


text:
Q: Question about obj I'm reading a book "A history of religion in 5 1/2 objects" these days, and one sentence is quite tricky for me.

Our bodies are a matrix of connecting points that, when used appropriately, allow us to relate to and draw breath, meaning, and inspiration from the environment around (Plate, S. Brent. A History of Religion in 5½ Objects (p. 5). Beacon Press)

It seems like people are allowed to relate and draw breath. But, I don't get why the objects meaning, inspiration, and environment are placed behind of breath. These could have been written right after "relate to".

A: It's possible to relate to and draw ALL of the following things: breath, meaning, and inspiration.
If two verbs can apply to a complement, combining them with and is normal.

I washed and dried the clothes = I washed the clothes and I dried the clothes

It's possible to stick separate prepositions after one, some, or all verbs; in order to "position" the complement for one of the verb's in a way that makes sense.

I paid for and threw out the junk = I paid for the junk and I threw out the junk

I walked to and ate at the park = I walked to the park and I ate at the park

A: The sentence is rather clumsy, but might perhaps be a bit more understandable if we added some dashes.

Our bodies are a matrix of connecting points that, when used appropriately, allow us to relate to - and draw breath, meaning, and inspiration from - the environment around us.

So now we can understand it as two sets of verbs applying to the same object: the environment. Rephrasing again:

... connecting points that [...] allow us to relate to the environment around us and draw breath, meaning and inspiration from it.

(I still don't think there is any actual meaning there, but that might be par for the course in such a book.)


text:
Q: Implication (Propositional Logic) I am studying propositional logic and I am having real difficulty understanding implication (despite reading numerous examples). The book I am following has the following examples and answers, but no explanation:
Let JoelHappy stand for "Joel is happy" and AnnaHappy stand for "Anna is happy", determine whether JoelHappy => AnnaHappy or AnnaHappy => JoelHappy for the following statements:

*

*"Joel is happy whenever Anna is happy."

*"Joel is happy only if Anna is happy."

*"Joel is happy unless Anna is not happy."
With the answers being:

*

*AnnaHappy => JoelHappy

*JoelHappy => AnnaHappy

*AnnaHappy => JoelHappy
I have tried using truth tables to determine these answers, but cannot get the correct answer. English is not my first language, so I am not sure if I am not understanding the sentences correctly.
If someone could explain a simple method for determining implication sentences using these examples, I would be very thankful.

A: In essence, implication simply means that if one statement is true, then another must be true as well. For example take $A\Rightarrow B$. This simply means that if $A$ is true, then $B$ must also be true. An example with numbers would be, $$x<0 \Rightarrow x<10$$ Here if $x$ is a number that is less than $0$, then it is certainly less than any number greater than $0$ so we say $x<0$ implies $x<10$ or whenever $x<0$ is true, then $x<10$ must also be true. The best way to build an intuition for this is to do as many examples as you can, preferably simple mathematical ones such as the above.
For one of your examples, the statement that "Joel is happy whenever Anna is happy." is simply a different way to say that if Anna is happy, then Joel must also be happy. Notice how this sentence does not say what occurs when Anna is not happy. Then Joel can be either happy or sad. Implication in a sense was defined to only "care" about the case when the statement on the left of the $\Rightarrow$ is true. That is then, that the statement on the right side must also be true.
A different way to think about this is to consider some special circuit that contains two lights, one on the left and one on the right. Whenever the light on the left is turned on, then the light on the right is turned on as well. If you take the light as being turned on to mean "this statement is true", then it is similar to the logical meaning of implication.
Returning to the first example statement "Joel is happy whenever Anna is happy", you can consider Anna to be that leftmost light. Whenever it is true that Anna is happy i.e. the light is turned on, then the light on the right must be turned on as well i.e. it must also be true that Joel is happy.
Don't feel too intimidated by the wording of the propositions, the language that is used to phrase them is not as important as what happens to one statement when the other one is true. For your second example "Joel is happy only if Anna is happy", if you take "Joel is happy" as being the leftmost light, then in the way we created our little circuit, the left light can only be on at the same time as the right light is on, i.e. the leftmost light cannot be turned on and the right one turned off. I hope this intuition is helpful.

A: Truth-tables won't help you; you need to get the right translation in the first place.
One important distinction that often helps with these translations is to distinguish between sufficient conditions and necessary conditions.
Here is an example to illustrate the difference: to be a bachelor, you need to be unmarried. So: Bachelor => Unmarried.  Being unmarried is thus a necessary condition for being a bachelor. But is it sufficient? Is anyone who is unmarried a bachelor? Clearly not: unmarried females are not bachelors. So, we don't have Unmarried => Bachelor.  We can say, however, that being a bachelor is a sufficient condition for being unmarried.  That is: once we know someone is a bachelor, then we know the person is unmarried. So, once again we have Bachelor => Unmarried.
Contrapositives can also often help you with making sense of these conditionals. For example, note that anyone who is married is not a bachelor. So, we have NOT Unmarried => NOT Bachelor.  But the contrapositive of that is: Bachelor => Unmarried.
A final and simple trick is specific to the 'unless': read the 'unless' as 'if not'!
Now, let's apply these strategies to your statements:
The first statement, which states that Joel is happy whenever Anna is happy, is a good example of a sufficient condition. Apparently Anna being happy is sufficient for Joel to be happy. Or, in logic in terms: if we know that Anna is happy, then we immediately know that Joel is happy: nothing else needs to happen for Joel to be happy. So, this translates to AnnaHappy => JoelHappy
The second statement, which says that Joel is happy only if Anna is happy, is a good example of a necessary condition: Anna being happy is a necessary condition for Joel to be happy. Thus, Anna being happy may not be by itself sufficient for Joel to be happy. So, this time we can't say AnnaHappy => JoelHappy.  We can, however, say JoelHappy => AnnaHappy: when we see Joel being happy, we can infer that Anna must be happy as well, because the only way for Joel to be happy is for Anna to be happy.
We can also use the contrapositive here: if Anna is not happy, then Joel will definitely not be happy either, and so we have NOT AnnaHappy => NOT JoelHappy, which by contraposition is the same as JoelHappy => AnnaHappy
Finally, for the third sentence 'Joel is happy unless Anna is not happy', we use the trick as indicated, and re[phrase this as 'Joel is happy if not Anna is not happy' ... which works out to: NOT NOT AnnaHappy > JoelHappy, and thus to AnnaHappy > JoelHappy

A: I'll offer a different perspective. I like to think of this in terms of set theory. $S_A\subset S_B$ means
$A\Rightarrow B$. Here a set $S_A$ is the part of the universe where statement $A$ is true.

*

*$A$ whenever $B$ means that $S_B\subset S_A$.

*$A$ only if $B$ means that $S_A\subset S_B$.

*$A$ unless $~B$ means that $S_A^c\subset S_B^c$ and thus  $S_B\subset S_A$.

So for 1, the times and places that Anna is happy are a subset of the times and places that Joel is happy, therefore we know that AnnaHappy $\Rightarrow$ JoelHappy.
For 2, Joel is only going to be happy when Anna is happy but Joel may also be not happy when Anna is happy, therefore JoelHappy $\Rightarrow$ AnnaHappy.
For 3,  the times and places where Joel is not happy are a subset of the times and places where Anna is not happy, therefore AnnaHappy $\Rightarrow$ JoelHappy.

A: It does need to be said that (contrary to what is implied in some other answers) "Joel is happy whenever Anna is happy" can not be translated by something of the form $A \Rightarrow B$.
The reason is simple "Joel is happy whenever Anna is happy" is a quantified conditional -- it says that, for any time $t$, if Anna is happy at time $t$, then Joel is happy at time $t$. As the OP in effect says. So a logical regimentation could be something like $(\forall t)(Hat \to Hjt)$, where $Hxt$ says that $x$ is happy at time $t$.
The Joel proposition then belongs to the same family as e.g. "If a number is prime and greater than two, then it is odd". This is another generalisation. And this sort of quantified content cannot be represented by something from propositional logic of the form $A \Rightarrow B$. For that is a singular conditional relating complete propositions with determinate truth-values, telling us that if the proposition $A$ is true (e.g. Anna is happy here and now; 9 is prime and greater than two), then $B$ is true (e.g. Joel is happy here and  now, 9 is odd). And we don't get the intended generality.

A: Put your propositions that do not have a connective in the left colums and list each possible values so: F, F next row F,T and so on. Then move write the statement you want to calculate the value for as 1 column and divide it in such way that each column connects two propositions or the columns left and right of the connectives are propositions.
I write your propositions in the same order als you defined them.
but written them in another order:

*

*Can Joel be happy in this case when Anna is not happy? If so Anna being happy implies that Joe is happy (so it cant be that JoelHappy is false when AnnaHappy is true)

*Again same question. It seems one side is true only if the other is also true. So we use a bi-implication $\iff$ between the propositions.

*Can Joel be happy when Anna is not? Hmmm doesn't look like it. So when AnnaHappy is False or is false after a negation, we cant have Joel be happy. Again a implication
We then get the following truth table: You can split up the last colums to this order
1. $\neg(AnnaHappy)$
2. $\implies$
3. $\neg(JoelHappy)$
\begin{array}{ | m{5em} | m{1cm} | m{1cm}| }
\hline
JoelHappy & AnnaHappy  & JoelHappy  \to AnnaHappy   & JoelHappy  \iff AnnaHappy   & \neg( AnnaHappy  ) => \neg(JoelHappy) \\
\hline
F & F & T & T & T\\
\hline
F & T & T & F & F\\
\hline
T & F & F & F & T\\
\hline
T & T & T & T & T\\
\hline
\end{array}


text:
Q: Java-like Arrays.asList() in c++ Does c++ support either in the STL or there exists an external library supporting Arrays.asList()?
Typical usage
private ArrayList<String> lexeme = new ArrayList<String>(Arrays.asList(" ", ",", "(", ")", ";", "=", ".", "*", "-"));

I am using Visual Studio 11 (2012) and they have not included the c++11 feature Initializer lists leaving me in a quandry as to initialize a vector of nine unique strings without
std::vector<std::string>::push_back("a");
std::vector<std::string>::push_back("b");
std::vector<std::string>::push_back("c");
                 . . .

A: A common thing to do before C++11 was to first create an array, then initialize the vector with it, for example:
char const * arr[] = { " ", ",", "(", ")", ";", "=", ".", "*", "-" };
std::vector<std::string> str_vec(arr, arr + sizeof(arr) / sizeof(*arr));

Of course, VS11 does support some of C++11, so you can do this instead, which is slightly more readable:
char const * arr[] = { " ", ",", "(", ")", ";", "=", ".", "*", "-" };
std::vector<std::string> str_vec(std::begin(arr), std::end(arr));

A: You could use:
const char* arr[] = {"a", "bc", "def"};
std::vector<std::string> vec(std::begin(arr), std::end(arr));

If your compiler doesn't support std::begin() and std::end(), they are easy to do without:
std::vector<std::string> vec(arr, arr + sizeof(arr) / sizeof(*arr));


text:
Q: reposman.rb fails querying projects : "invalid character at I try to update the projects to the SVN repos using reposman, here is the command I use :
ruby /home/redmine/redmine-1.2.1/extra/svn/reposman.rb --redmine redmine.mywebsite.com --svn-dir /var/svn --owner redmine --group www-data --url http://svn.mywebsite.com --key=myapikey --verbose

And here is the result I got from reposman.rb :
querying Redmine for projects...
Unable to connect to http://redmine.mywebsite.com/sys/: invalid character at "<?xml vers"

When I look at the production.log, here is what I have :
Processing SysController#projects to json (for 91.121.201.65 at 2011-09-05 14:31:50) [GET]
  Parameters: {"key"=>"myapikey"}
Completed in 40ms (View: 1, DB: 0) | 200 OK [http://redmine.myewebsite.com/sys/projects.json?key=myapikey]

But when I go to the http://redmine.myewebsite.com/sys/projects.json?key=myapikey url, I have a correct xml page with a list of my projects.
What is wrong? (Please ask me what I have to show you more from my server to help you.).

A: I had the same problem and this was the only promising looking search result.
My problem was, that I was using a wrong version of the active record gem. I had version 3.1.0 installed. But with version 2.3.11 it works fine. Hope this helps.

A: I downgraded activerecord 3.1.0 to activerecord 2.3.11, but still had the problem.  Like ServiusHack, mentioned.  Downgrading activeresource from 3.1.0 to 2.3.11 did the trick for me.
Thanks for the advice guys!