text:
Q: How to fix text quality in Java graphics? Code:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;

public class TextRectangle extends JFrame {

    private static final long serialVersionUID = 1L;

    public static void main(String[] a) {
        TextRectangle f = new TextRectangle();
        f.setSize(300, 300);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(
            RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, getWidth(), getHeight());

        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("Calibri", Font.BOLD, 18));
        g2d.drawString("Why does this text look so ugly?", 30, 150);
    }

}

Result:

As you can see the letter spacing is uneven. Sometimes it's 1px, sometimes it's 2 or even 3 pixels. Another issue is the dot above 'i' is wider than the bottom part.

The same text written in a text editor looks much better. Do you know how to fix this problem?
My environment is Windows 8.1, Java 1.8.

A: The graphics context uses integer metrics by default - meaning that rounding is applied to the location vectors of the glyph shapes.
You can switch to fractional metrics using:
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
    RenderingHints.VALUE_FRACTIONALMETRICS_ON);

As you can see, no subpixel antialiasing was used (only gray antialias pixel). You can enable subpixel antialiasing for better legibility on LCD screens:
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

There are 4 modes:

*

*VALUE_TEXT_ANTIALIAS_LCD_HRGB: horizontally oriented RGB

*VALUE_TEXT_ANTIALIAS_LCD_HBGR: horizontally oriented BGR

*VALUE_TEXT_ANTIALIAS_LCD_VRGB: vertically oriented RGB

*VALUE_TEXT_ANTIALIAS_LCD_VBGR: vertically oriented BGR

I haven't found out where to query the appropriate value of the current display and orientation. Some displays can be tilted (landscape/portrait) or even rotated, requiring to redetect the mode when painting.
EDIT
I found something in the Filthy Rich Clients book: apparently, the Java AWT Toolkit can provide appropriate rendering hints:
Map<?, ?> desktopHints =
    (Map<?, ?>) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints");

Graphics2D g2d = (Graphics2D) g;
if (desktopHints != null) {
    g2d.setRenderingHints(desktopHints);
}
// no need to set more rendering hints

On my system, this renders the text with fractional metrics and LCD HRGB antialiasing, same as with the code above. The hints on my system are:

*

*Text-specific antialiasing enable key: LCD HRGB antialiasing text mode

*Text-specific LCD contrast key: 120


text:
Q: Unable to load dynamic library in a .NET app on Linux Unable to load dynamic library on Linux

*

*I built a project on Mac OS and the output was a libmylibrary.so and libmylibrary.dylib files.

*I copied the .dylib into a Visual Studio Console project and was able to load and invoke the functions of the library using the DllImport function. The project works as expected

*I copied the project (including the .so and .dylib files) into a Ubuntu-based Docker container

*When I run the project using dotnet run, I get the below error

System.DllNotFoundException: Unable to load shared library 'mylibrary' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(libmylibrary, 1): image not found

Edit 1
 Below is the Dockerfile used to create the container
FROM streetcred/dotnet-indy AS base
WORKDIR /app

# Expose the default port
EXPOSE 5000

COPY SomeProject/ ./

RUN dotnet restore "SomeProject.csproj"
RUN dotnet build "SomeProject.csproj" -c Release -o build
RUN dotnet publish "SomeProject.csproj" -c Release -o build
RUN COPY libmylibrary.dylib build/libmylibrary.dylib
RUN COPY libmylibrary.so build/libmylibrary.so
CMD dotnet build/SomeProject.dll --urls http://0.0.0.0:5000

Edit 2
 I tried the following, but I get the same error

*

*Compile the mylibrary project in a Linux Docker Container (Ubuntu)

*Copy the generated mylibrary.so file in the SomeProject

Edit 3
 Based on @paladin324 comments, I tried the following, but I get the same error
LD_LIBRARY_PATH=/app/SomeProject/build
cd /app/SomeProject/build
dotnet SomeProject.dll --urls http://0.0.0.0:5000

A: .NET uses the platform's naming conventions.
DllImport("myLibrary") is going to look for a file named libmylibrary.so (the original filename of the binary).
Try changing:
RUN COPY mylibrary.so build/mylibrary.so

to
RUN COPY mylibrary.so build/umylibrary.so

redpajama_set_name: RedPajamaStackExchange


text:
Q: plotting an Integration output How to solve this integral by Mathematica even by numerical methods (plotting the solution)
Integrate[(Cos[x] - a)/(1 + a^2 - 2*a*Cos[x])^1.5, {x, 0, 2*Pi}]

It consumes huge time on Mathematica 9 home edition and no output.
I just want the Taylor expansion in the vicinity of a=0

A: expr =  Assuming[a > 0, Integrate[(Cos[x] - a)/(1 + a^2 - 2*a*Cos[x])^(3/2), {x, 0, 1}]]

gives:
(-(-1 + a) Sqrt[1 + a^2 - 2 a Cos[1]] ((-1 + a) EllipticE[1/
      2, -((4 a)/(-1 + a)^2)] + (1 + a) EllipticF[1/
      2, -((4 a)/(-1 + a)^2)]) -
 2 a Abs[-1 + a] Sin[1])/(a (-1 + a^2) Abs[-1 + a] Sqrt[
 1 + a^2 - 2 a Cos[1]])

Note: I replaced 1.5 by the radical 3/2. If you want numerical value use NIntegrate
As suggested by b.gatessuck (also belisarius' answer), taking the indefinite integral makes this faster:
expr = Integrate[(Cos[x] - a)/(1 + a^2 - 2*a*Cos[x])^(3/2), x]

Gives:
 (-(-1 + a)^2 Sqrt[(1 + a^2 - 2 a Cos[x])/(-1 + a)^2]
       EllipticE[x/2, -((4 a)/(-1 + a)^2)] - (-1 + a^2) Sqrt[(
      1 + a^2 - 2 a Cos[x])/(-1 + a)^2]
       EllipticF[x/2, -((4 a)/(-1 + a)^2)] -
     2 a Sin[x])/(a (-1 + a^2) Sqrt[1 + a^2 - 2 a Cos[x]])

You can then Plot this like any other function:
Plot[(expr/.x -> 1) - ( expr /. x -> 0 ), {a, 0, 5}]

OR from 0 to 2 Pi
Plot[(expr/.x -> 2 Pi) - ( expr /. x -> 0 ), {a, 0, 5}]

A: This will compute the Taylor expansion:
Define the integrand.
g[θ_, a_] := (Cos[θ] - a)/(1 + a^2 - 2 a Cos[θ])^(3/2)

Integrate a series expansion.
gi[a_, n_] := Integrate[Series[g[θ, a], {a, 0, n}] // Normal, {θ, 0, 2 π}]

Find a sequence function that fits a sufficiently long series expansion.
gs[a_, n_] = FindSequenceFunction[List @@ Expand@gi[a, 15]][n] // FullSimplify

(* (4 (a^2)^n Gamma[1/2 + n]^2)/(a Gamma[n] Gamma[1 + n]) *)

Summing this over $n = 1, 2, ...$ gives you the required series expansion.

A: This is instantaneous:
p = Integrate[(Cos[x] - a)/(1 + a^2 - 2*a*Cos[x])^(3/2), x,
    Assumptions -> Element[a, Reals], GenerateConditions -> True];
Plot[(p /. x -> 1) - (p /. x -> 0), {a, 0, 5}]

In case you made a mistake and the upper integration limit was 2 Pi:
Plot[(p /. x -> 2 Pi) - (p /. x -> 0), {a, 0, 5}]

Edit
As for the series expansion:
s = Normal@Series[(p /. x -> 2 Pi) - (p /. x -> 0), {a, 0, 10}]

a π + (9 a^3 π)/8 + (75 a^5 π)/64 + (1225 a^7 π)/1024 + (19845 a^9 π)/16384

The numerators are the Denominators of the column sums of the BG2 matrix
The denominators follows some power of 2 rule, but not trivial:
s = Series[(p /. x -> 2 Pi) - (p /. x -> 0), {a, 0, 100}];
lf = Denominator /@ List @@ Normal@s;
ListLogPlot@lf

Perhaps the following may help you if you need to find a closed expression:
s = Series[(p /. x -> 2 Pi) - (p /. x -> 0), {a, 0, 1000}];
lf = Differences[Last /@ Flatten /@ FactorInteger /@ Denominator /@ List @@ Normal@s];
ListLinePlot@lf


text:
Q: Magento: concatenation of two fields while displaying records in admin in my own module Can anybody help me to get the desired result in custom module of Magento.
I have creating packages and the packages database is as follows:
CREATE TABLE IF NOT EXISTS `packages` (
  `packages_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `package_name` varchar(255) NOT NULL DEFAULT '',
  `package_description` text NOT NULL,
  `package_price` varchar(20) NOT NULL DEFAULT '0',
  `time_type` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'days->1, weeks->2, months->3, years->4',
  `time` int(4) NOT NULL DEFAULT '0',
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`packages_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

I want to display the records in my grid as follows:
Id    Package Name      Package Description    Package Time   Package Price    Status
1     Half Yearly       Bla Bla Bla...         12             USD 200          Active

Note:-
I want to display Package Time with time type(like): time, time type
Eg.: 12 Months


text:
Q: How can I make a service dependent on another service value Ok, so I have this service that is dependent on another service value that the user can change in the app interface. Something like this:
app.service('Applications', ['$resource', 'URL',
    function ($resource, URL) {
        var applicationsResource = $resource(URL + '/applications/:id', { id: '@id' }, {
            query: {
                method: 'GET',
                isArray: true,
                transformResponse: function(body, header) {
                    var response = angular.fromJson(body);
                    return response.data.applications;
                }
            }
        });

        var applications = applicationsResource.query(function() {
            applications.current = applications[0];
        });

        return applications;
    }
]);

app.service('Users', ['$resource', 'URL', 'Applications',
    function ($resource, URL, Applications) {
        return $resource(URL + '/users/:id', { id: '@id' }, {
            query: {
                method: 'GET',
                isArray: true,
                headers: {
                    'User': Applications.current.username,
                    'Pass': Applications.current.password
                },
                transformResponse: function(body, header) {
                    var response = angular.fromJson(body);
                    return response.data.users;
                }
            }
        });
    }
]);

Example of working controller code:
app.controller('usersController', ['$scope', '$resource', 'URL', 'Applications',
    function ($scope, $resource, URL, Applications) {
        $scope.users = [];

        $scope.reload = function() {
            $scope.loading = true;
            var usersResource = $resource(URL + '/users/:id', { id: '@id' }, {
                query: {
                    method: 'GET',
                    isArray: true,
                    headers: {
                        'User': Applications.current.username,
                        'Pass': Applications.current.password
                    },
                    transformResponse: function(body, header) {
                        var response = angular.fromJson(body);
                        return response.data.users;
                    }
                }
            });
            $scope.users = usersResource.query(function() {
                $scope.loading = false;
            });
            /*
            // after injecting Users, this is what I want to do, instead of what's above
            $scope.users = Users.query(function() {
                $scope.userTable.reload();
                $scope.loading = false;
            });
            */
        };

        $scope.$watch('Applications.current', function (newApplication, oldApplication, scope) {
            if (newApplication && newApplication !== oldApplication) {
                scope.reload();
            }
        });
    }
]);

I want to replace that usersResource with my Users service, but that's where I'm stuck now.
The issue is that no matter what I do, the Applications.current on the Users service is always null. (I only make use of this service after making sure that Applications.current is not null on the controller)
If I move the resource directly to the controller, it works, but I want to move these away from the controllers.
Any tips on how to fix or improve this?

A: You should know that $resource is async and you call Users service before actually you got response from server and populated applications.current. This a reason why Applications.current is null into Users service.
In your case I would use Uses service into Applications:
app.service('Applications', ['$resource', 'URL', 'Users',
function ($resource, URL, Users) {
        var applicationsResource = $resource(URL + '/applications/:id', { id: '@id' }, {
            query: {
                method: 'GET',
                isArray: true,
                transformResponse: function(body, header) {
                    var response = angular.fromJson(body);
                    return response.data.applications;
                }
            }
        });

        var applications = applicationsResource.query(function() {
            applications.current = applications[0];

                     // call the Users
                     Users.query(applications.current) /**/

                    return /* ... */;

        });

        return applications;
    }
]);


text:
Q: Django-ckeditor not displaying correctly in html I have a little problem, I installed Django-ckeditor in my admin section.
I can perfectly use it in Admin, but when I display on the Html page it is not showing correctly, I'll put some image to have a better visual.
Here is my admin ckeditor, works perfectly!

Here is my html page, where the ckeditor don't works correctly

How Can I resolve this issue ? (I use python 2.7.4 and Django 1.7.4)

A: When rendering html in templates, make sure you mark it as safe...
{{ article.content|safe }}

See documentation:
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#safe

A: For me the problem was that I was just writing
{{form.as_p}}

Instead use-
<form method="POST" enctype="multipart/form-data">
  {% csrf_token %}
  {{form.media}}     //this was missing
  {{form.as_p}}

A: Whether Its tinymce, ace editor or ck Editor not showing / working:
try:
1)python manage.py collectstatic
2)python manage.py makemigrations and python manage.py migrate
3)  {% csrf_token %}
{{form.media}}
{{form.Text_areas_name}}

A: In my case it worked by using {{ article.content|safe }} while rendering the page.


text:
Q: Find 3D rotation matrix for a plane, given surface normal and point lying on the plane Given two points $P_0(x_0,y_0,z_0)$ and $P_1(x_1,y_1,z_1)$, and being $P_0$ the centroid of a square delimited by the following points:
$$
(x_0 - 0.25, y_0 - 0.25, z_0)
$$
$$
(x_0 + 0.25, y_0 - 0.25, z_0)
$$
$$
(x_0 + 0.25, y_0 + 0.25, z_0)
$$
$$
(x_0 - 0.25, y_0 + 0.25, z_0)
$$
we know that vector $\vec{P_0P_1} = (x_1 - x_0, y_1 - y_0, z_1 - z_0)$ should be a normal of the previous plane. I would like to find the rotation matrix for the plane that solves the issue.

A: The normal to the original square is $\vec{n}=(0,0,1)$. To calculate the rotation of $\vec{n}$ onto $\vec{p}=\vec{P_0P_1}$, the axis of rotation is given by $\vec{p}\times\vec{n}$. Yo can calculate the angle from the dot product. You can get the rotation matrix using https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
If you want to rotate the square instead, it's the same rotation axis, with the opposite sign angle


text:
Q: Network Switch Help for Lan Party I am having 5 friends over for a gaming weekend/event thing. I was wondering if the switch I bought is good enough to handle this kind of traffic and whatnot. Should I keep the amount of connections going through the switch to a minimum? This is what I bought. My Ip connection is 50/10 so would it matter if it bottlenecks? If I were to stream from my PC should I connect straight to the router?
I have the means to return this switch and buy a better one. But this event is costing a bunch already and I am trying to save cash where I can. So in total, I have 4 ports on my router and 5 ports on the switch. So 7 total ports available for connecting.
Games likely to play:

*

*Overwatch

*Rocket League

*Call of Duty

*TableTop Simulator

A: That switch is more than capable of handling the load of 5 people for gaming.


text:
Q: How to access structure variable defined in another structure? I have following structure
typedef struct List_Node {
     struct File_Descriptor *data;
     char *key;
    struct List_Node *next;
}List_Node;

Now I inserted some values into the both the structures and want to access the data of type File_descriptor. How to do this?
I tried this
struct List_Node *ln1;
printf("%s", ln1.File_Descriptor->data);

but it is giving error
error: request for member 'error: File_Descriptor' in something not a structure or union`

A: You just want:
struct List_Node *ln1;
printf("%s", ln1->data);

struct File_Descriptor is the type. data is the struct member name.
Also though the printf format looks entirely wrong. Not sure what you're trying to do there. %s is string, and data certainly doesn't look like a string.

A: I believe you are confusing the type name with the variable name. In order to access the data member of the List_Node struct, you use the following:
struct List_Node *ln1; // initialize this
printf("%s", ln1->data);

Don't forget that you first have to initialize the ln1 pointer to point to a valid memory location before dereferencing it.


text:
Q: How to automate making charts for every N number of cells and rows in Excel? I am working with a large data set that contains around 17k values and I need to make a chart for every 29 values. For instance if the data set is of 58 values, I need to make a chart for every 29 values and thus make two charts.
I have written the following code to make the charts:
'''
Sub Charts()
'
' Charts Macro
'

'
    Range("D3:D32").Select
    ActiveSheet.Shapes.AddChart2(227, xlLine).Select
    ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$D$32")
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    ActiveChart.FullSeriesCollection(1).Name = "=""Marginal Costs"""
    ActiveChart.FullSeriesCollection(1).XValues = "=Sheet1!$C$3:$C$32"
     Range("D32:D61").Select
    ActiveSheet.Shapes.AddChart2(227, xlLine).Select
    ActiveChart.SetSourceData Source:=Range("Sheet1!$D$32:$D$61")
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    ActiveChart.FullSeriesCollection(1).Name = "=""Marginal Costs"""
    ActiveChart.FullSeriesCollection(1).XValues = "=Sheet1!$C$32:$C$61"
End Sub

'''
This is quite a tedious step for 17k values.
Can someone please suggest an easier way of making charts for the data? I would be deeply grateful for the same.

A: Use a For/Next Loop with Step size of 29.
Option Explicit

Sub ChartsMacro()

    Const SIZE = 29

    Dim ws As Worksheet, cht As Chart, c, sTitle As String
    Dim lastrow As Long, r As Long, n As Long, L As Long, T As Long
    Dim t0 As Single: t0 = Timer

    Application.ScreenUpdating = False
    Set ws = ActiveSheet
    With ws

        lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
        For r = 3 To lastrow Step SIZE
            n = n + 1
            Application.StatusBar = "Chart " & n

            ' position and title chart
            sTitle = "Chart " & n & " (" & r & " to " & r + SIZE & ")"
            L = .Range("F" & r + 1).Left
            T = .Range("F" & r + 1).Top
            .Range("C" & r).Resize(, 10).Borders(xlEdgeTop).Color = vbBlack
            ' create chart
            Set cht = .Shapes.AddChart2(227, xlLine, Left:=L, Top:=T).Chart
            cht.SetSourceData Source:=.Range("D" & r).Resize(SIZE + 1)
            cht.ChartTitle.Text = sTitle
            cht.FullSeriesCollection(1).Name = "=""Marginal Costs"""
            cht.FullSeriesCollection(1).XValues = .Range("C" & r).Resize(SIZE + 1)
        Next
    End With
    Application.ScreenUpdating = True
    Application.StatusBar = "Done"

    MsgBox n & " Charts created in " & Format(Timer - t0, "0.0") & " secs"
End Sub

A: Nested for loop is how I've handled similar problems in the past. Something like
For i=1 to 17k/29
     create chart
     for k=1 to 29
         range = i*k
         data = range

Assuming your data is sequential and in same range each time you just have to figure out the actual steps for a single set then let it go.


text:
Q: mysql Remote Connection with vbnet I get this error: " Reading from the stream has failed."
Below is my code:
Imports MySql.Data.MySqlClient

Public Class Form1
    Dim dbds As New DataSet
    Dim MySQLconn As New MySqlConnection
    Dim SQLda As New MySqlDataAdapter
    Dim cmd As MySqlCommand

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    MySQLconn = New MySqlConnection("server=www.address.com;User Id=user_nem;pwd=***;port=2082;database=db_db_db")

    Try
        MySQLconn.Open()
        MsgBox("Sucess, press ok to continue…", vbOKOnly)
         cmd.CommandText=(("set net_write_timeout=99999; set net_read_timeout=99999"), MySQLconn)
        cmd.ExecuteNonQuery()
        SQLda = New MySqlDataAdapter(("SELECT * FROM log_in"), MySQLconn)
        SQLda.Fill(dbds, "doctors")
        DataGridView1.DataSource = dbds.Tables("doctors")

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try

End Sub

End Class

This code works fine with my localhost.
Any help will be appreciated.Thanks.

A: i guess the mysql user user_nem has only access to the database via localhost.
try creating a user like this
GRANT ALL PRIVILEGES ON yourDbName.* To 'myuser'@'%' IDENTIFIED BY 'password';
the 'myuser'@'%' means the user with name myuser from any % location. (dont forget to update that username in your connection string)
I guess now its something like 'user_nem'@'localhost' or 'user_nem'@'127.0.0.1' thats why it works in local, but not in remote.
Try checking for firewalls also.


text:
Q: How to use providedIn 'root' in angular service How to use providedIn 'root' in angular service?

A: Style of alert() JS function is defined by the browser you are using. You can't change that.
But you can implement custom alert boxes using, for example, jQuery UI or other libraries.


text:
Q: Java see what OS process is focused ( i.e firefox ) I have a java program that launches a program on start up. This can be any executable. Problem is that the java app is applying several inputs to any running app when it's focused ( the app performs keyboard input/output)
Someone told me it's not possible to make such call directly from Java to see which program is focused. So I can't make a check whether the desired application is focused or not.
like
if(processName == launchedExeName) // Do code

Are there any tools or libraries which I can implement in my java project?
thanks,
Sidar

A: You won't be able to do that directly from java without some native calls. Some library may already do that for you, but I'm not aware of any. So you'll have to write it yourself - also that's obviously completely OS dependent.
For windows it's relatively simple (and afaik there's some JNI wrapper for the win32 api so you don't have to do that yourself, maybe look around a bit), I actually had to write something similar some time ago, so here's the basic version (without error checking for simplicity):
HWND hForeground = GetForegroundWindow();
DWORD pid;
GetWindowThreadProcessId(hForeground, &pid);
HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid);

We now have the handle to the process and you can do whatever you want with it. If you want the path of the process, this would go something like:
DWORD size = MAX_PATH;
TCHAR pathName[MAX_PATH];
QueryFullProcessImageName(hProc, /*win32 path format*/ 0, pathName, &size);

Trivial really (it gets a good bit more complicated though if you want to receive events whenever the foreground changes), just the error handling blows the code up as usual.
As I said I remember reading about some Win32 wrappers in Java, so you may not have to write the JNI/JNA stuff yourself. And no idea about *nix here.


text:
Q: Pip uses a different python version than the one I installed I installed Python 3.8.2 on Mac OS with Homebrew. I added the directory to PATH, but it seems to have installed wrong versions. I tried to install pygame with pip3, but when I ran the .py with python3, it told me the module was missing. pip3 --version tells me it uses Python 3.7. However, pip3.8 --version tells me it uses Python 3.8. Both python3 --version and python3.8 --version show "Python 3.8.2". I'm really confused - is there something really obvious that I'm missing? Did Python not find pygame because pip installed it on another version of Python?

A: First, always use virtual environments and do not install packages globally.
Second, I was back then dealing with this confusion, too. After lots of research, I gave up and finally decided to go with the following command, even though I would want to just type pip or pip3.
python3.8 -m pip install pygame
This way, you install the package(pygame here) for a specific version of python(3.8 here).
You can find something more detailed in here.


text:
Q: Zabbix agent не подключается к серверу Агент заббикса не видит сервер, пинг есть. Если поставить агент на самом сервере тогда он сам себя видит и агент отображается. Пробовал настроить на коммутаторе внутреннюю сеть для обеих машин, так же видят друг друга, но агент не работает.
Такая конфигурация:
- Windows 10 с отключенным фаерволом
- Установлен Hyper-V, в нём настроен виртуальный коммутатор (external).
- Виртуальная машина Ubuntu 17.04 , Zabbix 3.2.0.

A: Попробуйте добавить шаблон к хосту. Судя по картинке, у Вас это поле пустое.
Configuration -> Hosts -> "Нужный хост" -> Templates -> Select -> "Нужный шаблон" -> Select -> Add -> Update
После чего, на всякий случай, перезапустите zabbix-agent.


text:
Q: Regarding another definition of skewness of an RV I am working on the following exercise:

Let $X$ be an RV with $\mathbb{E}(X) = \mu$, $m$ a population median of $X$ and $Var(X) = \sigma^2$. We define the skewness $S$ of $X$ by
$$S:= \frac{\mu - m}{\sigma}.$$
REMARK: A population median is defined as follows: Let $X$ be a RV. Then $m$ is a population median of $X$ if $P[X \ge m] \ge 1/2$ and $P[X \le m] \le 1/2$ holds. This is equivalent to $m$ is a minimiser of $g(v):=\mathbb{E}(\vert X - v \vert)$.
I need to show that:

*

*$S \in [-1,1]$

*Are the bounds neat? When are they reached?

I suppose that the fact that $\sigma = \sqrt{\mathbb{E}(X^2) - \mathbb{E}(X)^2}$, could be helpful here, but I do not see how to proceed here. Could you help me?

A: Hint:
$$E[|X-m|] \le E[|X-\mu|] \le \sqrt{E[(X-\mu)^2]} = \sigma$$
The first inequality is due to the characterization of the median as a minimizer of $g(v)=E[|X-v|]$; the second inequality is Jensen's inequality.
To finish the first question, find a connection between the left-hand side of the above with $|\mu-m|$.

For the second inequality, use the intuition that $S$ represents skew. Make a sequence of simple distributions that you think has more and more skew and see how $S$ behaves.

 A very weird example is just the $\text{Bernoulli}(1/2)$ distribution. Any number in $[0,1]$ serves as a median, so choosing $m=0$ gives $S=1$. (Of course, choosing $m=1/2$ gives $S=0$.)

 For something less odd, you can approximate this with $\text{Bernoulli}(p)$ as follows. For $p < 1/2$, the median must be $m=0$. We have $\mu=p$ and $\sigma = \sqrt{p(1-p)}$ so $S = \sqrt{p / (1-p)}$. As $p \uparrow 1/2$ we have $S \to 1$.


text:
Q: Custom Query for count_user_posts function I'm using a plugin to show user post count on my website's backend.Plugin uses "count_user_posts" function in loop to show post count for all users.I want to modify $count value of "count_user_posts" function which is a sql query and append some more conditions at the end. i.e AND post_date BETWEEN '$startDate' AND '$endDate'. Function returns a hook to "get_usernumposts" with $count query , $userId as parameter.
//wp function
 function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
    global $wpdb;
    $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
    $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
    /**
     * Filters the number of posts a user has written.
     *
     * @since 2.7.0
     * @since 4.1.0 Added `$post_type` argument.
     * @since 4.3.1 Added `$public_only` argument.
     *
     * @param int          $count       The user's post count.
     * @param int          $userid      User ID.
     * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
     * @param bool         $public_only Whether to limit counted posts to public posts.
     */
    return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
}

//my function
function author_post_count(){
$where = get_posts_by_author_sql( "post", true, 3, $public_only );
$where .= " AND post_date BETWEEN '2018-03-11' AND '2018-03-13'";
$result = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return $result;
}

add_filter( 'get_usernumposts', 'author_post_count');

is there any way to modify or append "count_user_posts" core function.

A: Your filter callback isn't accepting any arguments from the hook. When you write the callback function you need to include the arguments passed in apply_filters, and in your add_filter() call you need to specify how many of the arguments you're using:
// Accept all 4 arguments provided to callbacks for this filter.
function wpse_296863_author_post_count( $count, $userid, $post_type, $public_only ) {
    global $wpdb;
    $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
    $where .= " AND post_date BETWEEN '2018-03-11' AND '2018-03-13'";
    $result = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );

    return $result;
}
add_filter( 'get_usernumposts', 'wpse_296863_author_post_count', 10, 4 ); // Using 4 arguments.

Also note:

*

*I prefixed the function. Your code should be prefixed with something unique to your project to avoid conflicts.

*You were missing global $wpdb;. You can't use $wpdb->get_var() without it.

*I passed through the original values from the filter into get_posts_by_author_sql(), otherwise all post counts will be for the one user. I assume you'd done this for testing.


text:
Q: Replace grouped Id from second table I have two tables.
Table1
    Id, Column1, Column2, Column3
     1     1       2        3
     2     1       2        3
     3     2       1        3
     4     2       1        3
     5     2       2        2

Table2
      Id, Table1_Id
       1      1
       2      1
       3      2
       4      2
       5      2
       6      3
       7      4
       8      4
       9      5

From first table I need remove duplicate rows with same Column1, Column2 and Column3 values and to Table 2 I need replace FKs Table1_Id column with Id after removes duplicate rows from Table1.
I need this
Table1
Id, Column1, Column2, Column3
 1     1       2        3
 3     2       1        3
 5     2       2        2

Table2
   Id, Table1_Id
    1      1
    2      1
    3      1
    4      1
    5      1
    6      3
    7      3
    8      3
    9      5

A: -- Build test data

create table #table1(
    id int,
    column1 int,
    column2 int,
    column3 int
)

create table #table2(
    id int,
    table1_id int
)

insert into #table1
select 1, 1, 2, 3 union all
select 2, 1, 2, 3 union all
select 3, 2, 1, 3 union all
select 4, 2, 1, 3 union all
select 5, 2, 2, 2

insert into #table2
select 1, 1 union all
select 2, 1 union all
select 3, 2 union all
select 4, 2 union all
select 5, 2 union all
select 6, 3 union all
select 7, 4 union all
select 8, 4 union all
select 9, 5

-- update rows of table2
;with cte as(
    select
        *,
        rn = row_number() over(partition by column1, column2, column3 order by id)
    from #table1
)
update t2
    set t2.table1_id = c.id
from #table2 t2
inner join #table1 t1
    on t1.id = t2.table1_id
inner join cte c on
    c.column1 = t1.column1
    and c.column2 = t1.column2
    and c.column3 = t1.column3
    and c.rn = 1

-- delete duplicate rows of table1
;with cte as(
    select
        *,
        rn = row_number() over(partition by column1, column2, column3 order by id)
    from #table1
)
delete from cte where rn > 1

select * from #table1
select * from #table2

--drop test data
drop table #table1
drop table #table2

A: -- test tables
declare @t1 table
(Id int, Column1 int, Column2 int, Column3 int)
declare @t2 table
(Id int, Column1 int)

-- data
insert @t1 values
(1,1,2,3),(2,1,2,3),(3,2,1,3),(4,2,1,3),(5,2,2,2)

insert @t2 values (1,1)
,(2,1),(3,2),(4,2),(5,2)
,(6,3),(7,4),(8,4),(9,5)

-- update t2
begin transaction
;with cte as(
    select
      id,
      lowrow_id = min(id) over(partition by column1, column2, column3)
    from @t1
)
update t2
set
  Column1 = cte.lowrow_id
from
@t2 t2
join cte
on t2.Column1 = cte.id
where cte.lowrow_id < cte.id

-- delete t1
;with cte as(
    select
      id,
      lowrow_id = min(id) over(partition by column1, column2, column3)
    from @t1
)
delete cte
where
  lowrow_id < id

commit transaction

-- show result
select * from @t1
select * from @t2

Output
Id  Column1 Column2 Column3
1   1       2       3
3   2       1       3
5   2       2       2

Id  Column1
1   1
2   1
3   1
4   1
5   1
6   3
7   3
8   3
9   5

A: with tbl1 as (
select ROW_NUMBER() over (partition by column1,column2,column3 order by id) as rownb,min(id) over (partition by column1,column2,column3) as pid,id,column1,column2,column3 from Table1
)
update table2 set Table1_id = tbl1.pid from table2 left join tbl1 on table2.Table1_id = tbl1.id

with tbl1 as (
select ROW_NUMBER() over (partition by column1,column2,column3 order by id) as rownb,min(id) over (partition by column1,column2,column3) as pid,id,column1,column2,column3 from Table1
)
delete from tbl1 where rownb > 1


text:
Q: How to save the preferences with a JButton? I'm new to Java and I am trying to save the preferences on an option window. I am creating maps of the game with JLabel matrices. I have 3 maps, and the user will select them with a Combo box and select rounds (1 rounds,3 rounds or 5 rounds) for the game and I need to save those options being selected by the user.
This is the method for the combobox, now the this is that I don't know how to added to the botton so that it save the settings, so when the user click on New Game it will open the options that was being selected before. I'm using Menu Items. Where tab is the variable for my class Tablero.
public void itemStateChanged(ItemEvent e) {
   int selectedIndex = combobox.getSelectedIndex();
             switch(selectedIndex){
                    case 0: //small map

                          tab.matrizpeque();
                          tab.llmatrizpeque(5,8);
                                             break;
                   case 1: //med map

                          tab.matrizmed();
                          tab.llmatrizmed(8,12);
                                             break;
                  case 2: //big map

                          tab.matrizbig();
                          tab.llmatrizbig(10,15);
                                             break;
                        }

}

A: Java preferences api is the standard way to do this
http://docs.oracle.com/javase/6/docs/technotes/guides/preferences/overview.html

A: You can use mysql to persist the data, that's the easier way. Another good option is an xml file. do a search for persistence with xml.


text:
Q: How to subscript x_n+1 in microsoft word equation I am writing my report and this equation is quite tricky to write which has 'x' and in subscript 'n+1'. I try to do x_n+1 inside equation, but this doesn't work. How to I subscript sequence of letters in a same line

A: You can add subscripts using the 'add subscript' tool'. It'll add blank boxes that you can fill with 'x' and 'n+1'

A: Just write in the following way in the equation editor
x_(n+1)


text:
Q: Codeigniter /application/core/Frontend_Controller.php not found on live server I have developed my website at XAMPP on Win 7 machine, and it works perfect on localhost. When I uploaded it to a live server (linux). It started showing me this error:
Fatal error: Class 'Frontend_Controller' not found in /home/acephm3/public_html/phenomesoft.com/application/controllers/Home.php on line 3
I've checked and applied everything I could from google but no luck at all.
I am using CI version 3.0.3.
I have set $config['subclass_prefix'] = 'MY_';
Created My_Controller.php as follows in /application/core:
class My_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code

    }

    public function send_mail($from, $from_name, $to, $subject, $message, $smtp, $debug) {

        $this->load->library('email');

        if (!$smtp) {

            $this->email->from($from, $from_name);
            $this->email->to($to);

            $this->email->subject($subject);
            $this->email->message($message);

            if ( $this->email->send() ) {

                $this->session->set_flashdata('message', 'We\'ve received your message. Thank you for contacting us.');
                redirect('contact_us');

            } else {

                if ($debug) {
                    echo $this->email->print_debugger();
                }

                return false;

            }

        }

    }

}

Included:
include_once('Frontend_Controller.php');

Created Frontend_Controller.php in /application/core/ as follows:
class Frontend_Controller extends My_Controller {

    public $data;

    public function __construct()
    {
        parent::__construct();
        // Your own constructor code

        $this->data = array();
    }

    public function _load_template($tpl, $data)
    {
        $this->load->view('frontend/includes/header', $data);
        $this->load->view('frontend/'.$tpl, $data);
        $this->load->view('frontend/includes/footer', $data);
    }

}

Created a controller Home.php under apllication/controllers/:
class Home extends Frontend_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code
    }

    public function index(){
        $this->_load_template('home', $this->data);
    }

}

Set $route['default_controller'] = 'home'; in routes.php.
What else I have to do? Please note it once again that I have no issues on localhost.

A: Put this code at the end of APPPATH . 'config.php' file:
spl_autoload_register(function ($class) {
    if (substr($class,0,3) !== 'CI_') {
        if (file_exists($file = APPPATH . 'core/' . $class . '.php')) {
            include $file;
        }
    }
});

A: Change:
include_once('Frontend_Controller.php');

To:
include_once( APPPATH.'core/Frontend_Controller.php' );

In Home controller

A: I rather used another approach, took me a whole day to figure this out.

*

*Removed My_Controller.php and Frontend_Controller.php from application/core folder.

*Created a new controller Application.php in application/controllers and extended it from CI_Controller.

*Created another controller Frontend.php in application/controllers and extended it from Application controller (Don't forget to include Application.php at top of this Frontend.php controller).

*Now in my actual controller Home.php included Frontend.php at the top and extended home controller from Frontend controller.

That's all, now every time you create a new frontend controller extend it from Frontend controller.
Now in the same way I can create another controller for my backend controllers and extend all my backend controllers from it.
Enjoy..!!

A: Another way you could try is
Filename: MY_Controller.php
<?php

class MY_Controller extends CI_Controller {
   // Code Here
}

class Frontend_Controller extends MY_Controller {
    // Code here
}

With the front end controller class on the same file as MY_Controller.php
Home Controller
File name: Home.php
<?php

class Home extends Frontend_Controller {

}


text:
Q: A resource was acquired at attached stack trace but never released. memory leak If I comment out the method (*a)->CallVoidMethod(a, b, meth, "FROM JNI");
The app doesn't crash else it crashes.
Assuming that I haven't released the resource "jstr" which might have caused a memory leak then why does it happen only when CallVoidMethod() ?
What should I do to solve this issue?
Thanks to all who spend their time writing down a solution or reading through this
ERROR:

android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
  java.lang.Throwable: Explicit termination method 'close' not called

This is my native "C" code ...
#include "com_example_prabhu_helloworldnative_HelloWorld.h"
#include <jni.h>
#include <android/log.h>

#define  LOG_TAG    "testjni"
#define  ALOG(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

JNIEXPORT jstring JNICALL Java_com_example_prabhu_helloworldnative_HelloWorld_HelloJNI(JNIEnv *a, jobject b)
{
    //jstring jstr = (*a)->NewStringUTF(a, "This comes from jni....");
    jclass clazz =(*a)->GetObjectClass(a, b);
    jmethodID meth = (*a)->GetMethodID(a, b, "messageMe", "(Ljava/lang/String;)V");
    __android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n this is log messge \n");
    ALOG("Hello World");
    if(meth == 0)
    {
        return;
    }

    (*a)->CallVoidMethod(a, b, meth, "FROM JNI");
    //(*a)->Release
    ALOG("REACHING HERE");

    return (*a)->NewStringUTF(a, "APXOR");
}

A: StrictMode only reports failures to release objects that are explicitly monitored by StrictMode. It doesn't fire because you fail to release a string from JNI. The object allocated at the point in the code indicated by the stack trace needs to be released with an explicit close() call before the last reference to it is dropped. If the object is discarded and finalized before it is closed, the system reports an error.
The method you're calling may or may not have anything to do with the failing object -- it may simply be doing allocations that cause the GC to happen sooner, so your app reports the error immediately rather than doing so later.
Including more of the logcat output in your question may be useful here.  The strict mode code is typically configured to issue warnings... if your app is actually crashing the problem may not be related to the failure to close the resource.
One possible problem with your code is misuse of b.  You're passing it to GetMethodID(), which takes a jclass as its second argument; since that apparently works, I would expect 'b' to be a class.  This will be the case if the HelloJNI method were declared static in the Java code.  (You call GetObjectClass(a,b), but ignore the result.)  That being the case, passing 'b' as the second argument to CallVoidMethod() is probably wrong, and will lead to a failure.
Further, as noted in another answer, you cannot pass a C string or char* when a jstring is required.  "FROM JNI" must be converted to a jstring with NewStringUTF.  The compiler should warn about that.
With CheckJNI enabled I would expect a JNI error to be reported, which does kill the app.

A: I think you have to create Java string yourself:
...
jstring str = env->NewStringUTF("FROM JNI");
(*a)->CallVoidMethod(a, b, meth, str);
env->DeleteLocalRef(str);
...


text:
Q: How to set Spatial parameters in SoleQuery.java of com.github.takezoe.solr.scala We need to set spatial fields like pt, field, and d programmatically. we are using solr library 7.1.0. Looking at the SolrQuery class methods it seems it doesn't have any support to enable spatial query and add spatial parameters. Here is the parameter list which I want to set in my query. Any idea how I can achieve this?

A: You should be able to use solrQuery.set("fieldname", "value") to supply custom parameters:
solrQuery.set("pt", "-34...");
solrQuery.set("sfield", "location");

These can also usually be given in your query if you're using {!geofilt or similar: {!geofilt sfield=location}.


text:
Q: C Reader Writer Mutexes for a Copying a File using Shared Memory and Ring Buffer I want to build a File Copier using Reader-Writer Synchronization Paradigm.
The Writer initializes the both of the Mutexes. The FullMutex is denoting how many Buffers are available to Write and the FreeMutex is denoting how many Buffers are available to Read.
The Writer waits when the Block is Full.
The WritePointer and ReadPointer is using the Ring Buffer. Therefore I have used Mod Operation.
The Block Size=M.
The Buffer Size=B.
There are N number of Buffers.
So, M=N*B.
The File Size=2M.
And therefore BufferCount is actually advancing File Pointer.
When all Bytes are written, I am issuing FileEnding=1.
The compilation commands are-
g++ Writer.c -o Writer -lpthread -lrt
g++ Reader.c -o Reader -lpthread -lrt

And in 2 different comand prompts are open and the commands are issued-
./Writer
./Reader

Now I do not know why it is not copying and do not know how to use sem_post.
Here is the Writer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main(void){
    struct MemData{
        sem_t FullMutex;
        sem_t FreeMutex;
        char FileName[128];
        int ReadPointer;
        int WritePointer;
        int FileEnding;
        char Data[512000];//MEMORY BLOCK SIZE: 500 KB
    };
    int SD;
    struct MemData *M;
    int NumberOfBuffers=10;
    //int BufferSize=51200;//FILE BUFFER SIZE 50 KB
    int BufferSize=2;//EXPERIMENATION
    unsigned char Buf[BufferSize];
    int BufferCount=0;

    SD= shm_open("/program.shared", O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
    if(SD< 0){
        printf("\nshm_open() error \n");
        return EXIT_FAILURE;
    }
    fchmod(SD, S_IRWXU|S_IRWXG|S_IRWXO);
    if(ftruncate(SD, sizeof(MemData))< 0){
        printf ("ftruncate() error \n");
        return EXIT_FAILURE;
    }
    M=(struct MemData*)mmap(NULL, sizeof(MemData), PROT_READ|PROT_WRITE, MAP_SHARED, SD, 0);
    if(M== MAP_FAILED){
        printf("mmap() error");
        return EXIT_FAILURE;
    }else{
        sem_init(&M->FullMutex, 1, 0);
        sem_init(&M->FreeMutex, 1, NumberOfBuffers);
        strcpy(M->FileName, "aaa.txt");
        M->FileEnding=0;
        M->ReadPointer=0;
        M->WritePointer=0;
        memset(M->Data, '\0', strlen(M->Data));
    }
    char FileName[128]="aaa.txt";
    FILE *FP= fopen(FileName, "rb");
    if(FP!= NULL){
        struct stat StatBuf;
        if(stat(FileName, &StatBuf)==-1){
            printf("failed to fstat %s\n", FileName);
            exit(EXIT_FAILURE);
        }
        long long FileSize=StatBuf.st_size;
        printf("\nFile Size: %lld", FileSize);
        long long FilePosition=ftell(FP);
        FilePosition=ftell(FP);
        long long CopyableMemorySize=FileSize-FilePosition;
        printf("\nCopyable File Size: %lld", CopyableMemorySize);
        int NumberOfFileBuffers=CopyableMemorySize/BufferSize;
        printf("\n Number Of File Buffers: %d", NumberOfFileBuffers);
        while(1){
            sem_wait(&M->FreeMutex);
            fseek(FP, BufferCount*BufferSize, SEEK_SET);
            fread(Buf, sizeof(unsigned char), BufferSize, FP);
            int FreeMutexValue;
            sem_getvalue(&M->FreeMutex, &FreeMutexValue);
            int FullMutexValue;
            sem_getvalue(&M->FullMutex, &FullMutexValue);
            printf("\nMutexes-Free: %d and Full: %d", FreeMutexValue, FullMutexValue);
            printf("\nBuffer Writing: %s", BufferCount);
            memcpy(&M->Data[M->WritePointer*BufferSize], &Buf, sizeof(Buf)*sizeof(unsigned char));
            BufferCount++;
            M->WritePointer=(M->WritePointer+1)%NumberOfBuffers;
            if(BufferCount>=NumberOfFileBuffers && M->WritePointer==M->ReadPointer){
                M->FileEnding=1;
                break;
            }
            sem_post(&M->FullMutex);
        }
        fclose(FP);
    }
    close(SD);
    return 0;
}

The Reader is using the Mutex opened by the Writer.c.
All the Block Size, Buffer Size and Number of Buffers are same like the Writer.c.
When the Reader gets FileEnding==1, it breaks the loop since there is nothing to process.
The Reader destroy the Mutex and deallocates Memory.
Here is the Reader.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main(void){
    char FileName[128]="bbb.txt";
    struct MemData{
        sem_t FullMutex;
        sem_t FreeMutex;
        char FileName[128];
        int ReadPointer;
        int WritePointer;
        int FileEnding;
        char Data[512000];//MEMORY BLOCK SIZE: 500 KB
    };
    int SD;
    struct MemData *M;
    int NumberOfBuffers=10;
    //int BufferSize=51200;//FILE BUFFER SIZE 50 KB
    int BufferSize=2;//EXPERIMENATION
    unsigned char Buf[BufferSize];
    int BufferCount=0;
    SD= shm_open("/program.shared", O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
    if(SD< 0){
        printf("\nshm_open() error \n");
        return EXIT_FAILURE;
    }
    M=(struct MemData*)mmap(NULL, sizeof(MemData), PROT_READ|PROT_WRITE, MAP_SHARED, SD, 0);
    if(M== MAP_FAILED){
        printf("mmap() error");
        return EXIT_FAILURE;
    }

    FILE *FP= fopen(FileName, "wb");
    if(FP!= NULL){
        while(1){
            sem_wait(&M->FullMutex);
            int FreeMutexValue;
            sem_getvalue(&M->FreeMutex, &FreeMutexValue);
            int FullMutexValue;
            sem_getvalue(&M->FullMutex, &FullMutexValue);
            printf("\nMutexes-Free: %d and Full: %d", FreeMutexValue, FullMutexValue);
             printf("\nBuffer Writing: %d", BufferCount);
            printf("\nReadPointer: %d", M->ReadPointer);
            printf("\nWritePointer: %d", M->WritePointer);
            fseek(FP, BufferCount*BufferSize, SEEK_SET);
            fseek(FP, BufferCount*BufferSize, SEEK_SET);
            fwrite(&M->Data[M->ReadPointer*BufferSize], sizeof(unsigned char), BufferSize, FP);
            BufferCount++;
            M->ReadPointer=(M->ReadPointer+1)%NumberOfBuffers;
            if(M->FileEnding){
                fclose(FP);
                break;
            }
            sem_post(&M->FreeMutex);
        }
    }
    munmap(M,sizeof(MemData));
    close(SD);
    return 0;
}

The input(aaa.txt) file contains these lines-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The output(bbb.txt) file contains these lines-
1
2
3
4
5
6
7
8
9
10
11
12
13
14


text:
Q: Flask-Admin: How to filter selectable data of a field based on values entered in the previous field, with search conditions in another table in flask-admin model view I want to filter a dropdown menu in the edit/create view of field that is a relationship, based on values entered in the previous field.
In the specific case, I would like to see only the ones in the "posto" that are displayed in another table belonging to the selected 'categoria'
class Tag(db.Model):
    __tablename__ = 'tags'
    nr_TAG = db.Column(db.Integer, primary_key=True)
    categoria_id = db.Column(db.Integer, db.ForeignKey('categorie.id'), nullable=False)
    categoria = db.relationship('Categoria', backref='tags')
    posto_id = db.Column(db.Integer, db.ForeignKey('stalli.id'), nullable=False)
    posto = db.relationship('Stallo', backref='tags')
    cognome = db.Column(db.String(30), nullable=False)
    nome = db.Column(db.String(30))
    auto = db.Column(db.String(20))
    targa = db.Column(db.String(10))
    recapito = db.Column(db.String(80))
    stato = db.Column(db.Integer)
    posto_occ = db.Column(db.Integer)
    orario = db.Column(db.Integer)
    fuoriposto = db.Column(db.String(10))
    parcheggio = db.Column(db.String(40))

class TagsAdmin(sqla.ModelView):
    can_edit = True
    can_create = True
    column_list = ['nr_TAG', 'categoria', 'posto', 'cognome', 'targa',
                        'stato', 'orario', 'fuoriposto', 'parcheggio']
    can_view_details = True
    details_modal = True
    form_columns = ['nr_TAG', 'categoria', 'posto', 'cognome', 'nome', 'auto', 'targa', 'recapito']

Any idea?
Thanks

A: I came up with following solution, maybe it's not perfect but it does the job:
master.html

function populateSelectField(to_populate, options, select) {
  $('#s2id_' + to_populate + ' > a > span').text('');

  var el = $('select[name$="' + to_populate + '"]');
  el.children().remove();

  option = '<option value=""></option>';
  el.append($(option));

  options.forEach(function(row) {
    var option_id = row.id,
      option_title = row.title;

    if (select && option_id == select) {
      option = '<option value="' + option_id + '" selected>' + option_title + '</option>';
      $('#s2id_' + to_populate + ' > a > span').text(option_title);
    } else {
      option = '<option value="' + option_id + '">' + option_title + '</option>';
    }

    el.append($(option));
  });
}

function getOptions(el, to_populate, url, select) {
  var item_id = el.val(),
    url = window.location.origin + url + item_id + '/';

  $.get(url).done(function(options) {
    populateSelectField(to_populate, options, select);
  }).fail(function(err) {
    console.error(err.message);
    return false;
  });
}

function selectFieldManipulation(from_populate, to_populate, url) {
  var main_select = $('select[name$="' + from_populate + '"]'),
    to_populate_el = $('select[name$="' + to_populate + '"]');

  getOptions(main_select, to_populate, url, to_populate_el.val());

  main_select.change(function(e) {
    getOptions(main_select, to_populate, url, null);
  });
}

create.html / edit.html

$(document).ready(function() {
  selectFieldManipulation('from_populate', 'to_populate', '/api/route_to_view/');
});


text:
Q: Specifying DataTemplate for Live Charts Series I'm looking to build a Scatter plot with a best fit line using Live Charts.
Now the way I've been doing this is by having a SeriesCollection on the main view model like so, within the class of this interface I manually add the BubbleSeries and the LineSeries for the chart:
public interface IPointAnalysisViewModel : IAnalysisViewModel
{
    SeriesCollection Series
    {
        get;
    }
}

PointAnalysisViewModel:
foreach (var pointSliceViewModel in this.slices)
{
    this.series.Add(pointSliceViewModel.Series);
}
this.bestFitLineSeries = this.BuildBestFitLine(pointAnalysisModel.BestFitValues);
this.series.Add(this.bestFitLineSeries);

This series is then bound within xaml to the Series of the CartesianChart as follows:
<wpf:CartesianChart Grid.Column="1"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch"
                        Series="{Binding Path=Series}" >
... UI Fluff
</wpf:CartesianChart>

Pretty basic as you'd expect, but this means that in my ViewModels for the series I then have know that the view will display a bubble series for me as follow:
public interface IPointSliceViewModel : IViewModel
{
    IBubbleSeriesView Series
    {
        get;
    }

    bool Show
    {
        get;
        set;
    }
}

To me this looks badly like some code 'smell' in that I need to know view specific objects within my View Model.
The only way that I can think that would allow me to separate the concerns of the View and the ViewModel is if I were able to provide the CartesianChart with the data templates for the Series and bind the Series to a collection of IPointSliceViewModels instead as follows:
<wpf:CartesianChart Grid.Column="1"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    SeriesSource="{Binding Path=Series}">
    <wpf:CartesianChart.SeriesTemplates>
        <DataTemplate DataType={x:Type local:PointSliceViewModel}>
            <wpf:BubbleSeries .../>
        </DataTemplate>
    </wpf:CartesianChart.SeriesTemplates>
... UI Fluff
</wpf:CartesianChart>

Which would simply allow me to have:
public interface IPointAnalysisViewModel : IAnalysisViewModel
{
    ObservableCollection<IPointSliceViewModel> Series
    {
        get;
    }
}

and:
public interface IPointSliceViewModel : IViewModel
{
    ChartValues<ObservablePoint> Values
    {
        get;
    }

    bool Show
    {
        get;
        set;
    }
}

Is it currently possible to provide the DataTemplates for the Series or do I have to manually do this in the code behind at the moment?
Or is there a different way of having potentially limitless numbers of series in a chart without having to define each of them in the View and without having to keep track of the view specific details in the VM?


text:
Q: Three identical SMTP server configurations, one succeeds, two fail in Mail I have three e-mail accounts each with a different domain name, however all of them send e-mail via the same domain name via SMTP (but each has its own login credentials). To clarify, it looks something like this:
user@domain1.tld    imap:mail.domain1.tld    smtp:mail.domain1.tld
user@domain2.tld    imap:mail.domain2.tld    smtp:mail.domain1.tld
user@domain3.tld    imap:mail.domain3.tld    smtp:mail.domain1.tld

Each account uses its own e-mail address and password to login via both IMAP and SMTP. This means that I have three SMTP servers listed in Mail, one for each account, and each logging in with the appropriate user-name and password.
However, while one of these works flawlessly, the other two refuse to connect, with no specific error given. If I go into the SMTP server list, neither has a password listed, entering one and saving will cause it to become online then immediately offline, with the password field once again empty.
If I verify the details manually using openssl on a command line, then I can confirm that the details are in fact correctly, and that the SMTP server (postfix) is happy to accept requests from user@domain2.tld and user@domain3.tld even though they're connecting via mail.domain1.tld.
Is this a bug specific to Mail? Does it have something to do with the shared domain?
Of course I can just use one common SMTP server, however it seems as though I shouldn't need to. While I'm not sure if it's relevant, the server uses client authentication (by specifying a unique TLS certificate for each user); fortunately it isn't using this for passwordless logins, otherwise a common SMTP server wouldn't work, but perhaps it's related to why Mail is failing to handle this properly?


text:
Q: Android application can't launch I have made this app but when i try to launch it a message pops saying application has stopped.I really can't find any mistake in the code..
  This is the code it is just many ImageButtons :
package com.fanis.math;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class MyResistance extends Activity implements OnClickListener {
View b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12;
Button bok, bclear;
TextView t;
int k = -1;
int[] ar = new int[4];
double n = 0;
double multi=0;
String nString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.resistance);

    b1 = (ImageButton) findViewById(R.id.im1);
    b2 = (ImageButton) findViewById(R.id.im2);
    b3 = (ImageButton) findViewById(R.id.im3);
    b4 = (ImageButton) findViewById(R.id.im4);
    b5 = (ImageButton) findViewById(R.id.im5);
    b6 = (ImageButton) findViewById(R.id.im6);
    b7 = (ImageButton) findViewById(R.id.im7);
    b8 = (ImageButton) findViewById(R.id.im8);
    b9 = (ImageButton) findViewById(R.id.im9);
    b10 = (ImageButton) findViewById(R.id.im10);
    b11 = (ImageButton) findViewById(R.id.im11);
    b12 = (ImageButton) findViewById(R.id.im12);
    bok = (Button) findViewById(R.id.ok);
    bclear = (Button) findViewById(R.id.clear);
    t = (TextView) findViewById(R.id.tv1);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);
    b4.setOnClickListener(this);
    b5.setOnClickListener(this);
    b6.setOnClickListener(this);
    b7.setOnClickListener(this);
    b8.setOnClickListener(this);
    b9.setOnClickListener(this);
    b10.setOnClickListener(this);
    b11.setOnClickListener(this);
    b12.setOnClickListener(this);
    bok.setOnClickListener(this);
    bclear.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.im1:
        k += 1;
        ar[k] = 0; // dianisma pou krataei kathe psifio
        break;
    case R.id.im2:
        k += 1;
        ar[k] = 1;
        break;
    case R.id.im3:
        k += 1;
        ar[k] = 2;
        break;
    case R.id.im4:
        k += 1;
        ar[k] = 3;
        break;
    case R.id.im5:
        k += 1;
        ar[k] = 4;
        break;
    case R.id.im6:
        k += 1;
        ar[k] = 5;
        break;
    case R.id.im7:
        k += 1;
        ar[k] = 6;
        break;
    case R.id.im8:
        k += 1;
        ar[k] = 7;
        break;
    case R.id.im9:
        k += 1;
        ar[k] = 8;
        break;
    case R.id.im10:
        k += 1;
        ar[k] = 9;
        break;
    case R.id.im11:
        k += 1;
        multi = 0.01;
        break;
    case R.id.im12:
        k += 1;
        multi = 0.1;
        break;
    case R.id.ok:
        for (int i = 1; i <= k; i++) {
            n = n + ar[i - 1] * Math.pow(10, k - i);
        }
        if (multi == 0) {
            multi = Math.pow(10, ar[k]);
        }
        n = n * multi;
        nString = String.valueOf(n) + "" + "Ω";
        t.setText(nString);
        break;
    case R.id.clear:
        t.setText("");
        n = 0;
        k = -1;
        multi=0;
    }

}

}
  And this is the manifest
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fanis.math"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MyResistance"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

This is layout though i don't think it is the reason i can't launch the app..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:gravity="center"
    android:text=""
    android:textSize="40dp" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/im1"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/black" />

        <ImageButton
            android:id="@+id/im2"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/brown" />

        <ImageButton
            android:id="@+id/im3"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/red" />

        <ImageButton
            android:id="@+id/im4"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/orange" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/im5"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/yellow" />

        <ImageButton
            android:id="@+id/im6"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/green" />

        <ImageButton
            android:id="@+id/im7"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/blue" />

        <ImageButton
            android:id="@+id/im8"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/purple" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/im9"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/grey" />

        <ImageButton
            android:id="@+id/im10"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/white" />

        <ImageButton
            android:id="@+id/im11"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/silver" />

        <ImageButton
            android:id="@+id/im12"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/gold" />
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/ok"
        android:layout_width="110dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:text="Ok" />

    <Button
        android:id="@+id/clear"
        android:layout_width="110dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:text="Clear" />
</LinearLayout>

My logcat:
 04-11 04:29:17.420: E/AndroidRuntime(847): FATAL EXCEPTION: main
 04-11 04:29:17.420: E/AndroidRuntime(847): Process: com.fanis.math, PID: 847
04-11 04:29:17.420: E/AndroidRuntime(847): java.lang.RuntimeException:           Unable to start activity        ComponentInfo{com.fanis.math/com.fanis.math.MyResistance}:    android.view.InflateException: Binary XML file line  #44: Error inflating class  <unknown>
   04-11 04:29:17.420: E/AndroidRuntime(847):   at    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
   04-11 04:29:17.420: E/AndroidRuntime(847):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
  04-11 04:29:17.420: E/AndroidRuntime(847):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.os.Handler.dispatchMessage(Handler.java:102)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.os.Looper.loop(Looper.java:136)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.app.ActivityThread.main(ActivityThread.java:5017)
04-11 04:29:17.420: E/AndroidRuntime(847):  at java.lang.reflect.Method.invokeNative(Native Method)
04-11 04:29:17.420: E/AndroidRuntime(847):  at java.lang.reflect.Method.invoke(Method.java:515)
04-11 04:29:17.420: E/AndroidRuntime(847):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-11 04:29:17.420: E/AndroidRuntime(847):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-11 04:29:17.420: E/AndroidRuntime(847):  at dalvik.system.NativeStart.main(Native Method)
04-11 04:29:17.420: E/AndroidRuntime(847): Caused by: android.view.InflateException: Binary XML file line #44: Error inflating class <unknown>
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.createView(LayoutInflater.java:620)
04-11 04:29:17.420: E/AndroidRuntime(847):  at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
04-11 04:29:17.420: E/AndroidRuntime(847):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)     04-11 04:29:17.420: E/AndroidRuntime(847):     at android.app.Activity.setContentView(Activity.java:1929)
04-11 04:29:17.420: E/AndroidRuntime(847):  at com.fanis.math.MyResistance.onCreate(MyResistance.java:25)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.app.Activity.performCreate(Activity.java:5231)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-11 04:29:17.420: E/AndroidRuntime(847):  ... 11 more
04-11 04:29:17.420: E/AndroidRuntime(847): Caused by: java.lang.reflect.InvocationTargetException
04-11 04:29:17.420: E/AndroidRuntime(847):  at java.lang.reflect.Constructor.constructNative(Native Method)
04-11 04:29:17.420: E/AndroidRuntime(847):  at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.view.LayoutInflater.createView(LayoutInflater.java:594)
04-11 04:29:17.420: E/AndroidRuntime(847):  ... 26 more
04-11 04:29:17.420: E/AndroidRuntime(847): Caused by: java.lang.OutOfMemoryError
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.content.res.Resources.loadDrawable(Resources.java:2110)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.widget.ImageView.<init>(ImageView.java:129)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.widget.ImageButton.<init>(ImageButton.java:87)
04-11 04:29:17.420: E/AndroidRuntime(847):  at android.widget.ImageButton.<init>(ImageButton.java:83)
04-11 04:29:17.420: E/AndroidRuntime(847):  ... 29 more

A: Change this line :
View b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12;

to:
ImageButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12;


text:
Q: Permissions in a MAMP development environment I use MAMP as my local development environment. A persistent problem I have is reliably setting folder/file permissions.
For example, I currently have an images folder I need 666 permissions on. In the more info menu in the mac finder my permissions are read & write. However in the Dreamweaver permissions dialog the same folder has 000 permissions. This resets to 000 every time I leave the dialog.
So I have one screen saying I have full permission and another saying I have none for the same folder. When attempting test uploads to this folder, my script returns an error when moving the file from the tmp location.
chmod ($directory, 0755) returns false.
The temporary file exists

A: A folder should have an execute bit, in this case 777.
Without it, the folder can't be read.


text:
Q: Magento 2 Order Confirmation How to Send Two Email I am using Magento 2.1.6, I want to send two different email on order confirmation.
Order confirmation email sent successfully.But how i send my custom another email.
Thanks in Advance

A: I assume you want a second email field in customer account area.  Then providing this has a value then order confirmation will be cc'd to this addresses
I put together an extension
https://github.com/DominicWatts/EmailCC

One minor note.  Amazon payment seemed to get in the way.  So I had to override the default functionality.  Not cleanest solution.  Basically <referenceContainer name="form.additional.info"> didn't seem to want to work.  If you take a look at phtml you will see what I've done.


text:
Q: Save & load best model in AutoTS python After fitting AutoTS model over some time series data, how can I save & load the best model trained? Though, the AutoTS object has export_template() & import_template() functions to save best model, but while loading best model from this template, it requires re-fitting. How can such a solution be used in production? My code:
from autots import AutoTS

model = AutoTS(
frequency='infer',
prediction_interval=0.9,
ensemble=None,
model_list="fast",  # "superfast", "default", "fast_parallel"
transformer_list="fast",  # "superfast",
drop_most_recent=1,
max_generations=4,
num_validations=2,
validation_method="backwards")

 model.fit(df_day,date_col='xyz',value_col='abc')
 model.export_template("unique_user_1", models='best', n=1, max_per_model_class=3)

Now, in some new instance, when I do
 model = model.import_template('unique_user_1.csv',method='only')

The model required retraining.

A: The major issue with your code is that you have named your export_template as 'unique_user_1' without an extension. Try saving it as csv file with 'unique_user_1.csv'
Once you feel you are done with training your model. Write the following lines
model.export_template(
    "unique_user_1.csv",
    models="best",
    max_per_model_class=1,
    include_results=True
)

To load the template & reuse it
model = model.import_template(
    "unique_user_1.csv",
    method="only",
    enforce_model_list=True)

model.fit(data)

prediction = model.predict(forecast_length=15)


text:
Q: Effective way of using RelativePanel for UWP App I am creating an UWP Application, and in my App I want structure like default Mail App, where there is a Listview which has list of all the mails and when user click on that mail it open on the right side of it.
I read about RelativePanel and tried to use that in my App, it works pretty well for now, below is the xaml which I am using:
   <RelativePanel Grid.Row="1">

        <Frame x:Name="listFrame"
               Width="600"
               Height="500"/>

        <Frame x:Name="contentFrame"
               RelativePanel.RightOf="listFrame"
               Width="600"
               Height="500" />

    </RelativePanel>

For Tablet/PC it works well and when I open it in Mobile view it automatically adapt by putting contentFrame at bottom, but my concern is that should I use this for Mobile view? because keeping contentFrame is not making sense as user should not able to view content in mobile view, for that I user should click any item and than only content view gets visible and listview will gets collapse, similar to Mail App.
I am not sure which way to go for, do I need to create different UI for PC and Mobile or there is something baked in the SDK that I can use for?
I am new to UWP so didn't know much options that I can go for.

A: There are many options to handle multi views for multi devices.

*

*Create difference views (XAML file) for each device family. Use this when your xaml changes dramatically between device families.

*Use adaptive trigger to change the visibility or re-flow your XAML, use it with x:DeferLoadStrategy="Lazy" to have better performance because element will not be initialized until you change the visibility from trigger

*Check the device family in code behind and react accordingly

A: What you are looking for is called "Master-Detail".
There's a sample for that in the windows-universal-sample git repo -> Master/Detail sample
Download the sample, run it and take a look into the code. I think it's a good starting-point.


text:
Q: Issue with 'FirebaseUser' Future I am having an issue implementing Google Sign in with Firebase in a new project saying the expression doesn't evaluate to a function. The code has worked in my other projects over the past year. Here is my code:
class FirebaseAuthService {
  final FirebaseAuth _firebaseAuth;
  final GoogleSignIn _googleSignIn;

  FirebaseAuthService({FirebaseAuth firebaseAuth, GoogleSignIn googleSignin})
      : _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance,
        _googleSignIn = googleSignin ?? GoogleSignIn();

  Account _userFromFirebase(User user) {
    if (user == null) {
      return null;
    }
    return Account(
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoUrl: user.photoURL,
    );
  }

  Stream<Account> get onAuthStateChanged {
    return _firebaseAuth.onAuthStateChanged.map(_userFromFirebase);
  }

  Future<Account> signInAnonymously() async {
    final authResult = await _firebaseAuth.signInAnonymously();
    return _userFromFirebase(authResult.user);
  }

  Future<Account> signInWithGoogle() async {
    final googleUser = await _googleSignIn.signIn();
    final googleAuth = await googleUser.authentication;
    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    final authResult = await _firebaseAuth.signInWithCredential(credential);
    return _userFromFirebase(authResult.user);
  }

  Future<void> signOut() async {
    return _firebaseAuth.signOut();
  }

  Future<Account> currentUser() async {// The Issue is here in the Future<>
    final user = await _firebaseAuth.currentUser();
    return _userFromFirebase(user);
  }
}

A: In the latest version of firebase_auth(0.18.0+1), there is no currentUser function, and it does not return a Future. There were major breaking changes done to many of the FlutterFire packages that may have changed this syntax and you likely updated your packages without looking at the changelog for these breaking changes.
Getting the currentUser has now been changed to a getter and no longer returns a Future.
The currentUser function should be modified to the following:
Account currentUser() {
  final user = _firebaseAuth.currentUser;
  return _userFromFirebase(user);
}


text:
Q: PHP adding days to a date in a new variable changes the other I have a variable invoiceDate, which is a datetime type. I calculate the dueDate by adding 14 days to the invoiceDate with the following:
private $invoiceDate; // this is any datetime.
private $dueDate;

public function calculateDueDate(){
    $due = date_add($this->invoiceDate, new \DateInterval('P14D'))  ;
    return $due;
}

public function getInvoiceDate()
{
    return $this->invoiceDate;
}

public function getDueDate()
{
    $this->dueDate = $this->calculateDueDate();
    return $this->dueDate;
}

What I don't get is that when I use the method getDueDate() or getInvoiceDate() I always get the original invoiceDate plus 14 days, on both methods. Why is the original date affected and what can I do to prevent this?

A: Open date_add manual and see that first argument of date_add is:

A DateTime object returned by date_create(). The function modifies this object.

So, you need to modify another object, for example, a clone:
public function calculateDueDate(){
    $due = date_add(
        clone $this->invoiceDate,
        new \DateInterval('P14D')
    );
    return $due;
}


text:
Q: Why doesn't JQuery scroll to the first DOM element after a given event is fired? When a user submits form "x", the form goes through a JavaScript validation and error messages are placed underneath any elements that have errors. This is the last section of my code that places the errors:
errorElement: "span",
errorClass: "field-validation-error",
errorPlacement: function (error, element) {
error.insertAfter(element.closest('div'));}

When the user clicks submit and all the errors are placed, the page does not move from where the user had it.  I want the page to scroll to the first error on the page so the user can clearly see what he did wrong.
This is probably way wrong but I tried something like this underneath the code above:
var position = element.position;
$.scrollTop(position.top);

Why doesn't this work?

A: Depending on what your "element" is you can simply do (Assuming element is a JQuery object already):
http://api.jquery.com/position/
and
http://api.jquery.com/scrollTop/
$(window).scrollTop(element.position().top);

Keep in mind if element is already a JQuery object you don't need to do $(element).  If element is not a jquery object it needs to be the ID or unique selector to return to that element.
Edit: Animation Support
http://api.jquery.com/animate/
$(window).animate({"scrollTop": element.position().top});

Edit: Address picking an element from comments
Your other options are to give your error elements all the same class, this way you could always (when completed) scroll to the first error on the page.
var scrollPosition = Number($(".common-error-class:first").position.top);

Then from there you only have to invoke the window to scroll:
$(window).scrollTop(scrollPosition);

Edit: Verified working example
//The line you are focusing on
$(window).scrollTop($("input:last").position().top);

The full html file:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <button id="triggerScroll">Scroll</button>

Index

<form action="/Request/InvokeAction" method="post">    <input type="hidden" name="ActionID" value="10" />

FirstName

<input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="" />

LastName

<input class="text-box single-line" id="LastName" name="LastName" type="text" value="" />

Company

<input class="text-box single-line" id="Company" name="Company" type="text" value="" />

BirthMonth

<input class="text-box single-line" data-val="true" data-val-number="The field BirthMonth must be a number." data-val-required="The BirthMonth field is required." id="BirthMonth" name="BirthMonth" type="number" value="" />

BirthDay

<input class="text-box single-line" data-val="true" data-val-number="The field BirthDay must be a number." data-val-required="The BirthDay field is required." id="BirthDay" name="BirthDay" type="number" value="" />

BirthYear

<input class="text-box single-line" data-val="true" data-val-number="The field BirthYear must be a number." data-val-required="The BirthYear field is required." id="BirthYear" name="BirthYear" type="number" value="" />

BirthDate

<input class="text-box single-line" data-val="true" data-val-date="The field BirthDate must be a date." data-val-required="The BirthDate field is required." id="BirthDate" name="BirthDate" type="datetime" value="" />

Email

<input class="text-box single-line" id="Email" name="Email" type="text" value="" />

    <button type="submit">Submit</button>

</form>

A: The problem is that you're using element.position instead of element.position(). Position is a jQuery function, not a property.


text:
Q: How to use the OpenAI stream=true property with a Django Rest Framework response, and still save the content returned? I'm trying to use the stream=true property as follows.
completion = openai.Completion.create(
            model="text-davinci-003",
            prompt="Write me a story about dogs.",
            temperature=0.7,
            max_tokens=MAX_TOKENS,
            frequency_penalty=1.0,
            presence_penalty=1.0,
            stream=True,
        )

Unfortunately, I don't know what to do from here to return it to my React frontend. Typically, I've used standard response objects, setting a status and the serializer.data as the data. From my readings online, it seems I have to use the StreamingHttpResponse, but I'm not sure how to integrate that with the iterator object of completion, and actually save the outputted data once it is done streaming, as the view will end after returning the iterator to the endpoint. Any help?

A: Answer ended up being I was thinking of approaching it incorrectly. Use websockets! Not StreamingHttpResponse.


text:
Q: Как правильно удалить диапазон элементов зная начало и конец диапазона в списке? Есть такой код:
Необходимо удалить диапазон элементов по индексу, скажем с 5-го по 8-й включительно.
class DataRow
{

    public string Time { get; set; }

    public Int32 Temperature { get; set; }

    public DataRow(string time , Int32 temperature)
    {
        Time = time;
        Temperature = temperature;
    }

    public override string ToString() {

        return $"{Time} {Temperature}";

    }

}

List<DataRow> listData = new List<DataRow>();

listData.Add(new DataRow("10:00:00", 0));
listData.Add(new DataRow("10:00:01", 1));
listData.Add(new DataRow("10:00:02", 2));
listData.Add(new DataRow("10:00:03", 3));
listData.Add(new DataRow("10:00:04", 4));
listData.Add(new DataRow("10:00:05", 5));
listData.Add(new DataRow("10:00:06", 6));
listData.Add(new DataRow("10:00:07", 7));
listData.Add(new DataRow("10:00:08", 8));
listData.Add(new DataRow("10:00:09", 9));
listData.Add(new DataRow("10:00:10", 10));
listData.Add(new DataRow("10:00:11", 11));

A: Серьёзно? Задача на вычитание двух чисел вызвала затруднения?
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
Console.WriteLine(string.Join(", ", list));

// Диапазон: 8..11
int start = 8;
int end = 11;
int count = end - start;

list.RemoveRange(start, count);

Console.WriteLine(string.Join(", ", list));

A: Просто ещё один способ, может кому пригодится
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int start = 5, end = 8;
var result = list.Where((i, ind) => ind < start || ind > end).ToList();
Console.WriteLine(String.Join(',', result));

Вывод
1,2,3,4,5,10,11,12


text:
Q: Using python for obtaining features from audio in unity I have to develop a android application which will capable of doing predictions on device meaning I have to perform every action on the device itself
The application has to extract features from audio and feed them to tensorflow lite model for prediction
For training the model, I extracted the features from audio using Librosa, but I am not able to find a suitable framework which can help me extract features from audio like librosa and make prediction using tflite model
I found out that I can do something using Ironpython or python.net in unity but I am still confused about how to achieve it.
So my question is whether there is way to run the python script written on android device with unity.
Also if there are other frameworks, that can help me achieve my goal of on-device prediction, ,I will welcome those suggestions

A: It was not feasible to accomplish the task using unity effectively.
I solved the problem using chaquopy plugin for android studio, this enables you to use python with java or you can code the whole android application in python using chaquopy.


text:
Q: How to convert infix equation to postfix equation on C#? I found so much algorithms on google but, I can't find runnable algorithm that convert infix to postfix. How to convert infix equation to postfix equation on C#? Please help...

A: This is a great little project for learning to program. There are two parts: parse the code into a tree, then print the tree as postfix. Each tree node is an operator with two children: 4 + (5/6) has + as the root node, and the children are 4 and 5/6. When you look deeper at the 5/6 node, you find a parent with two children: the parent is / and the children are 5 and 6.
Parsing is the hardest part. To parse an expression, look at what you need to parse, find the operator, and note what's left of the operator and what's to the right. The operator is the node, and it has two children: the Parse(stuff to the left) and Parse(stuff to the right). You'll need to pay extra attention to minus (which is a unary operator and so not strictly infix). I suggest treating minus as a special case: -4 should be parsed as -4, not a minus node with one child 4. When you parse the equation, all the internal nodes should be operators and all the leaf nodes will be numbers.
After you've parsed it, just print. For the root node, print(node) will print "(", the left child (print it recursively), the right child (print it recursively), the operator, then close the expression (node) with ")".
I don't have a link to the algorithm handy, but you'll actually grow a lot more if you implement it yourself.


text:
Q: Xcode Nested IBAction Hey I have some code generating and displaying a random word from a list like this:
-(IBAction)secondWord {
    int text = rand() % 2;
    switch (text) {
        case 0:
            secondWord.text = @"random1";
            break;
        case 1:
            secondWord.text = @"random2";
            break;
        default:
            break;
    }

I have this twice with 2 buttons changing the text on 2 labels. Is there a way I can set up another action to execute both of these IBActions at once. Thus allowing the words to be randomly generated individually and at the same time.
Thanks.

A: -(IBAction)allWords {
    [self firstWord];
    [self secondWord];
}

Something like this? You can call those actions just like any other function.


text:
Q: C++ Stop Preprocessor Macro Expansion Here is my example code https://godbolt.org/z/VKgKik
#define delete MyCustomDelete(__FILE__, __LINE__), delete

#define CAT(X,Y) CAT2(X,Y)
#define CAT2(X,Y) X##Y
#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))

class A {
    A() = CAT_3(de,le,te);
};

The godbolt example is setup to display the preprocessor output. The goal is that at the end of the preprocessor pass i want the output code to be
class A {
    A() = delete;
};

currently "ThisShouldNotshowUp" is displayed there instead. I thought the use of the ## operator would stop the preprocessor from reexpanding but it did not.
I realize removing the "#define delete" would solve the problem but I need this define there. The reason I have created a macro with the same name as delete is because I want to be able to track the news and deletes, and If a memory leak occurs I can see what line of code aloced it. This macro thus means I can continue to use the keyword delete in my code and the File and line numbers get filled in for free. As far as i know there is no other way to achieve this functionailty except by defined a delete macro. This is the crux of the problem. The delete macro has given me a powerful debug tool however it has removed a useful language feature for me to use.

A: You have no chance in creating a preprocessing token that is the name of an object-like macro from expanding a macro. The relevant section of n3337 is [cpp.rescan]. I quote a shortened part of the first paragraph in it.

After all parameters in the replacement list have been substituted and # and ## processing has taken place [...]. Then the resulting preprocessing token sequence is rescanned [...] for more macro names to replace.

Nonwithstanding the problem, that delete is technically forbidden to be a macro name, there is no way to prevent the macro name to be recognized while rescanning.
You probably mixed up the fact that ## operator does use it's parameters without expansion with the idea that the result of ## doesn't undergo macro expansion.

A: What you're trying to do is not possible, as Michael Karcher's answer states: #define delete already makes the program ill-formed, and expanding an object-like macro (outside its own expansion) cannot be avoided.
However, for your particular use case detailed in the question, a workaround is possible. You could put your #define delete into a header file (let's call it debug_delete.hxx), like this:
#ifdef delete
# undef delete
#endif
#define delete MyCustomDelete(__FILE__, __LINE__), delete

Then, create another header file (let's call it normal_delete.hxx):
#ifdef delete
# undef delete
#endif

Note in particular that there is no mechanism in these headers to prevent multiple inclusion; in fact, we want them includable an arbitrary number of times.
Then, wrap code which must use = delete; in appropriate #include directives:
class A {
#include "normal_delete.hxx"
    A() = delete;
#include "debug_delete.hxx"
    ~A() { delete p; }
};

(Yes, it's ugly, but what you're doing is sort of ugly in the first place, so ugly code may be required to make it work).

A: Presumably you want to use a macro so you can turn on and off your delete tracking. If you're only using this on your source, and not trying to rig it up to transform existing C++, you could use a function-like macro in order to effect the optional tracking that you desire.
#define TRACK_DELETES 0
#if TRACK_DELETES
  #define DELETE( a ) \
    do { MyCustomDelete( __FILE__, __LINE__ ); delete (a); } while (0)
  #define DELETEALL( a ) \
    do { MyCustomDelete( __FILE__, __LINE__ ); delete [] (a); } while (0)
#else
  #define DELETE( a ) do { delete (a) ; } while(0)
  #define DELETEALL( a ) do { delete [] (a) ; } while(0)
#endif

int main(){

  DELETE( A );
  DELETEALL( B );

  return 0;
}

See if this does what you want with TRACK_DELETES set to 0 or 1 under gcc -E.
You'll want to leave the bare delete keyword alone so it can be used appropriately.


text:
Q: Oracle stored procedure to generate sequence numbers? I have a employee, product and product odometer tables which looks like below

Each employee has a unique emp_code depending on the product he has access to.
Each product will have a unique prefix to its identifier.
I need to generate a unique alphanumeric identifiers per product and assign it to the employee.
This product identifier is going to be 9 characters long including the prefix.
Odometer table will store the last emp_code assigned to employees in that particular product.
How do I write a stored procedure to generate these alphanumeric emp_codes based on product for each new employee being added in the system?
Please help.
EDIT 1:
Just a small correction in the odometer table, we may not need to store the odometer as A00000001. Instead we could only store 00000001 and then append the prefix.
EDIT 2:
This is what I have do so far.
create or replace PROCEDURE SP_GEN_NEXT_DUMMY_DB_PRISM_ID
(
  in_product_id number,
  db_prism_id out varchar2
)
AS
BEGIN

  UPDATE BI_DB_PRISM_ID_ODOMETER
  SET DB_PRISM_ID =  DB_PRISM_ID + 1
  WHERE
    PRODUCT_ID = in_product_id;

  SELECT to_char(db_prism_id, 'FM00000000') into db_prism_id FROM     BI_DB_PRISM_ID_ODOMETER WHERE PRODUCT_ID = in_product_id;

END;

But how can I make sure that it runs in a transaction and also how do I append the product prefix to the number generated.

A: You have two options that I can think of:

*

*Create an Oracle sequence for each product, perhaps with some kind of maintenance procedure that would detect new products and create the sequences dynamically.

*Roll your own sequence code. Store the last value in the Product table. Write a procedure that generates a new value for a given product. The procedure would first obtain a row lock on the product table (so that you don't get two sessions getting the same value at the same time), advance the value, and write the new value to the Product table. You would need this procedure to be an autonomous transaction (otherwise other sessions would just wait if a session doesn't commit or rollback straight away).
An advantage of #1 is that it's the fastest.
A disadvantage of #1 is you're having to run dynamic DDL, and you'd have to make sure the DDL for a product has been run before trying to insert odometer records for it. You might also need to think about whether to drop a sequence if a product is deleted.
Another disadvantage of #1 is that you can only get sequence values with dynamic SQL (you'd have to determine the name of the sequence at runtime).
A disadvantage of #2 is that it's easy to get it wrong for a system that allows concurrent DML. You'd want to make sure you get the logic right, and test it under high concurrent load. Also, #2 will perform worse than #1 because it serializes access for each product.
Edit

"But how can I make sure that it runs in a transaction and also how do
  I append the product prefix to the number generated."

Transactions are automatic in Oracle. In this case, however, what you want is an autonomous transaction.
Appending the product prefix is done using the string concatenation function - e.g. ||

A: Seems to be that you're denormalising the data model here.
The odometer table is 1:1 with the product table, and the odometer value also depends on the number of employees currently assigned with that product.
The emp_code sequence number can be derived from the employee id and the product table. Aerguably the identifier prefix can be inferred from the product id also, so in fact you have redundant columns and a redundant table in your schema.
Are you sure that you really need them?

A: Perhaps I'm missing something here, if so accept my apologies.
It seems to me that the odometer is merely a counter of how many Employees have access to each product.
If that is the case, why not get rid of the table (and the EMP_CODE column) altogether and "build" that info in one or more views?
Alessandro
PS: looks like I posted the same suggestion of David Aldridge. Sorry for the confusion.