text:
Q: MySQL, count distict elements across months I have SELECT to count distict elements across months. But if few elements have the same name and are in different months then DISTINCT works in each month separetely
SELECT
    YEAR( `date` ) AS "year",
    MONTH( `date` ) AS "month",
    count( DISTINCT name ) AS "howmany"
FROM
    `XYZ`
GROUP BY
    name,
    year,
    month
ORDER BY
    `date` DESC

Data:
_________________________
|01-01-2018  |  name1    |
|01-02-2018  |  name1    |

Returns:
2018  |  01  |   1
2018  |  02  |   1

and I want:
2018  |  02  |   2

Is it possible? How to fix query?

A: I'm on Oracle here, don't have a MySQL handy, so you'll have to adapt the query, but I hope you get the idea:
select XYZ.d, XYZ.name, a.howmany
from XYZ
join (select name, count(name) as howmany from XYZ group by name ) a
on XYZ.name = a.name


text:
Q: MySQL - archiving data in tables I am a developer for an insurance app. We are using AWS RDS with a MySQL implementation. The scenario we would want is to automatically archive data from one table to another. Something like this:
Let's say you have a table called user_profile. You want to record a history of the changes of each user profile in another table, let's say we call it user_profile_history. Is it possible in RDS to do real time porting from the main user_profile table to its history table, whenever updates are done to the main table?
End scenario would be, user_profile table only contain the latest user data. All other past snapshots of profile are in the history table.
I did my due diligence and did a little bit of research and there are possible options to do this:

*

*MySql Event scheduler

*Cron Job

*Partitioning

My question is, which do you think would be best suited specifically for this scenario? or are there other better ones that I have missed? Currently records in the main table are in the millions (15M approximately) with about 5k records added each day. That is why we decided to have a separate history/archive table to it, to be able to transfer some of the old stale data to a separate table.

A: I think triggers is your best option as mustaccio mentioned.
There are multiple options:
Create a BEFORE INSERT Trigger
Create an AFTER INSERT Trigger
Create a BEFORE UPDATE Trigger
Create an AFTER UPDATE Trigger
Create a BEFORE DELETE Trigger
Create an AFTER DELETE Trigger
Select the one you want, or all :D, you can control it all.
See also this tutorial:
https://www.mysqltutorial.org/mysql-triggers

A: I prefer to do it when initially storing the data.  Two tables:
History contains all the data, including what was just now received.  Example: all your bank statements on a single list.
Current contains the information as of now.  Example: your current balance.
The History contains all the data necessary to reconstruct what is in Current.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read a stream from Azure File Store using Filehelpers I'm trying to read a csv file from Azure File Store using FileHelpers. How does this work?
I can connect to the azure file store and build a reference to te file. This is done by looping through the directories and files, in this example these are named subdirectory and filename.
Code:
//connect to storage account
CloudStorageAccount storageAccount = new CloudStorageAccount("link to account and credentials");
//connect to file client
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
//create cloudfileshare to in process
CloudFileShare inprocessShare = fileClient.GetShareReference("inprocess");
//get reference to root directory of inprocess share
CloudFileDirectory inprocessRootDir = inprocessShare.GetRootDirectoryReference();
//get reference to the subdirectory
CloudFileDirectory inprocessDir = inprocessRootDir.GetDirectoryReference(subdirectory);
//get reference to the current file
CloudFile destfile = inprocessDir.GetFileReference(filename);

This works to get a reference to the file that I want to process.
When I use StreamReader I can use the following code and this works:
\\open stream
System.IO.Stream filepath = destfile.OpenRead()
\\read the file
System.IO.StreamReader file = new System.IO.StreamReader(filepath)

But I want to use FileHelpers, I've tried the following:
\\create async filehelper
FileHelperAsyncEngine fhe = new FileHelperAsyncEngine<MyType>();
using (fhe.BeginReadFile(filepath))

This gives the error that it only accepts a string as input. When I put in a reference to a local file like "C:\inprocess\filename.csv" it works. When I put the complete URL to the file I get the error that the connection cannot be parsed. I've also tried to map the Azure File Share to a local driveletter. This works, but I want it to be a cloud app and since it does work for StreamReader I think it should also work for FileHelpers.

A: You must use the BeginReadStream of the FileHelperAsyncEngine
It uses a TextReader so you need to do something like
TextReader tr = new StreamReader(destfile.OpenRead());

using (fhe.BeginReadStream(tr))
{
   foreach(var record in fhe)
   {
   ...
   }
}


text:
Q: How do I get text bounding box drawn with pgmagick I successfully draw some text on an image by pgmagick:
from pgmagick.api import Image
img = Image((300, 200))
img.annotate('Hello World')
img.write('helloworld.png')

but how to get the bounding box of text? Anyone can help me?

A: I don't know anything about pgmagick but maybe it will help if I show you a couple of things you can do at the command line with ImageMagick.
Option 1
Use label to create a canvas just big enough for the desired text and then ask ImageMagick how big that canvas's geometry is:
convert label:"Hello world" -format %G info:
62x15

So, "Hello world" in the default font size is 62 pixels wide and 15 pixels high.
Option 2
Or, use -annotate as you did, and then ask ImageMagick how big that would be if you trimmed the excess space around it:
convert -size 300x200 xc:red -annotate +10+20 "Hello world" -format %@ info:
61x8+10+12

Option 3
Create the canvas and annotate it, then trim it and get the size:
convert -size 300x200 xc:red -annotate +10+20 "Hello world" -trim info:
xc:red XC 61x8 300x200+10+12 16-bit sRGB 0.000u 0:00.000

Option 4
Create canvas, annotate, trim, save and then get dimensions of result:
convert -size 300x200 xc:red -annotate +10+20 "Hello world" -trim result.png

identify result.png
result.png PNG 61x8 300x200+10+12 16-bit sRGB 887B 0.000u 0:00.000

Maybe (hopefully) you can adapt one of these to pgmagick.


text:
Q: Prevent Bootstrap Button Invisible Width/Prevent New Line I have two Bootstrap button dropdown menus.  How to I prevent the menus from wrapping to two lines?  I can control the width of the menus with span classes, but the code acts as if there's still more invisible input field which forces the next drop-down menu to the next line.  The even more core problem is that these dropdown inputs force a fixed amount of space between them in the next element to their right, regardless of their actual width.
Ultimately, I want them to behave similarly to input buttons, which align right next to each other.  See screenshot.

        <input type="text" class="input-small" placeholder="Eye Color">
        <input type="text" class="input-mini" placeholder="Hair">

                <button class="btn dropdown-toggle" data-toggle="dropdown">

                </button>

                        aa

                        aa

                        aa

            <input class="span4" id="prependedDropdownButton" type="text"  placeholder="Hair">

                <button class="btn dropdown-toggle" data-toggle="dropdown">

                </button>

                        mm

                        mm

                        mm

            <input class="span4" id="prependedDropdownButton" type="text"  placeholder="Hair">

A: After more reading on the Bootstrap documentation and testing I notice that those kind of dropdowns that you want to use suck, they are not responsive. I think you are better off using <select> dropdowns.
Demo
http://jsfiddle.net/sulfureous/X8hdg/
HTML

        <input type="text" class="span12" placeholder="Eye Color">

        <input type="text" class="span12" placeholder="Hair">

        <select class="span12">
          <option>Hair</option>
          <option>Black</option>
          <option>Blonde</option>
        </select>

        <select class="span12">
          <option>Race</option>
          <option>Race 01</option>
          <option>Race 02</option>
        </select>

So I guess this is an alternate solution, I cleaned up the code indentation, commenting and what not and divided the spans in a way that I feel would make sense for that kind of responsive menu.
Notice I added clearfix, removed the inline style and the height.
Let me know if this solution is what you expected, otherwise with the other kind of dropdown you want you use it's doable but you will need to hack quite a bit, if it was easy the guys at Twitter Bootstrap would have made that element responsive from the get go.
Cheers.


text:
Q: overflow with left shift I have a simple program where I have a few macros for bit manipulation.
One of the macro translates to following
unsigned long val = 1 << 0x1f;

Here, I am getting output as `
val = 0xffffffff80000000;

I understand it is some kind of int overflow. I am confused about the part about the final result. Why is the result coming out to be the one I am getting?
(I do understand here for some reason 1 is treated as int and when left shift is making it a negative int. But the part I am confused about the type casting.)

A: 1 is a signed integer, so in case of overflow it is undefined behavior.
According to the standard (emphasis mine):

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with
  zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo
  one more than the maximum value representable in the result type. If E1 has a signed
  type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is
  the resulting value; otherwise, the behavior is undefined.

Instead, try unsigned long value 1ul:
unsigned long val = 1ul << 0x1f

(I do understand here for some reason 1 is treated as int and when left shift is making it a negative int. But the part I am confused about the type casting.)

It could happen in practice indeed, if the sign bit gets set to 1. (But, once again, according to the standard it is UB.)
Nevertheless, let's consider a legal case (I used short and int since int and long have the same size on my system):
                        // on my system
short int s = SHRT_MIN; // 0x8000
unsigned int i = s;     // 0xffff8000

The following part of the standard clarifies it:

6.3.1.3 Signed and unsigned integers
When a value with integer type is converted to another integer type other than _Bool, if
  the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or
  subtracting one more than the maximum value that can be represented in the new type
  until the value is in the range of the new type

(If I interpret it right) since we cannot represent a negative value in unsigned type, we add UINT_MAX + 1 to SHRT_MIN (in pure mathematical terms, without considering overflow):
UINT_MAX + 1 + SHRT_MIN // 0xffff8000


text:
Q: Python - Iter through identified component features I am standing in front of a huge problem. Using the python libraries NumPy and SciPy, I identified several features in large array. For this purpose, I created a 3x3 neighbor structure and used it for a connected component analysis --> see docs.
struct = scipy.ndimage.generate_binary_structure(2,2)
labeled_array, num_features = ndimage.label(array,struct)

My problem now is that I want to iterate through all identified features in a loop. Someone has an idea how to address individual features in the resulting NumPy array?

A: Here's an example of handling features identified by ndimage.label.  Whether this helps you or not depends on what you want to do with the features.
import numpy as np
import scipy.ndimage as ndi
import matplotlib.pyplot as plt

# Make a small array for the demonstration.
# The ndimage.label() function treats 0 as the "background".
a = np.zeros((16, 16), dtype=int)
a[:6, :8] = 1
a[9:, :5] = 1
a[8:, 13:] = 2
a[5:13, 6:12] = 3

struct = ndi.generate_binary_structure(2, 2)
lbl, n = ndi.label(a, struct)

# Plot the original array.
plt.figure(figsize=(11, 4))
plt.subplot(1, n + 1, 1)
plt.imshow(a, interpolation='nearest')
plt.title("Original")
plt.axis('off')

# Plot the isolated features found by label().
for i in range(1, n + 1):
    # Make an array of zeros the same shape as `a`.
    feature = np.zeros_like(a, dtype=int)

    # Set the elements that are part of feature i to 1.
    # Feature i consists of elements in `lbl` where the value is i.
    # This statement uses numpy's "fancy indexing" to set the corresponding
    # elements of `feature` to 1.
    feature[lbl == i] = 1

    # Make an image plot of the feature.
    plt.subplot(1, n + 1, i + 1)
    plt.imshow(feature, interpolation='nearest', cmap=plt.cm.copper)
    plt.title("Feature {:d}".format(i))
    plt.axis('off')

plt.show()

Here's the image generated by the script:

A: Just a quick note on an alternative way to solve the above mentioned problem. Instead of using the NumPy "fanzy indexing" one could also use the ndimage "find_objects" function.
example:
# Returns a list of slices for the labeled array. The slices represent the position of features in the labeled area
s = ndi.find_objects(lbl, max_label=0)
# Then you can simply output the patches
for i in n:
    print a[s[i]]

I will leave the question open because i couldn't solve an additional arising problem. I want to get the size of the features (already solved, quite easy via ndi.sum() ) as well as the number of nonlabeled cells in direct vicinity of the feature (ergo counting the number of zeros around the feature).


text:
Q: Replace Win7 w/ Win8 after setup w/ Ubuntu 13.10 dual boot My machine now runs dual boot with Win 7 and ubuntu 13.10. I have installed the Win 7 first on my pc in C Drive then I have installed Ubuntu 13.10 in D drive. I used GRUB 2.0 for Dual boot.
When I boot my pc I have to select the OS I want to login. There are ubuntu and win 7 listed. Which I think a screen appeared from ubuntu OS. Now I want to install a fresh copy of win 8 in C Drive. Is there any precaution or steps of work should I follow for this installation? Or I install both OS again?

A: Install windows 8 in your C drive. Download   Ubuntu boot repair disk.Make a liveCd or live USB(you can do this from windows using softwares like unetbootin, or you can make a liveUSB from Ubuntu before installing windows.)
Restart and boot into liveUSB or live CD, and do a recommended repair to recover your grub and Ubuntu.
Usually everything should be ok by this procedure


text:
Q: Using shiny's renderUI in Module this is my first question at stackoverflow. I have a problem with modules and renderUI in shiny (1.0.5).
When I use renderUI in
#### Main Part

ui <- bootstrapPage(
  uiOutput("DynamicContent")
)

server <- function(input, output,session) {

  S_A <- selectInput("S_A_Input"  ,"Change Me for print message",choices=1:3 )

  output$DynamicContent <- renderUI({
    tagList(S_A)
  })

  observe({
    print(input$S_A_Input)
  })

}

shinyApp(ui = ui, server = server)

then changing the selectInput will cause changing input$S_A_Input, so the print will occur. That's fine.
On the other hand, input$S_A_Input seems not to work, if I work with modules:
### Module Part

Module_YYY_Server <- function(input, output, session){

  S_A <- selectInput("S_A_Input"  ,"Change Me for print message",choices=1:3 )

  output$DynamicContent <- renderUI({
    tagList(S_A)
  })

  observe({
    print(input$S_A_Input)
  })

}

Module_YYY_Ui <- function(id){

  ns <- NS(id) # Creates Namespace

  tagList(
    uiOutput("DynamicContent" %>% ns)
  )

}

And then calling the module.
#### Main Part

ui <- bootstrapPage(
  Module_YYY_Ui("YYY")
)

server <- function(input, output,session) {
  callModule(Module_YYY_Server,"YYY")
}

shinyApp(ui = ui, server = server)

I haven't found a solution to this behaviour.

A: Late to the party but this is another option to solve your problem using

session$ns("id")

Here how it looks like:
Module_YYY_Server <- function(input, output, session){

  output$DynamicContent <- renderUI({
    selectInput(session$ns("S_A_Input"), "Change Me for print message", choices = 1:3)
    })

  output$text <- renderText({
    req(input$S_A_Input)
    input$S_A_Input})
}

Module_YYY_Ui <- function(id){

  ns <- NS(id) # Creates Namespace

  tagList(
    uiOutput(ns("DynamicContent")),
    textOutput(ns("text"))
  )
}

ui <- bootstrapPage(
  Module_YYY_Ui("YYY")
)

server <- function(input, output,session) {
  callModule(Module_YYY_Server,"YYY")
}

shinyApp(ui = ui, server = server)

This is based on the example here

A: While I am sure your example is simplified, If your input$S_A_Input is not changing based on what you are doing, as is the case in your example, I would not recommend using renderUI. Regardless of that, the reason that your input is not printing is because you are not generating it as an output.
Module_YYY_Server <- function(input, output, session){

  output$DynamicContent <- renderUI({
    ns <- session$ns
    tagList(
      selectInput("S_A_Input" %>% ns, "Change Me for print message",choices=1:3 )
    )
  })

  output$text <- renderText({input$S_A_Input})

}

Module_YYY_Ui <- function(id){

  ns <- NS(id) # Creates Namespace

  tagList(
    uiOutput("DynamicContent" %>% ns),
    textOutput("text" %>% ns)
  )

}


text:
Q: How do ensure sp_cdc_help_change_data_capture returns values? I am trying to review some CDC setup information about a SQL Server 2017 database and I'm getting stuck because a specific query that I would expect to return information is not performing as expected.
When I run EXEC sys.sp_cdc_help_change_data_capture no values are returned. However, I know there my table has CDC enabled from running SELECT [name], is_tracked_by_cdc FROM sys.tables order by [name]
and I do have select access to the tables that have CDC enabled.
I tried to run the more granular
EXEC sys.sp_cdc_help_change_data_capture @source_schema='dbo', @source_name='SUMMARY_CHANGELOG'

but the following error appears:
Msg 22981, Level 16, State 1, Procedure sys.sp_cdc_help_change_data_capture, Line 51 [Batch Start Line 0]
Object does not exist or access is denied.

If I run select * from dbo.SUMMARY_CHANGELOG, I can see the results I expect.
It seems I have proper access to the table, and proper access to the stored procedure, but the data being returned as well as the messages being displayed are telling me something is amiss. Beyond verifying the existence of the table and its having CDC enabled, and my access allowing for querying this information, what else could I look at to correct this issue?

A: As it turned out the user ID needed to have CDC_Role to view the results of the stored procedure.


text:
Q: Non-affine, projective vector field on $R^n$ I wanted recently to discuss with a fairly elementary mathematics class the kinds of self-maps of Euclidean space that carry triangles to triangles.  Obviously linear maps do this, and it seemed just as obvious to me that they were the only ones (up to translation).
I asked a colleague, and he pointed out an obvious counterexample:  Project to the $x$-axis, then apply whatever continuous but non-linear map one likes.  He quickly suggested a remedy:  Is a line-segment-preserving local diffeomorphism necessarily (affine) linear?
Well, surely that's enough --but I have been told that Walter Poor's "Differential geometric structures" assigns as an exercise to prove that there exist non-affine, projective vector fields on $\mathbb R^n$, and that a solution to this exercise gives a counterexample to the revised conjecture.  (I don't know the words, but it sounds plausible to me.)
Under fairly weak continuity hypotheses (certainly local diffeomorphism is sufficient!), it suffices to prove additivity; and, to prove additivity, it suffices to prove that parallelograms are carried to parallelograms.  The only way that this can fail for a local diffeomorphism is if there are some lines carried onto proper subsets of lines; and I just can't seem to see how this can happen without breaking some line segments.
(Another colleague to whom I proposed the problem argued as follows:  If the Jacobian matrix isn't constant, then there is a point at which the Hessian is non-$0$.  Near this point, the map is approximately a non-linear quadratic, and one can show that such quadratics don't preserve line segments.  Of course, it is the 'approximately' that bites us here; but I'd be interested in seeing how such a straightforward estimate fails.)

A: I don't know what was meant in that exercise, but your revised conjecture is certainly true and well-known. Here is an elementary proof.
The assumptions (local injectivity, continuity and segment-to-segment mapping) imply that the map is injective and preserves collinearity of points and endpoints of segments. By continuity it suffices to show that the midpoint of every segment is sent to the midpoint of its image.
Consider any two points $A,B$. Let $A',B'$ be their images and $D'$ the midpoint of $[A'B']$. By continuity there is a point $D\in[AB]$ mapped to $D'$. We are to prove that $D$ is the midpoint of $[AB]$. Pick a point $C$ such that its image $C'$ is not collinear with $A'$ and $B'$ and choose points $E\in[AC]$ and $F\in[BC]$ such that $CD$, $BE$ and $AF$ have a common point $G$ in the triangle $ABC$. Note that all these points belong to the plane containing $A,B,C$.
By elementary geometry (see e.g. Ceva's theorem), $D$ is the midpoint of $[AB]$ if and only if $EF$ is parallel to $AB$. Suppose it is not, then the line $EF$ intersects the line $AB$ at some point $H$. This configuration is mapped to a configuration $A',B',\dots,H'$ with the same collinearity relations. Since $E'F'$ is not parallel to $A'B'$ (they intersects at $H'$), the same application of Ceva's theorem shows that $D'$ is not the midpoint of $[A'B']$, a contradiction.

A: The short way of stating the answer is, I guess, that the vector fields you refer to are not complete on $\mathbb{R}^n$, so that they do not integrate to a diffeomorphism of Euclidean space.
Here are some details. Projective transformations map lines to lines, and therefore triangles to triangles (and even non-degenerate triangles to non-degenerate triangles), but they do not act on $\mathbb{R}^n$ (unless they are affine) but on the projective space $\mathbb{R}\mathrm{P}^n$ (which I recall is the quotient $\mathbb{R}^{n+1}/\mathbb{R}^*$ where the action is by multiplication, in other words the projective space is the set of linear lines of $\mathbb{R}^{n+1}$ ; it is acted upon by $\mathrm{GL}(n+1;\mathbb{R})$ or, quotienting by the kernel of scalar matrices,
$\mathrm{PGL}(n+1;\mathbb{R})$ ; details awailable in any old-school projective geometry book, for example Pierre Samuel's one, or Marcel Berger's geometry).
A simple exemple of a projective non-affine transformation is
$$(x,y)\mapsto \left(\frac{x}{x+1},\frac{y}{x+1}\right).$$
You can easily check that it maps lines to lines where it is defined (and in fact, if the goal space is extended to the projective plane it is defined everywhere).
On the level of vector fields, you can consider the $t$ derivative of
$$\left(\frac{x}{tx+1},\frac{y}{tx+1}\right)$$
to get one that does what you ask for. As stated above, the point is that the vector field you get is not complete (although it becomes complete on the projective space).

A: Recall two connections on a manifold are said to be projectively equivalent, if they have the same geodesics.  You want to know what local diffeos $\mathbb{R}^n\mapsto\mathbb{R}^n$ preserve geodesics; that is, what flat metrics on $\mathbb{R}^n$ are projectively equivalent to the Euclidean one.  I think your conjecture, that the only such metrics are those obtained by affine-linear transformations of the Euclidean metric, is correct.
Let's discuss this first locally, then globally.
Local question: What flat connections on a neighbourhood of $\mathbb{R}^n$ are projectively equivalent to the Euclidean one?
Answer:  If $n=1$, all.  If $n\geq 2$, exactly those obtained by what depending on your terminology you might call a a perspective transformation or a projective linear transformation or something else.
Comment:  Sketch proof below.  The case distinction (which explains your colleague's observation) comes from a factor of $1/(n-1)$ in the formula for the appropriate Schouten curvature tensor.  This is analogous to the case distinction $n\leq 2$ vs $n\geq 3$ in conformal geometry, see
http://en.wikipedia.org/wiki/Liouville's_theorem_(conformal_mappings)
Now we can deal with
Global question: What flat connections on $\mathbb{R}^n$ are projectively equivalent to the Euclidean one?
Answer:  Just the standard one.  The others "blow up"/"go off to infinity"/involve-division-somewhere-by-zero if you try to extend them to all $\mathbb{R}^n$.
Sketch proof of local version:  Use the notation and some formulae from, eg.,
http://www.maths.adelaide.edu.au/michael.eastwood/projective.pdf
Let $\nabla$ be the standard connection on $\mathbb{R}^n$.  Consider a projectively equivalent connection defined by a 1-form $\Upsilon_i$ (so the new connection acts on a 1-form $\omega_i$ by,
$\nabla_i\omega_j - \Upsilon_i\omega_j -\Upsilon_j\omega_i$.)
The projective Schouten curvature tensor of $\nabla$ is zero (since it's flat).  If the new connection's also flat, then, applying appropriate transformation laws, we have that
$\nabla_i\Upsilon_j = \Upsilon_i\Upsilon_j$,
and that $\Upsilon_i$ is closed, so locally exact.
Write $\Upsilon = df$.  Then in standard Euclidean co-ordinates we have the system of PDE
$\partial_i\partial_j f = \partial_i f \ \partial_j f$
for the function $f$, which we can solve to get
$f(x^1, ... x^n) =-\log (a_1 x^1+ \cdots + a_nx^n + c)$
for some fixed constants $a_i$ and $c$.  Hence $\Upsilon_i = \frac{-a_i}{a_1 x^1+ \cdots + a_nx^n + c}$.  It should probably turn out that the family of connections this gives are all indeed flat, and correspond to the projective-linear-transformations of the Euclidean metric on $\mathbb{R}^n$.


text:
Q: How to add data from textbox to database table I am a student and just start learning asp.net with C#.
I am using visual Studio 2015 and MSSQL Server 2012. I am facing a problem adding data in the database table from a webform.
I have established the connection successfully but couldn't be able to insert the data in the database table from a textbox.
I have search it at many places but couldn't able to do that.
So can anybody please tell me the simple and exact method to do that?

A: Kumar I am not sure if you facing issue in inserting any data into database or in capturing text from textbox and then inserting it into database.
However i will try to address both the issue.
for inserting into database you can visit Invalid column name sql error
as it has already been answered
now to capture the text froim textbox you can make use of HtmlElementClass
HtmlElement txtBox = null;
    HtmlDocument doc = webBrowser1.Document;
    if (doc != null)
    {
        txtBox = doc.GetElementByID("TxtboxelementId");
        string txtValue=txtBox.InnerHtml
    }

A: ASPX Page :
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
        <asp:Button ID="btnInsert" runat="server" Text="Button" OnClick="btnInsert_Click" />
    </div>
</form>

CS Code :
protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void InsertValue(string value)
    {
        using (SqlConnection con = new SqlConnection("YOUR_CONNECTION_STRING")) //Creating connection object
        {
            try
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO YOUR_TABLE_NAME (Field_Name) VALUES (@value)", con))
                {
                    if (con.State == System.Data.ConnectionState.Closed) con.Open();
                    cmd.Parameters.AddWithValue("@value", value);   // Adding parameter with value to command object
                    int result = cmd.ExecuteNonQuery();             // Executing query and it returns no of rows affected.
                    if (result > 0) Response.Write("Successful.");  // Checking if no of rows affected is > 0 meaning value successfully inserted.
                }
            }
            catch (SqlException ex)  //Handling SQL Exceptions
            {
                this.LogErrors(ex);
            }
        }
    }

    private void LogErrors(Exception ex)
    {
        // Write error log logic here
    }

    protected void btnInsert_Click(object sender, EventArgs e) // insert data button click event handler
    {
        this.InsertValue(this.txtValue.Text);
    }

A: SqlConnection con= (Connection Name)

If you are using without primary key in Database please go ahead with this
SqlCommand query = new SqlCommand("Insert into TABLE values ("+txtsample1.Text+")",con)

If it's with primary key mention your field names
SqlCommand query = new SqlCommand("Insert into TABLE (column1) values ("+txtsample1.Text+")",con)


text:
Q: undefined method `first' for # I am creating a blog with tags. Using Mongodb.
I got this error when submitting a new article with tags. And new artcile is not created. If I do not put any tags in the form, the article is created.
NoMethodError in ArticlesController#create
undefined method `first' for #
Rails.root: c:/Sites/blogK
Application Trace | Framework Trace | Full Trace
app/models/article.rb:18:in all_tags='
app/controllers/articles_controller.rb:22:innew'
app/controllers/articles_controller.rb:22:in `create'
article.rb
  class Article
  include Mongoid::Document
  has_many :comments, dependent: :destroy
  field :title, type: String
  field :text, type: String

    embeds_many :taggings
    embeds_many :tags

    def all_tags=(tags_string)
        tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
        new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
        self.tags = new_or_found_tags
    end

    def all_tags
        self.tags.collect do |tag|
            tag.name
        end.join(", ")
    end

  validates :title, presence: true,
                    length: { minimum: 5 }
end

tag.rb
  class Tag
  include Mongoid::Document
  field :name, type: String

    embeds_many :taggings
    embeds_many :articles
end

tagging.rb
class Tagging
  include Mongoid::Document
  embedded_in :article
  embedded_in :tag
end

article_controller.rb
class ArticlesController < ApplicationController
  http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path
  end

  private
  def article_params
    params.require(:article).permit(:title, :text, :all_tags)
  end
end

_form.html.erb
<%= form_for @article do |f| %>

  <% if @article.errors.any? %>

        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:

        <% @article.errors.full_messages.each do |msg| %>

<%= msg %>

        <% end %>

  <% end %>

    <%= f.label :title %>

    <%= f.text_field :title %>

    <%= f.label :text %>

    <%= f.text_area :text %>

<%= f.text_field :all_tags, placeholder: "Tags separated with comma" %>

    <%= f.submit %>

<% end %>


text:
Q: How to do redirection with traefik for custom docker ports Hello  I have a problem with redirecting HTTP requests to HTTP, when traefik is running in docker and I have mapped the ports.
I am running traefik (v1.5.4 on CentOS as a docker service.
The docker-compose.yml I use to start (docker stack deploy) looks like this
# use docker stack deploy to start a service running  traefik
version: '3.6'

services:
  proxy:
    image: traefik
    command: --api  --logLevel=DEBUG
    networks:
      - proxy
    ports:
      - "70:80"
      - "7443:443"
      - "7070:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /home/frank/docker/traefik/traefik.toml:/etc/traefik/traefik.toml

The reason for mapping the ports in docker is that on my development system I want to run traefik in parallel to an existing apache.
In my traefik.toml file I try to redirect from Port 80 to 443.
 [entryPoints]

    # Port 80 (HTTP) is redirected to PORT 443 (HTTPS)
    [entryPoints.http]
       address = ":80"
       [entryPoints.http.redirect]
          entryPoint = "https"

    [entryPoints.https]
    address = ":443"

Before adding the certificates für HTTPS, I wanted to test the redirection.
It did not work.
I send a request to http:/server.net:70/xxx. And I got a redirection to http:/server.net:443/xxx. What I need or expected was that I would be redirected to  http:/server.net:7443/xxx.
Thus my request is not redirected to my app
Is there a way to make this happen?
I think I could in the toml file redirect to port 7443. However, I do not like this solution, since then I will in the traefik configuration use information from the docker configuration. I would prefer to keep them as independent as possible?


text:
Q: urllib.error.URLError: Code:
import os
import tarfile
from urllib.request import urlretrieve
import pandas as pd

download_root = "https://raw.githubusercotent.com/ageron/handson-ml2/master/"
housing_path = os.path.join("datasets", "housing")
housing_url = download_root + "datasets/housing/housing.tgz"

def fetch_housing_data(housing_url=housing_url, housing_path=housing_path):
    os.makedirs(housing_path, exist_ok=True)
    tgz_path = os.path.join(housing_path, "housing.tgz")
    urlretrieve(housing_url, tgz_path)
    housing_tgz = tarfile.open(tgz_path)
    housing_tgz.extractall(path=housing_path)
    housing_tgz.close()

def load_housing_data(housing_path=housing_path):
    csv_path = os.path.join(housing_path, "housing.csv")
    return pd.read_csv(csv_path)

fetch_housing_data()
housing = load_housing_data()
housing.head()

Error: urllib.error.URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
I have tried this code using both a python file in VSCode and in a Jupyter notebook. I believe the error is due to proxy/firewall settings on Windows. I have tried disabling Windows Defender Firewall, I have also enabled and disabled a variety of proxy settings, with no luck.
Most posts have this error with python2 - I have not been able to find a fix for python3 yet.

A: It looks like a minor misspelling in the url, just a missing 'n' in "githubusercontent"
Current:
download_root = "https://raw.githubusercotent.com/ageron/handson-ml2/master/"

Fixed:
download_root = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"


text:
Q: Can we train multiple NER spacy model at the same time? I am working on the SPacy 3.1 NER pipeline.
I have created an application using FastAPI and running from the VM server by exposing the IP using the Unicorn server command [uvicorn main: app --host 0.0.0.0 --port 00].
Now, when I call my training API and start the training non of the other API are working, seems like they all are in queue.
I have used async and await.
Can anyone guide me on how to run multiple APIs when training is in progress.


text:
Q: GeoDjango's within and contains queryset filters differ to direct GEOS lookups I've got two models, one which has areas and one which has points. I'm trying to do some simple lookups when the point-model is saved (sends a message to users in who's area the point appears).
The following code is from within a post_save signal handler.
(Pdb)   PointBasedModel.objects.filter(location=instance.location)
[<PointBasedModel: on 2011-12-03 16:05:52>, <PointBasedModel: on 2011-12-03 16:05:52>]

(Pdb)   PointBasedModel.objects.filter(location__within=PolyBasedModel.objects.all()[0].area)
[<PointBasedModel: on 2012-01-03 17:36:51>, <PointBasedModel: on 2011-12-03 16:05:52>, <PointBasedModel: on 2011-12-03 16:05:52>, <PointBasedModel: on 2011-11-09 19:53:34>, <PointBasedModel: on 2011-11-09 19:53:34>, <PointBasedModel: on 2011-11-06 15:24:31>, <PointBasedModel: on 2011-10-17 07:40:39>, <PointBasedModel: on 2011-02-27 20:46:04>]

(Pdb) PolyBasedModel.objects.filter(area__contains=PointBasedModel.objects.filter(location__within=PolyBasedModel.objects.all()[0].area)[0].location)
[]

As you can see, it is possible to retrieve the instance that I have just created, then find all the PolyBasedModels in which that PointBasedModel instance appears, filtering the PolyBasedModel back using the PointBasedModel that is known to be within the Poly, fails.
The code is a little contrived to demonstrate the problem, but simply put, this is what I'm seeing:
(pdb) PolyBasedModel.objects.filter(area__contains=instance.location)
[]
(pdb) instance.location.within(PolyBasedModel.objects.get(pk=2).area)
True
(Pdb) PolyBasedModel.objects.get(pk=2).area.contains(instance.location)
True

It makes no sense... Anyone had a similar problem/know a solution?

A: With a little more digging, I found this problem:
(Pdb) str(PolyBasedModel.objects.filter(area__contains='POINT (-2.6203333333300001 51.4453333332999989)').query)
*** AttributeError: 'str' object has no attribute 'ewkb'

A quick search for 'str' object has no attribute 'ewkb' revealed http://groups.google.com/group/geodjango/browse_thread/thread/11a3016a0aeceec9 which points out that you have to be using a GeoManager... obviously.
Changing the PolyBasedModel to use a GeoManager fixed it.
I guess that's what you get for converting from non-geospatial to geospatial! Do it right first time. :-)


text:
Q: Get string from a Observable I get one Observable<string> called this.downloadURL which after calling to my database gets the following value:

I would like to get its value in the following method:
 //Upload a new picture to the database as a profile picture
      uploadBetPicture(event) {
        const id =
          "bet_" +
          Math.random()
            .toString(36)
            .substring(2) +
          "_Photo";
        this.ref = this.afStorage.ref(id);
        this.task = this.ref.put(event.target.files[0]);
        this.downloadURL = this.task.downloadURL();
        //UNTIL HERE I HAVE JUST STORE THE PICTURE AND SET THE OBSERVABLE

        //HERE I GET THE ERROR
        this.photoUrl = this.downloadURL.value;
      }

Nevertheless, even when I see the value in my console, I can not access this variable, and I get the following error in this.photoUrl = this.downloadURL.value

Property 'value' does not exist on type 'Observable'.

Just to add that the storing method works, as I said before, I get the value

A: Since this.task.downloadURL() is an Observable and your downloadURL is wrapped somewhere within that Observable, you'll have to subscribe to it, to unwrap the value.
Try this:
uploadBetPicture(event) {
  const id =
    "bet_" +
    Math.random()
    .toString(36)
    .substring(2) +
    "_Photo";
  this.ref = this.afStorage.ref(id);
  this.task = this.ref.put(event.target.files[0]);
  this.task.downloadURL()
    .subscribe(value => this.photoUrl = value);
}

NOTE:
There might be some other keys as well in the value unwrapped from the Observable, so you might want to first log the value inside the subscribe block to the console and then use the appropriate key from the value object.

A: Look up the RxJs documentation, and you'll see that the Angular form of reactive is pretty useful, since you get to do more than just subscribe and wait on the async callback.
For instance, you could query for the first value in the observable:
YourObservable.first()
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-first

Or the last value:
YourObservable.last()
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-last

The full Observable documentation is here:
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html


text:
Q: How does a reflected photon keep its entanglement I'm curious how a photon from an entangled pair, travelling through say a delayed choice quantum eraser experiment, can bounce around between mirrors but remain entangled with its partner photon, when any kind of "observation" of that photon destroys its entanglement.
Surely there is some form of interaction happening at the site of reflection that causes the photon to change its direction. What is special about this type of interaction that does not cause decoherence in the photon's wave function?

A: Typically the entanglement between photons is with respect to their polarizations.  As long as the interaction between a photon and a mirror is polarization-independent, it should not affect the entanglement between the photon and the twin photon with which it is entangled.  However, it is safe to conclude (and pretty easy to test) that if the mirror is polarization-dependent it will reduce the (polarization) entanglement between the photons.  If entanglement is with respect to another property of the photons such as the direction of propagation, phase, or frequency, then the mass of the mirror will enter into the equation: quantum uncertainty in the velocity of even a tiny mirror whose mass is a few grams is negligible, so the amount by which reflection can add uncertainty to the frequency of a reflected photon (and thereby reduce frequency entanglement between it and its twin) is negligible.
Not that Wikipedia should always be trusted, but in this case it is correct [https://en.wikipedia.org/wiki/Quantum_entanglement]:"Measurements of physical properties such as position, momentum, spin, and polarization, performed on entangled particles are found to be correlated." The point there is that any conserved quantity can lead to entanglement: when two particles are created, e.g., by conversion of a gamma ray into an electron-positron pair or conversion of a visible light photon into two new photons of twice the wavelength of the original via downconversion, the two new particles are entangled.  Quantities that are conserved (energy, momentum, spin, charge, etc.) result in correlations between the corresponding properties of the new particles, such that the total values of those conserved quantities are not changed by the creation of the new particles. Measuring the value for one particle automatically reveals the value for the other particle.
Loss of entanglement or decoherence results when any part of the value of a conserved quantity (let's use momentum for convenience) is transferred to the outside systems.  The total momentum is still conserved, but only a portion of it is represented by the sum of the two particles' momenta.  The rest is somewhere off in the rest of the universe; and to the extent that the amount of that quantity that is lost cannot be determined, the correlation between the momenta of the two particles is reduced.
In the case of one of a pair of entangled photons reflecting off a mirror, the interaction between the mirror and the photon cannot alter the energy of the photon significantly.  It does alter the momentum of the photon of course, but in a very well-determined way simply because the mirror is, from the photon's perspective, immovable.  So whatever correlation there was between that photon and its twin is not lost; it is simply altered in a predictable way.  The same is true for a photon's polarization: circular polarization reverses sign upon reflection from a mirror, so the mirror alters the polarization of a photon, but in a fully predictable way.
On the other hand, if the mirror has extremely low mass, comparable to an atom, it will recoil upon reflecting the photon. The reflected photon will have an unpredictably altered frequency and momentum simply because the exact position, orientation, and velocity of the mirror are subject to quantum indeterminacy.  As a result, there will be a loss of entanglement coherence: measurement of the photon's properties will not provide a fully reliable basis for predicting the properties of the twin photon.
However, in setups of the sort you are concerned with, the mirrors are massive and, from the photon's perspective, immovable.  Yes, there is loss of coherence upon reflection, but the percentage loss is immeasurably small.


text:
Q: Numbers of solutions $e^x=-x^2+2x+5 $ Prove that $e^x=-x^2+2x+5 $ have exactly two solutions.
Is it enoguht that Vertex of the parabola is over $y=e^x$ and arms of it looks down

A: This is a little out of the blue, but...
Since $e^x > 0$ for all $x \in \mathbb{R}$, there can only be two points where RH intersects $e^x$ since $e^x = -x^2+2x+5 \implies x^2-2 x+e^x = 5$.
If we rewrite $x^2-2 x+e^x = 5$ as $x^2-2 x+e^x = y$, observe that its minima is at $x^2-2 x+e^x = W(\frac{e}{2}) (W(\frac{e}{2})+2)-1,\, x = 1-W(\frac{e}{2})$
where $W(n)$ denotes the Lambert W function.
As $x$ tends from $1-W(\frac{e}{2}) \to \infty$ or $1-W(\frac{e}{2}) \to -\infty$, $y\to\infty$, thus it is easy to see that $e^x = -x^2+2x+5$ has only two solutions.

A: Yes. More rigorously, we can use the Intermediate Value Theorem (IVT) to prove that at least two solutions exist. Then we can use Rolle's Theorem to prove that at most two solutions exist.

Let $f(x) = e^x + x^2 - 2x - 5$. Note that $f$ is continuous for all $x$. Furthermore, note that:
\begin{align*}
f(-10) &= e^{-10} + 100 + 20 - 5 = e^{-10} + 115 > 0 \\
f(0) &= 1 + 0 - 0 - 5 = -4 < 0 \\
f(10) &= e^{10} + 100 - 20 - 5 = e^{-10} + 75 > 0 \\
\end{align*}
Hence, by IVT, we have $f(x)=0$ for some $x \in (-10,0)$ and for some $x \in (0,10)$.

Now suppose instead that the equation $f(x)=0$ has three solutions $a<b<c$. Since $f$ is continuous and differentiable everywhere and $f(a)=f(b)=f(c)=0$, the conditions of Rolle's Theorem are satisfied. Hence, we know that for some $r\in (a,b)$ and for some $s \in (b,c)$, we have $f'(r) = f'(s) = 0$.
We will now apply Rolle's Theorem a second time to the equation $f'(x)=0$. Since the function $f'(x)=e^x + 2x - 2$ is continuous and differentiable everywhere and $f'(r) = f'(s) = 0$, the conditions of Rolle's Theorem are satisfied. This yields $f''(t)=e^t + 2=0$ for some $t \in (r,s)$. But this is impossible, since $e^t$ is nonnegative for all $t$.


text:
Q: How to activate can bus support in Yocto/BeagleBoneBlack? I am trying can bus support for Yocto with beagleboneblack.
I did kernel config by bitbake -c menuconfig virtual/kernel and add following driver to kernel.

*

*Raw CAN Protocol

*Broacast Manager CAN Protocol

*CAN Gateway/Router

*Platform CAN drivers with Netlink support

*Can bit-timing calculation

*TI High End CAN Controller

And add IMAGE_INSTALL_append = " can-utils iproute2" to local.conf.
When my yocto boot up, serial console seems to show
[    1.239593] can: controller area network core (rev 20170425 abi 9)
[    1.246828] NET: Registered protocol family 29
[    1.251438] can: raw protocol (rev 20170425)
[    1.255758] can: broadcast manager protocol (rev 20170425 t)
[    1.261517] can: netlink gateway (rev 20190810) max_hops=1

So, i think that kernel have can driver and socketcan.
But there is no can device.
root@beaglebone:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 78:a5:04:b4:18:cf brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.19/24 brd 192.168.100.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 240b:251:520:5b00:7aa5:4ff:feb4:18cf/64 scope global dynamic mngtmpaddr
       valid_lft 2591946sec preferred_lft 604746sec
    inet6 fe80::7aa5:4ff:feb4:18cf/64 scope link
       valid_lft forever preferred_lft forever
3: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/sit 0.0.0.0 brd 0.0.0.0

Could you tell me how can i find can device in ip a?
BR, Soramame

A: AM335X has Bosch C_CAN/D_CAN controller but not TI High End CAN Controller.
So i changed kernel config from bitbake -c menuconfig virtual/kernel.
And I modified device tree and rebuild kernel.
Then, I could find can0 and can1.


text:
Q: disable chrome pop-up window " leave site? changes you made may not be savecd" after submit form I have a simple form where the user chooses a value that I will be saved in the database.
HTML
<form  method="get" >
        <div class="select-block1">
            <select name="proximID" onchange="this.form.submit(); ">
                <option value="" disabled selected> Votre Proxim'IT</option>
                <?php foreach ($results as $output){?>

                <option value="<?php echo $output['id']; ?>"> <?php echo $output["first_name"], $output["last_name"]; ?></option>
                <?php } ?>
            </select>

        </div>
    </form>

PHP
<?php
if(!empty($_GET['proximID'])) {

$stmt6 = $pdo1->query("UPDATE proximit SET ProximID = {$_GET['proximID']} "); ?>

when i choose a value, pop-up window appear " leave site?" changes you made may not be savecd". Please how can i disable this pop-up window for chrome

A: That popup is shown because the onsubmit event triggers a page refresh which also calls onbeforeunload event.
From the docs:
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.
To take control over this popup, you need to modify this event.
Add an id attribute to the <form> tag
<form  method="get" id="selectForm" >

Assign onChange a function
<select name="proximID" onchange="onSelectHandler();">

which triggers
function onSelectHandler() {
    const form = document.getElementById('selectForm');
    window.onbeforeunload = null;
    form.submit();
}


text:
Q: Appengine taskqueues to cloud tasks migration I am migrating some Appengine taskqueues to use the Cloud Tasks API.
Many things are different and among them is the eta and countdown in taskqueues vs scheduled_time in Cloud Tasks. As I understand, one can only use scheduled_time instead of eta on a task, and for countdown one has to implements ones own countdown to scheduled_time converter. Is this true or is there another "google-native" way to port the countdown feature that I am missing?
Relevant docs:
A Cloud Task Task
A Cloud Task CreateTaskRequest
Appengine taskqueue (please search for "countdown")


text:
Q: flutter get pdf files string data to variable I want to take a pdf files string data in a fast way and the package which I use is giving some problems.
How can I get correctly and fast way a pdf file?
Thanks for your help.
this is the way ı using
  PDFDoc? _pdfDoc;
  String _text = "";

  _getPdfFile() {
    setState(() async {
      _pdfDoc = await PDFDoc.fromPath(filePath!);
      data = await _pdfDoc!.text;
    });
  }

A: this is the source of code. this code will take string data from the pdf page 3.
Instead, if you want all the data in pdf you can look at this link.https://help.syncfusion.com/flutter/pdf/working-with-text-extraction
final String data;
    final PdfDocument document =
          PdfDocument(inputBytes: myFile.readAsBytesSync());

      setState(() {
        data = PdfTextExtractor(document).extractText(startPageIndex: 3);
      });

      document.dispose();


text:
Q: Continuity of $f^{(n-1)}$ in Taylor's Theorem with Mean-value remainder I refer to Rudin's proof of Taylor's Theorem with the Mean-value form of the remainder.

I'm not sure if I'm understanding the proof correctly. Why must $f^{(n-1)}$ be continuous on $[a,b]$? I believe continuity at the endpoints is only used in the application of the mean value theorem for $g(\beta)$ and $g(\alpha), g'(\alpha), \cdots, g^{(n-1)}(\alpha)$. Also, I don't get the point of $a$ and $b$. Thus, is it ok to restate Taylor's theorem as follows:
Suppose $f : D \to \mathbb{R}$ is continuous on $[\alpha, \beta] \subseteq D$, $n$ is a positive integer, $f^{(n-1)}$ is continuous on $[\alpha, \beta)$, $f^{(n)}(t)$ exists for every $t \in (\alpha, \beta)$. Then there exists a point $x \in (\alpha, \beta)$ such that
$$f(\beta) = \sum_{k=0}^{n-1}\frac{f^{(k)}(\alpha)}{k!}(\beta-\alpha)^k + \frac{f^{(n)}(x)}{n!}(\beta-\alpha)^k.$$
I checked the statement of the theorem on Wikipedia and it also has the condition of continuity of $f^{(n-1)}$ on the closed interval between $\alpha$ and $\beta$. So I thought I might be missing something. Thanks!


text:
Q: How to fix an issue with shaders? I'm working on writing code for simpliest shader.
Here is its code.
const char* Vertex_Shader_Descrip = "#version 330/n"

"layout(location = 0) in vec3 position;/n"

"void main()/n"
"{/n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);/n"
"}/0";

glsl shader compilation fails with the error
error C0206: invalid token "<invalid atom 199709744>" in version line

Don't remember the exact version of shader, but it supports opengl 3.3
Please, could you point on my mistakes if there's any or just explain me what is wrong?

A: You need to use reverse slash instead of used.
const char* Vertex_Shader_Descrip = "#version 330\n"

A: Remove all the /n and try adding \n.


text:
Q: How to connect to Gmail IMAP through VPN? Recently, I changed to a shorter mail address(from Google Apps, to Google Apps, just for an address). As I have Google Apps standard version, I have to use 3rd party tools to migrate my two mailboxes.
However, I have a slow connection to imap.gmail.com, and I cannot get some of my mails with big attachments migrated, because before the FETCH command finishes, the server would disconnect me.
I've searched about this, and found that if a client didn't SEND and commands to server within a time limit, the server will make this connection timeout. But actually I'm receiving data, and the tool would not send any commands.
Since my connection cannot finish the transfer in time, I can't get those mails migrated. To accelerate the connection, I tried to use several VPNs, but when I connect, I always get "connect timeout" message. Seems that the connection cannot be established.
How to get it worked? Why can't I connect to Google's IMAP server through VPN?
(Google's IMAP uses SSL on 993 port)

A: Is there any specific reason behind using a third party tool? Why don't you use email fetcher to fetch emails from your Gmail account to Google Apps absolutely free.
I have recently migrated 40,000 emails for one of my clients from Yahoo! Small Business to Gmail and it worked pretty well.


text:
Q: Flutter : can't get all response body from get request I have get request in Flutter app, when I test the request in postman I get all data, something like this :
{
"result":{
   "name" : "somename",
   "images":[
      "test.jpg",
      "test2.jpg"
    ],
   "sizes":[
     {
       "id": 1,
       "value" : 5
     },
     {
       "id": 2,
       "value" : 15
     }
    ]
 }
}

I call data and print them like this without using models:
var data = json.decode(response.body);
print(data['result']['name']);
print(data['result']['images']);
print(data['result']['sizes']);

it is print all things expect last one.
where must be the mistake?

A: Solved, by adding "?sizesView = true" to the link
final response = await http.get(path +'?sizesView = true'):

A: you should get the index of the last one because it is in a dictionary not a list do this:
print(data['result']['sizes'][0]['id']) // it will get the first index of the sizes list and then get the id key

or you can creat a model of list to get the indexes of your list


text:
Q: How can I achieve a limit character in jquery in this situation? Run the code to see result, it will replace space with '-'. I want to achieve only  one'-' between two text, like 'good-day', but not good----day. Therefore, I want to know how to limit only one between word in jquery.

$('#tag').on("keydown",function(event){
var $input = $('#tag');
     $input.val(function(_,v){
return v.replace(/\s+/g,'-');
     });// '-'repace space
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tag" />

A: It is because when you enter a space it is replaced with -, then when you enter another space, (the previous one is already replaced with -) so you have -<space> now the new space is again replaced with - so you get --

$('#tag').on("keydown", function(event) {
  $(this).val(function(_, v) {
    return v.replace(/[\s-]+/g, '-');
  }); // '-'repace space
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tag" />


text:
Q: Azure DevOps Server does not update pages with Live updates Since we updated from TFS to Azure DevOps Server 2020 we have a problem with live updates when using the client. I expect pages to automatically update with new information as they come available like it did with TFS, but that doesn't happened anymore. Instead we get an error:
'Live updates for this pull request were temporarily interrupted. Refresh to view the latest.'

I suspect it is a problem with a server setting, but I have no idea where to look.
Azure DevOps Server
Version Dev18.M170.4


text:
Q: How to declare an array and store records as elements in Oracle SQL developer Trying to learn pl/sql and wondering if anybody can help declare an array and store records? thanks.

A: You can use a cursor to store set of records from a query. But more specifically if you want to add , remove values(like a java array) you can use table type


text:
Q: Do word boundaries work on symbol characters? I'm trying to implement word boundaries in my emoticons feature for a chat. But for some reason I can't seem to get the word boundaries to work. I am new to regex.
So when I do:
var reg = /\b\Hi\b/gi;
var str = 'HiHiHi Hi HiHiHi Hi';
alert(str.replace(reg, ''));

This happens: Jsfiddle
It actually works fine, and does remove those 2 Hi's that are standing alone.
But when I change the reg to an escaped smiley and then change the string:
var reg = /\b\:\)\b/gi;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(reg, ''));

This happens:
Jsfiddle
It just doesn't work. The string stays the same. Is it that word boundaries can't be used on symbols? If so, how does Facebook do it on their chats?

A: Word boundaries \b represent a zero-width boundary between word characters \w (in javascript, [A-Za-z_]) and non-word characters \W (everything else).
Because of this, there will not be a boundary between two emoticons or when the emoticon is surrounded by spaces, punctuation, etc.
The simplest regex would be /[:;]-?[()]/gi, which supports smileys ) and frownies ( with optional dashes and eyes : or winks ;.
Edit:
This will require either a space or the beginning of the string (as a capturing group since Javascript doesn't support look-behinds), then it uses the above regex, then it must be followed by the end of string or whitespace.
var reg = /(\s|^)[:;]-?[()](?:\s|$)/gi;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(reg, '$1'));

Should replace in these situations: :-), cool :( not!
Should not replace in these situations: Digits:(0,1,2,3), hi :(.

A: As \b will not work in this case, you could use:
var re = /(\s|^):\)(?!\S)/g;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(re, '$1'));

Which works like a space boundary.
You can add several smileys to it like so:
/(\s|^)(?::\)|:\(|:\||:\]|:\[)(?!\S)/g;


text:
Q: Manage multiple forms validate inside a pageview with one onpressed I have to submit 4 forms at the same time when pressing the callback button. However, when this button is pressed, the function called with onpressed must validate that all requirements are being performed in the field validations of the textformfield.
I'm using just one formkey and using formkey.validate to verify if the requirements are being accepted, but it doesn't work, and I don't have idea to how can I try in a different way.
class CreateAccountPage extends StatefulWidget {
  CreateAccountPage({Key? key}) : super(key: key);

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

class _CreateAccountPageState
    extends ModularState<CreateAccountPage, CreateAccountController> {
  static var _focusNode = FocusNode();
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool? policy;
  int currentPage = 0;

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
      print('Has focus: $_focusNode.hasFocus');
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        //physics: NeverScrollableScrollPhysics(),
        controller: controller.pageViewController,
        onPageChanged: (index) {
          currentPage = index;
        },
        children: [
          SafeArea(
            child: Scaffold(
              backgroundColor: AppColors.background,
              body: SingleChildScrollView(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      top: 74,
                      left: 48,
                      child: Image.asset(
                        'assets/images/logo_budget.png',
                        height: 53.85,
                        width: 100,
                      ),
                    ),
                    Positioned(
                      top: 144,
                      left: 48,
                      child: SizedBox(
                        width: 255.0,
                        height: 118.0,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Bem-Vindo!',
                              style: TextStyles.h3HeadCreateAccount,
                            ),
                            Text(
                              "Por favor insira seus dados nos campos abaixo.",
                              style: TextStyles.h6HeadCreateAccount,
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 419, left: 48, right: 48),
                      child: Form(
                        key: formKey[0],
                        child: Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: AppTextFormFieldWidget(
                                controller: controller.nameCreate,
                                hintText: 'Nome',
                                labelText: 'Nome',
                                //validator: (value) =>
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: AppTextFormFieldWidget(
                                controller: controller.emailCreate,
                                labelText: 'E-Mail',
                                hintText: 'E-Mail',
                                validator: (value) => InputValidators()
                                    .emailValidator(value ?? ""),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          SafeArea(
            child: Scaffold(
              backgroundColor: AppColors.background,
              body: SingleChildScrollView(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      top: 74,
                      left: 48,
                      child: Image.asset(
                        'assets/images/logo_budget.png',
                        height: 53.85,
                        width: 100,
                      ),
                    ),
                    Positioned(
                      top: 144,
                      left: 48,
                      child: SizedBox(
                        width: 255.0,
                        height: 86.0,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Bem-Vindo!',
                              style: TextStyles.h3HeadCreateAccount,
                            ),
                            Text(
                              "Mais alguns dados.",
                              style: TextStyles.h6HeadCreateAccount,
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 419, left: 48, right: 48),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: AppTextFormFieldWidget(
                                controller: controller.telefoneCreate,
                                keyboardType: TextInputType.phone,
                                hintText: 'Telefone',
                                labelText: 'Telefone',
                                inputFormatters: [
                                  FilteringTextInputFormatter.digitsOnly,
                                  TelefoneInputFormatter(),
                                ],
                                validator: (value) => InputValidators()
                                    .emailValidator(value ?? ""),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: AppTextFormFieldWidget(
                                controller: controller.cpfCreate,
                                labelText: 'CPF',
                                keyboardType: TextInputType.number,
                                inputFormatters: [
                                  FilteringTextInputFormatter.digitsOnly,
                                  CpfInputFormatter(),
                                ],
                                validator: (value) =>
                                    InputValidators().passwordValidator(value!),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          SafeArea(
            child: Scaffold(
              backgroundColor: AppColors.background,
              body: SingleChildScrollView(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      top: 74,
                      left: 48,
                      child: Image.asset(
                        'assets/images/logo_budget.png',
                        height: 53.85,
                        width: 100,
                      ),
                    ),
                    Positioned(
                      top: 144,
                      left: 48,
                      child: SizedBox(
                        width: 255.0,
                        height: 86.0,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Bem-Vindo!',
                              style: TextStyles.h3HeadCreateAccount,
                            ),
                            Text(
                              "Leia com atenção e aceite.",
                              style: TextStyles.h6HeadCreateAccount,
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 274, left: 27, right: 22),
                      child: Column(
                        children: [
                          Container(
                              height: 193.0,
                              width: 311.0,
                              child: Text(
                                "Lorem Ipsum neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Ipsum neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Nque porro  est qui dolorem ipsum quia dolor sit amet, , adipisci velit. Quisquam est qui dolorem ipsum.",
                                style: TextStyles.blackRoboto16400,
                              )),
                          SizedBox(
                            height: 30.0,
                          ),
                          Row(children: [
                            Container(
                              height: 48,
                              width: 48,
                              child: Radio<bool>(
                                value: policy ?? true,
                                groupValue: policy,
                                toggleable: true,
                                onChanged: (value) {
                                  setState(() {
                                    policy = value;
                                    print(policy);
                                  });
                                },
                              ),
                            ),
                            Container(
                              height: 48,
                              width: 272,
                              child: Text(
                                "Eu li e aceito os termos e condições e a Política de privacidade do budget.",
                                style: TextStyles.blackRoboto16400,
                              ),
                            )
                          ]),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          SafeArea(
            child: Scaffold(
              backgroundColor: AppColors.background,
              body: SingleChildScrollView(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      top: 74,
                      left: 48,
                      child: Image.asset(
                        'assets/images/logo_budget.png',
                        height: 53.85,
                        width: 100,
                      ),
                    ),
                    Positioned(
                      top: 144,
                      left: 48,
                      child: SizedBox(
                        width: 255.0,
                        height: 118.0,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Bem-Vindo!',
                              style: TextStyles.h3HeadCreateAccount,
                            ),
                            Text(
                              "Agora crie sua senha contendo:",
                              style: TextStyles.h6HeadCreateAccount,
                            )
                          ],
                        ),
                      ),
                    ),
                    Positioned(
                      top: 320,
                      child: Container(
                        margin: EdgeInsets.only(left: 60, right: 48),
                        height: 72,
                        width: 267,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "•  pelo menos oito caracteres",
                              style: TextStyles.blackRoboto16400,
                            ),
                            //TODO Verificar o campo com Bullet Point
                            Text(
                              "•  letras maiúscula, letras minúsculas, números e símbolos",
                              style: TextStyles.blackRoboto16400,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 419, left: 48, right: 48),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: AppTextFormFieldWidget(
                                  controller: controller.passwordCreate,
                                  hintText: 'Crie uma senha',
                                  validator: (value) {
                                    InputValidators().passwordValidator(value!);
                                  }),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: AppTextFormFieldWidget(
                                  controller:
                                      controller.passwordCreateConfirmation,
                                  hintText: 'Confirme sua senha',
                                  validator: (value) {
                                    if (value !=
                                        controller.passwordCreate.text) {
                                      return "As senhas não coincidem";
                                    } else {
                                      InputValidators()
                                          .passwordValidator(value!);
                                    }
                                  }),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.only(bottom: 8),
        child: AnimatedBuilder(
          animation: controller.pageViewController,
          builder: (context, snapshot) {
            return Padding(
              padding: const EdgeInsets.only(left: 12),
              child: Container(
                color: Colors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      width: 116,
                      height: 48,
                      child: TextButton.icon(
                        icon: Icon(
                          Icons.arrow_back,
                          color: Color.fromRGBO(0, 0, 0, 0.26),
                        ),
                        label: Text(
                          "VOLTAR",
                          style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontSize: 16,
                            fontFamily: "Roboto",
                            fontWeight: FontWeight.w500,
                            letterSpacing: 0.4,
                            textBaseline: TextBaseline.alphabetic,
                            color: Color.fromRGBO(0, 0, 0, 0.26),
                          ),
                        ),
                        onPressed: () {
                          if (currentPage == 0) {
                            Modular.to.popAndPushNamed('/initial');
                          } else {
                            controller.pageViewController.previousPage(
                              duration: Duration(milliseconds: 400),
                              curve: Curves.easeInOut,
                            );
                          }
                        },
                      ),
                    ),
                    Text("${currentPage + 1}/4",
                        style: TextStyles
                            .createAccountTextStyleBottomNavigatorNumber),
                    Padding(
                      padding: const EdgeInsets.only(right: 12),
                      child: ElevatedButtonWidget(
                          mainAlign: MainAxisAlignment.spaceBetween,
                          fontSize: 14,
                          buttonText: "CONTINUAR ",
                          width: 116,
                          height: 32,
                          paddingValue: 4,
                          sufixicon: Icon(
                            Icons.arrow_forward,
                            size: 18,
                          ),
                          onpressed: () {
                            if (currentPage == 3 &&
                                _formKey.currentState!.validate() &&
                                policy == true) {
                              final user = User(
                                cpf: controller.cpfCreate.value.text,
                                name: controller.nameCreate.value.text,
                                email: controller.emailCreate.value.text,
                                password: controller.passwordCreate.value.text,
                                telephone: controller.telefoneCreate.value.text,
                                policyAccepted: policy!,
                              );

                              print(user);
                              // Modular.to.popAndPushNamed(
                              //   "create_account_module/onboard");

                            } else {
                              controller.pageViewController.nextPage(
                                duration: Duration(milliseconds: 400),
                                curve: Curves.easeInOut,
                              );
                            }
                          }),
                    )
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

A: The _formKey should be unique in the Widget tree.
https://api.flutter.dev/flutter/widgets/Widget/key.html
Declare more GlobalKey() and assign to each Form()


text:
Q: Anonymous functions and Maps in Scala I'm not sure why this doesn't work:
scala> case class Loader(n: String, x: String, l: List[String])
scala> val m: Map[String, (List[String])=>Loader] =
     | Map("x" -> Loader("x", "x1", _:List[String]))

<console>:8: error: type mismatch;
 found   : (List[String]) => (java.lang.String, Loader)
 required: (String, (List[String]) => Loader)
       Map("x" -> Loader("x", "x1", _:List[String]))

but this does?
scala> Loader("t", "x", _:List[String])
res7: (List[String]) => Loader = function1>

scala> val m = Map("x" -> res7)
m: scala.collection.immutable.Map[java.lang.String,(List[String]) => Loader] =
  Map((String,function1>))

A: One more victim of the overload of _ in Scala. Consider this:
f(_, 5) + 1 // Partial function application
f(_ + 1, 5) // Closure

In the first case, _ is replacing the entire parameter. In this case, it stands for a partial application of f. In practice, it's equivalent to x => f(x, 5) + 1, as the whole expression that contains f is turned into a closure.
In the second case, _ is part of an expression. In this case, the whole expression is turned into a closure, up to any expression delimiter -- by which I mean that if the expression is nested inside another, only the inner expression is turned into a closure. In practice, it is equivalent to f(x => x + 1, 5).

A: The parser was not sure where to put the beginning of the anonymous function. Sometimes you can solve this by adding another pair of parentheses (though not always):
val m: Map[String, (List[String])=>Loader] =
Map("x" -> (Loader("x", "x1", _:List[String])))

I don't see any ambiguities here, so it might just not have been smart enough to figure it out. I think, the parser overlooked the possibility to have an anonymous function just after the -> (which also is a library construct and uses implicit magic and all the wicket stuff which makes the little parser's mind loop).
When you write it as an explicit tuple, it'll work fine.
val m: Map[String, (List[String])=>Loader] =
Map(("x", Loader("x", "x1", _:List[String])))


text:
Q: Событие для onclick Ребят,
у меня на странице есть 4 фрэйма с разным содержимым, мне нужно, чтобы по кнопке "обновить" содержимое фрэйма менялось (получает изображение с сервера), сопсна, я поставила кнопку
<input type='button' value ='обновить' onclick='window.location.reload()'/>

Но, как вы понимаете, она ни к чему не привязана, поэтому обновляет всю страницу. Меня такая ситуация не устраивает и вот уже 2 часа я пытаюсь это исправить, но пока тщетно.
P.S. Какое событие на onclick еще есть? А то я роюсь и не нахожу по своему запросу.
Заранее спасибо.
A: document.getElementById('id_твоего_фрейма').contentWindow.location.reload();


text:
Q: How to convert Azure cookie AppServiceAuthSession to a valid OAuth JWT access token? In Azure I have an App Service which hosts an SPA and ASP.NET Core WebAPI.
Azure App Service
I have activated Authentication
Authentication active in App Service
When I try to access the SPA I am first direct to a login page
Login
After logging in a cookie (AppServiceAuthSession) is set.
Cookie 1
Cookie 2
The WebAPI uses the middleware app.UseAuthentication(); and [Authorize] to protect the API.
Before the SPA calls the WebAPI I convert the cookie (AppServiceAuthSession) to an OAuth access token using
https://my-app-service.azurewebsites.net/api/values

This does return what looks like an access_token.
Token
[{
        "access_token": "PAQABAAAAAABeAFzDwllzTYGDLh_qYbH85B5eMV5PaPELRI_hsnIMx2_pQkgf_TZr-9Z_OC26BOyQqoFM2fR...",
        "id_token": "...",
        "provider_name": "aad",
        "refresh_token": "AQABAAAAAABeAFzDwllzTYGDLh_qYbH8k6pCkZIL4QZzJa06T0AYngu8K2WJV...",
        "user_claims": [{
                "typ": "aud",
                "val": "..."
            }, {
                "typ": "iss",
                "val": "https:\/\/sts.windows.net\/...\/"
            }, {
                "typ": "iat",
                "val": "..."
            }, {
                "typ": "nbf",
                "val": "..."
            }, {
                "typ": "exp",
                "val": "..."
            }, {
                "typ": "aio",
                "val": "..."
            }, {
                "typ": "http:\/\/schemas.microsoft.com\/claims\/authnmethodsreferences",
                "val": "pwd"
            }, {
                "typ": "c_hash",
                "val": "..."
            }, {
                "typ": "ipaddr",
                "val": "..."
            }, {
                "typ": "name",
                "val": "..."
            }, {
                "typ": "nonce",
                "val": "..."
            }, {
                "typ": "http:\/\/schemas.microsoft.com\/identity\/claims\/objectidentifier",
                "val": "..."
            }, {
                "typ": "http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/claims\/nameidentifier",
                "val": "..."
            }, {
                "typ": "http:\/\/schemas.microsoft.com\/identity\/claims\/tenantid",
                "val": "..."
            }, {
                "typ": "http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/claims\/name",
                "val": "..."
            }, {
                "typ": "http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/claims\/upn",
                "val": "..."
            }, {
                "typ": "uti",
                "val": "..."
            }, {
                "typ": "ver",
                "val": "1.0"
            }
        ],
        "user_id": "...@....onmicrosoft.com"
    }
]

But this token does not seem to be a JWT.

*

*When using this token (in the GET header "Authorization": "Bearer ) to call the API falls with 401 unauthorized.

*Using a decoder like jwt.io fails.

*The refresh token is not JWT.

*The id_token is valid.

How do I get a valid JWT access_token from the cookie AppServiceAuthSession?

Update
A possible solution: do not attempt to convert the cookie to an access_token. Rather do the normal OAuth2 authentication request. Azure recognizes that the user is already logged in and returns the access token (I'm using implicit flow, so the token is in the URL query string).
To trigger the normal authentication request I do
var url = config.authorization_endpoint
  + "?response_type=token id_token"
  + "&client_id=" + client_id
  + "&state=" + state
  + "&scope=" + requested_scopes
  + "&redirect_uri=" + redirect_uri
  + "&nonce=" + nonce;

// Redirect to the authorization server
window.location = url;

Below is the SPA
var config = {
  client_id: "client_id_hash",
  redirect_uri: "https://my-app-service.azurewebsites.net/index.html",
  authorization_endpoint: "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize",
  token_endpoint: "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token",
  requested_scopes: "openid api://some-guid/user_impersonation"
};

function generateRandomString() {
  var array = new Uint32Array(28);
  window.crypto.getRandomValues(array);
  return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('');
}

function parseQueryString(string) {
  if (string == "") { return {}; }
  var segments = string.split("&").map(s => s.split("="));
  var queryString = {};
  segments.forEach(s => queryString[s[0]] = s[1]);
  return queryString;
}

function parseJwt(token) {
  try {
    // Get Token Header
    const base64HeaderUrl = token.split('.')[0];
    const base64Header = base64HeaderUrl.replace('-', '+').replace('_', '/');
    const headerData = JSON.parse(window.atob(base64Header));

    // Get Token payload and date's
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace('-', '+').replace('_', '/');
    const dataJWT = JSON.parse(window.atob(base64));
    dataJWT.header = headerData;

    return dataJWT;
  } catch (err) {
    return false;
  }
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function component() {
  const element = document.createElement('div');
  const btn = document.createElement('button');

  const btnApi = document.createElement('button');
  btnApi.innerHTML = 'Call API';
  btnApi.onclick = callAPI;
  element.appendChild(btnApi);

  return element;
}

async function callAPI() {
  console.log('callAPI');
  const data = await fetchValues();
  console.log(data);
  const element = document.createElement('div');
  element.innerHTML = `API response: ${data.toString()}`;
  document.body.appendChild(element);
}

function fetchValues() {

  const accessToken = getCookie('access_token');
  console.log('Access token (from cookie):', accessToken);

  const url = 'https://my-app-service.azurewebsites.net/api/values';
  return fetch(url, {
    headers: {
      "Authorization": "Bearer " + accessToken
    }
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data);
      return data;
    });
}

(async function () {
  document.body.appendChild(component());

    const url = "https://my-app-service.azurewebsites.net/.auth/me";
    const response = await fetch(url);
    const data = await response.json();
    const accessToken = data[0].access_token
    const accessTokenJwt = parseJwt(accessToken);

    console.log('accessTokenJwt: ', accessToken, accessTokenJwt);

    document.cookie = "access_token=" + accessToken + "; expires=Fri, 31 Dec 9999 23:59:59 GMT;samesite";

}());


text:
Q: pattern recognition in a time series I understand that the question I am asking seem the be somewhat related to another question which has been asked already here and here.
But I feel that this is an entirely different question. (I have also submitted this question on the dsp.stackexchange)
I have a huge (over 100K data points) time series data of the position (x, y coordinates) of an element in space. This element is vibrating randomly, and both amplitude and the frequency of vibration is random. I want to look at the events which are similar and see if there is any pattern in those events, are they periodic or related somehow.
I am working on a biological problem and have very little knowledge about signal processing. I can provide more details. Any help would be really appreciated.

A: One of the areas of the research on time series patterns is called Motif Detection or Discovey, some use association strategies, other are probabilistic.
Some links here http://dl.acm.org/results.cfm?query=motif+discovery&Go.x=5&Go.y=12


text: Q: How can Raman Spectra be utilised to know the crystal structure? If Raman spectroscopy is using a visible or infrared source to excite phonons in the crystal, that is much different from XRD which is using higher energy X-rays scattered from the crystal planes. How can we use Raman spectroscopy to know the crytsal structure? Do you know and example? Any simple reference with excercises.


text:
Q: Correcting data v Manipulating Query to accommodate data discrepancy? I hope this is not the wrong place to ask, if so, please kindly advice the right place.
Say in a company you have 2 database that are different yet contains the same data. While how the data stored is generally the same, it has quite a lot small data inconsistency and discrepancy. But you are given a task to collect data from those two databases.
I wanted to know how would a DBA handle this situation, given that you cannot fiddle directly to the actual data without getting permissions from involved departments.
Will they, say :
1. Create a temporary DB to accommodate things.
2. Adjust the Query to accommodate for all kinds of problem that can be traced
or maybe there are other solutions?
Thanks before.


text:
Q: postgreSQL default collation (case insensitive) I am using PostgreSQL 12 and I would like to create a schema with insensitive collation. I read about Nondeterministic Collations here https://www.postgresql.org/docs/current/collation.html
When I create a new Database I always get the collation German_Germany.1252. This is not listed in pg_collations. I tried to create a new collation and use it like this
CREATE COLLATION german FROM "de_DE";
create database test2 LC_COLLATE german;

but the new database is also created with German_Germany.1252. I read that PostgreSQL use the collations provided by the operating system. I am running on windows and by executing the command line systeminfo, I get
System Locale en-us;English (United States)
Input Locale de;German (Germany)

So I assume that German_Germany.1252 comes from my windows, is there a way to change it to be nondeterministic or case-insensitive?
In generla is there any way to set a case-insensitive collation in PostgreSQL?


text:
Q: Datepicker: Setting input value to current date I am using this plugin for Bootstrap, for date picking http://eternicode.github.io/bootstrap-datepicker/
I have it working here FIDDLE
But I dont know if this is the right way to do it? Or if there's a way to do it through the plugin. I've tried to but I haven't got it right.
HTML:
Date: <input type="text" name="" class="datepicker" />

Jquery:
var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var output =((''+month).length<2 ? '0' : '') + month +  '/' + ((''+day).length<2 ? '0' : '') + day + '/' + d.getFullYear();

$('.datepicker').datepicker();

$('.datepicker').val(output);

So I'm using Jquery to get the current date then I just fire the datepicker and then set the input value to the current date.
Any other ideas or suggestions will be appreciated!

A: Your method is good.
You could, however, reduce it a couple of characters - if you'd like - to something like this:
var d = new Date(),
    output = [
        ('0' + (d.getMonth() + 1)).substr(-2),
        ('0' + d.getDate()).substr(-2),
        d.getFullYear()
    ].join('/');

$('.datepicker').datepicker().val(output);

Also - if you're doing more work with dates - it might be a good idea to have a look at some date libraries, like date.js or sugar.js, then you could do something like this:
$('.datepicker').val(new Date().toString('MM/dd/yyyy'));        // date.js
$('.datepicker').val(Date.create().format('{MM}/{dd}/{yyyy}')); // sugar.js

A: Datepicker is initialized with current date by default. (demo)
You can set it manually too:
$("#datepicker").datepicker({defaultDate: new Date()}); //at initialization
$("#datepicker").datepicker("setDate",new Date());      //runtume

Setting to other dates is easy too:
$("#datepicker").datepicker("setDate","14/12/2014");

With self defined format:
$("#datepicker").datepicker({ dateFormat: "yy-m-d" });
$("#datepicker").datepicker("setDate","14-12-4");

To get that formatted value, use:
$("#datepicker").datepicker().val();

Documentation here.


text:
Q: making whole div tag clickable ,css html anchor tag
Hello I have one accordion as you can see in image. I want to make that whole Resources clickable but when I do that , Gyphyicon I am using get messed up.
I want that icon and Resources text in one line.
Here is my html code for this thing:

Resources

P.S: I already try different css thing in my style.css but it wont work, FYI also I am only practicing on resource thing(see image) not on calculation , that's why calculation is not clickable
Any help Appreciated.
Thanks in Advance

A: have you tried this?

Resources

A: Try This Code

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

 Resources

A:

Resources

In addition to any other solution, I would like to add a flexbox solution. Since the H4 tag is the containing element here, I've adding display: flex and align-items: center here. The first part will force them next to each other and the second part will make sure the items will be aligned properly.
Be aware this solution is not supported in IE9 or older IE browsers.


text:
Q: Weird result with empty vector and paste0 in R I'm writing a function which generates vector of filenames based on content of data frame.
It works perfectly for a non-empty data frame, but produces weird result for an empty data frame:
> head(c)
  id nobs
1  1  117
2  2 1041
3  3  243
4  4  474
5  5  402
6  6  228
> cc <- c[c$nobs > 1000, ]
> cc
     id nobs
2     2 1041
154 154 1095
248 248 1005
> paste0("specdata", "/", sprintf("%03d", cc$id), ".csv")
[1] "specdata/002.csv" "specdata/154.csv" "specdata/248.csv"
> cc <- c[c$nobs > 5000, ]
> paste0("specdata", "/", sprintf("%03d", cc$id), ".csv")
[1] "specdata/.csv"

Does anybody have an idea why it produces "specdata/.csv" instead of an empty vector?
(At the moment I use if(nrow(cc)) to return an empty vector, but I hope there must be a better way to do it)

A: paste0 is used for concatenating strings.
paste0("specdata", "/", sprintf("%03d", cc$id), ".csv")

In your case, sprintf("%03d", cc$id) will return empty string because cc is empty.
Here, you are concatenating "spedata", "/", "", ".csv"
and the result you get is expected.