text:
Q: ADC sampling frequency - Noise filtering I have to take the reading of two analog sensors temperature & Fuel level. Both of them are analog signal & i have to remove noise from this reading. And i want to use the Digital filter for these. My MCU is running at 32 MHZ, also i am taking reading of ADC for both the sensors every 5 msec.
Now i want to reduce Noise from my sample by using external analog filter & software digital fileter (IIR & FIR).
This link says we should follow Nyquist criteria for sampling to avoid alising problem.
https://en.wikipedia.org/wiki/Analog-to-digital_converter
Now to design a Digital IIR filter, this link use to state about using cutoff frequency.
https://stratifylabs.co/embedded%20design%20tips/2013/10/04/Tips-An-Easy-to-Use-Digital-Filter/
Now if i am right then Nyquist criteria & aliasing & setting sampling frequency is important for analog signals recording, where we are aware that human voice is < 20,000 HZ.
But how to set these criteria of (Analog or Digital filter cutoff frequency & sampling rate & nyquist criteria) for sensor signal like temperature & Fuel where we get simply the analog signals & we are not aware what frequency is for these signals.
Please suggest.

A: You can sample them 2 to 20 times per second and then calculate a moving average over a second.  your response time will be about a second and there should be no noise if your electronics are even remotely reasonable.
Unless you have some interesting micro-turbine and want to measure accurate fuel consumption you are not likely to need very fast response from your filters or ADC if your sensors only respond at 1 to 10 Hz.
EDIT:
If you have or think you will have non random electrical noise much greater than 5 times the resolution that you actually need (not what can be calculated) you may gain benefit by adding analogue filtering.  The cut-off frequency should be around half of your sampling frequency.
However any low pass filtering above your desired response frequency would be a benefit though the digital averaging filter is a low pass filter already that can eliminate a lot of random noise sources.  if you have noise near some multiple of the sampling frequency then the aliased noise may cause a beat signal in the output that is not actually there, an analogue front end filter would minimise this risk.

A: You have a sampling rate of 200 Hz (1/5 ms).
But you have not stated the needed response time for the output from the filter. To find the answer to that you should ask yourself how slow can the response be before it gives you a problem. Ie. if this is the fuel level and temperature of a car, then one minute is plenty good response time. But if this is some internal measurement of a fuel chamber for a mini turbine engine, then even a second delay might give you trouble. It's not possible for me to determine. (Ok the turbine is a far fetched and nearly useless example, could not think of any better examples where a delay time in the region of one second could cause problems).
You should filter the analog signal with a low-pass filter with a cut-off frequency (-3 dB frequency) of less than the Nyquist frequency. Same with the cut-off frequency in the digital filter. I would keep the cut-off frequency of the analog filtering as close to the Nyquist frequency as possible. That way you are free to alter the filter characteristics as you please by only altering the digital filter.
The other design criteria fro the analog filter is the sampling depth (in bits) of the ADC. The damping of the signals above the Nyquist frequency should be more than the S/N ratio of the ADC. Ie. 8 bit ADC, roughly 7 bit S/N -> more than 42 dB damping at the Nyquist frequency to avoid aliasing.
200 Hz sampling rate -> Nyquist freq = 100 Hz.
Analog low pass cut off frequency < 100 Hz.
Assuming 8 bit as in my example above: Damping at 100 Hz >42 dB
Suggested analog filter: 2. order filter (40 dB/decade). Filter frequency < 8.8 Hz.
And for the digital filter, you can filter as much as you want as long as you keep the needed response time in mind.


text:
Q: unify two models (edmx) with visual studio 2010 Hello as actually as i know you can not make relations between tow models or have in one models entities from two databases, it's a posibility two join two models both of them with existig databases behind? or there is some experience with a method like:
move entities from the designer of one of them to the other and some bcp (SQL server) magic to move data and recreation on only one database?
Thanks.

A: As I know the answer is: No you can't join models targeting different databases and you can't place entities from multiple databases in single model. However you should be able to make relations among entities from multiple models targeting the same database. More in these articles: part 1, part 2.
The partial workaround for multiple databases can be views representing tables from the second database in your first model and creating relations directly in the model (by Foreign key associations with referential constraints) but I didn't try this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Architecture design for a multi-tier web-application using delphi and firebird I have an application that allows for searches, display of images, etc from a database.  This is written in Delphi running on a local database Firebird
I would like to make the application portable so that one could access the data from anywhere.
I need to know how to structure the whole system.  For example, the database could reside on a cloud server e.g. Azure and people can retrieve information from this via the internet.  However, the display UI must be able to display in various formats, based on query results and thus has some processing so that it cannot just be a web page.
My thinking is to use something like TMS WEB Core to do the display on any type of device and then an application based on TMS XData on the server to actually access the database.  Is this a viable architecture or am I totally clueless on how to implement such an application.
I also wondered why any remote application cannot simply connect to a cloud database for information.
If anyone has experience or could direct me to appropriate tutorials/resources I will appreciate it.
This is for a Delphi App running on mobile device or desktop, using a back-end Firebird DB.  Haven't tried much as I don't have an idea how to start.  Have investigated TMS WEB Core and TMS DataX
None yet
None yet

A: TMS XData on the server and TMS Web Core for the front-end is not only a viable architecture but actually a robust and wise choice. Remote applications are not supposed to connect to cloud databases because of performance and security issues.
Having a REST API server is also a better architecture in the sense all your business logic resides in this server. If you connect from the client directly to the database you will have more business logic in the client which is not recommended as well.


text:
Q: Why redim prevent type mismatch error? I have this simplified code where infosOptions is a global variable with different types in it :
Dim optionsVecteur As Variant
For j = 0 To UBound(infosOptions)
   If infosOptions(j, 11) & " Index" = transac.optionName Then
      optionsVecteur(1) = infosOptions(j, 6)
      optionsVecteur(2) = infosOptions(j, 5)
      optionsVecteur(3) = infosOptions(j, 10)
      Exit For
   End if
End j

I have a type mismatch error on optionsVecteur(1) = infosOptions(j, 6) but if put Redim optionsVecteur(3) it works, why ?

A: There are a couple of issues with your code. As pointed out in the comments, you have created a scalar Variant (as in a single variable) and not an array. You need to correct this.
Also, your use of UBound on a multi-dimensional array is liable to fail in other circumstances. It is best practice to use the full definition of UBound to ensure that you actually pick the right limit.
Changes like the below should see your problems resolved:
Dim optionsVecteur() As Variant 'This creates an array of variants - But has not dimensioned the array.
ReDim optionsVecteur(1 to 3) as Variant 'This dimensions the array as having 3 elements. You could have just put this in the original line above, but doing this allows you to dynamically change the length of the array of required.

For j = 0 To UBound(infosOptions, 1)'This ensures that VBA considers the upper boundary of the first dimension.
   If infosOptions(j, 11) & " Index" = transac.optionName Then
      optionsVecteur(1) = infosOptions(j, 6)
      optionsVecteur(2) = infosOptions(j, 5)
      optionsVecteur(3) = infosOptions(j, 10)
      Exit For
   End if
Next j 'You want next j not end j.


text:
Q: julia executable path in vscode on windows I am trying to get Julia to run on VSCode on windows. I cannot get julia Language server to run. The executable path = "C:\Julia-1.1.1\bin\" which is the correct path. Where am I going wrong?

A: As stated in the parameter's description, the path should point to the julia executable. You need to add julia.exe to the end.
C:\Julia-1.1.1\bin\julia.exe

If you are editing the JSON file directly, you will need to escape the backslashes.
C:\\Julia-1.1.1\\bin\\julia.exe

A: The following setting works for me, without the .exe extension.
"julia.executablePath": "C:\\Users\\...\\Julia-1.3.0\\bin\\julia"


text:
Q: eclipse hides/blocks text near cursor I am having ubuntu 13.04 64 bit and eclipse.
when i try to click on the editor(any editor, java or xml), eclipse blocks/hides the text near the cursor.
let me explain with the pictures.
below is the part of xml file i am trying to edit.

When I click on the text entry key="json" value="application/json", it blocks the letters nearby cursor, as shown in image below :

in the above image, the cursor is between value and =, like value{cursor}=, but i am not able to see the cursor, and also not able to see some characters near the cursor.
However when I try to click on different line, the previously blocked text becomes visible but the characters nearby new cursor position gets blocked, for example when i click near property name="mediaTypes", exactly my cursor is like property name="me{cursor}diaTypes", but what eclipse shows me is shown in below image.
first I thought that it may be the problem with eclipse(juno), so i removed the eclipse installation, and downloaded new eclipse(kepler), but still the problem is not resolved.

A: Try Right-Click->Input Methods-> (Simple or IBus or X Input Method). Seemed to work for me. Hope it helped :)

A: Problem Solved :
I updated the ubuntu to latest version and the issue is gone.
But the mystery remails unsolved, why it was blocking texts near cusrsor.


text:
Q: Regex - Date format along with having max value set I'm using the regex from this question Regular Expression Help for Date Validation - dd/mm/yyyy - PHP from validating the date format
/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/

However I'd also like to ensure that the date is in this specific format DD/MM/YYYY and NOT as MM/DD/YYYY, so I was wondering whether there's a way to "tell" my regex that this part
\/[0-9]{1,2}\/
should also have a value up to 12

A: You can use
/(0[1-9])|(1[0-2])/


text:
Q: USB vendor and product ID I am an embedded systems engineer and eager to learn USB. So, I started by looking at the device manager in windows to get a persepective how the usb devices are identified and what are the specific features which gets listed in windows.Later, I have used usbview software to get more details rather than the Device manager.
Nothing was connected to the pc before/while running the usbview.
Here's what I have found in usbview:
Image 1: corresponds to a composite device and I have looked on the web to find the company (which wasn't listed in usbview) using the vendor and product ID at this link. I have found the company, it is Syntek but product ID wasn't identified. Since Syntek had all other products related to webcam, I am assuming Syntek's product Id correponds to webcam.
Image 2: correponds to a Realtek bluetooth device+High Speed Chip, where I have no idea what  an high speed chip refers to.
Here are my doubts,
1) In image 1, what is the composite device refer to? If it is a webcam, does it mean webcam is connected as a USB device to my motherboard? But, why is it connected in that way?
2) In image 2, why is the Realtek bluetooth listed as a USB device? Does it mean bluetooth is connected as a USB device to my motherboard? If yes, why is it connected in that way? Finally, what is this High Speed chip?

A: Basically, the USB controller ("root hub") translates USB to PCI(-Express). See also Relation between USB and PCI and How to interpret the output of 'lsusb' — What are all these Linux Foundation root hubs? for more explanation.
So any device that can talk USB, like your webcam or a bluetooth module, can be connected internally to an USB hub.
This USB data and commands have to end up in your CPU or memory. The hubs do this by talking to the controller, which in turns talks to the rest of your machine through PCI(-Express).


text:
Q: Flutlab.io "package:flutter/material.dart" not importing so FlatButton widget not working Using the online IDE Flutlab.io, I wanted to create a FlatButton widget so I imported "package:flutter/material.dart" in my main.dart file but when I run my code it says that the method FlatButton is not defined for my project. How do I fix this?
I imported that statement but got an error.


text:
Q: Moving App.xaml Styles to Resource Dictionary I have a custom control that uses styles that are in a resource dictionary that is in linked in the app.xaml. If I take the link off and add the link to the page that contains the control it doesn't work. Why is that? Why would my control (a dll) need the styles to be in the app.xaml and not just on the page that the control is contained in?

A:
Why would my control (a dll) need the styles to be in the app.xaml and not just on the page that the control is contained in?

Custom controls need a default style. This default style is set within the constructor.
eg:
public CustomControl()
{
    DefaultStyleKey = typeof(CustomControl);
}

When this is set it looks within the containing assembly for this style. If the control is within an application, then it looks within the App.xaml. If the control is within a class library, it looks within a file Generic.xaml that must be placed within a folder "Themes". You do not need to place the style within either of these files. You can create a separate file that contains the style and reference it from either App.xaml or Themes/Generic.xaml (based on where the control is defined). To do this you create a MergedDictionary within one of those files. If your control is defined in your application you would do
<Application x:Class="MyApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!--Application Resources-->
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Controls/CustomControl.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    <Application.Resources>
</Application>

If your control is defined within a class library the Themes/Generic.xaml should look like this
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/My.Custom.Assembly;component/FolderLocationOfXaml/CustomControl.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

No matter where your custom control is placed the xaml for this will always look the same
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:My.Custom.Assembly.Controls">
        <Style TargetType="local:CustomControl">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:CustomControl">
                    <Grid>
                        <! -- Other stuff here -->
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Without this default style defined, there is no way to determine what style to override. Once the default style is defined you can change the style within your app or anywhere else the control is being used.

A: Try moving the style into the control to verify that all of the required references are in place for your control to use items from the dictionary.
Make sure that the project containing your UserControl has a reference to the project that contains the resource dictionary.
Verify your Source path to the dictionary:
<ResourceDictionary Source="/AssemblyName;component/StylesFolderName/ResourceDictionaryName.xaml" />


text:
Q: a quick way to maven install a lib folder is there a quicker way to maven install say a complete lib folder to maven dependencies rather than the individual command for each jar:
mvn install:install-file -DgroupId=third-party -DartifactId=app-eventinfo -Dversion=1.0 -Dpackaging=jar -Dfile=EventInfoToOrder.jar

Is there a way I can say this is a folder of dependencies or a little work around in eclipse where I trick maven into using a user defined library as a dependency.
Yes I have a lot of folders that have been sitting on my buildpath which I must install to my local repo.
Cheers for reading :)

A: There is no standard way of doing this as it would go against Maven's philosophy of managed (versioned) dependencies.

A: The problem is not about the folder contents, but specifying the correct values for groupId, artifactId and version.
If you are ok with random values for this, then you could write a dirty batch file/shell script to do this.
Otherwise, the time you spend trying to automate this (by having a mapping of groupId, artifactId and version for each jar in your folders), you can arguably do mvn install:install-file manually.
A better option would be to review your dependencies and see which are not available in maven repo and only install those.  The remaining will be downloaded by maven on its own.


text:
Q: Kubernetes showing Image Pull Error while scheduling pods I have configured a secret on Kubernetes and inside the node, I am able to pull an image with docker pull perfectly. But when kubectl tries to schedule a pod on the node it shows image pull backoff error. Is there any setting needs to be done while bootstrapping. I am using community AMI on AWS for Kubernetes node.

A: Try this:

*

*kubectl describe pod-name - see event log at the end. it should show series of events starting from initial image pull to subsequent attempts and may continue to restart in order to achieve desired state as per deployment record

*In most scenarios something within container erroring out resulting restart expected behavior by k8s. to check logs - kubectl logs pod-name

*Try to keep container running so you can peek inside running container for more troubleshooting using kubectl exec -it pod-name (if single container) or kubectl exec -it pod-name -c container-name.


text:
Q: Pinch to zoom independent axes in 4.0 ice cream sandwich I developed a mobile app inside Adobe Flex (4.6) and it includes using pinch-to-zoom functionality to zoom in on pictures to make it easier to read words in the pictures. In previous android versions (2.1 to 2.3.3 and 2.3.4 if you're running cyanogenmod) the pinch-to-zoom works fine. But if the app is run on an ICS (Android 4.x) device, the axes seem to handle the enlargement of the picture individually. i.e. when you move your fingers apart horizontally, the image gets very wide, but stays the same vertical size, and vice versa.
First, does anyone know why this is happening?
And second, does anyone know of a way to fix it to work as it did before?
I will update to include screenshots.
Update: I have confirmed this is also an issue with Honeycomb. i.e., 3.x OS acts the same as 4.x ICS.
Sense, running the latest HTC update:

ICS, on AOKP, but verified this is an issue with standard ICS distros as well:

A: Solved this. Code was previously:
        protected function onZoom(e:TransformGestureEvent, img:Image):void
        {
                DynamicRegistration.scale(img, new Point(e.localX, e.localY), img.scaleX*e.scaleX, img.scaleY*e.scaleY);
        }

change the final e.scaleY to e.scaleX. This makes it scale based on only one portion of the zoom (in the x direction) and scales both X and Y accordingly. Not exactly perfect, but it works very well in practice.
Final code is this:
        protected function onZoom(e:TransformGestureEvent, img:Image):void
        {
                DynamicRegistration.scale(img, new Point(e.localX, e.localY), img.scaleX*e.scaleX, img.scaleY*e.scaleX);
        }


text:
Q: telnet send a http request I am using telnet to send a http request , like this:
telnet> open 192.168.4.135 8087
Trying 192.168.4.135...
Connected to 192.168.4.135.
Escape character is '^]'.
POST /rpc/ HTTP/1.1
HOST:192.168.4.135:8087
Content-length:18
Content-type:application/x-http-form-urlencoded

action=loadrsctype
HTTP/1.1 200 OK
Date: Thu, 17 May 2012 03:52:53 GMT
Content-Length: 45
Content-Type: text/html; charset=ISO-8859-1

return=fail&error=Configuration doesn't existHTTP/1.1 400 Bad Request
Content-Type: text/html
Connection: close
Date: Thu, 17 May 2012 03:52:53 GMT
Content-Length: 94

<TITLE>400 Bad Request</TITLE>

Bad Request

Connection closed by foreign host.

the response code is 200 , but why there is a paragraph like this :
HTTP/1.1 400 Bad Request
Content-Type: text/html
Connection: close
Date: Thu, 17 May 2012 03:52:53 GMT
Content-Length: 94

<TITLE>400 Bad Request</TITLE>

Bad Request

This is the output of the server or telnet itself ? How to avoid to show this ?
--update--
When i change "HTTP/1.1" to "http/1.1", i get the right response.
Now i wonder wheather this is requirement of protocol or related with the implementation of the server?

A: In HTTP 1.1, all connections are considered persistent unless declared otherwise.
Then... I think the server is receiving some spurious newline char and reply with a Bad Request.
If you use http/1.1 instead of HTTP/1.1 could make fallback the version to the version 1.0 that's not persistent by default and after the 200 OK response it drops the connection.

A: Try replacing & with &.

A: The code at the URL you are accessing is printing some text:
return=fail&error=Configuration doesn't exist

But then your code continues on to print a HTTP 400 error.  Probably you forgot to abort after printing the response, and so your code goes on to print the HTTP 400 as well.


text:
Q: Prove that the number $7^n+1$ is divisible by $8$ if $n$ is odd. In the case where $n$ is even, give the remainder of the division of $7^n+1$ by $8$.
Prove that the number $7^n+1$ is divisible by $8$ if $n$ is odd. In the case where $n$ is even, give the remainder of the division of $7^n+1$ by $8$.

*

*If $n$ is odd

$7 \equiv -1 \mod 8$
$7^n \equiv (-1)^n \mod 8$
$7^n \equiv -1 \mod 8$
$7^n +1 \equiv 0 \mod 8$
Therefore, $7^n+1$ is divisible by $8$ if $n$ is odd.

*

*If $n$ is even

$7 \equiv -1 \mod 8$
$7^n \equiv (-1)^n \mod 8$
$7^n \equiv 1 \mod 8$
$7^n +1 \equiv 2 \mod 8$
Therefore, the remainder of the division of $7^n+1$ is $2$.
Is that true, please?

A: Yes, you are right. Another way to present it would be like so:
For $n$ odd,
$$7^n+1 \equiv (-1)^n+1 \equiv -1+1 \equiv 0 \pmod 8$$
and for $n$ even,
$$7^n+1 \equiv (-1)^n+1 \equiv 1+1 \equiv 2 \pmod 8$$

A: Note that
$\forall n \in \Bbb N, \; 7^n + 1 = (8 - 1)^n + 1 = \displaystyle \sum_0^n \dfrac{n!}{k!(n - k)!}8^{n - k}(-1)^k + 1 = \sum_0^{n - 1} \dfrac{n!}{k!(n - k)!}8^{n - k}(-1)^k + (-1)^n + 1  , \tag 1$
via the binomial theorem; when $n$ is odd this yields
$7^n + 1 = \displaystyle  8\sum_0^{n - 1} \dfrac{n!}{k!(n - k)!}8^{n - k - 1}(-1)^k  , \tag 2$
whence
$8 \mid 7^n + 1, \; \text{odd} \; n; \tag 3$
for even $n$ we obtain
$7^n + 1 = \displaystyle  8\sum_0^{n - 1} \dfrac{n!}{k!(n - k)!}8^{n - k - 1}(-1)^k + 2; \tag 4$
we note that
$0 \le 2 < 8; \tag 5$
that is, the remainder of $7^n + 1$ when divided by $8$ is $2$.

A: Just to be different:
$(a-1)(a^{n-1} + a^{n-2} + ..... + a + 1)=(a^n - 1)$.
$(a+1)(a^{n-1} -a^{n-2} + ........ \mp a \pm 1) = (a^n \pm 1)$.
with $n$ even yielding $(a+1)(a^{n-1} -a^{n-2} + ........ + a - 1)=a^n -1$
and $n$ odd yielding $(a+1)(a^{n-1} -a^{n-2} + ...... -a +1) = a^n+1$
So we $a = 7$ we get $7+1=8|a^n+1$ if $n$ is odd.  And $7+1=8|a^n-1$ if $n$ is even.  And as $a^n-1 = (a^n -1) + 2$, $a^n + 1$ will have remainder $2$ if $n$ is even.
But that's just to be different.
What you did was shorter and better.  This just shows why it's no surprise.


text:
Q: C# Forms Loading ComboBox Items on Startup public Form1()
{
    InitializeComponent();
    loadComboEmail();
}

private void loadComboEmail()
{
    string path = Directory.GetCurrentDirectory();
    string build = (path + "\\" + "email.txt");
    string[] lines = System.IO.File.ReadAllLines(build);

    comboEmail.Items.AddRange(lines);
    comboEmail.SelectedIndex=0;
}

I've got a combobox that I wanted to load with the client email addresses which are stored in an text file. Using the loadComboEmail() I read from the text file and load the Combobox. Am I doing something that is considered bad practice by calling  the loadComboEmail at the form startup? If so, how do I properly read from the textfile and then load it into the combo, so when the form loads, it has the necessary data?

A: No, this seems quite legit. You don't have to worry as this is the way all things get loaded in WinForms... This will block the UI thread for a short amount of time, but since your not going to load huge masses of something, you won't even notice it.
When you start performing a greater amount of Actions and big files you should think about using a BackgroundWorker or a Task!
Anyway you should also consider using the following instead of your Code:
private void loadComboEmail()
{
    string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath); //seems to be the same to me, but is safer
    string build = System.IO.Path.Combine(path, "email.txt"); //much more safer then simple string addition
    string[] lines = System.IO.File.ReadAllLines(build);

    comboEmail.Items.AddRange(lines);
    comboEmail.SelectedIndex = 0;
}

A: You can use:
 Task task = Task.Factory.StartNew(() =>
 {
    // Background work
    loadComboEmail();
 }).ContinueWith((t) =>
 {
    //If you need to execute something after the loading process.
 });

In order to update the UI thread, you can maybe do the reading on another thread and when the list of emails is loaded, just update it.
Task.Factory.StartNew(() =>
        {
            // Background work - read the file
        }).ContinueWith((t) => {
            // Update UI thread here

        }, TaskScheduler.FromCurrentSynchronizationContext());

A: Using the constructor to load that is not considered as a bad practice. Read the answer of Hans Passant about when you should use the Load Event of the window. What setup code should go in Form Constructors versus Form Load event?
Altough as said in comments, you are blocking the UI Thread. In the constructor the keyword await cannot be used. So you have to 'Fire and forget'. When using the Load event you can use await but event handlers are async void. So they are not awaited, you have stil 'Fire and forget'.
public Form1()
{
    InitializeComponent();
    loadComboEmail();
}

private async Task loadComboEmail()
{
    string path = Directory.GetCurrentDirectory();
    string build = (path + "\\" + "email.txt");
    string[] lines = await Task.Run(() => File.ReadAllLines(build));

    comboEmail.Items.AddRange(lines);
    comboEmail.SelectedIndex=0;
}


text:
Q: c++ работа с файлами Когда вывожу в файл данные (язык - c++), через fstream, они появляется в нём только после того, как я этот файл закрою (то есть, если ofstream file, то информация в нём появляется только после того, как file.close()). Как сделать так, чтобы информация в нём обновлялась автоматически после каждого вывода, т. к. так удобнее выполнять пошаговую отладку?

A: Вызвать file.flush() и сбросить буфер.
Также буфер можно сбросить, отправив в поток std::flush.
file << std:flush;

std::endl кроме вставки новой строки также вызывает flush


text:
Q: Find the the coefficient of $\,x^r\,$ in $\,(1+x+x^2)^n$ I want to be able to explicitly write it as $a_r = \dots $
When using multinomial theorem, I'm getting stuck at 2 conditions, but I'm not able to simplify from there.
I wrote $(1+x+x^2)^n =\displaystyle \sum_{a,b,c}^{a+b+c=n}\frac{n!}{a!b!c!}(1)^a(x)^b(x^2)^c = \frac{n!}{a!b!c!}x^{b+2c} $
so my conditions are $b+2c=r$ and $a+b+c=n$, how do I proceed from here?
Edit: Since in this particular case, we are able to write $
(1+x+x^2)^n = \displaystyle(\frac{1-x^3}{1-x})^n$, how can we do it for any random multinomial like $(1+3x+7x^2)^n $?

A: Guide:
One possible way\begin{align}
(1+x+x^2)^n &= \left(\frac{1-x^3}{1-x}\right)^n \\
&= (1-x^3)^n (1-x)^{-n}
\end{align}
Try to find the expansion for each term.

A: First, observe that
$$
x^2+x+1=(x+w)(x+\overline{w})
$$
where $w=\frac{1}{2}+\frac{i\sqrt{3}}{2}$. Thus
$$
\sum_{r=0}^{2n}c_rx^r=(x^2+x+1)^n=(x+w)^n(x+\overline{w})^n=\sum_{k=0}^n\binom{n}{k}x^kw^{n-k}\cdot \sum_{k=0}^n\binom{n}{\ell}x^\ell \overline{w}^{n-\ell}
$$
and hence
$$
c_r=\sum_{j=0}^r\binom{n}{j}\binom{n}{r-j}w^{n-j}\overline{w}^{\,n-(r-j)}=\sum_{j=0}^r\binom{n}{j}\binom{n}{r-j}w^{r-2j}
$$
since $w\overline{w}=1$.

A: With respect to OP's edit: We can consecutively apply the binomial theorem in order to determine the coefficient of $x^r$. It is convenient to use the coeffcient of  operator $[x^r]$ to denote the coefficient of $x^r$.

We obtain
  \begin{align*}
\color{blue}{[x^r]}\color{blue}{(1+3x+7x^3)}
&=[x^r]\sum_{j=0}^n\binom{n}{j}(3x+7x^2)^j\\
&=\sum_{j=0}^r\binom{n}{j}3^j[x^{r-j}]\left(1+\frac{7}{3}x\right)^j\tag{1}\\
&=\sum_{j=0}^r\binom{n}{j}3^j\binom{j}{r-j}\left(\frac{7}{3}\right)^{r-j}\tag{2}\\
&\,\,\color{blue}{=\sum_{j=0}^r\binom{n}{j}\binom{j}{r-j}7^{r-j}3^{2j-r}}
\end{align*}

Comment:

*

*In (1) we factor out $(3x)^j$ and apply the rule $[x^{p-q}]A(x)=[x^p]x^qA(x)$. We also set the upper bound of the sum to $r$ since the power of $x$ is non-negative.

*In (2) we select the coefficient of $[x^{r-j}]$.

A: Here is an easier method to solve this without complex analysis:
$\left(1+x+x^{2}\right)^{n}=\left(\frac{1-x^{3}}{1-x}\right)^{n}=\left(1-x^{3}\right)^{n}(1-x)^{-n}$
Now,
$\begin{aligned}\left[x^{r}\right]\left(1+x+x^{2}\right)^{n} &=\left[x^{r}\right]\left(1-{ }^{n} C_{1} x^{3}+{ }^{n} C_{2} x^{6} -\ldots\right )(1-x)^{-n} \\ &=\left[x^{r}\right]\left(\sum_{k=0}^{n} { (-1)^k} \  ^{n} C_{k} x^{3 k}\right)(1-x)^{-n} \end{aligned}$
We also know that cofficient of $x^{n}$ in $(1-x)^{-r}$ is ${ }^{n+r-1} C_{r-1}$
$\begin{aligned} \therefore \ \left[x^{r}\right]\left(1+x+x^{2}\right)^{n} &=\sum_{k=0}^{n}(-1)^{k}\ { }^{n} C_{k}\left[x^{r-3 k}\right](1-x)^{-r} \\
\left[x^{r}\right]\left(1+x+x^{2}\right)^{n} &=\sum_{k=0}^{n}(-1)^{k}\ \  {}^{n} C_{k} \ { }^{n+r-3 k-1}C_{n-1} \end{aligned}$
Which is the required coefficient.
You are welcome to do any sanity checks as desired.

A:
$\,x^r\,$ in $\,(1+x+x^2)^n$

I see a combinatorics way, notice the zero set consists of $\omega$ and $\omega^2$ repeated $n$ times. Coefficient of $x^r=x^{2n-p}$ for some $p \in \mathbb{N}$. Now, this coefficient by Vieta's theorem is sum of all the ways we can take roots $p$ at a time with a minus power:
$$ \text{coeff} = ( \text{roots taken p at a time} )(-1)^p$$
Suppose we take $t$ copies of $\omega$ then we take $p-t$ copies of $\omega^2$, the contribution to the choice to the coefficient is:
$$ (-1)^p \binom{n}{t}  \omega^t \binom{n}{p-t} \omega^{2p-2t}$$
This simplifies into:
$$ (-1)^p \omega^{-t+ 2p} \binom{n}{t} \binom{n}{p-t}$$
To get the total coefficient, we have to add up the terms:
$$ \text{coeff} = \left[ \sum_{t=0}^p \omega^{-t} \binom{n}{t} \binom{n}{p-t}\right]
 \omega^{2p} (-1)^p $$

Sanity check:
Suppose $n=1$,$r=1$ and $p=1$ then:
$$ \text{coeff}= \sum_{t=0}^1 \left[  \omega^{-t} \binom{1}{t}^2 \right] \omega^{2} (-1)^p=1$$


text:
Q: Microsoft Translate Voice limit 200-400 words when request I have a URL of Microsoft Translate Voice to get voice look like:

<audio controls autoplay>
  <source src="https://www.bing.com/tspeak?&format=audio%2Fmp3&language=en&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2&text=I'm Often at the End of My Rope as a Mom of Two" type="audio/mpeg">
</audio>

The problem is: text="any text here". Any text here is limit about 200-400 word. I don't know the reason at here. In Bing Translate I can insert full 5000 words and click button audio to hear.
Have any method to pass this problem? Microsoft is limit in this URL?
Have any method to insert 5000 words like Microsoft Translate homepage?

A: If you open your developer console on Bing's website and start playing the sound, you'll see it sends a first mp3 request with only a couple of words, and when it's done reading it, it sends another one, and so on.
You could do the same:

// When the DOM (basically the HTML) is loaded
document.addEventListener('DOMContentLoaded', function(){
    // Define your DOM elements
    var getAudioBtn = document.getElementById('getAudioBtn'),
        langSelect = document.getElementById("langSelect"),
        langSource = document.getElementById("langSource"),
        audioEl = document.getElementById('audioEl');

    // Setup an event listener on the button
    getAudioBtn.addEventListener('click', getContentTranslate);
    // Setup an listener on the audio onended event
    audioEl.addEventListener('ended', readChunkQueue);

    var chunkQueue = [], // Queue of chunks of text to read
        wordsPerChunk = 80, // Words per chunk
        language = 'en'; // Default language

    function getContentTranslate() {
        // Store the language
        language = langSelect.value;

        // Empty the chunks array
        chunkQueue = [];
        // Split the text into words
        var words = langSource.value.split(/ /g),
            tmp = []; // Temporary array for creating a chunk

        while(words.length) {
            // If out temporary chunk is full, add it to the list
            if (tmp.length === wordsPerChunk) {
                chunkQueue.push(tmp.join(' '));
                tmp = [];
            }
            tmp.push(words.shift());
        }
        if (tmp.length) {
            chunkQueue.push(tmp.join(' '));
        }

        // Start reading these chunks
        readChunkQueue();
    }

    function readChunkQueue() {
      // If the list is empty, stop
      if (!chunkQueue.length) {
        return;
      }
      // Get the first chunk in the list
      var chunk = chunkQueue.shift(),
          url = 'https://www.bing.com/tspeak?&format=audio%2Fmp3'
              + '&language=' + encodeURIComponent(language)
              + '&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2'
              + '&text=' + encodeURIComponent(chunk);
      // Set the URL as source for the audio element
      audioEl.setAttribute('src', url);
    }
});
<select id="langSelect">
  <option value="en">English</option>
  <option value="vi">Vietnamese</option>
</select>

<textarea id="langSource" placeholder="Enter text or webpage URL here">Obama Inaugural Address. 20th January 2009. My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition. Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents. So it has been. So it must be with this generation of Americans. That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet. These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights. Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics. We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.</textarea>

<button id="getAudioBtn">GET AUDIO</button>

<audio id="audioEl" autoplay controls></audio>


text:
Q: Can a JS function accept an argument object without any defined parameters? i.e. is there any way to accommodate an argument, e.g. the string, if a function is invoked like so: foo('str') while written like so:
function foo(){
  console.log(<the_argument>)
}
console.log(foo('str')) // <--- 'str'

A: You can use "arguments" keyword to get the arguments provided in foo('str'). For ex.
function foo(){
  var arg = arguments; // contains array of arguments provided
  console.log(arg[0]);
}
console.log(foo('str')); // prints "str"

A: You can use the arguments object to do the same:
    function foo() {
      if(arguments.length >0) {
         return arguments[0];
      }
    }
    console.log(foo('str'));

Additional info:
ES6 brings in Rest parameters & Spread syntax which help when working with functions

A: Arguments passed to a JS function can be retrieved by using the arguments array inside the function.
function func1(a, b, c) {
   console.log(arguments[0]);
   // expected output: 1

   console.log(arguments[1]);
   // expected output: 2

   console.log(arguments[2]);
   // expected output: 3
}

func1(1, 2, 3);

For more information please refer to the Mozilla documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

A: Yes there is. There is an implicit arguments local variable. It is iterable and can be used like an array (although it isn't an array) to access all the function's arguments without relying on any formal parameters.

function foo()
{
   for (i in arguments)
   {
  console.log(arguments[i]);
   }
}
foo('str','wasdf',9)

See Arguments object, for a more detailed definition.

A: Obviously not. You can check your self. If you are in angular side then you have something call DI and you can have service injected.
But you can do like make variable outside and access inside a function. If you see fit, you can test it.
Actually, you can do it, check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments


text:
Q: Javascript how to create an array of arrays Could somebody please help me to create an array of array.I have a matrix calculator and I want to create an array of arrays ('smaller').How can I do it?The functiions create2Darray and calculateDet are working ok,so now problem with them.Would be really grateful for the help.I need an array of these arrays (main matrix's minors) to calculate their determinants and calculate the inverted matrix
Here is the HTML:

Macierz odwrotna [3x3]

<form id = "row1">
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
 </form>
 <form id = "row2">
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
</form>
<form id = "row3">
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
</form>

Wylicz

Javascript
function invertMat(matrixClass) {
    var matrix = create2Darray(matrixClass);
    var det = calculateDet(matrix);
    //alert(det);
    var invMat = new Array();
    for (var i = 0; i < matrix.length; i++) {
        invMat[i] = new Array();
        for (var j = 0; j < matrix.length; j++) {
            invMat[i][j] = 0;
        }
    }
    if (matrix.length == 2) {
        invMat[0][0] = 1 / det * matrix[1][1];
        invMat[1][0] = 1 / det * (-matrix[1][0]);
        invMat[0][1] = 1 / det * (-matrix[0][1]);
        invMat[1][1] = 1 / det * matrix[0][0];
        alert(invMat);
    } else if (matrix.length == 3) {
        //var smaller = new Array();//creating an empty array for a matrix minor
        for (var i = 0; i < matrix.length; i++) {
            var smaller = new Array(matrix.length - 1);
            for (h = 0; h < smaller.length; h++) {
                smaller[h] = new Array(matrix.length - 1);
            }
            for (a = 1; a < matrix.length; a++) {
                for (b = 0; b < matrix.length; b++) {
                    if (b  i) {
                        smaller[a - 1][b - 1] = matrix[a][b];
                    }
                }
            }
        }
    }
}

A: Try Like this Fiddle
var array1 = new Array();

array1.push(1);
array1.push(2);

var array2 = new Array();

array2.push(3);
array2.push(4);

var array3 = new Array();
array3.push(array1);
array3.push(array2);

console.log(array3[0]);
console.log(array3[1]);

A: Live demo
function create2Array(d1, d2, fn) {
    var arr = [],
        d = function(x, y) {},
        f = fn || d;
    for (var i = 0; i < d1; i++) {
        for (var j = 0, curr = []; j < d2; j++) {
             curr[j] = f.call(window, i, j);
        };
        arr[i] = curr;
    };
    return arr;
};

function print2DArray(arr) {
    document.body.innerHTML += "
Array:
";
    for (var i = 0, len = arr.length; i< len; i++) {
        document.body.innerHTML += "
" + i + ": " + arr[i].join(" ") + "
";
    };
};

var matrix = create2Array(10, 10, function(x, y) { return 0;}),
    m2 = create2Array(10, 10, function(x, y) { return x + y;});
print2DArray(matrix);
print2DArray(m2);

Use it like this:
var matrix = create2Array(10, 10);

Or you can even specify a custom init function which takes the index as param.
Say if you want to init your matrix with 0 by default:
var matrix = create2Array(10, 10, function(x, y) { return 0;});


text:
Q: DateTime.ParseExact does not work as expected How should the input string format be in DateTime.ParseExact?
Just trying this out and I kept getting exception error:
DateTime value = DateTime.ParseExact("3/15/2019 06:30:23 PM", "M /d/yyyy hh:mm:ss tt", null);
//this works though..
string test = "3/15/2019 06:30:23 PM";
DateTime value = DateTime.ParseExact(test, "M /d/yyyy hh:mm:ss tt", null);

Aren't both the lines the same? How come one throws error?

A:
aren't both the lines the same? How come one throws error?

I see both lines throwing error saying String was not recognized as a valid DateTime. due to the space after M in "M /d/yyyy hh:mm:ss tt" in both lines.
Remove the space after the M from "M /d/yyyy hh:mm:ss tt" and then write as follows:
string test = "3/15/2019 06:30:23 PM";
DateTime value = DateTime.ParseExact(test, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);


text:
Q: Replace single file on tomcat-deployed war I'd like to know how to configure tomcat 6 in order to be able to replace a file from a war - for instance an image or a jsp - so I don't need to restart the server to keep it updated. I assume I'll have to deploy it as a directory - not just copying the war file to webapp ?
Thanks.

A: If you have access to the server you can explode the WAR to a separate directory (using jar -xf application.war) and then add the web-app to the Tomcat instance TOMCAT_ROOT/conf/Catalina/localhost directory.
For example - if your application were called "my-app" you would create a file within TOMCAT_ROOT/conf/Catalina/localhost/my-app.xml which contained details of the application. For a very simple application this might just be something like:
<Context docBase="/path/to/exploded/application/directory"/>

You might also have more complicated configuration (such as database connection parameters, etc.) within here.
If you then want to redeploy the application after you've changed an individual object (JSP, image, etc.) you can use the manager app to redeploy without having to restart the whole Tomcat environment.

A: You can deploy application by removing the *.war from the webpps directory.

$ rm -fr /var/lib/tomcat5/webapps/myapp.war

Also you can do that, if you connect to tomcat jmx manager http://server/manager/html, so select the application that you need to remove and click on deploy.

A: Yes, deploy a directory. You can also push a new .war file and Tomcat will do the right thing without the need for restarting Tomcat.
IIRC, you can modify files of an exploded war file, and it will work. But it will cause problems (the war will be reexploded on restart, for instance, and overwrite).


text:
Q: Look for the first "_" in a filename string I want to loop through a directory and group files by the filenames up until the first _ in the filename.
Files are structured by

Manager Name_Employee Name_Assessment.xlsx

I want this to group together strings up until the first underscore. I can't designate a character length because managers have different names.
I'm thinking changing the If Right(filename,4) statement should do what I want, but I can't specify a character limit.
Public Sub Move_Files()

Dim sourceFolder As String, fileName As String
Dim destinationFolder As String, foundDestinationFolder As String
Dim missingFolders As String

sourceFolder = "C:\Assessment\"
If Right(sourceFolder, 1) <> "\" Then sourceFolder = sourceFolder & "\"

'Loop through *.xls files in source folder

missingFolders = ""
fileName = Dir(sourceFolder & "*.xls")
While fileName <> vbNullString
    **If Right(fileName, 4) = ".xlsx" Then**
        destinationFolder = Left(fileName, InStrRev(fileName, ".") - 1)
        foundDestinationFolder = Find_Subfolder(sourceFolder, destinationFolder)
        If foundDestinationFolder <> "" Then
            Name sourceFolder & fileName As foundDestinationFolder & fileName
        Else
            missingFolders = missingFolders & vbCrLf & destinationFolder
        End If
    End If
    fileName = Dir
Wend

If missingFolders = "" Then
    MsgBox "All subfolders exist.  All files moved to their respective destination folder"
Else
    MsgBox "The following subfolders don't exist:" & vbCrLf & _
            missingFolders
End If

End Sub

After it identifies all that fit within that manager's name, I want to group only those manager's employee files into a folder with their name up until the first _.

A: *

*If the file extension is .xlsx, then change fileName = Dir(sourceFolder & "*.xls") to fileName = Dir(sourceFolder & "*.xlsx").

*Consider the InStr function, which "returns a Variant (Long) specifying the position of the first occurrence of one string within another."

*

*As is, destinationFolder = Left(fileName, InStrRev(fileName, ".") - 1) finds everything to the left of the last period.

*So if you want to the destination folder to be Manager Name, then perhaps destinationFolder = Left$(fileName, InStr(fileName, "_") - 1)

*Note that this can be made more robust to handle the possibility of no _ in the file name, or the file name beginning with _, with an initial If InStr(fileName, "_") > 1).


text:
Q: Assign edge pixels to lines of interest I am dealing with image processing using Matlab and my goal is to assign pixels to a characteristic line of an object.
In detail:
I take pictures of different metallic objects. I can distinguish the objects in 6 different classes. The classes are known to me only in "my brain", not in the computer. There is always one class in one picture. In the next step, I use color segmentation to distinguish my object from the background. After the segmentation, I use the Canny operator to find the edges of the object. So far, let's assume that there is no image "noise" and that the Canny operator determined the contour of the object. This is how far I have come so far.
Two different objects that give you an idea of the "characteristic lines"
In the next step, I want to assign the pixels to its "characteristic lines" which are colored in the given picture. Of course, they are not colored in the edge picture, where I only have the information that a pixel has the value "True" if it is an edge pixel or "false" if a pixel is background.
Do you guys know of an algorithm or method that can assign the edge pixels to "characteristic lines"?

A: Try using MatLab's corner() to break up the edge into sections
http://www.mathworks.com/help/images/ref/corner.html


text:
Q: Mongodb Async vs Sync Java driver I´m quite confused about java drivers for Mongodb. Reading the official documentation it seems that you can use the normal MondoDB Driver or the MongoDB Async Driver.
The first question is: Can I use both in the same application or I have to choose one?
Trying to use the Async driver I found things that I used to do (with the normal driver) in which I get a bit lost now. For example, I used to do this:
FindIterable<Document> iterable = db.getCollection("my_coll").find(query);
String json = JSON.serialize(iterable);

And now I really don´t know how to convert the result into a json string since they have not included the JSON class from the Async driver.
Second question: If I cannot use both drivers at the same time, how can I then serialize a FindIterable<Document>?

A: The answers are:

*

*Yes of course you can use both drivers. In fact, if you really care about performance in your application you should use the Sync driver for those actions that you need a response from MongoDB (like find()). And you will use the Async driver for the ones that you don't really need it, for "fire and forget" actions (like insert or update).

*So the serialization question gets answered from the above. If you get a response you are using the sync driver, therefore you can keep using JSON class:

JSON.serialize(iterable);

A: One thing to be conscious of is that the two drivers share some dependencies.
Try to align the versions of the drivers such that they are both expecting the same version of their common dependencies otherwise you can end up with some 'Class not found' type issues resulting from the class loader picking an incompatible version of a class for one or other of the drivers.
I'd add that the use-case I found the async driver great for was a large export style query, where I had to return a large amount of data from a web service. In this case I had to return a large CSV. Previously this method would use up a lot of RAM building up the whole set of CSV data up before writing it to the client. Using the async driver I could read small batches (500 records at a time seemed optimal) from MongoDB and write them to the browser client in a chunked response.


text:
Q: Indirect way of usine Model.objects.all() in a formset I'm using something like this to populate inlineformsets for an update view:
formset = inline_formsetfactory(Client, Groupe_esc, form=GroupEscForm, formset=BaseGroupEscInlineFormset, extra=len(Groupe.objects.all()))

(Basically I need as many extra form as there are entries in that table, for some special processing I'm doing in class BaseGroupEscInlineFormset(BaseInlineFormset)).
That all works fine, BUT if I pull my code & try to makemigrations in order to establish a brand new DB, that line apparently fails some django checks and throws up a "no such table (Groupe)" error and I cannot makemigrations. Commenting that line solves the issues (then I can uncomment it after making migration). But that's exactly best programming practices.
So I would need a way to achieve the same result (determine the extra number of forms based on the content of Groupe table)... but without triggering that django check that fails. I'm unsure if the answer is django-ic or pythonic.
E.g. perhaps I could so some python hack that allows me to specific the classname without actually importing Groupe, so I can do my_hacky_groupe_import.Objects.all(), and maybe that wouldn't trigger the error?
EDIT:
In forms.py:
from .models import Client, Groupe
class BaseGroupEscInlineFormset(BaseInlineFormSet):
    def get_form_kwargs(self, index):
        """ this BaseInlineFormset method returns kwargs provided to the form.
            in this case the kwargs are provided to the GroupEsForm constructor
        """
        kwargs = super().get_form_kwargs(index)
        try:
            group_details = kwargs['group_details'][index]
        except Exception as ex:                                    # likely this is a POST, but the data is already in the form
            group_details = []
        return {'group_details':group_details}

GroupeEscFormset = inlineformset_factory(Client, Groupe_esc,
                                         form=GroupeEscForm,
                                         formset=BaseGroupEscInlineFormset,
                                         extra=len(Groupe.objects.all()),
                                         can_delete=False)

A: The issue as already outlined is that your code is written at the module level and it executes a query when the migrations are not yet done, giving you an error.
One solution as I already pointed in the comment would be to write the line to create the formset class in a view, example:
def some_view(request):
    GroupeEscFormset = inlineformset_factory(
        Client,
        Groupe_esc,
        form=GroupeEscForm,
        formset=BaseGroupEscInlineFormset,
        extra=len(Groupe.objects.all()),
        can_delete=False
    )

Or if you want some optimization and want to keep this line at the module level to not keep recreating this formset class, you can override the __init__ method and accept extra as an argument (basically your indirect way to call Model.objects.all()):
class BaseGroupEscInlineFormset(BaseInlineFormSet):
    def __init__(self, *args, extra=3, **kwargs):
        self.extra = extra
        super().__init__(*args, **kwargs)
    ...

GroupeEscFormset = inlineformset_factory(Client, Groupe_esc,
                                         form=GroupeEscForm,
                                         formset=BaseGroupEscInlineFormset,
                                         can_delete=False)

# In your views:
def some_view(request):
    formset = GroupeEscFormset(..., extra=Groupe.objects.count()) # count is better if the queryset is needed only to get a count


text:
Q: How to get all the values of an enum with typescript? Given an a TypeScript enum:
export enum Color {
    Red,
    Green,
    Blue,
}

I want to get all its values in an array like so:
["Red", "Green", "Blue"]

Yet when I work on that enum with
const colors = Object.keys(Color);

I get weird array consisting of its index and value:
[ '0', '1', '2', 'Red', 'Green', 'Blue' ]

Why is this the case and how can I only get the values?

A: You have to filter out the numeric keys, either via Object.values or Object.keys:
const colors = Object.keys(Color).filter((item) => {
    return isNaN(Number(item));
});
console.log(colors.join("\n"));

This will print:
Red
Green
Blue

A TypeScript enum will transpile in the end into a plain JavaScript object:
{
  '0': 'Red',
  '1': 'Green',
  '2': 'Blue',
  Red: 0,
  Green: 1,
  Blue: 2
}

So you can use the numeric index as key to get the value, and you can use the value to lookup its index in the enum:
console.log(Color[0]); // "Red"
console.log(Color["0"]); // "Red"
console.log(Color["Red"]) // 0


text:
Q: What is the origin of the term confusion matrix? The confusion matrix is a fundamental term in machine learning.
However, that name itself is a bit, well, confusing.
I tried to trace its origin but I'm not sure I'm correct, and I'd like to hear what others know.
The term became popular in the ML community thanks to Kohavi and Provost at 1998.
However, already at 1971 Townsend wrote a paper discussing it.
The paper discusses and experiment in which the 26 English alphabet letters
(stimuli) are presented to a subject that should present reply with the same letter (reaction). The confusion is a 26 by 26 matrix with the probability of each reaction to each stimulus.
This explains the name (the matrix of the subject confusion) and matches the use in machine learning today.
I found even earlier references to the term confusion matrix, starting at 1953 using Google books, but the text wasn't available.
It seems that there are even earlier reference to the term in psychology since it is used as a known phrase.
Is the origin of confusion matrix indeed in psychology and due to such usage?
What else is known about the term?
References
(Kohavi & Provost, 1998) ⇒ Ron Kohavi, and Foster Provost. (1998). "Glossary of Terms." In: Machine Learning 30(2-3).
(Townsend, 1971) ⇒ J. T. Townsend. (1971). "Theoretical analysis of an alphabetic confusion matrix." In: Attention, Perception, & Psychophysics, 9(1).
1955
Journal of applied psychology, Volume 39
American Psychological Association, 1955
Реферативный журнал: Математика, Volume 2
Изд-во Академии наук СССР., 1953 - Mathematics

A: The question as I understand is not "where did the grid/matrix come from?" but rather "why is the term 'confusion' used?"  I think referring back to Pearson is not likely to help.
My sense, having learned the term in psychology, is that "confusion" refers to the intuition that an item can be correctly or incorrectly labeled/identified/detected and so on (i.e,. "confusion of labels").  Following this logic, I've understood the word "confusion" in this case to loosely refer to the idea:  did our classifier (or in the case of psychology, the observer) correctly identify the item, or "was it CONFUSED with another label"?  That's my best guess!

A: I think I understand the history of the term, thanks to an answer here: What is the origin of the term confusion matrix?
The confusion matrix was invented at 1904 by Karl Pearson. He used the term Contingency Table. It appeared at Karl Pearson, F.R.S. (1904). Mathematical contributions to the theory of evolution (PDF). Dulau and Co..
During War World 2, Detection Theory was developed as investigation of the relations between stimulus and responds.
The confusion matrix was used there.
Due to detection theory, the term was used in psychology.
From there the term reached machine learning.
It seems that though the concept was invented in statistics, a field very related to machine learning, it reached machine learning after a detour in during a period of 100 years.

A: What is odd to many veterans of data science is that what is now often called a confusion matrix has been called a classification matrix in the past.  Both have the same structure:  predicted outcomes in the columns and actual outcomes in the rows. I've always found the term classification matrix to be less confusing than confusion matrix, and I don't see any advantages to using the newer term.

A: It was called a "confusion matrix" by Miller and Nicely in 1955.  I don't know if this is the origin of the term "confusion matrix," but it might be.
G.A. Miller and P.E. Nicely, "Analysis of Perceptual Confusions Among Some English Consonants," Journal of the Acoustical Society of America 27:338-352, 1955


text:
Q: Character encoding problems with reading a csv file My csv file contains special characters like 'æ', 'å' etc. When I read and print the file, special characters in the file gets converted into '�'.
I tried setting page encodig to UTF-8 and ISO 8859-1. But none of these helped.
Could smb advice a solution?

A: I think you have to detect and change the original encoding as folows (if you are using php):
  <?php
        header( "Content-Type: text/html; charset=utf-8");
        $csvContent = file_get_contents( $fileName );
        $encoding = mb_detect_encoding( $csvContent,
                                        array("UTF-8","UTF-32","UTF-32BE","UTF-32LE","UTF-16","UTF-16BE","UTF-16LE"),
                                        TRUE );

        if( $fileEncoding !== "UTF-8" ) {
             $csvContent = mb_convert_encoding($csvContent, "UTF-8", $fileEncoding );
        }

        foreach( explode( PHP_EOL, $csvContent ) as $item ) {
           var_dump($item );
        }
 ?>


text:
Q: TYPO3 news (tx_news) ordering of records not working I'm running TYPO3 V6 and the latest version of tx_news (not tt_news) and when I attempt to change the order of sorting for the LIST display, the settings in the plugin are not overriding the Typoscript settings.  There doesn't seem to be a way to change to sort order of articles in the list view.  I am aware that flagging a news record as "top news" will float it to the top of the list, but none of my records have that flag set.
Has anyone else had this problem?

A: I got the same problem: My listview always showed the oldest news on the top. I've been searching for a solution for hours. As i wanted to start to change the extension files manually, I found the "setup.txt" in the configuration folder. From there I copied the following code into my Typoscript. The problem is solved now.
plugin.tx_news{
  settings{

    overrideFlexformSettingsIfEmpty = cropMaxCharacters,dateField,timeRestriction,orderBy,orderDirection,backPid,listPid,startingpoint,recursive
    orderBy = datetime
    orderDirection = desc
    orderByRespectTopNews = 0
    orderByAllowed = sorting,author,uid,title,teaser,author,tstamp,crdate,datetime,categories.title

    list{
      paginate {
        itemsPerPage=4
        insertBelow=TRUE
        lessPages=TRUE
        #forcedNumberOfLinks=3
        pagesBefore=1
        pagesAfter=1
      }
    }
  }
}

You can ignore the pagination lines. Important is the orderby stuff.
Typo3 Version: 4.7 (not my fault :D )
News System Version: 2.3

A: Found the solution to this one - basically I had been loading the TS setup code from an external file, which was overriding the default TS setup from the Typoscript template setup field, or rather, it wasn't.  I duplicated the TS code in the Typoscript template and the external file and finally it is being recognised and the fields can be sorted.


text:
Q: Planck's blackbody curve with "rainbow" in Tikz I am trying to transfer this image from here into Tikz.

Can you please help me with the "rainbow"?
As a starting point I found this code here:
\documentclass[border=3.14mm,tikz]{standalone}
\usepackage{siunitx}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
    \begin{tikzpicture}[samples=100, scale=1.15]
    \begin{axis}[
        xmin=0,
        xlabel={$\omega$ [\si{\hertz}]},
        ymin=0,
        ymax=pi,
        ylabel={$\rho (\omega; T)$ [\si{\joule\per\cubic\meter}]},
        ytick=\empty,
        no markers,
        grid=both,domain=0.1:40,
        style={ultra thick}]
    \pgfplotsinvokeforeach{3000, 4000, 5000}
    {
        \addplot+
        {(x^3)/((pi^2)*(exp(2000*x/(#1))-1))};
        \addlegendentryexpanded{$T = #1 [\si{\kelvin}]$}
    }
    \end{axis}
    \end{tikzpicture}
\end{document}

which produces this:

EDIT:
I found a related question regarding the rainbow with vertical shading here:
Can somebody make this fit to the code in the answers section?
\documentclass{article}
\usepackage[named]{xcolor}
\usepackage{pgffor}
\usepackage{tikz}
\usetikzlibrary{shadings}

\pgfdeclareverticalshading{rainbow}{100bp}
{color(0bp)=(red); color(25bp)=(red); color(35bp)=(yellow);
color(45bp)=(green); color(55bp)=(cyan); color(65bp)=(blue);
color(75bp)=(violet); color(100bp)=(violet)}
\begin{document}
\begin{tikzpicture}
\shade[shading=rainbow,shading angle=270] (0,0) rectangle (5cm,\textheight);
\end{tikzpicture}
\end{document}

producing:

Thank you for your help!

A: The fillbetween library might be helpful:
\documentclass[border=3.14mm,tikz]{standalone}
\usepackage{siunitx}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepgfplotslibrary{fillbetween}
\begin{document}
    \begin{tikzpicture}[samples=100, scale=1.15]
    \begin{axis}[
        xmin=0,
        xlabel={$\omega$ [\si{\hertz}]},
        ymin=0,
        ymax=pi,
        ylabel={$\rho (\omega; T)$ [\si{\joule\per\cubic\meter}]},
        ytick=\empty,
        no markers,
        grid=both,domain=0.1:40,
        style={ultra thick}]

       \addplot+ [forget plot,name path=A] {(x^3)/((pi^2)*(exp(2000*x/(5000))-1))};
       \addplot [forget plot,name path=B,samples=2] {0};
        \addplot [forget plot,blue] fill between [of=A and B,soft clip={domain=5:6}];
        \addplot [forget plot,green] fill between [of=A and B,soft clip={domain=6:7}];
        \addplot [forget plot,yellow] fill between [of=A and B,soft clip={domain=7:8}];
        \addplot [forget plot,orange] fill between [of=A and B,soft clip={domain=8:9}];
        \addplot [forget plot,red] fill between [of=A and B,soft clip={domain=9:10}];

    \pgfplotsinvokeforeach{3000, 4000, 5000}
    {
        \addplot+
        {(x^3)/((pi^2)*(exp(2000*x/(#1))-1))};
        \addlegendentryexpanded{$T = #1 [\si{\kelvin}]$}
    }

    \end{axis}
    \end{tikzpicture}
\end{document}

A: fillbetween isn't really necessary, \closedcycle appended to the end of an \addplot lets you fill the area below a plot. Obviously you'll need to decide on better colours and domains for the filled regions, but as an example:
\documentclass[border=3.14mm,tikz]{standalone}
\usepackage{siunitx}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
    \begin{tikzpicture}[
      samples=100,
      declare function={
        planck(\x,\T)=(\x^3)/((pi^2)*(exp(2000*\x/(\T))-1));
      }]
    \begin{axis}[
        xmin=0,
        xlabel={$\omega$ [\si{\hertz}]},
        ymin=0,
        ymax=pi,
        ylabel={$\rho (\omega; T)$ [\si{\joule\per\cubic\meter}]},
        ytick=\empty,
        no markers,
        grid=both,domain=0.1:40,
        style={ultra thick}]

    \begin{scope}[every axis plot/.append style={forget plot, draw=none, fill}]
      \addplot [blue, domain=5:6] {planck(x,5000)} \closedcycle;
      \addplot [green, domain=6:7] {planck(x,5000)} \closedcycle;
      \addplot [red, domain=7:8] {planck(x,5000)} \closedcycle;
    \end{scope}
    \pgfplotsinvokeforeach{3000, 4000, 5000}
    {
        \addplot {planck(x,#1)};
        \addlegendentryexpanded{$T = #1 [\si{\kelvin}]$}
    }

    \end{axis}
    \end{tikzpicture}
\end{document}


text:
Q: Jetpack compose Canvas blendmode not working as expected I'm attempting to apply blend mode to two shapes within Jetpack compose's canvas. Based on this blog I know roughly what the expected output should look like though I am not getting similar results.
For example, with the following simple Box + Canvas with two shapes, with the blend mode SrcIn
Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier.size(290.dp)
        ) {
            val sizeInPx = with(LocalDensity.current) { 150.dp.toPx() }

            Canvas(
                modifier = Modifier.fillMaxSize()
            ) {
                    drawCircle(
                        color = Color.Red,
                        radius = sizeInPx,
                    )

                    drawRect(
                        color = Color.Blue,
                        size = Size(sizeInPx, sizeInPx),
                        blendMode = BlendMode.SrcIn
                    )

            }
}

I would expect a red circle, and a blue square clipped to the shape of the red circle. Yet the output UI is as if no blend mode has been added at all
What am I doing wrong?

A: Changing alpha less then 1f creates a layer as buffer that's why it works. Other way of achieving this is to use layer directly if you don't want to change alpha. You can see my answere about it here
Canvas(modifier = canvasModifier) {

    val canvasWidth = size.width.roundToInt()
    val canvasHeight = size.height.roundToInt()

    with(drawContext.canvas.nativeCanvas) {
        val checkPoint = saveLayer(null, null)

        drawCircle(
              color = Color.Red,
              radius = sizeInPx,
        )

        drawRect(
            color = Color.Blue,
            size = Size(sizeInPx, sizeInPx),
            blendMode = BlendMode.SrcIn
        )
        restoreToCount(checkPoint)
    }
}

In painter code Android team uses it as
private fun configureAlpha(alpha: Float) {
    if (this.alpha != alpha) {
        val consumed = applyAlpha(alpha)
        if (!consumed) {
            if (alpha == DefaultAlpha) {
                // Only update the paint parameter if we had it allocated before
                layerPaint?.alpha = alpha
                useLayer = false
            } else {
                obtainPaint().alpha = alpha
                useLayer = true
            }
        }
        this.alpha = alpha
    }
}

And check alpha to apply layer
  fun DrawScope.draw(
        size: Size,
        alpha: Float = DefaultAlpha,
        colorFilter: ColorFilter? = null
    ) {
        configureAlpha(alpha)
        configureColorFilter(colorFilter)
        configureLayoutDirection(layoutDirection)

        // b/156512437 to expose saveLayer on DrawScope
        inset(
            left = 0.0f,
            top = 0.0f,
            right = this.size.width - size.width,
            bottom = this.size.height - size.height
        ) {

            if (alpha > 0.0f && size.width > 0 && size.height > 0) {
                if (useLayer) {
                    val layerRect = Rect(Offset.Zero, Size(size.width, size.height))
                    // TODO (b/154550724) njawad replace with RenderNode/Layer API usage
                    drawIntoCanvas { canvas ->
                        canvas.withSaveLayer(layerRect, obtainPaint()) {
                            onDraw()
                        }
                    }
                } else {
                    onDraw()
                }
            }
        }
    }
}


text:
Q: Decompose a Python string into its characters I want to break a Python string into its characters.
sequenceOfAlphabets = list( string.uppercase )

works.
However, why does not
sequenceOfAlphabets = re.split( '.', string.uppercase )

work?
All I get are empty, albeit expected count of elements

A: The '.' matches every character and re.split returns everything that wasn't matched, that's why you're getting the empty list.
Using list is usually the way to handle something like this but if you want to use regular expressions just use re.findall
sequenceOfAlphabets = re.findall( '.', string.uppercase )

That should give you ['A', 'B', 'C', .... ,'Z']

A: Because the delimiter character used by split does not appear in the resulting list.  This allows it be used like:
re.split(',', "foo,bar,baz")
['foo', 'bar', 'baz']

Also, you will find the resulting list from your split code actually contains one extra element, since split returns one more than the number of delimiters found.  The above has two commas, so it returns a three-element list.

A: If you can do something with both a built-in function and with regexes, then usually the built-in approach will be faster and more legible.
The regex world is a maze of twisty little passages, populated by purveyors of almost-truths like """The '.' matches every character""" ... which it does, but only when you use the re.DOTALL flag. This information is not cunningly concealed in the fine print of the documentation; it's right there as the FIRST entry of "special characters":
'.'
(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.
>>> import re
>>> re.findall(".", "fu\nbar")
['f', 'u', 'b', 'a', 'r']
>>>

A: Just an FYI, this also works:
sequenceOfAlphabets = [a for a in string.uppercase]

...but that does exactly what list() would do so I don't think it would be any faster (I could be wrong).

A: You can also create an empty set and use the update method, like so:
destroy_string = set()
destroy_string.update('Stack Overflow')
destroy_string
{'k', ' ', 'S', 'c', 'v', 'o', 'r', 't', 'w', 'e', 'f', 'O', 'l', 'a'}

Albeit, it will become unordered and the duplicates will be lost in the set, however, this is still a valid way to decompose a string into a set of its individual members.

A: From the documentation:

If capturing parentheses are used in
  pattern, then the text of all groups
  in the pattern are also returned as
  part of the resulting list.

Also note:

If there are capturing groups in the
  separator and it matches at the start
  of the string, the result will start
  with an empty string. The same holds
  for the end of the string.

So, use re.split( '(.)', string.uppercase)[1:-1] instead.


text:
Q: Is it possible to use augmented reality indoors without GPS Im thinking of developing augmented reality app for my school library. Basically we alreayd have a machine which will give us the duis decimal code for where the book is but the librarian still has to tell us where this is. An augmented reality application on top of this to who people where the book is might work well I think.
Just wondering how difficult it is to do such a thing without GPS as its indoors.
Intel had a good solution http://www.youtube.com/watch?v=WciFx66ojA4 but is it a viable app to make?

A: The IMHO easiest way would be to place some WLAN senders in the library and the use them to calculate the position based the signal strength of all WLAN senders in reception range.
There are a couple of scientific papers and demo-installations available around the world:
http://scholar.google.com/scholar?q=indoor+localization+wlan

A: If you haven't worked much with Android before, specifically with capturing and overlaying its video stream data I would say that creating an augmented reality application would be very difficult. I worked on a project capturing and analyzing live video streams through android for on-device analysis and found it significantly challenging.
If you're looking for an alternative I would suggest a static mapping application that showed a blueprint-like layout of the library, your current location at the terminal that provides the Dewey Decimal listing, and the calculated location of the book they just looked up. You can even add a section about the Dewey Decimal classification system and become your librarian's best friend.
If you really want to go for live navigation indoors your best bet may be through a combination of the compass and accelerometer data so you can infer direction and distance as a user moves through the environment. There are some good papers around in regard to this but you may need to go through the IEEE or ACM libraries to look them up.


text:
Q: props.array.map is not a function I have a few components that are to render dynamically based on values passed through props. My main component(1) is dynamically creating its subcomponents(2) and passing values into those components via props. Each component(2) created is then supposed to utilize the values in props to create new subcomponents(3) of this component.
The problem arises when I try to map the object array passed as props in component 2. Component 1 successfully creates components 2, but component 2 displays the error "this.props.section.map is not a function". I'm using the exact code from component one, the only difference is I am referencing the array via props.
this.state = {
  menuSections: [
    {
      id: 1, title: 'Starters', menuItem: [{
        id: 1,
        name: 'Meatball',
        description: 'Large Meatball',
        price: '11 meatballs'
      }]
    },
    {
      id: 2, title: 'Starters', menuItem: [{
        id: 2,
        name: 'Meatball',
        description: 'Large Meatball',
        price: '11 meatballs'
      }]
    },
    {
      id: 3, title: 'Starters', menuItem: [{
        id: 3,
        name: 'Meatball',
        description: 'Large Meatball',
        price: '11 meatballs'
      }]
    },
  ],

{this.state.menuSections.map(menuSection => (<MenuSection
  section={menuSection} mobileMode={this.state.mobileMode} />))}

This is the code from my App component, which works like a charm. the code for my 2nd component (MenuSection) is where the problem arises.
{this.props.section.map((itemContainer, i) => (<ItemContainer styles={styles}
  image={imageFood1} title={itemContainer.menuItem[i].name}
  description={itemContainer.menuItem[i].description}
  price={itemContainer.menuItem[i].price} />))}

Ideally, the section.map function in the 2nd component will render each individual menu item based on the props passed from the Main app. Instead, I receive the error "this.props.section.map is not a function".
edit: I know variations of this question have been asked before, but I have tried numerous suggestions, none of which have worked.

A: this.props.section is going to be an Object like :
{
    id: 1, title: 'Starters', menuItem: [{
    id: 1,
    name: 'Meatball',
    description: 'Large Meatball',
    price: '11 meatballs'
    }]
}

So you can't .map it  ,
either you pass the array :
{
    this.state.menuSections.map(menuSection => (
        <MenuSection
            section={menuSection.menuItem}
            id={menuSection.id}
            title={menuSection}
            mobileMode={this.state.mobileMode}
        />
    ))
}

Or, you map the array inside :
{
    this.props.section.menuItem.map((itemContainer, i) => (
        <ItemContainer
            styles={styles}
            image={imageFood1} title={itemContainer.menuItem[i].name}
            description={itemContainer.menuItem[i].description}
            price={itemContainer.menuItem[i].price}
        />
    ))
}

A: Section is an Object.
this.props.section.menuItem.map()


text:
Q: Custom Meteor autoform template I have nested schemas. Using {{> afQuickField name='work_item' template="myTemplate"}} outputs the inputs in a very logical way, but for some of my more complex objects this isn't terribly practical. I'd like to set up a template where I can precisely place each input with some other html.
These are also (usually) arrays of objects, so the .autoform-add-item and .autoform-remove-item button functionality is very nice and I would like to keep it.
How would I define custom templates for particular nested schemas and call them in my main form?
Have tried
Creating a <template name="afWorkItem_myTemplate"> named like my custom form templates extrapolated from the bootstrap3 form templates. I then try to call it like {{> afWorkItem name='work_item' template="myTemplate"}} but that did not work at all.
update
I tried to modify my custom afArrayField template to output different structures based on arrayFieldName. This seemed a little closer but still no cigar.
Template.afArrayField_autoupdate.helpers({
  whichTemplate: function(templateName){
    return this.arrayFieldName === templateName;
  }
});

Then in afArrayField_autoupdate template:
{{#if whichTemplate 'address'}}
  {{> afQuickField name=this.current.street options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}

  {{> afQuickField name=this.current.city options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}
  {{> afQuickField name=this.current.state_id options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}
  {{> afQuickField name=this.current.zip options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}

  {{> afQuickField name=this.current.address_type_id options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}
  {{> afQuickField name=this.current.active_address options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}
{{else}}
  {{> afQuickField name=this.name label=false options=afOptionsFromSchema template="autoupdate" placeholder="schemaLabel"}}
{{/if}}

Which came very close but all of my fields (including ones that are selects if I simply use the afQuickField method in the else block) came out as text inputs.

A: If you're trying to add a custom afWorkItem input type, you'll have to call AutoForm.addInputType to let AutoForm know about it. Not sure what you meant exactly by the template not working at all, but this might be a reason. There are plenty of examples in the form of the built-in input types.


text:
Q: How do I spy on a method from a sealed library class? I have an analytics client that has a track method getting invoked when an event is received.
When I go to mock the class I get this:
 Type to mock must be an interface or an abstract or non-sealed class.

Is there any way to spy on and verify parameters passed to a sealed class method?
in JUnit you can more freely do a "spyOn(class.method)..."
How can this be done in C# or with Moq?
Code looks like:
  private readonly TelemetryClient _telemetry;

    public ClassToTest(TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

 public async Task ProcessMessageAsync(EventMessage message, CancellationToken cancelToken)
    {
        try
        {
            var serviceNotificationEvent = JsonConvert.DeserializeObject<ServiceNotificationEvent>(message.Value);
            _telemetry.TrackEvent(AnalyticsConstants.EVENT_RECEIVED);

        }
        catch (Exception e)
        {
            _logger.LogError(e, "Error processing event message");
        }
    }

Current Unit test attempt:
    [TestMethod]
    public void Test_ReceivedEventAnalytic()
    {
        Mock<TelemetryClient> _mockTelemetry = new Mock<TelemetryClient>();

        _serviceNotificationProcessor.ProcessMessagesAsync(mockMessageList);
        IDictionary<String, String> matchingMap = new Dictionary<string, string>();
       // build out matchingMap

        _mockTelemetry.Verify(t => t.TrackEvent("seamEventReceived", It.IsAny<IDictionary<string, string>>(), null), Times.Once());
    }


text:
Q: Sending value through Jquery is showing null I am working on MVC3 and trying to pass values form view to controller using JQuery and JSON. The query is extracting values of checkboxes inside a grid. Following is the code
<script type="text/javascript">
function DeleteCustomer() {
    if (confirm("Are you sure to delete records")) {
        $('#myGrid table tr').each(function () {
            if ($(this).find("input[id*='assignChkBx']").length > 0) {
                if ($(this).find("input[id*='assignChkBx']")[0].checked == true) {
                    //var CustID = $(this).find("input[id*='assignChkBx']").attr("CustomerID");
                    var id = $(this).find("input[id*='assignChkBx']").val();
                    var DTO = JSON.stringify(id);
                    alert(DTO); **//Showing right value**
                    var temp = $(this);
                    $.ajax({
                        url: "Customer/DeleteCustomeByID",
                        type: "POST",
                        dataType: "json",
                        data: DTO,
                        contentType: 'application/json',
                        success: function (data) {
                            alert('Success');
                        },
                        error: function (xhr, textStatus, err) {
                            alert('Error :(' + err);
                        }
                    });
                }
            }
        });
    }
}

Above 'DTO' is checkbox value which is giving right value.
Below is my html
        <input type="button"  id="btnDelete" value="Delete" title="Delete" onclick="DeleteCustomer()" style="color:steelblue"/>

<div id="myGrid" style="width:100%">

@*@Html.Partial("_grid", Model)*@
@{
    WebGrid grid = new WebGrid(Model, rowsPerPage: 15, ajaxUpdateContainerId: "myGrid");
}
@grid.GetHtml(
        //htmlAttributes: new { id = "myGrid1" },
    fillEmptyRows: false,
    alternatingRowStyle: "alternate-row",
    headerStyle: "grid-header",
    footerStyle: "grid-footer",
    mode: WebGridPagerModes.All,
    firstText: "<< First",
    previousText: "< Prev",
    nextText: "Next >",
    lastText: "Last >>",
    columns: new[] {
        grid.Column(header: "", format: @<text><input class="check-box" type="checkbox" id="assignChkBx" value="@item.CustomerID" /></text>),
        //grid.Column(header: "", format: @<text>@Html.CheckBox("assignChkBx") </text>),
        grid.Column("CustomerID", "CustomerID", canSort: true, style: "CustomerID"),
        grid.Column("CompanyName", "Company Name", canSort: true, style: "CompanyName"),
        grid.Column("ContactName", "Contact Name", canSort: true, style: "ContactName"),
        grid.Column("Address", "Address", canSort: false, style: "Address"),
        grid.Column("City", "City", canSort: true, style: "City"),

       grid.Column("",
                    header: "Actions",
                    format: @<text>
                                @Html.ActionLink("Edit",   "Edit",   new { id=item.CustomerID} )
                                @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID} )
                            </text>
        )

})

Problem occurs when I  passing the value from view to controller. Please view the following code:
        //Delete multiple Customers by CustomeByID
    [HttpPost]
    public ActionResult DeleteCustomeByID(string DTO)
    {
        try
        {
            // delete the record from ID
            Customer customer = db.Customers.Find(DTO);
            db.Customers.Remove(customer);
            db.SaveChanges();
            return RedirectToAction("Index");

            //return View(customer);
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                        validationErrors.Entry.Entity.GetType().FullName,
                        validationError.PropertyName,
                        validationError.ErrorMessage);
                }
            }

            throw new Exception();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

Here two errors have been occurring.
i. The variable DTO is shwing  'null'
ii. When 'db.Customers.Remove(customer);' statement executes I am getting following error.
Value cannot be null.
Parameter name: entity
I can not understand why those errors are occurring. Remove statement is working perfectly when parameters are passing without JQuery.
I am using Northwing database.
Thanks

A: <script type="text/javascript">
function DeleteCustomer() {
if (confirm("Are you sure to delete records")) {
    $('#myGrid table tr').each(function () {
        if ($(this).find("input[id*='assignChkBx']").length > 0) {
            if ($(this).find("input[id*='assignChkBx']")[0].checked == true) {
                //var CustID = $(this).find("input[id*='assignChkBx']").attr("CustomerID");
                var id = $(this).find("input[id*='assignChkBx']").val();
                id="{'DTO':'+ id +'}" **//This is change**
                var DTO = JSON.stringify(id);
                alert(DTO); **//Showing right value**
                var temp = $(this);
                $.ajax({
                    url: "Customer/DeleteCustomeByID",
                    type: "POST",
                    dataType: "json",
                    data: DTO,
                    contentType: 'application/json',
                    success: function (data) {
                        alert('Success');
                    },
                    error: function (xhr, textStatus, err) {
                        alert('Error :(' + err);
                    }
                });
            }
        }
    });
}

}
Just check my code
id="{'DTO':'+ id +'}" //This is change


text:
Q: Android listview onclicklistener activity I want that if I click in the listview on 'Leerlingenraad' that he opens the class Leerlingenraad with leerlingenraad.xml and if I click on Contact that he opens the class Contact with contact.xml I have found a lot of topics of this but it won't work. Does anyone know what's wrong in my script? Please don't rate this down.
Myclass.java:
package com.example.myapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem.*;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import android.text.Editable;
import android.widget.AdapterView.OnItemClickListener;
import android.text.TextWatcher;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.view.ViewGroup;
import android.widget.Toast;

public class Myclass extends Activity {

// List view
private ListView lv;

// Listview Adapter
ArrayAdapter<String> adapter;

// Search EditText
EditText inputSearch;

// ArrayList for Listview
ArrayList<HashMap<String, String>> onderneming;

/**
 * Called when the activity is first created.
*/

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.myclass);

String onderneming[] = {"Leerlingenraad", "Medezeggenschapsraad", "3", "4", "5", "6", "Contact"};

lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, onderneming);
lv.setAdapter(adapter);

/**
 * Enabling Search Filter
 * */
inputSearch.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

// When user changed the Text
Ondernemerschap.this.adapter.getFilter().filter(cs);

}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable arg0) {
}
});

lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,

final int position, long id) {

String main = lv.getSelectedItem().toString();

}
});
}
private ListView getListView() {
return null;

}
}

myclass.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/pallasrood"
android:orientation="vertical" >

<ImageView

android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/android" />

<EditText android:id="@+id/inputSearch"

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"android:hint="Zoek de onderneming.."
android:inputType="textVisiblePassword"/>

<ListView

android:id="@+id/list_view"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="@+id/inputSearch"
android:background="@android:color/transparent"
android:cacheColorHint="@android:color/transparent" >

</ListView>

</RelativeLayout>

Androidmanifest.xml
<activity android:name=".Leerlingenraad"
android:label="Pallasapp">
</activity>

A: I assume you already have your detail activity, which I called OndernemingDetailActivity
In your ListView activity:
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            Intent in = new Intent(this, OndernemingDetailActivity.class);
            //Send onderneming
            in.putExtra("selected_onderneming", adapter.getItem(i));
            startActivity(in);
        }
    });

Then in your detail view you'd get the "selected_onderneming" from the bundle like so:
String selectedOnderneming;
Bundle extras = intent.getExtras();
    if(extras != null)
        onderneming = extras.getString("selected_onderneming"); // retrieve the selected onderneming

This is the quickest way to get the extras out of the bundle. Check out this post for a more robust and safe way to do so.
You can then show the data you need of the 'selected onderneming'. I hope this answers your question.