text:
Q: How to write a regexp with AND operator? I have definition string from my user to match an input string and i would like to simplify the definition string so my user won't need to know regexp internal.
my thought was to allow */-7721/-7722/-7723 to match any given 4 digit string which is not 7721 AND not 7722 AND not 7723.
I am searching for a regexp to perform the above on an input string which is a 4 digit number.
I have tried using the ?! notation, but it can't mis-match the entire string.
(?![0-9]{4}) - this doesn't allow any 4 digit string.
((?!(7721))(?!(7722))(?!(77223)) - this also didn't work
Is there an AND operator to perform the above?
Thanks,

A: You forgot ^:
^(?!(?:7721))(?!(?:7722))(?!(?:7723))\d{4}

Edited: added \d{4} for actually matching the string, not just testing


text:
Q: In Unix, is it possible to give getops a range of values to expect? Sorry if the title is confusing, but here's what I mean:
If I have a script that can accept several parameters, I'd use the getops command in order to more easily control script actions based on the parameters passed. However, lets say one of these parameters can be any number from 5 - 9, or whatever. Is there a way to tell getops that any number passed as command to the script between 5 and 9 should be taken as a single user-command?
My code so far is something like:
#!/bin/sh
args=`getopt -o abc: -- "$@"`
eval set -- "$args"
echo "After getopt"
for i in $args
do
 case "$i" in
    -c) shift;echo "flag c set to $1";shift;;
    -a) shift;echo "flag a set";;
    -b) shift;echo "flag b set";;
done

I want to see if I can do something like:
#!/bin/sh
args=`getopt -o ab[0-9]c: -- "$@"`
eval set -- "$args"
echo "After getopt"
for i in $args
do
 case "$i" in
    -c) shift;echo "flag c set to $1";shift;;
    -a) shift;echo "flag a set";;
    -b) shift;echo "flag b set";;
    -[0-9]) shift; echo $i;;
done

A: No, at least not with the one I use (someone may have an enhanced one out there but it won't be standard anywhere).
For that particular case, it's probably okay to use:
args=`getopt -o ab0123456789c: -- "$@"`

although, for larger cases, that might be unwieldy.
Have you thought about not treating them as individual options? In other words, say they're debug levels for a logging procedure. Why could you not use:
args=`getopt -o abc:d: -- "$@"`

and specify them with progname -b -d4 instead of progname -b -4?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Through hole SMA parasitic effects I'm designing a PCB involving signals up to 6 GHz. I want to use through-hole SMA connectors like these:
If I route the RF traces on the top of the board, will the center contact of the through-hole connector sticking out to the other side of the board have any significant effects (compared to something like an edge mount connector)?
(I have been looking around for advice on this but have not really found anything, apart from USB 3.0 application notes suggesting that the superspeed traces better be routed on the opposite side of the board when using through-hole USB 3.0 connectors.)
In case my description is not clear I'd be happy to provide pictures to illustrate.
Thank you!
Update: I think I'm going to go with edge launch connectors, just to be safe. Thanks for the answers.

A: Assuming that the connector is fine for 6 GHz, the 3mm or so protrusion on the solder side would become an issue if 3mm represented about one-tenth of the wavelength of 6 GHz. This is a general rule of thumb and some people say one-twentieth but I'll stick with 1/10.
6 GHz has a wavelength of 5 cm and one tenth of this is 5 mm so, you could argue that it's beginning to be a small effect. Maybe just trim it back so that it barely protrudes.
If it were a quarter of a wavelength long then you would have effectively an impedance transformer that would look like zero ohms and that wouldn't be very good but, a quarter wave is 12.5 mm and you maybe have 3mm protruding (PCB thickness dependent).

A: When I worked at 1 and 2.5 GHz, we used these connectors without consideration for stub effects. Now, working at 25 GHz , we would just about never use them (even the variants with coax connector types appropriate for 25 GHz). However, your operating band is somewhere between there so these rules of thumb aren't especially helpful.
I agree with Andy's analysis that, especially if you trim the stub protruding from the opposite side of the board, this connector is likely to work well at 6 GHz. But you haven't said what your application is and whether you have particularly stringent requirements for VSWR or for insertion loss flatness across a wide frequency band. So I'll add a few suggestions.
Using an edge-mount SMA connector would produce a smaller discontinuity between the pcb trace and the connector.
Routing the trace on the opposite side (or, on a buried layer close to the opposite side) of the board from where the connector is mounted would produce a smaller discontinuity.
In comments you asked,

Do you have any suggestions regarding the ground planes underneath the connector?

I'd pull all copper away (maybe by 3 - 5 mm?) from the stub part of the connectors center pin. (The stub is the part that isn't on the path from the trace to the other side of the connector). This will reduce capacitance between the pin and other nets (mainly power and ground) which I'd expect to reduce the impedance discontinuity. (The trade-off is it could increase radiation from the stub)
If you want to get really fancy, and your signals are not particularly wide-band, you could break out an EM simulation and probably find a way to add an inductive discontinuity (neck down the trace as it approaches the connector) to your trace to compensate for the capacitive discontinuity from the stub --- but I wouldn't advise doing this without being able to optimize it in simulation, and it's probably not justified if your application doesn't have especially strict VSWR requirements.


text:
Q: SharedSizeGroup to different Grid in different parent control So, I have 3 user controls :
1. SectionV.xaml
<UserControl x:Class="NumberedMusicalScoresWriter.V.SectionV"...>
...
    <Grid Background="{Binding BackgroundColor, Mode=OneWay}" Grid.IsSharedSizeScope="True">
        ...
        <V:BarV Grid.Column="0" Grid.Row="0" DataContext="{Binding GClefBarVM, Mode=OneWay}"/>
        <V:BarV Grid.Column="0" Grid.Row="2" DataContext="{Binding FClefBarVM, Mode=OneWay}"/>
    </Grid>
...

2. BarV.xaml
<UserControl x:Class="NumberedMusicalScoresWriter.V.BarV"...>
...
    <Grid Background="{Binding BackgroundColor, Mode=OneWay}">
        ...
        <ItemsControl Grid.Column="0" Grid.Row="0"
                      ItemsSource="{Binding NotationGroupVMs, Mode=OneWay}">
            ...
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <V:NotationGroupV/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
...

3. NotationGroupV.xaml
<UserControl x:Class="NumberedMusicalScoresWriter.V.NotationGroupV"...>
...
    <Grid Background="{Binding BackgroundColor, Mode=OneWay}">
        ...
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto" SharedSizeGroup="Mid"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        ...
    </Grid>
...

As you have figured, NotationGroupV is a collection of UserControl in BarV, and BarV is owned by SectionV as a two of. (SectionV is also used as a collection member of its parent control)
The issue is on the center row height of NotationGroupV, which has SharedSizeGroup="Mid". I want to share it to fellow NotationGroupV in the apps.
So, basically, I want to share SharedSizeGroup to other NotationGroupV in different parents.
Anyone know how to expose SharedSizeGroup this way?
(Please ask anything to clarify)
Thank you.
P.S. In this link, it's explained how to share them in a different grid, BUT in the same xaml.

A: While I can't confirm for sure that your requirement will work, I can confirm that as long as you set the Grid.IsSharedSizeScope Attached Property to True on a parent container control of both of the Grids that you have set up SharedSizeGroups for, then it should work. To find out for sure, just try it out... you could have probably tested it yourself quicker than the time it took you to write this question.
If there is no parent container control at the moment, just add one.... (put everything into it).
The important thing to note here is that you're only supposed to set Grid.IsSharedSizeScope to True on the one single parent container control and not on every Grid.


text:
Q: Degree $5$ embeddings of genus 1 curves, plucker embedding of a Grassmannian... Here is something Ravi Vakil says after 19.9F in his notes. He is talking about embeddings of a genus 1 curve $C$ by complete linear series associated to the divisors $O(nP)$.
"The beautiful structure doesn't stop with degree 4, but it gets more complicated. For example, the degree 5 embedding is not a complete intersection (of hypersurfaces),but is the complete intersection of G(2,5) under its Plucker with five hyperplanes (or perhaps better, a codimension 5 linear space)."
2 questions about this:

*

*The degree 5 embedding is a map of $C$ into $\mathbb{P}^4$. The plucker embedding of $G(2,5)$ lives in $\mathbb{P}^9$. So I am not sure what he means when he says the degree 5 embedding "is" the intersection of the Plucker embedding with the planes. Currently I would be willing to believe a statement along the lines of: if $X$ is the Plucker embedding of the Grassmannian $G(2,5)$, then the intersection of $X$ with 5 generic hyperplanes gives a smooth genus one curve. I guess there is something I am missing.

*Does anyone know a good reference for this? I am fascinated by this image. (I know about the papers by Tom Fischer that deal with the description using Pfaffians, but it doesn't seem to be obviously connected to the description with the plucker embedding of the Grassmannian. Besides, I am still confused about that description, as hopefully I communicated in point 1.)
Thanks!

A: Let $W,V$ be $5$ dimensional vector spaces. Let $f\colon \wedge^2W\to V$ be a linear map.
Consider the following diagram:
$$\require{AMScd}
\begin{CD}
E @>{i}>> \mathbb{P}(V)\\
@VVV @VVV \\
\mathrm{Gr}(2,W) @>{\mathrm{Plu}}>> \mathbb{P}(\wedge^2W)
\end{CD}$$
To show $E$ is an elliptic curve, we calculate its canonical bundle by adjunction formula:
$$K_E=K_{\mathrm{Gr}(2,W)}|_E+\det(N_{E/\mathrm{Gr}(2,W)}|_E).$$
Note that $$N_{E/\mathrm{Gr}(2,W)}|_E=i^*N_{\mathbb{P}(V)/\mathbb{P}(\wedge^2W)}=i^*\mathcal{O}(1)^{\oplus5}$$
Also note that $$K_{\mathrm{Gr}(2,W)}=\mathrm{Plu}^*(\mathcal{O}(-\dim W))=\mathrm{Plu}^*(\mathcal{O}(-5))$$
So $K_E=0$, $E$ is an elliptic curve.
(For the relation with Pfaffian: Pick basis $\{w_1,\dots, w_5\}$ of $W$, we can write $f=a_{ij}\cdot w_i\wedge w_j$, where $a_{ij}=-a_{ji}\in V.$ So we view $a_{ij}$ as functions on $\mathbb{P}(V)$.
The Pfaffian of all the $4\times 4$ minors in $(a_{ij})$ vanishes
 exactly when $\mathrm{rk}(a_{ij})=2$. In this case, vanishing locus of Pffafian coincides with fiber product with Grassmannian.)


text:
Q: Что происходит, когда метод возвращает значение? Допустим есть такой метод:
int val() {
  return 1 + 1;
}

Если его вызвать, не сохраняя в переменную таким образом:
val();

Что в этот момент происходит и почему компилятор не выдает ошибку?
Я думал, что при вызове метода, он просто заменяется значением, которое возвращает.
То есть, если написать такую строку кода:
System.out.println(val());

То val(); заменяется значением, которое этот метод возвращает и код начинает выглядеть так:
System.out.println(2);

Но это не так. Ведь если написать просто число в коде, не присваивая его переменной, компилятор выдаст ошибку error: not a statement
Так что, метод не просто заменяется значением, которое он возвращает, а происходит что-то другое.
Объясните, пожалуйста


text:
Q: No response to a HTTP Get request in WebAPI in .NET 4.5 while using SpeechSynthesis for converting text to speech I'm trying to setup a simple web service using WebAPI. Here is what I have for code:
public class SpeakController : ApiController
    {
        //
        // api/speak

        public HttpResponseMessage Get(String textToConvert, String outputFile, string gender, string age = "Adult")
        {
            VoiceGender voiceGender = (VoiceGender)Enum.Parse(typeof(VoiceGender), gender);
            VoiceAge voiceAge = (VoiceAge)Enum.Parse(typeof(VoiceAge), age);

            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
            {
                synthesizer.SelectVoiceByHints(voiceGender, voiceAge);
                synthesizer.SetOutputToWaveFile(outputFile, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                synthesizer.Speak(textToConvert);
            }

            return Request.CreateResponse(HttpStatusCode.OK, new Response { HttpStatusCode = (int)HttpStatusCode.OK, Message = "Payload Accepted." });
        }
    }

The code is fairly straight forward and it is by no means production ready. But in my tests I have noticed the following occurs for any request to the controller:

*

*the WAV file gets generated successfully

*during debug, I can see the control hit return and exit the method

*however, my browser just keeps spinning and I never get a response back from the server

I tried the same with Postman (a REST client for Chrome) and got the same result. Though I do want this to be a blocking call, in the interest of trying other things I modified synthesizer.Speak to synthesizer.SpeakAsync and encountered the same issue.
However when I test the snippets separately as shown below, the code works as expected.
Testing WebAPI call with speech section commented out:
public class SpeakController : ApiController
{
    //
    // api/speak

    public HttpResponseMessage Get(String textToConvert, String outputFile, string gender, string age = "Adult")
    {
        VoiceGender voiceGender = (VoiceGender)Enum.Parse(typeof(VoiceGender), gender);
        VoiceAge voiceAge = (VoiceAge)Enum.Parse(typeof(VoiceAge), age);

        //using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
        //{
        //  synthesizer.SelectVoiceByHints(voiceGender, voiceAge);
        //  synthesizer.SetOutputToWaveFile(outputFile, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
        //  synthesizer.Speak(textToConvert);
        //}

        return Request.CreateResponse(HttpStatusCode.OK, new Response { HttpStatusCode = (int)HttpStatusCode.OK, Message = "Payload Accepted." });
    }
}

Testing speech separately in a console application:
static string usageInfo = "Invalid or no input arguments!"
    + "\n\nUsage: initiatives \"text to speak\" c:\\path\\to\\generate.wav gender"
    + "\nGender:\n\tMale or \n\tFemale"
    + "\n";

static void Main(string[] args)
{
    if (args.Length != 3)
    {
        Console.WriteLine(usageInfo);
    }
    else
    {
        ConvertStringToSpeechWav(args[0], args[1], (VoiceGender)Enum.Parse(typeof(VoiceGender), args[2]));
    }

    Console.WriteLine("Press any key to continue...");
    Console.ReadLine();
}

static void ConvertStringToSpeechWav(String textToConvert, String pathToCreateWavFile, VoiceGender gender, VoiceAge age = VoiceAge.Adult)
{
    using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
    {
        synthesizer.SelectVoiceByHints(gender, age);
        synthesizer.SetOutputToWaveFile(pathToCreateWavFile, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
        synthesizer.Speak(textToConvert);
    }
}

WebAPI and SpeechSynthesis do not seem to play well together. Any help in figuring this out would be greatly appreciated.
Thanks!

A: I have no idea why this happens but running your SpeechSynthesizer in a separate thread seems to do the trick (incompatible threading model?). Here's how I've done it in the past.
Based on: Ultra Fast Text to Speech (WAV -> MP3) in ASP.NET MVC
public dynamic Post(dynamic req)
{
    try
    {
        string phrase = req["phrase"].Value;

        var stream = new MemoryStream();
        var t = new System.Threading.Thread(() =>
            {
                using (var synth = new SpeechSynthesizer())
                {
                    synth.SetOutputToWaveStream(stream);
                    synth.Speak(phrase);
                    synth.SetOutputToNull();
                }
            });

        t.Start();
        t.Join();

        stream.Position = 0;

        var resp = new HttpResponseMessage(HttpStatusCode.OK);
        resp.Content = new StreamContent(stream);

        resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        resp.Content.Headers.ContentDisposition.FileName = "phrase.wav";

        return resp;
    }
    catch
    {
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
}


text:
Q: Parsing Filenames and outputing sorted list in HTML using PHP Say I have a directory with the following files, named by date (month, day and year).
030313.pdf
030513.pdf
040113.pdf
052013.pdf
I know it is possible to break about the file names using explode() and I'm assuming I would need to save the data somehow to a multidimensional array like this:
$files = array
(
array("030313.pdf", 03,03,13),
array("030513.pdf", 03,05,13),
array("040113.pdf", 04,01,13),
array("052013.pdf", 05,20,13)
);

Is it possible to then take that information, group by month, sort by day and then echo that out as a bullet list of links?
Something like:
March 2013:

*

*03/03/2013 (linked to actual file)

*03/05/2013 (linked to actual file)

April 2013:

*

*04/01/2013 (linked to actual file)

May 2013:

*

*05/20/2013 (linked to actual file)

If this is possible, say there were 100-1000's of files, would loading this page cause any server performance issues?
Thanks
Brett

A: The solution is very simple:
$files = array
(
    array("030313.pdf", 03,03,13),
    array("030513.pdf", 03,05,13),
    array("040113.pdf", 04,01,13),
    array("052013.pdf", 05,20,13)
);

$sortedData = array();

foreach ($files as $file) {
    $dt = mktime(0, 0, 0,  $file[1], 1, 2000);
    $key = date('F', $dt) . ' ' . $file[3];
    if (array_key_exists($key, $sortedData)) {
        $sortedData[$key] []= $file;
    } else {
        $sortedData[$key] = array($file);
    }
}

function sortFunc($a, $b) {
    if ($a[2] > $b[2]) {
        return 1;
    } else if ($a[2] < $b[2]) {
        return -1;
    }
    return 0;
}

foreach ($sortedData as &$sd) {
    usort($sd, sortFunc);
}

foreach ($sortedData as $key => $data) {
    echo "
".$key."
\n";
    foreach ($data as $d) {
        echo $d[0]."\n";
    }
}

Just reformat the output.
Performance depends mostly on filesystem, used on server. Reformating the array of 1000 elemens usually is nothing.

A: Here you go, just updated it to order them (I missed this when i first read your post.)
<?php

$files = array
(
    array("030313.pdf", 03,03,13),
    array("030513.pdf", 03,05,13),
    array("040113.pdf", 04,01,13),
    array("052013.pdf", 05,20,13)
);

$newArray = array();

foreach($files AS $file => $val){
        $newArray[$date = date('Ym', strtotime($val[1] . '/' . $val[2] . '/' . $val[3]))][] = $val[0];
}

ksort($newArray);

$list = '
';
foreach($newArray AS $key => $val){

    $list .= '
' . date('F Y', strtotime('01-' . substr($key, 4, 2) . '-' . substr($key, 0, 4)));

    if(is_array($val)){
        $list .= '
';
        foreach($val AS $file => $filename){

            $list .= '
Download ' . $filename . '
';

        }
        $list .= '
';
    }
    $list .= '
';

}

$list .= '
';

echo $list;

?>


text:
Q: Updating user control content from a different control I am new to wpf format, and ran into a problem at the end of my project.
So let's say I have a top bar, with one textbox and a button.
When the user clicks the button, the user control below this bar should update with the search results from the textbox, and it does, except it does not refresh the UI, only the data storage. For simplicity I will post a demo code modelling the issue, with a single string property.
<!-- the main window -->
 <Window.DataContext>
    <local:CustomerViewModel/>
</Window.DataContext>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Grid.Row="0">
        <Label Content="content of the textbox: " Margin="10"/>
        <TextBox Width="300" Text="{Binding Customer.Name}"/>
        <Button Content="Update" Command="{Binding UpdateCommand}"/>
    </StackPanel>

    <DockPanel Grid.Row="1">
        <local:TestControl />
    </DockPanel>

user control:
 <!-- the user control named TestControl-->
<UserControl.DataContext>
    <local:CustomerViewModel />
</UserControl.DataContext>
<DockPanel LastChildFill="True">
        <Label DockPanel.Dock="Top" Content="Saved" />
        <Label DockPanel.Dock="Bottom" Content="{Binding Info, UpdateSourceTrigger=PropertyChanged}" />
    </DockPanel>

datamodel class:
 public class Customer : ObservableObject
{
    private string mName;

    public string Name
    {
        get => mName;
        set
        {
            if (value != mName)
            {
                mName = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

}

viewmodel class:
 public class CustomerViewModel : ObservableObject
{
    private Customer mCustomer;

    public Customer Customer
    {
        get => mCustomer;
        set
        {
            if (value != mCustomer)
            {
                mCustomer = value;
                OnPropertyChanged(nameof(Customer));
            }
        }
    }

    private string mInfo;

    public string Info
    {
        get => mInfo;
        set
        {
            if (value != mInfo)
            {
                mInfo = value;
                OnPropertyChanged(nameof(Info));
            }
        }
    }

    private ICommand mUpdateCommand;

    public ICommand UpdateCommand
    {
        get
        {
            if (mUpdateCommand == null)
            {
                mUpdateCommand = new RelayCommand(p => SaveChanges());
            }
            return mUpdateCommand;
        }

    }

    public void SaveChanges()
    {
        Info = Customer.Name + " was updated";
        MessageBox.Show(Info);
    }

    public CustomerViewModel()
    {
        mCustomer = new Customer();
        mCustomer.Name = "Test";
        Info = mCustomer.Name;
    }

}

The correct value is displayed in the messagebox, but it does not change in the user control. I am calling the property changed interface, and have tried to invoke the button press with dispatcher.invoke, same issue, am I missing something very obvious here?

A: Your usercontrol is creating its own personal instance of the viewmodel, and using that for its DataContext. That usercontrol instance then sets Info on itself, not on the CustomerViewModel that the parent window has for its own datacontext.
<UserControl.DataContext>
    <local:CustomerViewModel />
</UserControl.DataContext>

Remove those three lines from your usercontrol. Keep the corresponding lines in the window. The usercontrol will then inherit its datacontext from its parent, and they'll both be on the same page.
Those three lines aren't just declaring the type of viewmodel the view uses; they're creating an actual instance of the class and assigning it to DataContext.


text:
Q: Pyinstaller error while building I am working on Ubuntu 20.04 LTS. I am trying to build exe files from my python files. But I am facing an issue while installing requirements.txt, I am using Python 3.8.10 version.
These are the error:
Building wheels for collected packages: PyInstaller
  Building wheel for PyInstaller (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for PyInstaller (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [18 lines of output]
      running bdist_wheel
      running build
      running build_bootloader
      Setting top to                           : /tmp/pip-install-iy49ulu4/pyinstaller_c5cf1762e2fd49588e5f6007c79b4445/bootloader
      Setting out to                           : /tmp/pip-install-iy49ulu4/pyinstaller_c5cf1762e2fd49588e5f6007c79b4445/bootloader/build
      Python Version                           : 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0]
      Checking for 'gcc' (C compiler)          : /usr/bin/gcc
      Checking size of pointer                 : 8
      Platform                                 : Linux-64bit detected based on compiler
      Checking for program '/usr/bin/strip'    : /usr/bin/strip
      Checking for program 'strip'             : /usr/bin/strip
      Checking for library dl                  : yes
      Checking for library m                   : yes
      Checking for library z                   : not found
      The configuration failed
      (complete log in /tmp/pip-install-iy49ulu4/pyinstaller_c5cf1762e2fd49588e5f6007c79b4445/bootloader/build/config.log)
      No precompiled bootloader found. Trying to compile it for you ...
      ERROR: Failed compiling the bootloader. Please compile manually and rerun setup.py
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for PyInstaller
Failed to build PyInstaller
ERROR: Could not build wheels for PyInstaller, which is required to install pyproject.toml-based projects

I have attached Screen shot for further reference.

Please help me out this

A: You should run the following as a non-root user.
pip3 install --upgrade pip

Log out and log back in and then run the following commands (again, as a non-root user):
pip install --upgrade wheel
pip install --upgrade PyInstaller


text:
Q: web service data transfer question Applicatins are built by using C#. one of the tasks is transfer a image file from server to client via web service (SOAP). in the client side, the image file will be saved to disk, no web page.
one of my co-workers told us, the data transferred between server and client must be under 8k, so we need to cut our image file, which is 2M, into smaller pieces.
is that true?
Right now the data can be transferred between client and server. The size is right but the content is not because the display is not the same when we open the received file. My co-workers tried different encoding but none works.
which encoding we should use? UTF8?

A: You could to open that image file as a byte[] and to transfer it. This way you shouldn't have any encoding problem. This article can provide more information: Large Data and Streaming

A: You can change default limit for WCF request/response message size by setting MaxReceivedMessageSize property in configuration.
And it's reasonable to transfer image as a binary object, not string.
You will probably also have to adjust other limit settings, like max array size, max string size, etc.


text:
Q: C++ template specialization, calling methods on types that could be pointers or references unambiguously Summary
Is there a way to call a class method on a templated type that could be a pointer or a reference without knowing which and not get compiler/linker errors?

Details
I have a templated QuadTree implementation that can take any of the following non-trivial user-defined types:
//Abstract Base Class
a2de::Shape

//Derived Classes
a2de::Point
a2de::Line
a2de::Rectangle
a2de::Circle
a2de::Ellipse
a2de::Triangle
a2de::Arc
a2de::Spline
a2de::Sector
a2de::Polygon

But they could be a pointer OR a reference as they are all derived from a2de::Shape. So the specializations are declared as:
template class QuadTree<a2de::Shape&>;
//...similar for all derived types as references.

template class QuadTree<a2de::Shape*>;
//...similar for all derived types as pointers

The problem I am having is the ability to call a class method when the indirection (or lack thereof) is unknown and due to the templates, both sets of code are generated:
template<typename T>
bool QuadTree<T>::Add(T& elem) {

    //When elem of type T is expecting a pointer here
    //-> notation fails to compile where T is a reference i.e.:
    //template class QuadTree<a2de::Shape&>
    //with "pointer to reference is illegal"

    if(elem->Intersects(_bounds) == false) return false;

    //...
}

If I change the above line to use the . (dot) notation:
template<typename T>
bool QuadTree<T>::Add(T& elem) {

    //When elem of type T is expecting a reference here
    //. (dot) notation fails to compile where T is a pointer i.e.:
    //template class QuadTree<a2de::Shape*>
    //with "pointer to reference is illegal"

    if(elem.Intersects(_bounds) == false) return false;

    //...

}

If I remove the reference-based types in favor of the pointer-based types (including in the declaration and usage of the Quadtree class) I get the error left of .<function-name> must have class/struct/union.
If I remove the pointer-based type in favor of the reference-based types (including in the declaration and usage of the Quadtree class) I get the aforementioned reference to pointer is illegal again.
compiler: VS2010-SP1

A: Small overloaded functions can be used to turn reference into pointer:
template<typename T>
T * ptr(T & obj) { return &obj; } //turn reference into pointer!

template<typename T>
T * ptr(T * obj) { return obj; } //obj is already pointer, return it!

Now instead of doing this:
 if(elem->Intersects(_bounds) == false) return false;
 if(elem.Intersects(_bounds) == false) return false;

Do this:
 if( ptr(elem)->Intersects(_bounds) == false) return false;

If elem is a reference, the first overload ptr will be selected, else the second will be selected. Both returns pointer, which means irrespective of what elem is in your code, the expression ptr(elem) will always be a pointer which you can use to invoke the member functions, as shown above.
Since ptr(elem) is pointer, which means checking it for nullptr be good idea:
 if( ptr(elem) && (ptr(elem)->Intersects(_bounds) == false)) return false;


text:
Q: Efficient Sampling I'm a beginner and need some guidance on what probably is a very basic problem, yet unsolvable to me :
I'm working on a Kaggle dataset with over 10M rows and would like to sample it to go into proper EDA. I've seen a couple people putting simply an nrows argument to the .read_csv method, but wouldn't it be inefficient sampling to cut it at an arbitrary point, and therefore bias any results ?
The method .sample uses a simple randomizer and I feel like it wouldn't capture the different proportions of categories. What would be a better sampling option ?

A: If this is supervised learning (i.e you have data label ) you can use
train_X, test_X, train_Y, test_Y = train_test_split(data, label, test_size = 0.2, random_state = 138,shuffle=True,stratify=label)

stratify will allow you to keep same proportion of each class in the final data set


text:
Q: Variable Scope of function inside function jquery I have this jquery function extend, but the exec command for the redColorBtn does not seem to work. If I move the var iframeDocument definition to inside the redColorBtn function, then it works. But, I can't wrap my head around why this would happen. I thought it would be because of variable scope, but then the iframe definition should also not be working outside the redColorBtn click function. Does anyone know?
$.extend({
 handleToolbarEvents: function(iframeDocumentId) {
     var iframe          = document.getElementById(iframeDocumentId);
     var iframeDocument  = iframe.contentWindow.document;
     var redColorBtn     = document.getElementById('rte-redColorBtn-' + iframeDocumentId);

     $(redColorBtn).click(function() {
        var command = $(this).val();//foreColor
        iframeDocument.execCommand(command, false, "red");
     });

     $('.rte-button').click(function() {
        var command        = $(this).val();
        var iframeID       = $(this).closest('iframe[class="rte-iframe"]');
        var iframeDocument = iframe.contentWindow.document;
        iframeDocument.execCommand(command, null, null);
    });
 }
});

A: i have once's the same problem that i add the click event but it doesn't work. It can be about if you are adding that redColorBtn dynamically it might be your problem. you can try redColorButton.bind('click', function(){}); I don't know why it but it worked for me.
Hope it works.


text:
Q: Searching for numerical algorithm realization Im searching for numerical algorithm realization for nonlinear equations system solver on PHP, C, C++, Java (with readable code :). Where I can find them?
Thx.

A: Here is a link that outlines lots of different options, and the code that is linked there is generally well documented and readable. For nonlinear solvers, my opinion is that Netlib has better stuff (such as MINPACK) than LAPACK, but there are bound to be many other good implementations as well.
Most of this stuff will be in C or Fortran, but there are some examples in Matlab which should be closer to usual linear algebra form. You should also consider iterative methods like gradient descent, Newton's Method and semi-Newton methods like the Davidon-Fletcher-Powell method.
Added
Since you expanded on the question in the comments, it seems clear that Newton's method will work for you. Your problem is small (only 3 variables) and has known analytical form so you can calculate the Jacobian matrix $J$ by hand. By reformulating the update equation of Newton's method, you do not need to compute the inverse of $J$.. you'll only need a linear solver. (See here for more details).
In your case, the vector of solutions will be $x_{k}$, and you initialize $x_{0} = (p_{0}, s_{1,0}, s_{2,0})^{T}$ as the vector of initial guesses. Then just run the iterative scheme for $k=1,2,...$ :
$$ x_{k}\textrm{ is solution to }J(x_{k-1})[x_{k} - x_{k-1}] = -F(x_{k-1})$$
where, with it understood that $x = (p,s_{1},s_{2})^{T}$ as above, so you'll rewrite the stuff below using $x_{i}$ to represent the $i$th thing you want to solve for:
$$ F\biggl( (p,s_{1},s_{2})^{T} \biggr) = \begin{pmatrix}
\frac{s_2 - K_2}{ps_2^{\gamma_1} + (1 - p)s_2^{\gamma_2}} - \frac{K_1 - s_1}{ps_1^{\gamma_1} + (1 - p)s_1^{\gamma_2}} \
\frac{s_2}{s_2 - K_2} - \frac{p\gamma_1s_2^{\gamma_1} + (1 - p)\gamma_2 s_2^{\gamma_2}}{ps_2^{\gamma_1} + (1 - p)s_2^{\gamma_2}} \
\frac{s_1}{s_1 - K_1} - \frac{p\gamma_1s_1^{\gamma_1} + (1 - p)\gamma_2 s_1^{\gamma_2}}{ps_1^{\gamma_1} + (1 - p)s_1^{\gamma_2}}
\end{pmatrix}  $$
You continue this until you reach some terminal criteria, such as hitting a maximum number of iterations or observing that the norm $||x_{k}-x_{k-1}||$ has become sufficiently small for your purposes, or that the value of the objective function at the current solution is small, $||F(x_{k})|| < tol$ for some tolerance $tol$.
These are all things that you can do with existing library functions in almost any scientific computing package. Almost any standard textbook on numerical analysis will offer a better explanation to this method, and how to check whether your particular problems falls into any of its pitfalls. Textbooks will also include references to computer code for solving such a problem. But your first step should be to calculate the Jacobian by hand in any case since it is available to you.
Two textbooks that I am familiar with and which should give good guidance for this problem are:

*

*Numerical Analysis and Scientific Computation by Jeff Leader (link)

*Numerical Methods in Engineering with Python by Jaan Kiusalaas (link)
Both of these are highly readable and focus on giving you an understanding of the methods rather than just formulas for using them (which you can find in the LAPACK and Netlib implementations, in Numerical Recipes, or in dozens of other places.)
The first book focuses on examples in Matlab if you prefer that language. Most of the examples can also be directly used in Octave as well, which is a free, open-source Matlab clone. The second book focuses on showing examples in Python, and if you choose to go the Python route, I recommend working with the NumPy library because pure Python will be very inefficient.


text:
Q: $T$-nilpotent ideals Recall that a subset $I$ of a ring $R$ is left (resp.,
right) $T$-nilpotent in case for every sequence $$a_1,a_2,\cdots $$
in $I$ there is an $n$ such that $a_1\cdots a_n=0$ (resp.,
$a_n\cdots a_1=0$). Every nilpotent ideal is left and right
$T$-nilpotent.
Is there any characterization for rings $R$ in which the Jacobson radical is $T$-nilpotent?


text:
Q: Stuck TCP Connection in Linux Strange problem.  I have server "ALPHA" in Dallas and server "BETA" in Hong Kong, about 195ms ping times apart from each other.  ALPHA is connected at 1gbps full, and BETA at 10mbps full.  Occasionally when they communicate to each other over TCP, the connection hangs.  Eventually ALPHA gives up and closes the connection, but BETA still sees the connection as established and waits for a long time until it eventually times out.
Example.
On BETA, wget -O /dev/null ALPHA:50001/1mb.test
--2013-05-19 02:45:54--  http://ALPHA:50001/1mb.test Resolving dfw... ip.address.redacted Connecting to ALPHA|ip.address.redacted|:50001... connected. HTTP request sent, awaiting response... 200 OK Length: 1000000 (977K)
[application/octet-stream] Saving to: `/dev/null'

and it freezes at 0 bytes received.  Note that it did get a 200 OK from the server, so they did seem to handshake successfully.  To eliminate wget as part of the problem, I did a telnet:
telnet ALPHA 50001
Trying ip.address.redacted...
Connected to ALPHA.
Escape character is '^]'.
GET /1mb.test HTTP/1.0

HTTP/1.1 200 OK
Server: nginx
Date: Sun, 19 May 2013 22:43:48 GMT
Content-Type: application/octet-stream
Content-Length: 1000000
Last-Modified: Sat, 21 Jan 2012 21:47:29 GMT
Connection: close
ETag: "4f1b3271-f4240"
Accept-Ranges: bytes

It also freezes at this point.
Both servers do have iptables rules of -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
Here is a tcpdump that was running on ALPHA during the above wget freeze.
http://pastebin.com/axX7ap6T
This problem happens only occasionally.  Sometimes it works just fine.  Actually, if I run about 3-5 wget's, usually everything starts working on about the fourth or fifth try.
BETA can communicate with GAMMA, DELTA, and my other servers without problem.  Only seems to happen when talking to ALPHA.  ICMP pings show no packet losses, but even if there was packet loss, it would slow it down, not disconnect.  Both machines have the same CentOS 6.4 64-bit OS, kernel 2.6.32-358.6.2.el6.x86_64.  Nothing useful logged in /var/log files.  ALPHA is listening on 50001 using nginx-1.4.1-1.el6.ngx.x86_64.  The nginx access log file shows a 200 (request OK) 43440 bytes delivered during the frozen connection.
The problem does not seem to be nginx related, since I have had an ssh connection also freeze in the middle of communicating on the same day.  Other servers connect to that nginx and never had any problems.
In summary, this appears to be what is happening in this particular communication:
BETA -> ALPHA "SYN!"
ALPHA -> BETA "SYN Acknowledgement"
BETA -> ALPHA "ACK"
ALPHA -> BETA "Established"
BETA -> ALPHA "GET /file HTTP/1.0"
ALPHA -> BETA "200 OK, here's a bunch of data"
BETA freezes, gets no data.

Anyone seen a situation like this?

A: Maybe an MTU/MSS problem? The small initial packets get through, the big ones (data transfer) get killed somewhere?
A work-around is to reduce the MTU (on both sides) a bit, from 1500 to 1450 e.g. Or to use the Netfilter target TCPMSS just for the affected connections (or differently for separate connections).
But the real solution is to get path MTU discovery working again. So check whether ICMP packets (fragmentation needed: Type 3, Code 4) are blocked. Use tcpdump -i $ifname -n icmp to see whether such packets arrive.

A: There is indeed defragmentation occurring.  That's what IPTABLES does to inspect packets.  It must reassemble them in order to validate content.
In my case, I would see periodic ping dropouts and web browser stalls while I was web browsing on a CentOS 7 system, or my PuttY sessions from windows would mysteriously hang -- permanently.
I used a variant of method Mick so kindly provided to determine the MTU size.  The problem with that method is that if you've set the MTU size small, you get a false reading on the fragmentation.  So set the size large (jumbo frame/9000) and then begin the ping probes.
After setting MTU to 1472 (what I determined was the correct value) the ping problem when browsing went away.  Hopefully when I next ssh from windows, that will work too.

A: My first guess is that it's a TCP Window scaling issue:
https://en.wikipedia.org/wiki/TCP_window_scale_option#Possible_side_effects
Disable it on both ends and see if it the problem goes away. Another option (as Hauke suggested) is there's defragmention occurring.
You can use ping to check for packet de-fragmentation, a simple HOWTO is here:
http://muzso.hu/2009/05/17/how-to-determine-the-proper-mtu-size-with-icmp-pings
Edit: missed a word.


text:
Q: How can I render a FieldList of variable length in WTForms? I'm trying to make a form to populate a calendar. The calendar can be five or seven days long, and I'd like to pass the number of days as an argument to the form. My form is defined like so:
class LoadForecastForm(Form):

    def __init__(self, n_days, *args, **kwargs):
        self.n_days = n_days
        super(LoadForecastForm, self).__init__(*args, **kwargs)
        self.day_values = FieldList(SelectField('Day Values', coerce=str, choices=[('low', 'Low'), ('medium', 'Medium'), ('high', 'High'), ('holiday', 'Holiday')]), min_entries=n_days, max_entries=n_days)
        self.send = SubmitField('Send Calendar')

It's rendered like so:
<form role="form" action="" method="POST">
{{ form.hidden_tag() }}

  {% for field in form.day_values %}

      {% if label %}
        {{ field.label }}
      {% endif %}
      {{ field(**kwargs) }}
      {% for error in field.errors %}
        [{{error}}]

      {% endfor %}

  {% endfor %}

{{ form.send }}

The form page is failing to render; the traceback ends with:
File "project/populate_schedule.tpl.html", line 25, in block "page_content"
{% for field in day_values %}
TypeError: 'UnboundField' object is not iterable

n_days used to be hardcoded, and the fields were defined as class variables with no __init__() function, and there were no errors. How do I correctly define the field programmatically? I am using Python 2.7.

A: You need to leave the field definitions in the class body, otherwise they won't be picked up with the class is constructed.  When the form instance is being initialised you can apply the max/min entries values to the fieldlist.
class F(Form):

    day_values = FieldList(SelectField('Day Values',
                           coerce=str,
                           choices=[('low', 'Low'), ('medium', 'Medium'),
                                    ('high', 'High'), ('holiday', 'Holiday')]))
    send = SubmitField('Send Calendar')

    def __init__(self, *args, **kwargs):
        ndays = kwargs.pop('n_days')
        super(F, self).__init__(*args, **kwargs)
        self.day_values.min_entries = n_days
        self.day_values.max_entries = n_days

Test:
n_days = 4
f = F(n_days=n_days)
for x in range(n_days):
    f.day_values.append_entry()
for field in f.day_values:
    print field()
    print

Output:
<select id="day_values-0" name="day_values-0"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="holiday">Holiday</option></select>

<select id="day_values-1" name="day_values-1"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="holiday">Holiday</option></select>

<select id="day_values-2" name="day_values-2"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="holiday">Holiday</option></select>

<select id="day_values-3" name="day_values-3"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="holiday">Holiday</option></select>


text:
Q: When to use Mage::getSingleton() in my custom module/Ext theoretically i know about Mage::getSingleton() & differences b/w
Mage::getSingleton() and Mage::getModel()
but my question is that in my custom
module when to use Mage::getSingleton(){Normally i used Mage::getModel() on lots of places}.
Please let me understand with example(if possible, please share a small custom modules having Mage::getSingleton()).

A: As per My Knowledge On Magento.
Mage::getSingleton() creates an single object for one time.
Mage::getModel() creates an object every time.

A: You know the difference and others already told you,
Its hard to give example, but I will try to give some scenario.
For example you are doing some work in some page and you need to load product id 1 in block class x .
now in same page you want to use same product object again in some other block class called Y, so at that time its preferred to use singleton over getModel
because product object already loaded in class x if you reload product object then it will impact your page performance.

But if you want to load some other product id in block class y then
  use getModel bcuz with the use of singleton you will get old
  object

Hope you bit clear now

A: public static function getModel($modelClass = '', $arguments = array())
{
    return self::getConfig()->getModelInstance($modelClass, $arguments);
}

public static function getSingleton($modelClass='', array $arguments=array())
{
    $registryKey = '_singleton/'.$modelClass;
    if (!self::registry($registryKey)) {
        self::register($registryKey, self::getModel($modelClass, $arguments));
    }
    return self::registry($registryKey);
}

GetModel

Mage::getModel() will always return a new Object for the given model:

GetSingleton

Mage::getSingleton() will check whether the Object of the given model
  already exists and return that if it does. If it doesn't exist, it
  will create a new object of the given model and put in registry that
  it already exists. Next call will not return a new object but the
  existing one:

A: Customer session model will be a great example of using getSingleton.
When you want to persist your data on that model object then you should use getSingleton.
It used to create model object at once and persist your data in memory .So that you can call using getSingleton same model into another class and then that object will have that data which was previously loaded.
For eg if you call (using getSingleton) a model inside controller and you are calling same model inside a block that is going to use on load of this controller then block will get same object that was initialize in controller.
But in case of getModel both will have separate object for same model.

A: Mage::getSingleton() = Return the same instance.
Mage::getModel() = Return a new instance.

Mage::getSingleton() :
When you use Mage::getSingleton(), Magento search in the memory if the object needed is available :

*

*If the object is available, It get it from that object every time and it will not create the object in every call.

*If the object is not available, so it create it one time and it return it from that new object in every call.

Mage::getModel() :
Unlike the Singleton, getModel create a new object in every call.


text:
Q: Cannot get image content from OneNoteAPI I am trying to display page content of my OneNote's page using Angular Web. Although I can get the other contents, I cannot get images from OneNote page. Here is the code that I am using for getting page content and the error.
public async getOneNoteContent(pageUrl: any) {
let url = pageUrl+'/?preAuthenticated=true';
let token =  await this.authService.getAccessToken();
let header = new HttpHeaders().set('Authorization', 'Bearer '+token);
return(this.http.get(url, {headers:header, responseType: 'text'}));}

How can I solve this. Please help me.


text:
Q: Sort through a Pandas dataframe and save unique entries I'm trying to figure out how to sort through rows in a spreadsheet read with pandas and save values to variables.
Here is my code so far:

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_excel('data_file.xlsx', sheetname='Sheet 1')

for line in df:
    if line.startswith(line):

The data is formatted the following way:
Column 1 has runner numbers, column 2 has 100 meter sprint times, Column 3 has 400 meter sprint times.
Here's an example of the data:

Runner  100m   400m
  1     43.7   93.5
  1     37.5   87.6
  1     39.2   82.5
  2     28.9   67.9
  2     26.2   69.9
  2     33.3   60.25
  2     34.2   60.65
  3     19.9   45.5
  3     19.8   44.0
  4     18.7   50.0
  4     19.0   52.4

How could I store the contents of all the rows starting with 1 in a unique variable, all the rows starting with 2 in another variable, 3, etc.? I know this has to involve a loop of some sort but I'm not sure about how to approach this problem.

A: Generally, you want to avoid trying to programmatically set unique variables.  This problem is probably best approached using a dictionary data structure to store the contents of the rows, with keys for each "Runner" ID (but runners would need to be unique).
You can quickly iterate through the data for each runner using pandas groupby.  In the loop, the i represents the "Runner" ID and tdf is the dataframe of just data for that runner.  This would store a numpy array of the data for each runner in dict d.
d = {}
for i, tdf in df.groupby('Runner'):
    d[i] = tdf[['100m', '400m']].values

EDIT:
If you really want to iterate line by line you can use df.iterrows() method.
d = {}
for i, x in df.iterrows():
    runner = x['Runner']
    data = x[['100m', '400m']].tolist()
    d[runner] = d.get(runner, []).append(data)


text:
Q: Suggestions with DevExpress GridView Custom Binding I am implementing custom paging and binding with a DevExpress MVCxGridView.
A link to the demo is here;
https://demos.devexpress.com/MVCxGridViewDemos/DataBinding/AdvancedCustomBinding
Now the data itself is coming from an api, so for example the GET end point for the data for example could be;
    public IHttpActionResult GetUsers(
        string username = null,
        string surname = null,
        string postcode = null,
        bool includearchived = false,
        int? pagesize = null,
        int? pageoffset = null)
    {
       var predicate = PredicateBuilder.True<Users>();

        if(username != null)
             predicate = predicate.And(x => x.Username.Contains(username));

        if(surname != null)
             predicate = predicate.And(x => x.Surname.Contains(surname));

        if(postcode != null)
             predicate = predicate.And(x => x.Postcode.Contains(postcode));

        if (!includearchived)
            predicate = predicate.And(x => x.Archived == false);

        var results = _Service.GetUsers(predicate, pageoffset, pagesize);

        //filter out columns which are not needed
        var filtered = from x in results
                       select new
                       {
                           userid = x.ID,
                           date = x.Date,
                           username = x.Username
                           firstname = x.Firstname,
                           surname = x.Surname,
                           postcode = x.Postcode,
                           typeid = x.Type.ID,
                           usertype = x.Type.ID == 0 ? "Demo1" : "Demo2",
                           archived = x.Archived
                       };

        return Ok(filtered);
    }

where pagesize and offset are passed across from the grid. So I can get a particular page of the data. The above is a crude example, but basically the idea is that the predicate is built up using the passed parameters, the return filter is done to whitle the fields returned from the EF down to only the required fields (and also set fields to lowercase).
(There is then an additional "/count" which takes the same params minus the pagsize and offset and returns the number of rows in the original query, so the Grid know the number of possible rows returned. An example method of this is)
    [Route("count")]
    public IHttpActionResult GetUsersCount(
        string username = null,
        string surname = null,
        string postcode = null,
        bool includearchived = false,
        int? pagesize = null,
        int? pageoffset = null)
    {
        var predicate = PredicateBuilder.True<Users>();

        if(username != null)
             predicate = predicate.And(x => x.Username.Contains(username));

        if(surname != null)
             predicate = predicate.And(x => x.Surname.Contains(surname));

        if(postcode != null)
             predicate = predicate.And(x => x.Postcode.Contains(postcode));

        if (!includearchived)
            predicate = predicate.And(x => x.Archived == false);

        var results = _Service.GetUsers(predicate, pageoffset, pagesize);

        return Ok(results.Count);
    }

I now need to add in the column filters to the grid which i posing the issue that the grid shows more columns than there are filters on the end point. (Which can be seend in the demo link above with the searchable header text fields).
My issue is how to best handle these filter for evey possible column. The JSON returned from the WebApi the example may (more oftern than not will) contain additional fields that are not present in the filter parameters of the GET endpoint (so in the example above it ma contain fields like country, postcode etc).
So when the user effectively filters using the columns the WebApi GET cannot handle the search parameters and return accordingly return?
(As this is a generic solution which is db driven, and so realitically the api endpoints cannot be edited to handle all returned column filters, unless we can pass across some kind of text array that it can generically pase api side?)
Does anyone have any ideas on possible solutions or workarounds to this? I am sure this is something that may have been seen before at somepoint by someone.


text:
Q: Self-Hosted Wcf Service with Certificate client authentication I have a self-hosted wcf service which uses wsHttpBinding with Transport security. I want the service to authenticate a client using a certificate.
When the client communicates with the service using clientCredentialsType set to 'None' everything works fine.
The certificate was created with OpenSSL (self-signed) and registered with netsh on a specific port. The name of the certificate is DomainName (machine name in my case).
Update
I have created certificates for both client and server and placed them in each others Trusted Root stores (server certificate in client's store and vice-versa).
I've gone over a lot of articles and other questions at SOF but even the ones that look relevant couldn't help me resolve the issue.
Current Configuration
Service
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" httpsHelpPageEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="httpsBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="01:00:00">
          <security mode="Transport" >
            <transport clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="serviceBehavior" name="Service">
        <endpoint binding="wsHttpBinding" bindingConfiguration="httpsBinding" contract="SomeNamespace.IService"/>
        <host>
          <baseAddresses>
            <add baseAddress="https://domain:port/Something/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

Client
<system.serviceModel>
    <client>
      <endpoint address="https://domain:port/Something/"
                behaviorConfiguration="endpointCredentialBehavior"
                binding="wsHttpBinding"
                bindingConfiguration="Binding"
                contract="SomeNamespace.IService"/>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="endpointCredentialBehavior">
          <clientCredentials>
            <clientCertificate findValue="DomainName"
                               storeLocation="LocalMachine"
                               storeName="My"
                               x509FindType="FindBySubjectName" />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding">
          <security mode="Transport">
            <transport clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>

I get the following exception:

System.ServiceModel.Security.MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
     at System.Net.HttpWebRequest.GetResponse()
     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

A: There is one more thing we need to do. We should make their certificate trusted by each other. the server's certificate must be trusted by the client and the client's certificate must be trusted by the server.
Specifically, the server certificate is installed in the client Trusted Root Certification Authorities, the client certificate is installed in the server Trusted Root Certificate Authorities. It is best to use a local machine certificate store. We could check the certificate by using Certlm.msc command.

Please refer to the official document with regards to this issue.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/transport-security-with-certificate-authentication
For some special certificates created by other special tools, such as PowerShell, we had better make the target framework of the project (server and client) above 4.6.2.
https://github.com/dotnet/docs/issues/12000
Feel free to let me know if there is anything I can help with.

A: your configuration file looks okay.
i have same issue with my 3rd party client certificate(public key) no matter where i add that certificate is still doesn't works.
However i've managed to make it work with my self-signed client certificate. i just had to add client CA certificate to Trusted Root Certification authorities on server.
i found those two topics helpful in determining some of issues:
Mutual authentication with a IIS hosted WCF
WCF – 2 Way SSL Security using Certificates
Hope it will be helpfull for you. i'll post updates if i'll manage to solve this problem.


text:
Q: Warping an image based on lines given with different orientations I would like to warp an image based on lines given with different orientations:

*

*for each line on the input image, I can get the coordinates of the pixels on the line

*then I would map these pixels to the warped image so that each line is now a column.

I would use interp2 since I already have X, Y and Z, and I would make Xi and Yi with the coordinates obtained for each line. However, how would you:

*

*avoid making a for loop which index goes all over the number of lines?

*make sure each column in the output warped image is the same size?

*sample the input image with radial lines?

*the hardest question in my opinion, how would you keep the neighbourhood structure even if I use different orientations : for instance, the horiontal lines (rows) of the left part of the input image, and the radial lines for the right part?

The input image here is a tire, there is this nice pattern of circles. I could make radial lines from the center of the tire and I would like to get a new image whose columns are the pixels from the radial lines.
Here is the code I have so far (no interp2 yet as I have not solved the problems explained above).
close all

%% Image
Z = imread('tire.tif');
% The corresponding mesh
sz = size(Z);
[X,Y] = meshgrid(1:sz(2), 1:sz(1));

%% Line
lineEquation = @(c, v) (v(1)*(X-c(2))+v(2)*(Y-c(1)))/norm(v);
getLine = @(c, v) abs(lineEquation(c, v))<1/2;
% Example
c = [93, 109];
v = [2, 1];
line = getLine(c, v);

%% Circle
circleEquation = @(c, r) ((X-c(2)).^2+(Y-c(1)).^2-r^2)/r^2;
getCircle = @(c, r) abs(circleEquation(c, r))<1/r;
% Example
r = 24;
circle = getCircle(c, r);

%% Plot a sequence of line
figure;
for delta = -1:0.1:1
        v = [0.1, delta];
        line_delta = getLine(c, v);
        Z_line = Z;
        Z_line(line_delta) = 255;
        imagesc(Z_line);
        colormap('gray');
        pause(0.05);
end

%% Plot examples
figure;

subplot(221);
imagesc(Z);
title('Image');

subplot(222);
Z_line = Z;
Z_line(line) = 255;
imagesc(Z_line);
title('Line');

subplot(223);
Z_circle = Z;
Z_circle(circle) = 255;
imagesc(Z_circle);
title('Circle');

subplot(224);
% TODO
title('Warped image');

colormap('gray');

Here are different outputs:

Here is the warped image:

Here is the code from the answer:
[ANG, RAD] = meshgrid(0:0.01:2*pi, 0:0.5:166);
XI = c(2) + cos(ANG).*RAD;
YI = c(1) + sin(ANG).*RAD;
WARPED = interp2(X, Y, double(Z), XI, YI);

WARPED(isnan(WARPED))= max(WARPED(:));
imagesc(WARPED);
title('Warped image');
colormap('gray');

A: Your main problem (I think) is constructing matrices XI and YI needed for interp2. You construct these by realising that in your new image the horizontal axis represents the angle of the line, and the vertical axis represents the distance from the centre of the circle so to construct those:
%% angle from 360 to 0, radius from 0 to 100
%% resulting image will be 361 x 101 pixels
[ANG, RAD] = meshgrid(360:-1:0,0:100);
%% I take the centre of the circle at (93, 109) Is this correct?
%% From there you can create XI and YI
%% from the angle and radius you have at each point
XI = ones(size(ANG))*93 + cos(ANG/(2*PI)).*RAD;
YI = ones(size(ANG))*109 + sin(ANG/(2*PI)).*RAD;

WARPED = interp2(X,Y,Z, XI, YI)

The output will be heavily distorted (of course) because the circle at each radius is stretched to be the same length. Along the lines distortion will be minimal. If all goes well and my math-fu hasn't left me this should give you a rolled out image of the tire, cut on the line from the centre to the right.

A: The best way:
Use polynomial transformation of second order to transform all the circles to lines and then just cut out the lines you need.
Use 2 Matlab commands cp2tform() with parameter 'polynomial' and imtransform()
Set inside the transformation T the values 1 for x^2 and y^2 to create a circle and translation to define the center pixel of the tire.
Sorry that I don't supply code, since I answer from iPhone.
P.s. Check Matlab help about polynomial and conformal transformation. They do exactly what you need.


text:
Q: What is the Win32 API function to use to delete a folder? What are the Win32 APIs to use to programically delete files and folders?
Edit
DeleteFile and RemoveDirectory are what I was looking for.
However, for this project I ended up using SHFileOperation.
I found the sample code at CodeGuru helpful.

A: I believe DeleteFile does not send the file to the Recycle Bin. Also, RemoveDirectory removes only empty dirs. SHFileOperation would give you the most control over what and how to delete and would show the standard Windows UI dialog boxes (e.g. "Preparing to delete etc.) if needed.

A: There are two ways to approach this.  One is through the File Services (using commands such as DeleteFile and RemoveDirectory) and the other is through the Windows Shell (using SHFileOperation).  The latter is recommended if you want to delete non-empty directories or if you want explorer style feedback (progress dialogs with flying files, for example).  The quickest way of doing this is to create a SHFILEOPSTRUCT, initialise it and call SHFileOperation, thus:
void silently_remove_directory(LPCTSTR dir) // Fully qualified name of the directory being deleted, without trailing backslash
{
    SHFILEOPSTRUCT file_op = {
        NULL,
        FO_DELETE,
        dir,
        "",
        FOF_NOCONFIRMATION |
        FOF_NOERRORUI |
        FOF_SILENT,
        false,
        0,
        "" };
    SHFileOperation(&file_op);
}

This silently deletes the entire directory.  You can add feedback and prompts by varying the SHFILEOPSTRUCT initialisation - do read up on it.

A:     /* function used to send files and folder to recycle bin in win32 */
            int fn_Send_Item_To_RecycleBin(TCHAR newpath[])
            {
            _tcscat_s(newpath, MAX_PATH,_T("|"));
            TCHAR* Lastptr = _tcsrchr(newpath, _T('|'));
            *Lastptr = _T('\0');                                         // Replace last pointer with Null for double null termination
            SHFILEOPSTRUCT shFileStruct;
            ZeroMemory(&shFileStruct,sizeof(shFileStruct));
            shFileStruct.hwnd=NULL;
            shFileStruct.wFunc= FO_DELETE;
            shFileStruct.pFrom= newpath;
            shFileStruct.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
            return SHFileOperation(&shFileStruct);
            }

A: I think you want DeleteFile and RemoveDirectory

A: See uvgroovy's comment above. You need 2 nulls at the end of the 'dir' field.
int silently_remove_directory(LPCTSTR dir) // Fully qualified name of the directory being   deleted,   without trailing backslash
{
  int len = strlen(dir) + 2; // required to set 2 nulls at end of argument to SHFileOperation.
  char* tempdir = (char*) malloc(len);
  memset(tempdir,0,len);
  strcpy(tempdir,dir);

  SHFILEOPSTRUCT file_op = {
    NULL,
    FO_DELETE,
    tempdir,
    NULL,
    FOF_NOCONFIRMATION |
    FOF_NOERRORUI |
    FOF_SILENT,
    false,
    0,
    "" };
  int ret = SHFileOperation(&file_op);
  free(tempdir);
  return ret; // returns 0 on success, non zero on failure.
}

A: For C++ programming, if you're willing to work with third-party libraries,
boost::filesystem::remove_all(yourPath)
is much simpler than SHFileOperation.


text:
Q: Can I describe the fact with "You broke my computer" when my son made my computer not working while it wasn't physically damaged? I am not sure about the usage of the word break. Do English native speakers use it to describe if something stops working?

A: Yes, break can refer to both physical damage and something that no longer works.

I broke my phone screen. Look at the crack!

and

You broke my computer! It still looks okay, but it no longer turns on.

are both proper sentences.

A: If we are confident that the computer

no longer works

then I believe the term "broken" is applicable regardless of whether it is a software or a hardware issue. Assuming that it "still works" and that there is a software issue, then the computer is more on the end of being  damaged (as referenced by @WS2) or messed up (more colloquial).


text:
Q: Only list categories that contain posts of a specific custom post type I have three custom post types set up, articles, videos and photos.
I am using standard categories for these post types, and sharing the categories across all post types.
I am trying to create a nav menu for each post type, listing the categories, that should follow the following structure:

*

*Photos

*

*Cat 1

*Cat 3

*Cat 5

*Videos

*

*Cat 2

*Cat 3

*Cat 5

*Articles

*

*Cat 1

*Cat 2

*Cat 4

Categories that do not contain the custom post type should be hidden.
get_categories() with hide_empty set to 1 is obviously close, but it doesn't allow you to specify a post type.

A: Put the following in your functions.php:
function wp_list_categories_for_post_type($post_type, $args = '') {
    $exclude = array();

    // Check ALL categories for posts of given post type
    foreach (get_categories() as $category) {
        $posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID));

        // If no posts found, ...
        if (empty($posts))
            // ...add category to exclude list
            $exclude[] = $category->cat_ID;
    }

    // Set up args
    if (! empty($exclude)) {
        $args .= ('' === $args) ? '' : '&';
        $args .= 'exclude='.implode(',', $exclude);
    }

    // List categories
    wp_list_categories($args);
}

Now you can call wp_list_categories_for_post_type('photos'); or wp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats'); and the like.

A: Updated this to be more flexible. Returns category objects, omitting all empty.
// Gets Categories by Post Type
// returns categories that aren't empty
function get_categories_for_post_type($post_type = 'post', $taxonomy = '') {
  $exclude = array();
  $args = array(
    "taxonomy" => $taxonomy,
  );
  $categories = get_categories($args);

  // Check ALL categories for posts of given post type
  foreach ($categories as $category) {
    $posts = get_posts(array(
      'post_type' => $post_type,
      'tax_query' => array(
        array(
          'taxonomy' => $taxonomy,
          'field' => 'term_id',
          'terms' => $category->term_id
        )
      )
    ));

    // If no posts in category, add to exclude list
    if (empty($posts)) {
      $exclude[] = $category->term_id;
    }
  }

  // If exclude list, add to args
  if (!empty($exclude)) {
    $args['exclude'] = implode(',', $exclude);
  }

  // List categories
  return get_categories($args);
}

add that to your functions.php
To use (for example, if populating a select for filtering):
<select>
<?php
$categories = get_categories_for_post_type('projects', 'project_categories');
foreach($categories as $category) { ?>
   <option value="<?php echo $category->slug; ?>">
       <?php echo $category->name; ?>
   </option>
<?php } ?>
</select>

A: function for category by post.
copy in function.php
function get_categories_by_post_type($post_type, $args = '') {
    $exclude = array();
    //check all categories and exclude
    foreach (get_categories($args) as $category) {
        $posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID));
        if (empty($posts)) { $exclude[] = $category->cat_ID; }
    }
    //re-evaluate args
    if (!empty($exclude)) {
        if(is_string($args)) {
            $args .= ('' === $args) ? '' : '&';
            $args .= 'exclude='.implode(',', $exclude);
        } else {
            $args['exclude'] = $exclude;
        }
    }
    return get_categories($args);
}


text:
Q: $\|A_\delta f - f \|_p \to 0$ as $\delta \to 0$ for this function-to-function mapping $A_\delta$ For an $L^p$ function $f:\mathbb R \to \mathbb R$ and a positive number $\delta$, we define a new function $A_\delta f$ by the step function
$$  A_\delta f = \sum_{n\in\mathbb Z} \textbf{avg }^\delta_n(f) \  \chi_{I^\delta_n} \ , $$
where $I^\delta_n$ is the interval $(\ (n-1)\delta,\, n\delta\ ]$ and $ \textbf{avg }^\delta_n(f)$ is the mean value
$$  \textbf{avg }^\delta_n (f) =  \frac 1 \delta \int_{I^\delta_n} f.  $$
Question. How to prove that
$$ \lim_{\delta \to 0} \| A_\delta f - f\|_p =0 \ ?$$
(The norm is of course the $L^p$-norm.)
What I have / haven't done. I already have proved that
\begin{align}
\text{the answer is YES if $f$ is of compact support. }
\end{align}
And what I have to do is to extend this result to the whole $L^p(\mathbb R)$ by the denseness of $C_c(\mathbb R)$ in $L^p(\mathbb R)$.
To do this I used the Minkowski inequality to get
$$  \|A_\delta f - f \|_p \le \|A_\delta (f - f_k)\|_p + \| A_\delta f_k -f_k \|_p + \|f-f_k\|_p \ , $$
where $f_k$ is a sequence in $C_c(\mathbb R)$ which converges to $f$ in $L^p(\mathbb R)$. Then the second and third terms in the right-hand side become small if $\delta$ is small and $k$ large.
But I don't see why the first term $\|A_\delta (f-f_k)\|_p$ becomes small when $\delta \to 0$ and $k \to \infty$. Is this true? If so, then how can I prove it?
Thanks for any help. The answer may or may not follow my approach.
You may even restrict $\delta$ to have the sequential values; that is, you may assume $\delta_n = 1/n$ or $\delta_n = 1/2^n$, etc, if that makes the thing easier.

A: The disjointness of $I_{n}^{\delta}$ yields that
\begin{align*}
\|A_{\delta}(f-f_{k})\|_{p}^{p}&=\sum_{n\in\mathbb{Z}}|\text{avg}_{n}^{\delta}(f-f_{k})|^{p}|I_{n}^{\delta}|\\
&=\delta\sum_{n\in\mathbb{Z}}|\text{avg}_{n}^{\delta}(f-f_{k})|^{p}.
\end{align*}
While,
\begin{align*}
\sum_{n\in\mathbb{Z}}\left(\dfrac{1}{\delta}\int_{I_{n}^{\delta}}|f-f_{k}|\right)^{p}\leq\sum_{n\in\mathbb{Z}}\dfrac{1}{\delta}\int_{I_{n}^{\delta}}|f-f_{k}|^{p}=\dfrac{1}{\delta}\|f-f_{k}\|_{p}^{p},
\end{align*}
so $\|A_{\delta}(f-f_{k})\|_{p}^{p}\leq\|f-f_{k}\|_{p}^{p}$.


text:
Q: Why is Object.prototype instanceof Object false? Why does the following return false?
Object.prototype instanceof Object

A: Because it basically asks whether Object.prototype does inherit from Object's .prototype object: It does not.
a instanceof b is equivalent to b.prototype.isPrototypeOf(a) - it tests whether b.prototype is in the prototype chain of a. In your case, it is not in the chain, because it is the start of the chain itself. isPrototypeOf is not reflexive.

A: Referencing MDN:

The instanceof operator tests whether an object has in its prototype
  chain the prototype property of a constructor.


text:
Q: Android testing of the floating view I add a floating view to the WindowManager, and make it movable around the screen, and i can perform click event when i click this view, everything works fine.
However, I don't know how to access this view in espresso or UIAutomator.
Add view to WindowManager
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    type,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                    PixelFormat.TRANSLUCENT
            );

            ImageView floatingView = new ImageView(mContext);
            floatingView.setContentDescription("bugtags_fab_des_normal");
            mWindowManager.addView(floatingView, layoutParams);

The Floating View

the white-blue icon in rect is the floating view i am talking about.

Question
The floating view response a click event, and perform some task, now i want to do this in AndroidJunit test.

*

*Espresso

I try Espresso, using onView method, but the test case:
onView(withContentDescription("bugtags_fab_des_normal")).perform(click());

Get:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with content description: is "bugtags_fab_des_normal"

*

*UIAutomator

I try UIAutomator Viewer, but i can't find the floatingView in view hierarchy.
How
How can i access this view in espresso or uiautomator and perform click to it?
Appendix
Test Case
@Test
public void testInvoke() {
    onView(withContentDescription("bugtags_fab_des_normal")).perform(click());
}

Output log
output-log-gist
Bugtags.com
Actually, i am using a sdk called bugtags.com, it's a simple tool for app bug reporting and crash analysis.

A: Your view is outside of Activity so can find it by using inRoot() method:
@Test
public void checkClickOnFloatingButton() {
    onView(withContentDescription("bugtags_fab_des_normal")).inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))).perform(click());
}

Also you probably should change reportImage to floatingView in this piece of code:
ImageView floatingView = new ImageView(mContext);
reportImage.setContentDescription("bugtags_fab_des_normal"); // <---`reportImage` to `floatingView`
mWindowManager.addView(floatingView, layoutParams);

A: Add an onClickListener on your floatingView


text:
Q: Connect HDMI or Displayport to PC and display output with window (Windows 7, Mac Mini) To clarify, What I want to be able to do is the following:
I have 3 monitors and have all of them connected to my windows machine. The specs are not important as i suspect I will need new hardware for this anyway.
I want to get the output of my mac mini (either HDMI or Displayport), connect it to the windows machine and then display that input as a window on the desktop. This way I can just view the mac mini when I need to without changing the input source on my monitor. Kind of like a virtual PC but with physical hardware.
Also, I have a gigabyte switch that both the mac and windows machine are connected to if there is a way to do this over the network. I would need to be able to log into the mac through windows though.
How can I accomplish this?

A: Turn on screen sharing on your mini, and put in a password. Use a VNC client (UltraVNC) and whenever you want to do anything with your mini, just VNC into it.


text:
Q: How to solve flutter project compile Debug Kotlin error I'm new to flutter development. I used audioplayers: ^0.19.0 package in one project but when the project runs on an emulator it pops up with big error messages. Can you guys please help me to solve this? I have no idea about is it my code error or a package problem.
Execution failed for task ':audioplayers:compileDebugKotlin'.

Compilation error. See log for more details

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Simple Music'),
          backgroundColor: Colors.amber[300],
        ),
        body: SafeArea(
          child: Center(
            child: TextButton(
              child: Text("music"),
              onPressed: () {
                final player = AudioCache();
                player.play("note2.wav");
              },
            ),
          ),
        ),
      ),
    );
  }
}

Debug Console
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
e: Incompatible classes were found in dependencies. Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors
e: C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/acer/.gradle/caches/transforms-2/files-2.1/4d4ccf1034ba5937e6e7ba3aa34d2661/jetified-core-ktx-1.6.0-beta02-api.jar!/META-INF/core-ktx_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/acer/.gradle/caches/transforms-2/files-2.1/77bab1911042ab2c6d5cc0b2e2ee053c/jetified-kotlin-stdlib-common-1.5.10.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\AudioplayersPlugin.kt: (18, 32): Unresolved reference: mutableMapOf
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\AudioplayersPlugin.kt: (25, 9): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\AudioplayersPlugin.kt: (26, 9): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\AudioplayersPlugin.kt: (27, 9): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\AudioplayersPlugin.kt: (28, 17): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class

e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (127, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (129, 9): Unresolved reference: synchronized

e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (130, 18): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (131, 59): Unresolved reference: mutableListOf

e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (136, 17): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (137, 17): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (143, 17): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class

e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (144, 17): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (154, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (156, 23): Unresolved reference: let
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (156, 39): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (156, 49): Unresolved reference: it
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (161, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (163, 23): Unresolved reference: let

e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (163, 39): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class
e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (163, 47): Unresolved reference: it

e: C:\Flutter\Flutter\Flutter_sdk\.pub-cache\hosted\pub.dartlang.org\audioplayers-0.19.0\android\src\main\kotlin\xyz\luan\audioplayers\WrappedSoundPool.kt: (235, 30): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/acer/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':audioplayers:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 50s

Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

A: Try changing the ext.kotlin_version value in your build.gradle file (located in the android folder of your project) like so:
buildscript {
    ext.kotlin_version = '1.5.10'

    repositories {
        google()
        jcenter()
    }

    dependencies{
        ...
    }
}


text:
Q: SQL syntax error check right syntax on mysql PHP
You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'FROM nyheder ORDER BY ID DESC LIMIT 2' at line 1

found the place where it was i dont no why it dont work
nyheder ( meaning news )

Nyheder

    <?php
$html = '';
$page = '';
$id = '';
$news_pr_page = 5;
$current_page = 1;
if (isset($_GET['pagenr']) && is_int($_GET['pagenr'] * 1)){
    $page = $_GET['pagenr'];
    $current_page = ($_GET['pagenr'] * 1);
}
$sql ="SELECT COUNT(ID) AS antal FROM nyheder";
   $result = mysqli_query($conn, $sql);
   $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
   $products = $row['antal'];
   //exit($products);
   //echo ($prody);
  // $total_pages = ceil($products / $news_pr_page);
   //exit($total_pages);
   $offset = ($current_page - 1) * $news_pr_page;

   $sql = "SELECT * FROM nyheder
   ORDER BY ID ASC LIMIT $news_pr_page OFFSET $offset";

    $arr = getData($sql, $conn);
    foreach($arr as $value){
        $html .= '

'.$value['overskrift'].'

'.$value['oprettelsesdato'].'

'. substr($value['tekst'], 0, 182) . '...

                    <button>Læs mere</button>

            ';
}

   $html .= '

';
$html .='
';
        if($page > 1 && $page !== 1)
        {
            $href = '?page=nyheder&id='.$id.'&pagenr='.($current_page > 1 ? $current_page-1 : 1).'';
            $html .= '
Tidligere nyheder
';
        }
        if($products >= $news_pr_page)
        {
            $href = '?page=nyheder&id='.$id.'&pagenr='.($current_page+1).'';
            $html .= '
Ældre nyheder
';
        }

return $html;
?>

found also this, hope this help i am not used to stackoverflow how can i explain better my english bad sorry
Tilbage
<?php
$id = $_GET['id'];
$html = '';
//Min SQL-sætning til hentning af data
    $sql = "SELECT * FROM nyheder

        WHERE nyheder.ID = " . $id . "
        ORDER BY ID ASC LIMIT 1";

$arr = getData($sql, $conn);
if(is_array($arr)){
    foreach($arr as $value){
        $html .= '

'.$value['overskrift'].'

'.$value['oprettelsesdato'].'

'.$value['tekst'].'

        ';
    }
}

return $html;

?>

A: sorry about all this found problem
$sql = "SELECT nyheder.* FROM nyheder ORDER BY ID DESC LIMIT 2";
it was on line 67.
<?php
$sql = " SELECT * FROM omklubben ";
$arr = getData($sql, $conn);
foreach($arr as $value){
$html = '

'. $value['headline'] .'

'. $value['text'] .'

Brugte kajakker

';
}

                        $sql = "
                        SELECT kajakker.model, kajakker.pris,
                        kajak_billede.billednavn

                        FROM kajakker

                        INNER JOIN kajak_billede
                        ON kajak_billede.fk_kajak = kajakker.ID

                        ORDER BY ID DESC LIMIT 3";

                        $arr = getData($sql, $conn);
                        foreach($arr as $value){
                            $html .= '

'. $value['model'] .'

'. $value['pris'] .' kr.

                            ';
                        }
                    $html .= '

                <form action="" method="get">

                    <input type="hidden" name="page" value="soegning">
                    <input type="search" name="fritekst" placeholder="Søg">

                </form>

Nyheder
';

                    $sql = "SELECT nyheder * FROM nyheder ORDER BY ID DESC LIMIT 2";
                    $arr = getData($sql, $conn);
                    foreach($arr as $value){
                    $html .= '
' . showDateSmall($value['oprettelsesdato']) . ' ' . $value['overskrift'] . '
';
                    }

                    $html .= '
                    <button style="cursor:pointer;">Nyheder >></button>

2018

Marts
';

                    $sql = "SELECT bgv_info.* FROM bgv_info ORDER BY ID DESC LIMIT 2";
                    $arr = getData($sql, $conn);
                    foreach($arr as $value){
                    $html .= '
' . showDateSmall($value['oprettelsesdato']) . ' ' . $value['bgv_navn'] . '
';
                    }
                    $html .= '
                    <button style="cursor:pointer;">Kalender >></button>

';

return $html;
?>


text:
Q: Prove $Z[\sqrt{2}]/\sqrt{2}Z[\sqrt{2}]$ has only 2 elements I need to prove that factor ring $$Z[\sqrt{2}]/\sqrt{2}Z[\sqrt{2}]$$ has only two elements.

A: Hint
$$\sqrt{2} \in \sqrt{2} \mathbb Z[\sqrt{2}] \\
2=\sqrt{2} \cdot \sqrt{2} \in \sqrt{2} \mathbb Z[\sqrt{2}]$$
Use this to show that
$$\sqrt{2} \mathbb Z[\sqrt{2}] =\{ a+b \sqrt{2} | a, b \in \mathbb Z, a \mbox{ even } \}$$

A: Hint: analyse the ring homomorphism $\phi$: $\mathbb{Z}[\sqrt2] \rightarrow \mathbb{Z}/2\mathbb{Z}$, $\phi(a+b\sqrt2)=a$ mod $2$.

A: notice that as abelian groups
$$
\mathbb{Z}[\sqrt{2}] \cong \mathbb{Z}\oplus \sqrt{2} \mathbb{Z}
$$
so
$$
\sqrt{2}\mathbb{Z}[\sqrt{2}] \cong \sqrt{2}\mathbb{Z}\oplus 2 \mathbb{Z}\cong 2\mathbb{Z} \oplus \sqrt{2}\mathbb{Z}
$$
and
$$
\mathbb{Z}[\sqrt{2}] /\sqrt{2} \mathbb{Z}[\sqrt{2}] \cong \mathbb{Z}\oplus \sqrt{2} \mathbb{Z} /  2\mathbb{Z} \oplus \sqrt{2}\mathbb{Z} \\ \cong  \mathbb{Z}/ 2\mathbb{Z}
$$


text:
Q: Parameterize docker build by passing jar file name from command line I am trying to parameterize the final jar file name in docker build. I need docker-maven-plugin to take jar file name passed via command line parameter. Maven build is not throwing any error while building image.
If I hard-code the jar file name in dockerfile, it is working fine.
Maven command to docker build:
mvn -X -s settings.xml docker:build -DJAR_FILE_NAME=${filename}

My docker file:
RUN curl -kfsSL https://example.com/UnlimitedJCEPolicyJDK8/US_export_policy.jar > US_export_policy.jar \
&& curl -kfsSL https://example.com//UnlimitedJCEPolicyJDK8/local_policy.jar > local_policy.jar \
    && mv local_policy.jar ${JAVA_HOME}/jre/lib/security \
    && mv US_export_policy.jar ${JAVA_HOME}/jre/lib/security \
    && rm -rf US_export_policy.jar local_policy.jar

ENV JAVA_KEYSTORE ${JAVA_HOME}/jre/lib/security/cacerts
RUN curl -kfsSL https://example.com/mycert.cer > mycert.cer \
    && ${JAVA_HOME}/bin/keytool -v -importcert -file mycert.cer -keystore ${JAVA_KEYSTORE} -storepass dummy -alias dummy -noprompt \
    && rm mycert.cer

VOLUME /tmp
#ADD myservice-2.0.2-SNAPSHOT.jar app.jar   <-hard-coded name works fine

RUN echo "final jar file name"
RUN echo ${JAR_FILE_NAME}

ADD ${JAR_FILE_NAME} app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

My POM.xml
<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.0</version>
    <configuration>
        <imageName>${docker.image.prefix}/myservice</imageName>
        <dockerDirectory>src/main/docker</dockerDirectory>
        <resources>
            <resource>
                <targetPath>${docker.resource.targetPath}</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>

Output from docker build process:
Step 6 : VOLUME /tmp
 ---> Using cache
 ---> xxxxxxxxx
Step 7 : RUN /bin/bash -c echo JAR_FILE_NAME1 in docker :$JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 8 : RUN /bin/bash -c echo JAR_FILE_NAME2 in docker :${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 9 : RUN echo $JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 10 : RUN echo "final jar file name"
 ---> Using cache
 ---> xxxxxxxxx
Step 11 : RUN echo ${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 12 : ADD ${JAR_FILE_NAME} app.jar
 ---> Using cache
 ---> xxxxxxxxx
Step 13 : RUN bash -c 'touch /app.jar'
 ---> Using cache
 ---> xxxxxxxxx
Step 14 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Using cache
 ---> xxxxxxxxx
Successfully built xxxxxxxxx
[INFO] Built xxx/myservice

Output while pulling image:
I0603 13:48:32.849159 23106 exec.cpp:132] Version: 0.23.0
I0603 13:48:32.857393 23114 exec.cpp:206] Executor registered on slave 20170523-104056-1453378314-5050-11670-S48
Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.
Error: Invalid or corrupt jarfile /app.jar

A: Why don't you use a regular docker build command instead of going through maven? You can use a maven base image, something like maven:onbuild even. An example here may help.

A: I parameterized the output jar to be used in docker image in this way.

*

*In Dockerfile, used a concrete name without any version. Removed ${JAR_FILE_NAME}, dynamic parameters from Dockerfile.

ADD myservice.jar app.jar

*In POM.xml, I made maven to output artifact without version in the jar file name, by adding below element right under  tag.

<finalName>${project.artifactId}</finalName>
So, no manual update needed for Dockerfile. Forgetting to update Dockerfile and then build getting failed was really disturbing. I let Maven to manage versions and those versions are used as finite image tags, and thus "reproducible builds" work for me.

A: I had the same kind of problem: I dont't want to hard-code the project version in my Dockerfile.
I first though about removing the version in the jar's file name (this can be achieved using your build tool, I personnaly use gradle).
Yet I was quite unhappy with it since I consider having the version in jar's name is a good practice (there is an interstning discustion about this in this question for instance).
So I came up with this solution: copy/add the jar using a wildcard:
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app/
COPY ./path/to/my/jar/*.jar /app/my-app.jar
ENTRYPOINT ["java", "-jar",  "/app/my-app.jar"]

Here I managed to make my build tool produce the jar I want alone in its folder.
The point is to have a way to use a wildcard to get this single jar without ambiguity.