text:
Q: Is there a way to check if a platform supports an OpenGL function? I want to load some textures using glTexStorageXX(), but also fall back to glTexImageXX() if that feature isn't available to the platform.
Is there a way to check if those functions are available on a platform?  I think glew.h might try to load the GL_ARB_texture_storage extensions into the same function pointer if using OpenGL 3.3, but I'm not sure how to check if it succeeded.  Is it as simple as checking the function pointer, or is it more complicated?
(Also, I'm making some guesses at how glew.h works that might be wrong, it might not use function pointers and this might not be a run-time check I can make?  If so, would I just... need to compile executables for different versions of OpenGL?)
if (glTexStorage2D) {
    // ... calls that assume all glTexStorageXX also exist,
    // ... either as core functions or as ARB extensions
} else {
    // ... calls that fallback to glTexImage2D() and such.
}

A: You need to check if the OpenGL extension is supported. The number of extensions supported by the GL implementation can be called up with glGetIntegerv(GL_NUM_EXTENSIONS, ...).
The name of an extension can be queried with glGetStringi(GL_EXTENSIONS, ...).
Read the extensions into a std::set
#include <set>
#include <string>

GLint no_of_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &no_of_extensions);

std::set<std::string> ogl_extensions;
for (int i = 0; i < no_of_extensions; ++i)
    ogl_extensions.insert((const char*)glGetStringi(GL_EXTENSIONS, i));

Check if an extension is supported:
bool texture_storage =
    ogl_extensions.find("GL_ARB_texture_storage") != ogl_extensions.end();

glTexStorage2D is in core since OpenGL version 4.2. So if you've created at least an OpenGL 4.2 context, there's no need to look for the extension.
When an extension is supported, all of the features and functions specified in the extension specification are supported. (see GL_ARB_texture_storage)

GLEW makes this a little easier because it provides a Boolean state for each extension.
(see GLEW - Checking for Extensions) e.g.:
if (GLEW_ARB_texture_storage)
{
    // [...]
}


text:
Q: How to insert many related records in one sql file I want to insert many records in  3 tables, businesses, business_categories (business_id), business_details(business_id),  I want to insert many data.
as you can see,   the data in business_categories and business_details will need to use the business's id, and when inserting data, I still don't know the business id.
in the past, I was writing a ruby script to do that things, but it's pretty slow.  and now I want to write a script to generate sql file directly, it can be the fast way.
I would write this.
insert into businesses(name, ..) values ("blabla", ...)
insert into business_categories(business_id, ..) values(? ..)
insert into business_details(business_id, ..) values(? ..)

Is it possible to set the right value to the ? ?
thanks.

A: You could save the last inserted id to a variable and set that value in the following inserts.
https://stackoverflow.com/a/17112962/1165441
This answer has some info that is really good.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it OK to pass reference to a pointer as a function argument? I had the understanding that in c++ & and * cancel each other i.e int *&p is essentially equal to p as its value at address of integer p.
Now is it valid to pass reference to a pointer in view of above i.e say i am trying to pass reference to a pointer as an argument in a function as below?
void func(int* &p)

Won't the above result in cancellation of * with & and will just be int p?
How correct is it if i try to pass reference to pointer of a class object on similar terms?
#include <iostream>

using namespace std;

int gobal_var = 42;

// function to change Reference to pointer value
void changeReferenceValue(int*& pp)
{
    pp = &gobal_var;
}

int main()
{
    int var = 23;
    int* ptr_to_var = &var;

    cout << "Passing a Reference to a pointer to function" << endl;

    cout << "Before :" << *ptr_to_var << endl; // display 23

    changeReferenceValue(ptr_to_var);

    cout << "After :" << *ptr_to_var << endl; // display 42

    return 0;
}

A: You are correct that the & address-of operator and the * indirection operator cancel each other out when used inside an expression.
However, when used inside a declaration, these operators have a very different meaning. Inside a declaration, * means "pointer" and & means "reference". Therefore, when used inside a declaration, they do not cancel each other out.
An object of type int*& is simply a reference to a pointer to an int.


text:
Q: not been updated for Face ID Message previously my app is using touchID for login and now i am going to implement faceID for login the app, and my app getting this message when the app start local authentication.
How can I prevent this message from show up when I use faceID for login?
The message content: "This app was designed to support Touch ID. It has not been updated for Face ID."
Note: I had NSFaceIDUsageDescription with values on my info.plist

Appreciated if any suggestion is given!

A: Adding a new key named: "Privacy - Face ID Usage Description" and insert a string value solved my issue!


text:
Q: How can i make an element from a bottom stacking context stays in front of another higher stacking context? How can i make that an element contained in a stacking context at the bottom of the stacking order appears in front of another element in a different stacking context that is higher in the stacking order ?
e.g:
HTML:

CSS:
.Parent-1{
    position: absolute;
    z-index: 10;
    background-color: green;
}

.Parent-2 {
    position: absolute;
    z-index: 5;
    background-color: red;
}

.pepe, .pepin{
    background-color: blue;
}

.pepin{
    position: fixed;
    z-index: 100;
}

this is what i have (this is what it's suppose to happen):

this is what i want:

Bare in mind that i can't change the elemnts order in HTML neither remove the z-index in Parents element

A: The short answer is that you can't. This image from MDN's explanation about stacking context explains it well:

There has been talk about escaping stacking context using position: fixed but it seems this is not happening just yet (see this fiddle and the question that generated it).
Alternate Solution:
For you, a possible alternative solution would be to nest Parent-1 inside Parent-2 and then use position: absolute to put Parent-1 wherever you want it.


text:
Q: When does the characteristic length deem a layer infinitely thin? When reading Real-time terahertz imaging with a single-pixel detector a paragraph states:
"(...) these carriers will diffuse inside the semiconductor with a characteristic length around ~ 0.3 mm rendering the infinitely thin conductive layer approximation invalid."
I thought 0.3 mm would be a very thin layer, but apparently it still isn't thin enough to consider it to be infinitely thin. So from what value is it viable to make such an assumption?

A: Sure, 0.3 mm is sort of thin, but such approximations tend to be valid only when some number is small relative to another. I think the relevant comparison here is between this characteristic length and the wavelength of the THz radiation used. While I didn't see what frequency they used at a quick glance, it's worth noting that 1 THz corresponds to $\lambda=0.3$ mm.
You may want to look to this review article for a broader perspective.


text:
Q: Сервис + передача видео Пытаюсь написать передачу видео с камеры, использую wcf. Видео шлётся только с одного компьютера другому, причём компьютер тут как реальная физическая сущность.
Суть проблемы. Есть компьютер 1 и компьтер 2. На 1-ом компьютере запустил сервис. Скопировал клиентскую часть на обе машины, т.е. исполняемые экземпляры полностью идентичны. При этом видео шлётся только с 1-го компьютера на 2-ой. Наоборот по какой-то причине не работает.
Я предположил, что может быть это как-то связано с тем, где запущен сервис, но - нет. Если сервис активировать на машине 2, то видео всё равно отсылается с 1-ой на 2-ую, но никогда наоборот. Прошу помочь разобраться, что не так.
Проект на гитхабе.
[ServiceContract(CallbackContract = typeof(IChatService))]
    public interface IChatService
    {
        [OperationContract(IsOneWay = true)]
        void Join(string memberName);
        [OperationContract(IsOneWay = true)]
        void Leave(string memberName);
        [OperationContract(IsOneWay = true)]
        void SendMessage(string memberName, string message);
        [OperationContract(IsOneWay = true)]
        void Call(string memberName, byte[] message);
    }

    public interface IChatChannel : IChatService, IClientChannel
    {
    }

    public partial class ChatClient : Form, IChatService
    {
        private delegate void UserJoined(string name);
        private delegate void UserSendMessage(string name, string message);
        private delegate void UserCall(string name, byte[] message);
        private delegate void UserLeft(string name);

        private static event UserJoined NewJoin;
        private static event UserSendMessage MessageSent;
        private static event UserCall userCall;
        private static event UserLeft RemoveUser;private void btnLogin_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                try
                {
                    NewJoin += new UserJoined(ChatClient_NewJoin);
                    MessageSent += new UserSendMessage(ChatClient_MessageSent);
                    RemoveUser += new UserLeft(ChatClient_RemoveUser);
                    userCall += new UserCall(ChatClient_Call);
                    channel = null;
                    this.userName = txtUserName.Text.Trim();
                    InstanceContext context = new InstanceContext(
                        new ChatClient(txtUserName.Text.Trim()));
                    factory =
                        new DuplexChannelFactory<IChatChannel>(context, "ChatEndPoint");
                    channel = factory.CreateChannel();
                    IOnlineStatus status = channel.GetProperty<IOnlineStatus>();
                    status.Offline += new EventHandler(Offline);
                    status.Online += new EventHandler(Online);
                    channel.Open();
                    channel.Join(this.userName);
                    grpMessageWindow.Enabled = true;
                    grpUserList.Enabled = true;
                    grpUserCredentials.Enabled = false;
                    this.AcceptButton = btnSend;
                    rtbMessages.AppendText("*****************************WEL-COME to Chat Application*****************************\r\n");
                    txtSendMessage.Select();
                    txtSendMessage.Focus();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        void ChatClient_Call(string name, byte[] message)
        {
            try
            {
                if (name == "1")
                {
                    EncodingImage enc = new EncodingImage();
                    var result = enc.EncodingImageForRecievedBuffer(message);
                    pictureBox1.Image = result;
                }
                else
                {
                    EncodingImage enc = new EncodingImage();
                    var result = enc.EncodingImageForRecievedBuffer(message);
                    pictureBox2.Image = result;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
            }
        }

        public void Call(string memberName, byte[] message)
        {
            if (MessageSent != null)
            {
                userCall(memberName, message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            isStop = false;
            Thread t1 = new Thread(start);
            t1.Start();
        }

        private void start()
        {
            while (!isStop)
            {
                Thread.Sleep(100);
                CodingImage image = new CodingImage();
                byte[] bytes = image.CodingImages(video);
                channel.Call(this.userName, bytes);
            }
        }


text:
Q: Does Kendo Grid work in Mono? Just a simple question I've been unable to track down an answer to. If anyone knows I would appreciate if you would be willing to share your knowledge here.

A: I guess you mean Kendo UI Grid for ASP.NET MVC. Yes, it works in Mono. In fact we are actively using Mono for development.


text:
Q: No module named apiclient.discovery I got this error in Google App Engine's Python, But I don't know how to fix,
I added into my project directory the following folders:
apiclient, gflags, httplib2, oauth2client, uritemplate
but I got always the same error

A: This is a Community Wiki post of Jorvis' answer
The apiclient.discovery service is a part of the Google API Client Library. You can therefore install the Client Library using the provided command (e.g for Python):
pip install --upgrade google-api-python-client

This will solve the 'No module named ...' warning for any of the supported APIs.


text:
Q: openCL platform/device query I'm using the Nvidia implementation of openCL.
cl_uint devicecount=NULL;
cl_uint NumPlatforms;
clGetPlatformIDs (0, NULL, &NumPlatforms);

cl_platform_id* PlatformIDs;
PlatformIDs = new cl_platform_id[NumPlatforms];
clGetPlatformIDs(NumPlatforms, PlatformIDs, NULL);

cl_device_id cdDevice;
clGetDeviceIDs(NULL, CL_DEVICE_TYPE_CPU, 1, &cdDevice, &devicecount);

cout << NumPlatforms << endl;
cout << PlatformIDs << endl;
cout << cdDevice << endl;
cout << devicecount << endl;

I actually probably don't have a compatible GPU at the moment, but I have a compatible CPU.  The query tells me that I have 0 platforms, and 0 devices.  Am I doing this correctly?  I don't exactly understand what a platform is, and why I don't have one.  What exactly does it take for openCL to find and use a platform?
EDIT:
I got my new card in the mail today, installed amd sdk, and reinstalled nvidia sdk, and I am now seeing all my platforms and devices!
The next step is to create contexts.  Can I put devices from different platforms on the same context?  Is it very difficult, given you need separate command queues for each device etc, to write a program to use all devices on a system even if the number is a hundred thousand?

A: Platform is, basically, an installed OpenCL implementation. Physically, it is an ICD record (file in /etc/OpenCL/vendors/ on *nix, registry record in Windows) which helps OpenCL.dll/libOpenCL.so find actual vendor-specific implementation(s).
In your case it looks like since you GPU does not support OpenCL, driver has not added nVidia's library to the list of the platforms. [offtop] I wonder whether it would be required to reinstall driver after upgrading you hardware to CUDA/OpenCL compatible...
In order to use your CPU as OpenCL device, you must install either AMD APP SDK or Intel OpenCL SDK, since nVidia's implementation does not support CPU in any way

A: I installed the intel, and amd SDK, and get interesting results when I get information for the cpu device on the intel platform vs the amd platform.
My intel I5 device, on the intel platform has 128 samplers and 128 execution capabilities, while on the amd platform it has 16 samplers and execution capabilities.  Also on the amd platform, the cpu has a max clock frequency of 3310, while on intel's platform 3300.
I wonder if this difference is in name only, or if there is a difference in performance between choosing an intel device off of an intel platform?


text:
Q: How to handle Spring transactions inside coroutines? It is known that Spring transactions are tied to threads: there are thread locals specific for an ongoing transaction. And transactions know nothing about coroutine context. So what if I would like to call a @Transactional method from inside a coroutine: is it safe?
Imagine we have a method inside JobProcessor bean processing a job list. Each job is processed inside async{}. And I would like to update DB after every successful or failed processing using @Transactional methods of bean JobService.
class JobProcessor {
    fun process(jobs: List<MyJob>) =
        jobs.map { job ->
            async {
                try {
                    ....//processing
                    jobService.success(job)
                } catch (t: Throwable) {
                    jobService.failure(job)
                }
        }
}

class JobService {
    @Transactional
    fun success(job: MyJob) {...}

    @Transactional
    fun failure(job: MyJob) {...}
}

A: First, please keep in mind that annotating bean methods with @Transactional will not suffice - make sure you enabled declarative transaction handling, e.g. by adding @EnableTransactionManagement to a @Configuration class or by using    <tx-annotation-driven /> in XML config.
Regarding your question: There will only be a transactional context while executing Spring bean methods annotated with @Transactional when they are being invoked from a Spring bean outside of their containing class! Declarative transactions in Spring rely on AOP proxy classes being created for the @Transactional annotated classes by Spring. At runtime if a Spring bean A calls a @Transactional method on a Spring bean B, the call will be intercepted by an AOP proxy that transparently spawns a transaction, calls the original method of Spring bean B and commits or rollbacks this transaction afterwards.
Remember: Only external method calls that come in through the proxy will be intercepted – any self-invocation calls, as in your example this.process() calling @Transactional methods this.success() or this.failure() will not start any transaction – even if the method is annotated with @Transactional.


text:
Q: SQL query to get all posts with their revision data I am trying to export all posts with their revision. So that i can see what has been changed at what time and who changed it.
I am not getting any idea how to do this. My query so far:-
select p.id, p.post_parent, p.post_title
from wp_posts p
join wp_posts p1 on p.id=p1.post_parent
where post_type in ('hg-scratch-card','revision') and
post_status='publish';

but it does not seem to work.
Any help regarding this will be really appreciated.
Edit:-
select * from wp_posts where post_type in('hg-scratch-card','revision') and post_parent in
(
    select id from wp_posts where post_type='hg-scratch-card'
)
order by post_modified DESC

It returns all post revision of a specific post type:- "hg-scratch-card" but the parent post is missing in the rows.

A: select p.id, p.post_author, p.post_date, p.post_title, p.post_content, p.post_status, p.post_modified, p.post_parent, p.post_type,
pm.meta_key, pm.meta_value,
u.display_name
from wp_posts p
inner join wp_postmeta pm on pm.post_id=p.id
inner join wp_users u on u.id=p.post_author
where p.post_type in('hg-scratch-card','revision') and
p.post_parent in(select id from wp_posts where post_type='hg-scratch-card') and
LEFT(pm.meta_key, 1)!='_'
order by post_modified DESC


text:
Q: Why Function is getting accessed without object in C++? In the following program.
#include<iostream>

using namespace std;

class Base{

public:
    Base(){
    cout<<"I am Constructor"<<endl;
    }
    void method();

};

void Base::method(){
cout<<"I am method"<<endl;
}

int main()
{

    Base *sc1;
    Base *sc2;
    sc1->method();
    sc2->method();

}

the output I am getting is as follows

I am method
I am method

How can this happen as no object is created?

A: It is undefined behaviour, so "anything" can happen. It probably runs because you do not access anything (implicitly or explicitly) via the this pointer.
This would be more likely to fail:
struct Foo
{
  int foo() const { return i; }
  int i;
};

int main()
{
  Foo* f;
  f->foo();
}

A: Because you have no object your code has Undefined Behaviour. Undefined behaviour means exactly what it says, it doesn't mean your program will crash, it means anything can happen, including accessing an object that doesn't exist.
One of the things that makes programming C++ hard is that you cannot rely on bugged programs to crash, sometimes they seem to work.

A: This is undefined behavior, but it is not crashing because you are not accessing any member variables from that class so even if the pointer sc1/sc2 is random value nothing is happening.


text:
Q: VB.net adding multiple controls on button click I'm trying to make a userinterface that generates itself on request (button click)
Private Sub Body_new_part_add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Body_new_part_add.Click

So when i add a Combobox as first it's no problem it generates the box & places it on the right position etc.
    Dim oTypeBox As New ComboBox
    oTypeBox.Name = "Body_type_" & oBodyPartsNumber
    oTypeBox.Location = New System.Drawing.Point(7, 78)
    Body_parts.Controls.Add(oTypeBox)

Now i want to add another control, a textbox next to the Combobox.
    Dim oTypeBox As New ComboBox
    oTypeBox.Name = "Body_type_" & oBodyPartsNumber
    oTypeBox.Location = New System.Drawing.Point(7, 78)
    Body_parts.Controls.Add(oTypeBox)

    Dim oTextbox As New TextBox
    oTextbox.name = "test"
    oTextbox.Location = New System.Drawing.Point(50, 78)
    Body_parts.Controls.Add(oTextbox)

This gives me this error.
'New' cannot be used on an interface.

What do i need to change in order to get this done? I need to add +- 10 controls on each button click event.

A: Try this one
Public Class Form1
    Dim cLeft As Integer = 1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        AddNewTextBox()
    End Sub
    Public Function AddNewTextBox() As System.Windows.Forms.TextBox
        Dim txt As New System.Windows.Forms.TextBox()
        Me.Controls.Add(txt)
        txt.Top = cLeft * 25
        txt.Left = 100
        txt.Text = "TextBox " & Me.cLeft.ToString
        cLeft = cLeft + 1
        Return txt
    End Function
End Class


text:
Q: How do I add a new SQL Server partition range to house future data without altering the existing data locations? Several years ago I partitioned a collection of very large columnstore indexed tables. For simplicity, let's say I have four partition files where data is stored based on ranges of customer ID.
CREATE PARTITION FUNCTION [CustomerPF](int) AS RANGE LEFT FOR VALUES (
    N'25'
    ,N'50'
    ,N'75')

CREATE PARTITION SCHEME [CustomerPS] AS PARTITION [CustomerPF] TO (
    customer0to25fg
    ,customer26to50fg
    ,customer51to75fg
    ,customer76plusfg

CREATE CLUSTERED COLUMNSTORE INDEX [CCI_GiantTable] ON [schema].[GiantTable] ON [CustomerPS]([CustomerId])

Now let's say I would like to create space, in advance, for customers 100 and above. I tried to do it like this:
ALTER PARTITION SCHEME CustomerPS NEXT USED customer100plusfg
ALTER PARTITION FUNCTION [CustomerPF]() SPLIT RANGE (100)

But I get the following error:

SPLIT clause of ALTER PARTITION statement failed because the partition
is not empty.  Only empty partitions can be split in when a
columnstore index exists on the table. Consider an ALTER TABLE SWITCH
operation from one of the nonempty partitions on the source table to a
temporary staging table and then re-attempt the ALTER PARTITION SPLIT
operation. Once completed, use ALTER TABLE SWITCH to move the staging
table partition back to the original source table.

I was hoping that, because I do not yet have a customerID of 100 or greater that I would be allowed to add a new partition without having to alter the columnstore tables themselves. How do I add a new partition for customers 100-n? Is it possible to do this without moving all the data for "customer75plus"? There are a lot of large columnstore tables in these partitions and moving data around is not all that feasible.

A: The new partition you create with SPLIT contains the split point.  So you are trying to create a new partition (75-100].  But the partition (75-MaxVal] contains data.
Instead use a RANGE RIGHT partition scheme, so when you split the new partition is on the end so you can split anywhere above the current max value.
With RANGE LEFT you would have to always maintain an empty partition on the end to split.


text:
Q: calling generic handler from code-behind I have a function that I'd like to put in generic handler to be called from ajax as well as from code-behind.  Is this possible in vb.net? Ajax works fine, but I'm having problems trying to call it from code using Webrequest method.  The handler sits in the root of my solution.  My handler returns a simple string for now.   I've tried..."Verify.ashx", "/Verify.ashx", "http:///Verify.ashx".  Right now, I'm testing only from development.
Dim request As System.Net.WebRequest = System.Net.WebRequest.Create("Verify.ashx")

The error I get is in the WebRequest.Create method:     Invalid URI: The format of the URI could not be determined.


text:
Q: VSCode Extension to underline certain keywords I want to make a new VSCode Extension that can help flag keywords by underlining them and suggesting alternatives.
I've been looking through the Extension docs and thought I'd find it in the Language Extensions section but seemingly no such luck:
https://code.visualstudio.com/api/language-extensions/overview
Anyone know what this "underline and suggest" feature is actually called or where I could find more info?


text:
Q: Setup Oracle SSL Listener I am trying to create an Oracle Database container that has an SSL enabled listener for connections.
But I am having trouble getting the listener to start.
I have tried many configurations but here is where I am stuck:
File structure:
[oracle@361ebc8481f2 /]$ ls -la $ORACLE_HOME/network/admin
total 24
drwxr-xr-x 1 oracle oinstall 4096 Mar 11 17:45 .
drwxr-xr-x 1 oracle oinstall 4096 Feb 26 16:36 ..
lrwxrwxrwx 1 root   root       44 Feb 26 17:07 listener.ora -> /opt/oracle/oradata/dbconfig/XE/listener.ora
drwxr-xr-x 2 oracle oinstall 4096 Feb 26 16:36 samples
-rw-r--r-- 1 oracle oinstall 1441 Aug 26  2015 shrept.lst
-rw-r--r-- 1 root   root      188 Mar 11 17:45 sqlnet.backup
-rw-r----- 1 oracle oinstall  589 Mar 11 17:45 sqlnet.ora
lrwxrwxrwx 1 root   root       44 Feb 26 17:07 tnsnames.ora -> /opt/oracle/oradata/dbconfig/XE/tnsnames.ora

sqlnet.ora:
[oracle@e05203241582 /]$ cat $ORACLE_HOME/network/admin/sqlnet.ora
# sqlnet.ora Network Configuration File: /opt/oracle/product/18c/dbhomeXE/network/admin/sqlnet.ora
# Generated by Oracle configuration tools.

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)

WALLET_LOCATION =
   (SOURCE =
     (METHOD = FILE)
     (METHOD_DATA =
       (DIRECTORY = /u01/app/oracle/wallet)
     )
   )

# General Settings
SSL_CLIENT_AUTHENTICATION = FALSE
# SSL_SERVER_DN_MATCH = FALSE
# SSL_CIPHER_SUITES = (TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_256_CBC_SHA256)

# SQLNET Settings
SQLNET.AUTHENTICATION_SERVICES = (TCPS,NTS,BEQ)
# SQLNET.WALLET_OVERRIDE = TRUE

listener.ora:
oracle@e05203241582 /]$ cat $ORACLE_HOME/network/admin/listener.ora
# listener.ora Network Configuration File:
         SID_LIST_LISTENER =
           (SID_LIST =
             (SID_DESC =
               (SID_NAME = PLSExtProc)
               (ORACLE_HOME = /opt/oracle/product/18c/dbhomeXE)
               (PROGRAM = extproc)
             )
           )

         LISTENER =
           (DESCRIPTION_LIST =
             (DESCRIPTION =
               (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
               (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
              )
           )

          SID_LIST_LISTENER2 =
           (SID_LIST =
             (SID_DESC =
               (SID_NAME = PLSExtProc)
               (ORACLE_HOME = /opt/oracle/product/18c/dbhomeXE)
               (PROGRAM = extproc)
             )
           )

         LISTENER2 =
           (DESCRIPTION_LIST =
             (DESCRIPTION =
               (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
               (ADDRESS = (PROTOCOL = TCPS)(HOST = 0.0.0.0)(PORT = 1522))
              )
           )

         DEFAULT_SERVICE_LISTENER = (XE)
         DEFAULT_SERVICE_LISTENER2 = (XESSL)

WALLET_LOCATION =
  (SOURCE =
    (METHOD = FILE)
    (METHOD_DATA =
      (DIRECTORY = /u01/app/oracle/wallet)
    )
  )

SSL_CLIENT_AUTHENTICATION = FALSE
# SSL_SERVER_DN_MATCH = FALSE

tnsnames.ora:
[oracle@e05203241582 /]$ cat $ORACLE_HOME/network/admin/tnsnames.ora
# tnsnames.ora Network Configuration File:

XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

LISTENER_XE =
  (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))

XEPDB1 =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XEPDB1)
    )
  )

XESSL =
  (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCPS)(HOST = 0.0.0.0)(PORT = 1522))
      (CONNECT_DATA =
        (SERVER = DEDICATED)
        (SERVICE_NAME = XESSL)
      )
  )

LISTENER2_XESSL =
  (ADDRESS = (PROTOCOL = TCPS)(HOST = 0.0.0.0)(PORT = 1522))

XEPDB1SSL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCPS)(HOST = 0.0.0.0)(PORT = 1522))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XEPDB1SSL)
    )
  )

EXTPROC_CONNECTION_DATA =
  (DESCRIPTION =
     (ADDRESS_LIST =
       (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
     )
     (CONNECT_DATA =
       (SID = PLSExtProc)
       (PRESENTATION = RO)
     )
  )

Okay so when I start the server LISTENER is running but LISTENER2 is not:
[oracle@e05203241582 /]$ lsnrctl status LISTENER

LSNRCTL for Linux: Version 18.0.0.0.0 - Production on 11-MAR-2021 18:06:01

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

Connecting to (ADDRESS=(PROTOCOL=tcp)(HOST=)(PORT=1521))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for Linux: Version 18.0.0.0.0 - Production
Start Date                11-MAR-2021 18:00:28
Uptime                    0 days 0 hr. 5 min. 33 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   /opt/oracle/product/18c/dbhomeXE/network/admin/listener.ora
Listener Log File         /opt/oracle/diag/tnslsnr/e05203241582/listener/alert/log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e05203241582)(PORT=1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=127.0.0.1)(PORT=5500))(Security=(my_wallet_directory=/opt/oracle/admin/XE/xdb_wallet))(Presentation=HTTP)(Session=RAW))
Services Summary...
Service "XE" has 1 instance(s).
  Instance "XE", status READY, has 1 handler(s) for this service...
Service "XEXDB" has 1 instance(s).
  Instance "XE", status READY, has 1 handler(s) for this service...
Service "bc414e16d5db0a27e053020011ac7dda" has 1 instance(s).
  Instance "XE", status READY, has 1 handler(s) for this service...
Service "xepdb1" has 1 instance(s).
  Instance "XE", status READY, has 1 handler(s) for this service...
The command completed successfully

[oracle@e05203241582 /]$ lsnrctl status LISTENER2

LSNRCTL for Linux: Version 18.0.0.0.0 - Production on 11-MAR-2021 18:06:26

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

TNS-01101: Could not find listener name or service name LISTENER2

If I try to start LISTENER2 I get:
[oracle@e05203241582 /]$ lsnrctl start LISTENER2

LSNRCTL for Linux: Version 18.0.0.0.0 - Production on 11-MAR-2021 18:07:49

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

Starting /opt/oracle/product/18c/dbhomeXE/bin/tnslsnr: please wait...

TNSLSNR for Linux: Version 18.0.0.0.0 - Production
System parameter file is /opt/oracle/product/18c/dbhomeXE/network/admin/listener.ora
Log messages written to /opt/oracle/diag/tnslsnr/e05203241582/listener2/alert/log.xml
TNS-01151: Missing listener name, LISTENER2, in LISTENER.ORA

Listener failed to start. See the error message(s) above...

But it does exist in that file.
Is there something else I need to configure to get this listener to start correctly?
Sorry I know throwing a bunch of outputs into a stack overflow question isn't great, but I haven't been able to find a way to resolve this for a couple of days.  Any help would be appreciated.


text:
Q: Material Table not reflecting changes on datasource This is my first question in Stack Overflow. I'll try to be specific but I don't know how to keep this short, so this is going to be a long post. Sorry about that. I promise I searched and tried a lot of stuff before asking, but I'm kind of lost now.
I'm developing a simple app in Angular 6 to keep track of software requisites and the tests associated to those requisites.

*

*I have a component, called RequisiteList, whose HTML part consists in a mat-table with an Array of my own Requisite model class as [dataSource]. This array is received as an @Input parameter, and it also has an @Output parameter which is an EventEmitter that notifies and passes to the parent component every time a Requisite on the list is clicked.

*I make use of RequisiteList inside of ReqListMain, which is a component consisting on the list and a hierarchical tree for filtering. This component is working fine, showing, and filtering requisites as intended. This component also captures the @Output event of the list and passes it as an @Output to its parent.

*Finally (for what it's related to this question), I have a TestView component that has both an instance of RequisiteList to show the requisites currently associated to current test, and an instance of ReqListMain to add new requisites to current test (like a "browser"). This TestView has an instance of the model class Pectest corresponding to the test that is being currently visualized, which has an array of Requisite.
The idea in this last component was that whenever a requisite of the "browser" list was clicked, it was added to the current test's list. In order to do that, in the callback method associated to the @Output event of the browser list, I tried to add the Requisite received as a parameter:
addrequisite(requisite: Requisite) {
this.currentTest.requisites.push(requisite);
console.log('Current test: ');
console.log(this.currentTest);
}

In the HTML part of TestView, I inserted the RequisiteList component like this:
<app-requisitelist [requisites]="currentTest.requisites" ngModel name="reqlistview"></app-requisitelist>

(The ngModel property is part of the things I've been trying, I'm not sure it's necessary).
The result is:

*

*The clicked requisite is not shown in the list.

*In the console output I can see the content of currentTest object, and I verify that clicked requisites are in fact added to the requisites array of that object, so the event fires and the object is passed upwards by the children components.

I'm not sure if my problem is that data binding is made by value (I don't think so, as I bind an Array, which is an object AFAIK), or the table is not detecting data changes (I've tried to force data change detection with ChangeDetector), or anything else.

A: You pass a array to the app-requisitelist component. This component waits this array changes to update the content. When you do this.currentTest.requisites.push(requisite), the array this.currentTest.requisites doesn't change, I mean, if you do
const tmp = this.currentTest.requisites;
this.currentTest.requisites.push(requisite)
if (tmp === this.currentTest.requisites) {
    console.log('The arrays are the same');
}

You will get the log printed. So, I suggest do something like that:
addrequisite(requisite: Requisite) {
    this.currentTest.requisites.push(requisite);
    this.currentTest.requisites = this.currentTest.requisites.map(item => item);
    console.log('Current test: ');
    console.log(this.currentTest);
}

The inserted line forces this.currentTest.requisites to be a new array with the same content.


text:
Q: AngularJS, UI Bootstrap Carousel link to a specific slide from a different view I'm trying to click through to a different view, with a specific slide in a Bootstrap UI Carousel open.
I've been able to create a button that goes to a specific slide by using the active property:
$scope.setActive = function(idx) {
   $scope.slides[idx].active=true;

but I can't seem to figure out how to link to another view and also open a specific slide.
Here's a plunker that show's my attempt so far. In this example I'm trying to link to the home.html with slide two open from page.html.
http://plnkr.co/edit/MXK8Auhc89AKMcoyy0Jn?p=preview
I'm new to AngularJS so there might be a very simple answer to this that I'm over looking.
I'd appreciate any help.
Thanks

A: You can use $routeParams for this. Here is working example: http://plnkr.co/edit/Ky2HEpOYuqtgqsTSUr1x?p=preview
 //in app.config
 .when('/home/:slide', {
    //introducing slide as parameter here
    templateUrl: 'pages/home.html',
    controller: 'SlideController'
  })

//in Ctrl controller
$scope.setActive($route.current.params.slide || 0);

    View Second Slide

second item of the array is array_name[1].


text:
Q: bad font quality in small fontsize wpf hi i changed font in my application but i think when app is running font quality is bad, As you can see in the picture in VS font quality is good but in runtime its bad is there any way to fix this? when i increase fontsize (like 100) quality is very good but when i use 14 its bad.
VS:

Runtime:


text:
Q: Exit out of a CPropertySheet Wizard I have a C++ application that is a Wizard.  During the application it detects if certain hardware is installed.  If it is not, it pops up a AFXMessage that asks if the user wants to retry or quit.  I have the retry part working but can not figure out to just exit out of the application.  I can have it go to the finish page, but I need it to just quit the application.
The class checks for the hardware in the OnSetActiveDelayed call.  If I do a QueryClose call it returns back to the base class but does not exit.  Should I have it call OnQueryCancel instead?

A: From MSDN Documentation:

Even though CPropertySheet is not derived from CDialog, managing a
  CPropertySheet object is like managing a CDialog object

To quit the wizard, just call the property sheet EndDialog() function, like
m_pPropertySheet->EndDialog(IDCANCEL);

where m_pPropertySheet is a pointer to your CPropertySheet derived class instance.


text:
Q: Apache Beam typecoders errors and fallback on typehint - GCP Dataflow tutorial While trying to do the GCP "Simple dataflow pipeline (Python)" codelab, I got stuck in a very weird error.
As a heads-up, I am not running on my localmachine. I create a new cloudshell instance on GCP with a clean slate and just clone the repo https://github.com/GoogleCloudPlatform/training-data-analyst.
I am trying to run on the local machine python ~/training-data-analyst/courses/data_analysis/lab2/python/grep.py as the grepc.py is the one to run on GCP Dataflow itself.
I get the following error (the same happens when trying to run grepc.py:
No handlers could be found for logger "oauth2client.contrib.multistore_file"
/usr/local/lib/python2.7/dist-packages/apache_beam/coders/typecoders.py:135: UserWarning: Using fallback coder for typehint: <type 'NoneType'>.
warnings.warn('Using fallback coder for typehint: %r.' % typehint)

Any ideas about this?


text:
Q: Specifying nodes on horizontal lines I have tried several to draw a graph representing with consecutive states in a straight line, S0 -> S1 -> S2.  Then actions in another straight line below.  There are edges between S0 -> A0 -> S1 -> A1 -> S2.  Which forms triangles lined up next to each other.

I have tried to use a cluster, and rank=same for the nodes I want to align.  I also tried to use [constraint=false] and other answers on Stack Overflow.
\begin{dot2tex}[fdp]
digraph G {
    newrank=true;
    node[group="states"]
    S0 [texlbl="$S_{t-2}$", shape=none];
    S1 [texlbl="$S_{t-1}$", shape=none];
    S2 [texlbl="$S_t$", shape=none];
    S3 [texlbl="$S_{t+1}$", shape=none];
    node[group=""]
    A0 [texlbl="$A_{t-2}$", shape=none];
    A1 [texlbl="$A_{t-1}$", shape=none];
    A2 [texlbl="$A_t$", shape=none];
    { rank=same; S0; S1; S2; S3;
    S0 -> S1-> S2 -> S3;
    S0 -> A0;
    S1 -> A1;
    S2 -> A2; }
    A0 -> S1;
    A1 -> S2;
    A2 -> S3;
}
\end{dot2tex}

However the output from the graph is a mixture of states and actions on a curve.

A: It seems that you are using fdp layout engine.
According to documentation,

fdp draws undirected graphs using a ''spring''model. It relies on a force-directed approach in the spirit ofFruchterman and Reingold

In your case you need to use dot layout engine.
I'm not familiar with the program you are using, but wild guess would be to replace \begin{dot2tex}[fdp] with \begin{dot2tex}[dot]

A: Your code looks like part of a LaTeX document but it wouldn't work for me; dot2tex is, as far as I can see, a Python script that produces LaTeX code. But I'm out of  my depth here, it seems to work for you.
What I have done - I have corrected the mistake you have made, putting the closing brace } for the rank = same instruction back into that same line, and took it out of the apparent LaTeX environment; I also changed the arrow direction for the edges showing "upwards". Then I commented out the unnecessary instructions, arriving at
digraph G {
#    newrank=true;
#    node[group="states"]
    S0 [texlbl="$S_{t-2}$", shape=none];
    S1 [texlbl="$S_{t-1}$", shape=none];
    S2 [texlbl="$S_t$", shape=none];
    S3 [texlbl="$S_{t+1}$", shape=none];
#    node[group=""]
    A0 [texlbl="$A_{t-2}$", shape=none];
    A1 [texlbl="$A_{t-1}$", shape=none];
    A2 [texlbl="$A_t$", shape=none];
    { rank=same; S0; S1; S2; S3; }
    S0 -> S1-> S2 -> S3;
    S0 -> A0;
    S1 -> A1;
    S2 -> A2;
    edge[ dir = back ];
    S1 -> A0;
    S2 -> A1;
    S3 -> A2;
}

Converting this to a LaTex document with
dot2tex -ftikz x > x.tex

I get

which I guess is what you want, or at least, what your code will produce. Your workflow may be different, but if you correct the main mistake and move the closing brace where it belongs, you should be done. Note that dot2tex uses the dot engine by default, which is what you should be doing, as rightly pointed out be @Dany.
If you want something that is close to the picture in your post, try
digraph G
{
    node[ shape =none ]

    S  [ label = "" ];
    S0 [ texlbl="$S_{t-2}$" ];
    S1 [ texlbl="$S_{t-1}$" ];
    S2 [ texlbl="$S_t$" ];
    S3 [ texlbl="$S_{t+1}$" ];

    A0 [ texlbl="$A_{t-2}$" ];
    A1 [ texlbl="$A_{t-1}$" ];
    A2 [ texlbl="$A_t$" ];

    { rank=same; S S0 S1 S2 S3 }
    S0 -> S1 -> S2 -> S3

    S0 -> A1;
    S1 -> A2;
    edge[ dir = back ];
    S0 -> A0;
    S1 -> A1;
    S2 -> A2;

    edge[ style = invis ];
    S -> S1
    S -> A0;
}


text:
Q: NSJSONSerialization Causing Crash in Swift when Verifying App Receipt I am trying to verify my app receipt and have successfully done so with some code I found online. However, I am simulating the event that the user is not connected to the internet when attempting to validate the receipt and am getting a crash when doing so. The following do/catch method causes a crash at the anyObj line only when my device is not connected to the internet:
func validateRecipt(){
        var response: NSURLResponse?
        var error: NSError?
    var receipt: NSData = NSData()

    if let url = NSBundle.mainBundle().appStoreReceiptURL {
        if let appReceipt = NSData(contentsOfURL: url) {
            print("Receipt Found")
            receipt = appReceipt
        }else {
            print("Receipt not Found")
        }
    }else {
        print("Could not load Receipt")
    }

    //https://buy.itunes.apple.com/verifyReceipt
    let request = NSMutableURLRequest(URL: NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)

    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    let receiptdata:NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
    //NSLog("%@",receiptdata)
    let payload:NSString = "{\"receipt-data\" : \"\(receiptdata)\"}"
    let payloadData = payload.dataUsingEncoding(NSUTF8StringEncoding)
    let err: NSError?

    request.HTTPBody = payloadData

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            var err: NSError?

            //let json = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
            var json: AnyObject?
            do {
                let anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
            ****//App Crashes Here ^^//****
                json = anyObj

            } catch  {
                print("Fetch failed: \((error as NSError).localizedDescription)")

            }

            if(err != nil) {
                print(err!.localizedDescription)
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
            else {
                if let parseJSON = json {
                    print("Recipt \(parseJSON)")
                    print(parseJSON.count)
                }
                else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print("Recipt Error: \(jsonStr)")
                }
    print("You gets nathan")
            }

    })

    task.resume()

}

The crash is just fatal error: unexpectedly found nil while unwrapping an optional value
I am having trouble understanding the do/catch method so I am not confident that I fully comprehend what is going on here. So I'm guessing my question is how can I avoid this crashing when anyObj returns nil?

A: I am guessing the line which the debugger cursor is pointing at is:
let anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]

...and your data variable is nil (i.e., optional contains no value). Check that before force-unwrapping (! operator).
(The (error as NSError).localizedDescription can't be, because error is supposed to be non-nil inside the catch block and failing to case to NSError would give a different error message, I think).

Edit:
This is how you unwrap safely:
if let safeData = data { // <-- YOU NEED TO DO THIS
    // data is 'NSData?', safeData is 'NSData'.

    // If data contained any value, it is now assigned to safeData.
    // Use safeData as the source of your JSON (**not** data).
}
else{
    print("error: data is nil!")
}


text:
Q: Checking width and setting width inside forEach loop performance I have two pieces of code below
Snippet#1
const doubleWidth = (element) => {
  const width = element.offsetWidth;
  element.style.width = `${width * 2}px`;
};
button.addEventListener('click', (event) => {
  boxes.forEach(doubleWidth);
});

Snippet#2
button.addEventListener('click', (event) => {
  var widths = boxes.map(item => item.offsetWidth);
  boxes.forEach((element, index) => {
         element.style.width = `${widths[index] * 2}px`;
  });
});

Snippet #1 has a lot 48ms compared to snippet #2 which is only 18.4ms. Why is that behaviour?
After all, I am still doing two operation of calculating and settings ( which forcers reflows ) each.
Here's the complete code - https://codepen.io/kushalmahajan/pen/mjXVqp?editors=0010
Update - So , let me explain a bit more
In Snippet #1, I see each time a pattern like calculate, Reset, Calculate, Reset ...so forth
In Snippet #2. That's not the case.
Please base you answers around render pipeline please

A: in Snippet 1
each time you are executing 2 commands:
const width = element.offsetWidth;
element.style.width = `${width * 2}px`;

while in Snippet 2
each time you are executing only 1 command:
element.style.width = `${widths[index] * 2}px`;

Therefore  I think it's natural to have more than double the time for the execution. depending on how much time it take to execute the following command:
const width = element.offsetWidth;

For a fair comparison between the 2 snippets I would suggest removing the above command from the loop and check how long it would take to execute snippet 1 in that case.
I hope that helps.

A: I'm not sure about the reason, but apparently if you store offsetWidth first, it doesn't matter performance-wise whether you use forEach or map: here's a pen to illustrate this behavior.
You can see that I timed three combinations:

*

*forEach with immediately getting offsetWidth and setting width

*forEach with storing offsetWidth and the corresponding element first and then setting width it in a second forEach

*map with storing offsetWidth and then setting width on the elements in a forEach loop

Option 2. an 3. were basically the same performance wise. Judging from that, I would say that the combination of getting offsetWidth and setting width is a performance bottleneck. Can't really tell you much more than that, sorry!

window.onload = () => {
    const boxes = Array.from(document.querySelectorAll('.box'));

    document.getElementById('double-sizes-forEach')
    .addEventListener('click', (event) => {
        console.time('Double Sizes ForEach');

        boxes.forEach((element, index) => {
        const width = element.offsetWidth;
        element.style.width = `${width * 2}px`;
        });

        console.timeEnd('Double Sizes ForEach');
    });

    document.getElementById('double-sizes-forEach-2')
    .addEventListener('click', (event) => {
        console.time('Double Sizes ForEach 2');

        let a = [];
        boxes.forEach((element, index) => {
        a.push([element, element.offsetWidth]);
        });
        a.forEach(([e, w]) => {
        e.style.width = `${w * 2}px`;
        });

        console.timeEnd('Double Sizes ForEach 2');
    });

    document.getElementById('double-sizes-map')
    .addEventListener('click', (event) => {
        console.time('Double Sizes Map');

        var widths = boxes.map(item => item.offsetWidth);
        boxes.forEach((element, index) => {
            element.style.width = `${widths[index] * 2}px`;
        });

        console.timeEnd('Double Sizes Map');
    });
};

OUTPUT:
Double Sizes ForEach: 12.341064453125ms
Double Sizes ForEach 2: 0.539794921875ms
Double Sizes Map: 0.590087890625ms

NOTES:

*

*what forces layout/reflow

*article on layout performance issues and layout thrashing
The second article argues that you should always separate changing style (e.g. setting width) and taking measurements (e.g. getting offsetWidth) to avoid layout thrashing. Seems that's the problem in your code as well.


text:
Q: jQuery find and replace second one I was wondering how I would go about finding and replacing some text in a div, but i want to find and replace the second occurrence of that text. For example:"You just added a item, please remove this item" so I would like to find the second "item" and replace it with whatever text I choose.
JS:
var compareCount = $('.compareWidget').find('.compareItem').length;

if (compareCount >= 2) {
    $('.message').find('.count').text(compareCount);
    $('message').html().replace('item', 'items');
}

$('.message').slideDown("Fast");

setTimeout(function () {
    $('.message').slideUp("Fast");
}, 5000);

HTML:

        You just added a item to compare, you currently have 1 item to compare

A: "you currently have 1 item to compare"
You want to turn item to items?
You can do it with regular expressions, or you can wrap it into an element and grab that.
1 item to compare

and
 $('.message').find('.type').text("items");

A: Using regular expressions you can
function replaceMatch(originalString, searchFor , replaceWith, matchNumber)
{
  var match = 0;
  return originalString.replace(searchFor, function(found){
                     match++;
                     return (match===matchNumber)?replaceWith:found;
                   },'g');
}

and call it like
var msg = $('.message');
msg.html( replaceMatch( msg.html(), 'item', 'items', 2) );

demo http://jsfiddle.net/gaby/crhvA/


text:
Q: Angular Typescript error for route navigation to detail page I am trying to pass object from main page to detail page via a route
The main page has below code
routeToEditProduct() {

    let route = '/product/edit'
    this._router.navigate([route], {state: {selected:  this.selProduct}})
}

The detail page has below constructor
this.sub = this._activatedRoute.params.subscribe( params =? {
        let nav: Navigation = this._router.getCurrentNavigation()
        if (nav.extras && nav.extras.state && nav.extras.state.selected) {
        this.selectedProduct = nav.extras.state.selected
    }
})

I am getting error ts 2322 for the variable declaration nav
        let nav: Navigation = this._router.getCurrentNavigation()

I think it's because variable nav can be null, so tried to use ? as shown below , but then I get ts(1109) expression expected error
this.sub = this._activatedRoute.params.subscribe( params =? {
        let nav: Navigation = this._router.getCurrentNavigation()?
        if (nav.extras && nav.extras.state && nav.extras.state.selected) {
        this.selectedProduct = nav.extras.state.selected
    }
})


text:
Q: Infinity Preloader I have a issue in preloader. And donot know how to correct it.
Problem is. Preloader is showing infinity while using Chrome. I saw some solutions like gZip Compression in server.
I want to know any other solution from flash side. because i'm developing game and we can play it anywhere.
I want the solution a soon as possible. Someone help me to do it.

A: When I was struggling with prealoaders, this page helped me tons for as2  and concepts in general, this one helped me doing it in as3
The basic idea is to listen to the progress event and do simple calculations using the total amount you need to download and the current bytes you already have.

A: You may occasionally get infinity in these calculations when the bytesTotal has not been correctly populated.
It's good practice to do something like
var loadper:Number = 0;
if (this.loaderInfo.bytesTotal >= 0)
{
    loadper = Math.round((this.loaderInfo.bytesLoaded/this.loaderInfo.bytesTotal)*100);
}
...

There are many reasons you could be getting 0 bytes returned as the total but usually it has to do with the way you are delivering files from your server.


text:
Q: Verify duplicate data before inserting in a SQLite table I am stuck on a project, need help to solve this issue.
I receive the data from 3 different inputs (2 are Spinners and 1 is a TextView).
The table column name are: customer id, quantity and production id.
I need to check production id for duplicate entries before inserting to my table.
Here is what I currently do:
if(res.getCount()==0){
            boolean isInserted = mytempDB.insertdataintotemptable(
                    ProducationSpinner.getSelectedItem().toString(), QuantityText.getText().toString(),
                    CustomerSpinner.getSelectedItem().toString());
            if (isInserted == true)
                Toast.makeText(orderChalan.this, "Data save successfully", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(orderChalan.this, "Data not Inserted", Toast.LENGTH_LONG).show();
        } else {

            while(res.isAfterLast()){

                if (res.getString(4).toString() == CustomerSpinner.getSelectedItem().toString()) {

                    boolean isInserted = mytempDB.insertdataintotemptable(ProducationSpinner.getSelectedItem().toString(),
                            QuantityText.getText().toString(), CustomerSpinner.getSelectedItem().toString());

                    if (isInserted == true)
                        Toast.makeText(orderChalan.this, "Data save successfully", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(orderChalan.this, "Data not Inserted", Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(orderChalan.this, "Production ID can not different", Toast.LENGTH_LONG).show();
                }
            }
        }

I select the first row and receive a production ID value.
After that I try to match the user input and data from the table each time, then   I insert into the table.
If the data don't match, I then display an error message "Production Id can not different" and also I check the first time entry if there is no data for the first input; in that case there are no checks.
The error I get is "Production id can not be different" - I get this message from the 2nd time input.
Any suggestion?

A: I am describing the logic. What you have to do in your code .

*

*First check your table contains any data or not .

*If table is empty then insert your current data into table .

*If table is not empty then run a query for checking the current "production id" available in table or not . query is " select * from TABLE_NAME WHERE Column_name(production id) = your current production id.

*If Cursor.getCount >0
//   current production id exists
else
   // insert current details in table

A: I believe that the issue that you are describing, is due to using == to compare strings. == will test if the string objects/instances are the same it does not compare the values held by the strings.
That is this line
if (res.getString(4).toString() == CustomerSpinner.getSelectedItem().toString()) {

will consistently return false.
Instead of using == you need to implement .equals()
So, something along the lines of
if ((res.getString(4).toString()).equals(CustomerSpinner.getSelectedItem().toString())) {


text:
Q: Upload image and from data with the help of api I have two database. I create a form image upload fiuld is also their. when I submit this form this form data will save in my both database using api.
i have alrady solv this problem with the connection of multiple database in env file but in the image upload case i need to save this image a perticule file in both project thets whey i need to api


text:
Q: Send html form data to database through php without switching page Hey guys so i have a form:
<form action="signup.php" method="post" class="cd-form">

                  <input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />

                  <input class="full-width has-padding has-border"  type="text" required  maxlength="15" placeholder="Last Name" name="segundo_nome">

                  <input class="full-width has-padding has-border"  type="email" required maxlength="50"  placeholder="E-mail" name="o_email">

                    <input class="full-width" type="submit" value="Sign Up!">

            </form>

And you may notice that the action is calling "signup.php" :
    <?php
 $con=new mysqli ("localhost","root","","chroniclemark");
    mysqli_set_charset($con, 'utf8mb4');
    if($con->connect_error)
    {
        echo $con->connect_errno;
        die("Database Connection Failed");
    }
    if(($_POST['primeiro_nome']) != ""){

    $sql = "INSERT INTO users (nome, sobrenome, email)
             VALUES('{$con->real_escape_string($_POST['primeiro_nome'])}', '{$con->real_escape_string($_POST['segundo_nome'])}', '{$con->real_escape_string($_POST['o_email'])}')";
        $insert = $con->query($sql);

}
?>

And this is working. The data from the form is getting inserted into my database. The problem i have is that the main page closes when the form is submitted and the "signup.php" page opens instead of it.
How do i fix this? I would very much like to have a "Thank you for signing up" popping up on the same page instead of it switching to another one.

A: You have to use AJAX instead of directly submitting the form
You send POST request with JS XMLHttpRequest or Fetch_API to signup.php, get the response and show the "Thank you for signing up" popup

A: There are mainly two ways you can do this.
1. You can use Jquery $.ajax method to send data, get a response and display your message.
2. Or you can simply let the php page it self do the processing. Add a submit button.
Change your <form action="signup.php" method="post" class="cd-form">to
<form action="" method="post" class="cd-form">

Add below after the form.
<?php
if (isset($_POST["submit"]){
  //do your processing here
  //at the end of processing you can use echo or HTML to display a thank you message
}
?>

A: You can use AJAX to save data to database and show user a message in same page. Clicking on button a request is sent to server, data is saved into database, on success or failure a response is returned then show a message to user.
Form
First Give ids to input types in you form and add a message div.

<form  method="post" class="cd-form">

              <input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" id="primeiro_nome" />

              <input class="full-width has-padding has-border"  type="text" required  maxlength="15" placeholder="Last Name" id="segundo_nome">

              <input class="full-width has-padding has-border"  type="email" required maxlength="50"  placeholder="E-mail" id="o_email">

                <input class="full-width" id='saverecords' type="button" value="Sign Up!">

jQuery Code to send AJAX request to server
Add a script tag include jQuery and inside click event get values of fields and then post to php page:

php server side code:
Please change it according to your requirement
Create a php page:  saverecords.php
 In saverecords.php you can insert data into database.
$conn = new mysqli($host, $username, $password, $dbname);
$pname  = $_POST['pname'];

$sname  = $_POST['sname'];

$email  = $_POST['email'];
$sql    = "insert into tablename (pname, sname, email) values (?, ?, ?)  ";

$stmt   = $conn->prepare($sql);

$stmt->bind_param('sss', $pname, $sname, $email);

  if($stmt->execute()){

     $result = 1;

  }

}

echo $result;

$conn->close();

If you still face issue please visit this link you can find a detailed tutorial on how to use jQuery Ajax with php mysqli

A: You can make action page run inside an iframe so your form page remains on top
just like that:
<form action="signup.php" method="post" class="cd-form" target="my_iframe">

              <input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />

              <input class="full-width has-padding has-border"  type="text" required  maxlength="15" placeholder="Last Name" name="segundo_nome">

              <input class="full-width has-padding has-border"  type="email" required maxlength="50"  placeholder="E-mail" name="o_email">

                <input class="full-width" type="submit" value="Sign Up!">

        </form>

Also you can send form data to your PHP page by using jquery:
$(document).on('submit','.cd-form',function(e){
e.preventDefault();
$.ajax( {
url: "signup.php",
type: 'POST',
data: new FormData( this ),
cache: false,
dataType: "json",
success: function(r){
alert("data sent successfully");
}
} );
} );


text:
Q: Having trouble getting event data from event listener in ReasonReact I'm trying to implement dynamic column resizing on a table (like in Excel or Google Sheets).
In my render function I use the handle callback when the user clicks mouse down on my resize control:
 <div
     className="resizer"
     onMouseDown={self.handle(handleColumnResizeStart)}
 />

In the handler I want to add a new event listener for mousemove so that when the user is "dragging" we can draw something to indicate where the new column edge would end up.
Within the mousemove handler I was thinking I could send a reducer action that contained the mouse clientX coordinate to update the component state so that the render function could draw something while they are dragging.
let handleColumnResizeStart = (evt, self) => {
  /* this handler gets invoked when the mouse is moved */
  let handleMouseMove = evt => {

    Js.log(evt); /* in js land I can see that clientX is in that evt object */
    Js.log(ReactEvent.Mouse.clientX(evt)); /* but this creates type errors */

  };
  /* adds an event handler using the bs-webapi module */
  Webapi.Dom.EventTarget.addEventListener(
    "mousemove",
    handleMouseMove,
    document,
  );

};

When I try to use ReactEvent.Mouse.clientX(evt) to get the specific int value of clientX, I get this error:
  25 Webapi.Dom.EventTarget.removeEventListener(
  26 ┆   "mousemove",
  27 ┆   handleMouseMove,
  28 ┆   document,
  29 ┆ );

  This has type:
    ReactEvent.Mouse.t => unit
  But somewhere wanted:
    Dom.event => unit

  The incompatible parts:
    ReactEvent.Mouse.t (defined as
      ReactEvent.synthetic(ReactEvent.Mouse.tag))
    vs
    Dom.event (defined as Dom.event_like(Dom._baseClass))

>>>> Finish compiling(exit: 1)

My understanding of the type system is limited here and I'm not sure how to get the value of the mouse clientX coordinate into variable.

A: Although events received from React and from event handlers attached directly to the DOM may look similar, they are in fact different. React doesn't give you a raw DOM event, but a SyntheticEvent, and in Reason they've therefore been given different types, which is what the type error is informing you of. You can't use a Dom.event where a ReactEvent.Mouse.t is expected. In this case evt is a Dom.event, because it was acquired by attaching an event handler directly to the DOM using bs-webapi, and ReactEvent.Mouse.clientX of course expects a ReactEvent.Mouse.t.
So instead of using ReactEvent.Mouse.clientX, you should use Webapi.Dom.MouseEvent.clientX.
Unfortunately that still won't work, because Webapi.Dom.MouseEvent.clientX expects a Dom.mouseEvent, not a Dom.event, which is the supertype of all DOM event types and too general to be used with functions specific to mouse events. And this in turn is because Webapi.Dom.EventTarget.addEventLsitener isn't able to understand that "mousemove"means it is a mouse event. You should instead use Webapi.Dom.EventTarget.addMouseMoveEventListener, which does give you a Dom.mouseEvent.
Note that the type error you get is more confusing than it needs to be, because it will infer the type and point to the error being somewhere other than where you perceive the error to originate. It's a good idea to annotate the types, at least when you get a type error you struggle to understand. That way the compiler won't infer the type to be something you don't expect it to be, and will contain the origin of the error.
You might also want to use Webapi.Dom.Document instead of Webapi.Dom.EventTarget. Document inherits everything in EventTarget, but will both document and constrain the type you operate on.


text:
Q: Double Partial Derivatives of sum of variances of dependent random variables I have the following function
$$f(α)=Var[αX+(1−α)Y]=Var(αX)+Var[(1−α)Y]+2α(1−α)Cov(X,Y)$$
Partial derivative of this function w.r.t α leads us to following result
$$f′(α)=2αVar(X)−2(1−α)Var(Y)+2Cov(X,Y)(1−2α)=0$$
$$ α=\frac{Var(Y)−Cov(X,Y)} {Var(X)+Var(Y)−2Cov(X,Y} $$
This α is the minimum value of the function but in order to prove that it is minimum value, one has to prove that double partial derivative of the function  f(α) is greater than Zero  i.e.  f′′(α) > 0 .
But upon solving for f′′(α) I get
$$f′′(α)=Var(X)+Var(Y)-2Cov(X,Y)$$
$$f′′(α)=Var(X-Y)$$
How can conclude that this f′′(α) > 0 . Please help on this.

A: As the variances is always a non-negative and Var(X-Y) is always greater than zero and our equaion leads to the proof that we wanted i.e.
                            $$f''(α)>0$$
So it has been proved that α denotes the minimum value of the function.
A special thanks to @Glen_b who forced me to learn by doing.


text:
Q: Restore time on dev servers We have 4 test environments running SQL Server 2014 Developer edition. Every night, we refresh one of those environments by restoring a SQL Backup file stored on a separate server, so that it's in a known state.
Every Monday, we refresh all 4 environments to the same known state. All restore jobs start at 1am.
The backup file we restore from is a regular SQL backup taken from a SQL 2014 Server using a standard BACKUP DATABASE command. The restore command is issued by SQL Server Agent using a standard RESTORE DATABASE command.
When the daily restore runs, it takes between 2-2.5 hours to complete. On a Monday morning, that server completes in around 3 hours. This makes some sense as there are 4 servers trying to read the same backup file instead of one.
When the other 3 servers restore on Monday morning, the restore command is issued as scheduled at 1am, but they restore command then appears to do nothing until about 11am (< 10% CPU, disk and network usage).
When selecting from sys.dm_exec_requests on all 3 servers during this time, I can see that the percentage complete is 0% until about 11am, when it starts increasing fairly evenly on all 3 servers. At the same time, network and disk usage both increase to around 100Mbps - which is an expected number for our dev environment.
I'm trying to work out what is happening for the approx. 10 hours between the restore command being issued and the data being written to disk.
The file doesn't appear to be locked by any one server, as at 11am all 3 servers are able to restore at roughly the same speed.
We will look to stagger the restore, or even move it to the weekend, but I'd really like to try and work out why the server is not restoring for 10 hours.
Is there something in the restore command that would cause it to wait?


text:
Q: How to Create a Spreadsheet in a particular folder via App Script Can anybody help me out,
I want to create a Spreadsheet through App Script in a particular folder. How to do that.
Presently I am doing as follow:
var folder = DocsList.getFolder("MyFolder");
var sheet = SpreadsheetApp.create("MySheet");
var file = DocsList.getFileById(sheet.getId());
file.addToFolder(folder);
file.removeFromFolder(file.getParents()[0]);

It is not working.......

A: In July 27, 2020 there have been these updates:
The File class now has the following methods:

*

*file.getTargetId(): Gets a shortcut's file ID.

*file.getTargetMimeType(): Returns the mime type of the item a shortcut points to.

*file.moveTo(destination): Moves a file to a specified destination folder.
The Folder class now has the following methods:

*

*folder.createShortcut(targetId): Creates a shortcut to the provided Drive item ID, and returns it.

*folder.moveTo(destination): Moves an item to the provided destination folder.

The following Folder class methods have been deprecated:

*

*addFile(File)

*addFolder(Folder)

*removeFile(File)

*removeFolder(Folder)
https://developers.google.com/apps-script/releases/#july_27_2020
So you can create a Spreadsheet file in a folder using file.moveTo(destination) method:
function createSpreadSheetInFolder(ss_new_name, folder_dest_id) {
    var ss_new = SpreadsheetApp.create(ss_new_name);
    var ss_new_id = ss_new.getId();
    var newfile = DriveApp.getFileById(ss_new_id);
    newfile.moveTo(DriveApp.getFolderById(folder_dest_id))
    return ss_new_id;
}

var file_name = 'SPREADSHEET NAME';
var folder_id = 'DESTINATION FOLDER ID';
var new_ssId = createSpreadSheetInFolder(file_name, folder_id)

A: You can create a spreadSheet and then add it to the folder.
function createSpreadSheetInFolder(name,folder){
    var ss = SpreadsheetApp.create(name);
    var id = ss.getId();
    var file = DriveApp.getFileById(id);
    folder.addFile(file);
    return ss;
}
folderId='your_folder_id'
name='my_new_ss'
folder=DriveApp.getFolderById(folderId)
createSpreadSheetInFolder(name,folder)

By using the folder.addFile method there's no need to use a temp file (no need to duplicate and remove file). Pretty straightforward !

A: As suggested by @Joshua, it's possible to create a Spreadsheet (in a specific folder) with the Advanced Drive Service (you'll need to activate this if you haven't already, by going into Services +, find Drive API and click Add).
var name = 'your-spreadsheet-name'
var folderId = 'your-folder-id'
var resource = {
  title: name,
  mimeType: MimeType.GOOGLE_SHEETS,
  parents: [{ id: folderId }]
}
var fileJson = Drive.Files.insert(resource)
var fileId = fileJson.id

No need to move files around with this method !

A: I finally got the answer to my question. The following works
var file = DocsList.getFileById(sheet.getId());
var folder = DocsList.getFolder("MyFolder");
file.addToFolder(folder);

// remove document from the root folder
folder = DocsList.getRootFolder();
file.removeFromFolder(folder);

A:   folder = DriveApp.getFolderById("FOLDER_ID")
  var ss = SpreadsheetApp.create("SPREADSHEET_NAME")
  DriveApp.getFileById(ss.getId()).moveTo(folder);

You may use the above code to achieve the same without using advanced drive services

A: The other answer is a bit short (and not very explicit).
While your approach is logic and should work if you replace
file.removeFromFolder(file.getParents()[0]);

with
file.removeFromFolder(DocsList.getRootFolder());
there is a better way to do the same job using the new Drive app and the Folder Class, Folder has a method to create a file and you can specify the file type using the mimeType enum.
Code goes like this :
function myFunction() {
  var folders = DriveApp.getFoldersByName('YOUR FOLDER NAME'); // replace by the right folder name, assuming there is only one folder with this name
  while (folders.hasNext()) {
   var folder = folders.next();
  }
  folder.createFile('new Spreadsheet', '', MimeType.GOOGLE_SHEETS); // this creates the spreadsheet directly in the chosen folder
}

A: Since you can no longer create Google Docs (Docs or SpreadSheets) using DriveApp, nor use addToFolder because DocList is deprecated. There is only one way to create or "move" Google Docs or Google SpreadSheets..
  //"Move" file to folder-------------------------------//
  var fileID = '12123123213321'
  var folderID = '21321312312'
  var file = DriveApp.getFileById(fileID).getName()
  var folder = DriveApp.getFolderById(folderID)
  var newFile = file.makeCopy(file, folder)

  //Remove file from root folder--------------------------------//
  DriveApp.getFileById(fileID).setTrashed(true)

As you can see this DOES NOT move the file, it makes a copy with the same name in the folder you want and then moves the original file to the trash. I'm pretty sure there is no other way to do this.

A: What is not working? Use getRootFolder in the last line.

A: Creating a new spreadsheet in a file can be done using this link as a reference.
createFile(name, content, mimeType)
Therefore using the enum MimeType we can do:
var folder = DriveApp.getFolderById("your-folder-id");
folder.createFile("My File Name","",MimeType.GOOGLE_SHEETS)


text:
Q: python 'listen' creates established socket. why? I created simple server.py that listen connection, but not accept connection.
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 1234
server_socket.bind(("", PORT))
server_socket.listen(5)

while 1:
        pass

server_socket.close()

When I run this code,

*

*nc client could connect to the server

*server created ESTABLISHED socket for the client
netstat -an | grep 1234
tcp        0      0 0.0.0.0:1234            0.0.0.0:*               LISTEN
tcp        0      0 3.3.3.3:1234      4.4.4.4:51493     ESTABLISHED
tcp        0      0 3.3.3.3:1234      4.4.4.4:51494     ESTABLISHED

Question:
As far as I know, listen just gather connection in backlog queue, and then accept creates ESTABLISHED socket.
However the result: listen itself creates socket.
I also checked source code but could not find the socket creation code.
Can anyone knows the reason why this happens?

A:
As far as I know, listen just gather connection in backlog queue, and then accept creates ESTABLISHED socket.

This is wrong. listen tells the OS to accept new connections.  accept then gets the inside the OS already established connections into the application. The backlog parameter for listen defines roughly how many connections can be accepted by the OS before they application needs to retrieve these using accept.
Therefore, the OS will accept new connections as long as listen was called, even before accept is called.


text:
Q: File wont repeat itself till End of File Everything in my code works, its getting input from file, computing average, and outputting. It just doesnt do it all at once by itself. If i hit enter it does the next line and so on till the end of file. How do i make it so that is does all the lines at once?
Code:
/***************************************************/
/* Author:     Sam LaManna                         */
/* Course:     CSC 135 Lisa Frye                   */
/* Assignment: Program 4 Grade Average             */
/* Due Date:   10/10/11                            */
/* Filename:   program4.cpp                        */
/* Purpose:    Write a program that will process   */
/*             students are their grades. It will  */
/*             also read in 10 test scores and     */
/*             compute their average               */
/***************************************************/

#include <iostream>     //Basic input/output
#include <iomanip>      //Manipulators
#include <string>       //String stuff
#include <fstream>

using namespace std;

void instruct ();       //Function declaration for printing instructionstring studname ();
void input (ifstream &infile, float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname);      //Function declaration for input
float aver (float test1, float test2, float test3, float test4, float test5, float test6, float test7, float test8, float test9, float test10);      //Function declaration for calculating average
void output (string studentname, float average);      //Function declaration for output

int main()
{
  float test1 = 0;              //Vars (test1 - test10) for test scores
  float test2 = 0;
  float test3 = 0;
  float test4 = 0;
  float test5 = 0;
  float test6 = 0;
  float test7 = 0;
  float test8 = 0;
  float test9 = 0;
  float test10 = 0;
  string studentname = "a";     //Define Var for storing students name
  float average = 0;            //Define var for storing average

  instruct();     //Function call to print instructions

  ifstream infile("grades.dat");

  input (infile, test1, test2, test3, test4, test5, test6, test7, test8, test9, test10, studentname);     //Function call for scores

  while (!infile.eof())
    {
      average = aver (test1, test2, test3, test4, test5, test6, test7, test8, test9, test10);    //Function call for average

      output (studentname, average);     //Function call for output

      cin.ignore(1);

      input (infile, test1, test2, test3, test4, test5, test6, test7, test8, test9, test10, studentname); //Get new input
    }     //end eof

  return 0;
}

/***************************************************/
/* Name: instruct                                  */
/* Description: Print instructions to user.        */
/* Paramerters: N/A                                */
/* Return Value: N/A                               */
/***************************************************/

void instruct()
{
  cout << "\n" << "This program will calculate the average of 10 test scores that are read from a file. " << "\n" << "\n";
  //Prints instructions

  return;
}

/***************************************************/
/* Name: input                                     */
/* Description: Get input                          */
/* Paramerters: N/A                                */
/* Return Value: N/A                               */
/***************************************************/

void input (ifstream& infile, float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname)

{
  getline(infile, studentname);
  infile >> test1 >> test2 >> test3 >> test4 >> test5 >> test6 >> test7 >> test8 >> test9 >> test10;
  infile.ignore(10, '\n');

  return;
}

/***************************************************/
/* Name: aver                                      */
/* Description: Calculate Average                  */
/* Paramerters: N/A                                */
/* Return Value: aver                              */
/***************************************************/

float aver (float test1, float test2, float test3, float test4, float test5, float test6, float test7, float test8, float test9, float test10)

{
  float aver = 0;
  aver = test1 + test2 + test3 + test4 + test5 + test6 + test7 + test8 + test9 + test10;
  aver = aver / 10;
  return aver;
}

/***************************************************/
/* Name: output                                    */
/* Description: Calculate Average                  */
/* Paramerters: N/A                                */
/* Return Value: aver                              */
/***************************************************/

void output (string studentname, float average)      //Function declaration for output
{

  cout << studentname;

  cout << average;

  return;
}

A: remove the
cin.ignore(1);

from the while loop in main, it is blocking the program execution until you input a char.
Oh and before you open a new question on why it prints all on one line, it is because the enter you fed to cin used to advance the line but now you should add a endl to your output
cout << blah << bleh << endl;

A: In your main function, you're using
cin.ignore(1);

which extracts/waits for an input character from cin and discards it. See this istream::ignore reference for further information on it.
Removing/commenting out this statement will fix your problem.


text:
Q: Return HTML from an Azure Function in c# I wrote an Azure function in c# which returns html. When I make a request from a web browser, it displays the full response as raw text instead of rendering it as html. I think I need to set the ContentType header on the response. I tried this answer but it seems I'd need a nuget package... and got complicated.
How to set the ContentType header on a response from an Azure Function?

A: Here's a way to set the ContentType header on a response from an Azure Function using only the System.Net namespace (which doesn't require adding any references or nuget packages). In this case, for html to be rendered by a browser, set "text/html".
using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
    var html = "Example Content";
    var response = req.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(html, Encoding.UTF8, "text/html");

    return response;
}

A: The first answer is for .NET Framework, if you need .NET Core/6.0 ...
var html = "Example Content";

return new ContentResult()
{
    Content = html,
    ContentType = "text/html",
    StatusCode = 200
};


text:
Q: showBluetoothAccessoryPicker returns error 2 Using the following code:
EAAccessoryManager.SharedAccessoryManager.ShowBluetoothAccessoryPicker(null,HandleAction1);

void HandleAction1(NSError obj)
{
   System.Diagnostics.Debug.WriteLine("HandleAction1");
}

Returns:

{The operation couldn't be completed.
  (EABluetoothAccessoryPickerErrorDomain error 2.)}

A: You have stated that you are cancelling the displayed picker.  In this case, it is expected to receive error 2, since that is EABluetoothAccessoryPickerError.Code.resultCancelled
You won't see standard Bluetooth accessories, such as handsfree devices or speakers, in this list; only MFi devices are shown:

Note
The picker displays only Bluetooth devices that include an iAP over Bluetooth unique ID in their extended inquiry response.

A: This library only works with MFI devices. It WILL NOT work with the majority of common devices. It is useless for typical devices.


text:
Q: How to check combination of records from multiple rows(MySQL) I am working on writing a query that is able to check multiple rows at the same time. If the combination of the same user's records provides the enough information I need, even every single record doesn't provides enough information I need, the user is considered passed.
For example:
There are two tables.
One is "user" which keep user's personal information:
id client_id  first_name  last_name  date_of_birth   ssn  address
Another one is "lab" which keep users' medical test information:
id  external_source_id  user_id date    wbc rbc hemoglobin  hematocrit  mcv mch mchc    rdw plateletcount
One user can only have one record in user table, but could have multiple records in labs table. What I want to do is check the users' multiple lab records that belongs to the same user to see if the combination of those records provide the necessary information I need. If yes, the user is passed, even if any single lab record doesn't provide enough information. For example, the necessary information includes cholesterol, ldl, triglycerides, glucose. If a user has two lab records, one record provides cholesterol(NOT NULL) and ldl(NOT NULL), another one provides triglycerides(NOT NULL), glucose(NOT NULL). He is considered passed.
How do I write the query that is able to do that?
The query I currently have is like this:
SELECT users.id AS user_id, users.first_name, users.last_name, clients.name AS client,
        users.social_security_number AS ssn, users.hiredate, hra.id AS hra_id, hra.date     AS hra_date, hra.maileddate AS hra_maileddate,
        screening.id AS screening_id, screening.date AS screening_date, screening.maileddate AS screening_maileddate
        FROM users
        INNER JOIN clients
        ON(
           users.client_id = clients.id
           )
        INNER JOIN hra
        ON(
           users.id = hra.user_id
           )
        LEFT JOIN labs
        ON(
           users.id = labs.user_id
        )
        WHERE users.client_id = '1879'
        AND hra.date BETWEEN '2011-07-01' AND '2011-11-15'
        AND hra.maileddate IS NOT NULL
        AND labs.date BETWEEN '2011-05-15' AND '2011-11-15'
        AND labs.maileddate IS NULL
        AND labs.cholesterol IS NOT NULL
        AND labs.ldl IS NOT NULL
        AND labs.triglycerides IS NOT NULL
        AND (labs.glucose IS NOT NULL OR labs.ha1c IS NOT NULL)
        GROUP BY users.id

A: This will select all users in your example
select u.*
from user u
join lab l1 on l1.user_id = u.id and l1.wbc is not null
join lab l2 on l2.user_id = u.id and l2.hemoglobin is not null
join lab l3 on l3.user_id = u.id and l3.plateletcount is not null
-- etc for other fields that need to be not null

This will work even if the same records have more than one desired column, or if the values are spread out across rows.
If you want the lab values too, just select u.*, l1.wbc, l2.hemoglobin, ... etc

A: If you want the Users who PASS :
You can use a IN with AND clause
Select u.* from user u
where
u.user_id in (select user_id from lab where wbc is not null) and
u.user_id in (select user_id from lab where hemoglobin is not null) and
u.user_id in (select user_id from lab where plateletcount is not null);

if you want the users who DONT PASS
You can use a IN with OR clause
Select u.* from user u
where
u.user_id in (select user_id from lab where wbc is null) OR
u.user_id in (select user_id from lab where hemoglobin is null) OR
u.user_id in (select user_id from lab where plateletcount is null);

i hope that makes sense :)


text:
Q: use threading in tkinter I have two class and use tkinter demo.
class App:
    def __init__(self, window, window_title, video_source=0):
        self.window = window
        self.window.title(window_title)
        self.video_source = video_source

        # open video source (by default this will try to open the computer webcam)
        self.vid = MyVideoCapture(self.video_source)

        # Create a canvas that can fit the above video source size
        self.canvas = tkinter.Canvas(window).place(x=50, y=0)

        # set plot parameter
        self.fig = Figure(figsize=(7, 4), dpi=100)
        self.fresh = FigureCanvasTkAgg(self.fig, master=self.window)
        self.ax1 = self.fig.add_subplot(211)
        self.ax2 = self.fig.add_subplot(212)

        self.fresh.get_tk_widget().place(x=700, y=0)
        self.window.geometry('1500x550')

        # Camera thread
        self.photo = None
        self.delay = 15
        self.t = threading.Thread(target=self.update, args=())
        self.t.setDaemon(True)
        self.t.start()

    def refresh(self, data):
        sample_track = pd.read_csv('/home/share/sample_track.csv')
        x = [i for i in range(len(sample_track))]
        y = sample_track['0']
        xdata = [i for i in range(len(data))]
        ydata = data
        self.ax1.plot(x, y, 'bo--')
        self.ax2.plot(xdata, ydata, 'ro--')
        self.fresh.draw()

    def update(self):
        # Get a frame from the video source
        ret, frame = self.vid.get_frame()
        if ret:
            self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))
            self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
        self.window.after(self.delay, self.update)

class MyVideoCapture:
    def __init__(self, video_source=0):
        # Open the video source
        self.vid = cv2.VideoCapture(video_source)
        if not self.vid.isOpened():
            raise ValueError("Unable to open video source", video_source)
        self.ret = None

    def get_frame(self):
        if self.vid.isOpened():
            self.ret, frame = self.vid.read()
            if self.ret:
                # Return a boolean success flag and the current frame converted to BGR
                return self.ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            else:
                return self.ret, None

if __name__ == '__main__':
    win = tkinter.Tk()
    panel = App(win, "Dance")
    value = []
    for i in range(15):
        value.append(np.random.randint(0, 800))
        panel.refresh(data=value)
        time.sleep(0.1)
    win.mainloop()

I want to start the Webcam and refresh the figure at the same time.
I tried to use the thread but still failed.
The following error occurred:

*

*RuntimeError: main thread is not in main loop

*AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
How can I solve it?

A: Here is a working tkinter camera taken straight from here (found by a quick search for 'tkinter camera'):
import tkinter
import cv2
import PIL.Image, PIL.ImageTk
import time

class App:
    def __init__(self, window, window_title, video_source=0):
        self.window = window
        self.window.title(window_title)
        self.video_source = video_source

        # open video source (by default this will try to open the computer webcam)
        self.vid = MyVideoCapture(self.video_source)

        # Create a canvas that can fit the above video source size
        self.canvas = tkinter.Canvas(window, width = self.vid.width, height = self.vid.height)
        self.canvas.pack()

        # Button that lets the user take a snapshot
        self.btn_snapshot=tkinter.Button(window, text="Snapshot", width=50, command=self.snapshot)
        self.btn_snapshot.pack(anchor=tkinter.CENTER, expand=True)

        # After it is called once, the update method will be automatically called every delay milliseconds
        self.delay = 15
        self.update()

        self.window.mainloop()

    def snapshot(self):
        # Get a frame from the video source
        ret, frame = self.vid.get_frame()

        if ret:
            cv2.imwrite("frame-" + time.strftime("%d-%m-%Y-%H-%M-%S") + ".jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))

    def update(self):
        # Get a frame from the video source
        ret, frame = self.vid.get_frame()

        if ret:
            self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
            self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)

        self.window.after(self.delay, self.update)

class MyVideoCapture:
    def __init__(self, video_source=0):
        # Open the video source
        self.vid = cv2.VideoCapture(video_source)
        if not self.vid.isOpened():
            raise ValueError("Unable to open video source", video_source)

        # Get video source width and height
        self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)

    def get_frame(self):
        if self.vid.isOpened():
            ret, frame = self.vid.read()
            if ret:
                # Return a boolean success flag and the current frame converted to BGR
                return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            else:
                return (ret, None)
        else:
            return (ret, None)

    # Release the video source when the object is destroyed
    def __del__(self):
        if self.vid.isOpened():
            self.vid.release()

# Create a window and pass it to the Application object
App(tkinter.Tk(), "Tkinter and OpenCV")


text:
Q: Using Auth0 with ember-simple-auth I'm currently adding Auth0 to an Ember Application that previously used ember-simple-auth to authorize it's users. I was hoping to plug auth0 into ember-simple-auth to avoid having to refactor too much. I found the following library provided by Auth0, but it appears to be deprecated: https://www.npmjs.com/package/ember-simple-auth-auth0
Is there any simple way to still accomplish this? The new instructions seem to be for if you're just using Auth0 and no ember-simple-auth.


text:
Q: How to login authentication with saved encrypted data using file(basically digital certificate) in laravel 5.1 I want to login with a file that contains digital certificate of someone, first registers with certificate contents that is base64 format, and when registering it will encrypt the content of certificate and save into database and when login with this file, i want to login with that data matched by decrypted way, pls help how to do this? And also when i encrypt each time file content saved with different characters, is it possible to save 3323 characters in database? pls help.....
// controller
 $main_file = $request->file;
    //$con = $main_file->getClientOriginalName();
    $con = file_get_contents($main_file->getRealPath());
    $files = Crypt::encrypt($con);
    dd($files);
    $file = Input::file('file')->getClientOriginalName();
    $contents = File::get($main_file);

     dd($contents);

Now to authenticate with this saved encrypted data, what is the possible way to save the encrypted 3322 characters in database, i am really in a stuck. can anyone help me...the main task is to login with file contents..thanks...

A: Sounds like you're trying to implement some kind of shared private key authentication. It's not clear why you want to do that (more on that later), but it sounds like a bad idea right from the start because you are immediately confronted with a difficult problem: how do you get the private key from the client to the server in a secure way?
A better way to do it would be a private/public key system, similar to the sort of thing SSH does when you set up passwordless login. Basically (very basically - I'm not an expert) the idea is that the client generates a private/public key pair and then sends the public key to the server. On authentication, the private key is used to encrypt a message. This encrypted message is sent to the server, where the public key is used to decrypt it. If the correct message was received, then the client is authenticated.
Rather than having some sort of shared certificate, I'd recommend following this model. That way you don't have to share sensitive information (the client's private key) with the server.
Ultimately, you need to think about why you want to do this.

*

*You think this will be more convenient for clients? Well, for SSH, it certainly is more convenient to log in this way, because SSH has a mechanism for automatically encrypting and passing messages in a secure way. For HTTP? Not so much. The user is going to need to generate a file then use an upload form just to log in. Passwords are much quicker and easier.

*You think it will be more secure? The way you've described it (a shared private key) will probably be less secure because you somehow have to get the private key from the client to the server without it being compromised - remember, if the private key is compromised, anyone can impersonate the client. The way SSH does it is more secure because the private key never leaves the client.
Ultimately, I think you can probably get what you're looking for with a) strictly enforced password complexity rules and b) HTTPS.
If security on your site is so important that you cannot rely on HTTPS and complex passwords, then you should probably be looking at a more comprehensive solution that will encrypt all traffic between the client and the server, such as a VPN (virtual private network).


text:
Q: Using "by" with the future perfect continuous Does anyone know if there is any reason why a sentence like:

"By 2020 I will have been working in London for 5 years."

Might be considered incorrect? I realise in everyday life this sentence would "pass". What I want to know, however, is whether there is any ground whatsoever to consider it incorrect under the strict standards that might be applied to formal or academic writing. Particularly in regard to the preposition "by".
I know that this usage of "by" is common with the future perfect "By 2020 I will have worked in London for...", but I find the future perfect continuous to be compatible with other prepositions (and even the absence of prepositions) e.g

"Next year I will have been working in London for 5 years."
"At 11pm I will have been working for 6 hours."
"In 2020 I will have been working in London for 5 years."

Is there any grammar rule that might prohibit this usage of "by" with the future perfect continuous?
I'm inclined to think not, as the sentence sounds fine to me, but I'd be interested to read the opinions of others on the matter.

A: "By 2020 I will have been working in London for 5 years." is not incorrect, I would only add a comma after "by 2020" or place it at the end of the sentence, as it's an adverbial of time.