text:
Q: How do you access UIViewControllerRepresentable NavigationBar property? In SwiftUI if you are transitioning using a NavigationLink() into a UIViewControllerRepresentable how would you; say, add buttons or change the title property on the navigationbar.
This is what I am doing right now:
import SwiftUI

/// Controls the actual action performed by the button upon taps.
struct CatagoryButton: View {

    @State var isPresenting :Bool = false

    var company : Company?
    var text : String

    var body: some View {

        NavigationLink(destination: UIKitWrapper(company: self.company, storyboardPointer: self.text)
            .navigationBarTitle(self.text)
            .edgesIgnoringSafeArea(.all),
                       isActive: self.$isPresenting,

                       label: {
            Button(action: {
                self.isPresenting.toggle()

            }){

                ZStack {

                    ButtonShadowLayer(text: text)

                    GradientBackground()
                        .mask(ButtonBaseLayer())

                    CircleAndTextLayer(text: text)
                }
            }
        })
    }
}

Here is the struct for my representable.
import SwiftUI

/// Wraps UIKIT instance in a representable that swiftUI can present.
struct UIKitWrapper: UIViewControllerRepresentable {

    //Specify what type of controller is being wrapped in an associated type.
    typealias UIViewControllerType = UIViewController

    //Company property passed from parent view. Represents the company the user selected from main view.
    private var company : Company

    //Determines which viewcontroller will be presented to user. This string corresponds to the name of the storyboard file in the main bundle.
    private var storyboardPointer : String

    init(company: Company?, storyboardPointer: String) {

        guard let company = company else {fatalError()}

        self.company = company
        self.storyboardPointer = storyboardPointer
    }

    func makeUIViewController(context: Context) -> UIViewControllerType {

        //Find user defined storyboard in bundle using name.
        let storyboard = UIStoryboard(name: storyboardPointer, bundle: .main)

        //Downcast returned controller to protocol AccessControllerProtocol. This step is required because we are not sure which storyboard will be accessed. Potential storyboard controllers that can be called all conform to this protocol.
        //FIXME: Remove fatalError and create error enum asap.
        guard let viewController = storyboard.instantiateInitialViewController() as? AccessControllerProtocol else { fatalError() }

        //Assign user selected company object to instance property on incoming viewController.
        viewController.company = company

        //Return UINavigationController with storyboard instance view controller as root controller.
        return viewController
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {

    }
}

Finally, here is one of the classes that use the representable.
import UIKit

class OrdersViewController: UIViewController, AccessControllerProtocol {

    var company : Company!
    @IBOutlet var companyNameLabel : UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        setBackgroundColor()
        companyNameLabel.text = company.name
        self.navigationController?.navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.tapRightBarButton))]
    }

    func setBackgroundColor(){

        let backgroundGradient = BackgroundGradientSetter()
        let viewWithGradient = backgroundGradient.setGradientToView(with: [DarkBlueHue_DEFAULT,LightBlueHue_DEFAULT], size: view.bounds)

        view.addSubview(viewWithGradient)
        view.sendSubviewToBack(viewWithGradient)
    }

    @objc func tapRightBarButton(){

    }
}

No matter what I do this button doesn't show up. I'm not sure if I need to put this in a makeCoordinator() or if there is just something I am missing. If anyone has insight please let me know!

A: If it isn't available in viewDidLoad, try calling your setupNavigation() in viewWillAppear()

A: In your case navigationController is not available yet on viewDidLoad, try instead as in below demo module
Tested & works with Xcode 11.2 / iOS 13.2

class MyUIController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.onAdd(_:)))
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // might be needed to remove injected item here
    }

    @objc func onAdd(_ sender: Any?) {
        print(">> tapped add")
    }
}

struct MyInjector: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<MyInjector>) -> MyUIController {
        MyUIController()
    }

    func updateUIViewController(_ uiViewController: MyUIController, context: UIViewControllerRepresentableContext<MyInjector>) {
    }
}

struct DemoNavigationBarUIButton: View {
    var body: some View {
        NavigationView {
            MyInjector()
                .navigationBarTitle("Demo")
        }
    }
}

struct DemoNavigationBarUIButton_Previews: PreviewProvider {
    static var previews: some View {
        DemoNavigationBarUIButton()
    }
}


text:
Q: asp.net Session variables inside of SharePoint So, here is a problem that I am having with asp.net app inside of SharePoint (as page viewer).
When the Default page is loaded, it works fine.  However, when I try to go to next page, i am getting a null reference exception.  It looks like my session variables are becoming null on the next page (even though I set them on the previous page).  Here are a couple things that I tried to diagnose the problem.

*

*I try on the couple other computers; some work fine, some still don'ts.

*In the property of the page viewer inside of the SharePoint, after I click on the "Test link", it started to work fine until the session expired (on the computer didn't work initially).

I am not sure if there are settings that I need to check on the browser or the app server.
Anyone had similar problem?

A: I don't know Sharepoint, but it sounds like either In Proc session state, and the application pool restarts, a webfarm not setup properly, or cookies not being stored correctly. A starter would be to install Fiddler to see which cookies are sent. Then you should install some logging mechanism in your global.asax to know if your application pool restarts. (Might show up in the event viewer as-is, don't remember.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stop duplicate entries into database Hi there i am trying to insert an array of information into fields in a database through the selection of checkboxes i have that sorted and inserting fine but i am able to insert duplicates which is no good  i am using the following to insert the items
    $list = $_POST['sub'];

    // for each loop to insert each value into the database with the selected users informtion
    foreach ($list as  $value)  {

        // The query to run
        $listQuery='INSERT INTO tbl_list (`userId`, `subId`) VALUES (\'' . $id . '\', \'' . $value . '\')';

        // Run the query
        $objects->query($listQuery);

    }

A: You should add a unique key for (userId, subId):
ALTER TABLE tbl_list ADD UNIQUE(`userId`, `subId`)

Then, you should use either INSERT IGNORE or REPLACE INTO to avoid errors during insert.

A: You can use  Insert Ignore instead of Insert in mysql query

A: For stop duplicate entries into database you have do this thing.follow step by step
> 1.set a unique key on the table

after Complete create unique key you have to decide what you want to do when there's a duplicate

> 2. ignore it

> 3.Overwrite the previously entered record

> Update some counter

A: You need to do two things
first make your userId primary key and then try this query
$listQuery='INSERT INTO tbl_list (userId, subId) VALUES (\'' . $id . '\', \'' . $value . '\') on duplicate key update userId = LAST_INSERT_ID()';


text:
Q: Alternates to Akka Clustering feature What are the alternate offerings available to Akka Cluster ? Currently it seems that to implement distributed applications (meaning being able to maintain cluster information so as to able to distribute the workload across nodes for effective utilization of resources), Akka-Cluster is the only choice. I see there are alternates available for Akka like Erlang but not Akka-Cluster.
Anyone aware of what other technologies offers ways to distribute the workload over cluster nodes ?

A: On the JVM, I think you can roughly break down distributed computing into a few categories.

*

*If you want distributed state, something like Hazelcast (an in-memory grid) will work, but you're on your own for organizing tasks that operate with/on that data.

*If you want distributed task execution, Flink and Spark can do that.  Coordinating state changes may be difficult, and you may have to contort input into their basic abstractions (RDDs and streams).

*Pubsub on top of a replicated log (as in Kafka and Pulsar) is, like Akka, explicitly message-based (in practice, anything in distributed computing becomes message-based: at some point you have packets going over the wire), but you can very quickly build up a tangle of services and topics.
Akka is to my knowledge the only (or at least most mature) option that covers state distribution and task distribution, and it does so a bit less statically (in terms of scalability: I'm specifically thinking about how Kafka's ordering guarantees become less guaranteed as you scale).  A tangle of actors interacting is also (especially if using the typed APIs in preference to the classic APIs) probably easier to trace in an IDE than a tangle of services interacting via Kafka.
To inject a little bit of opinion, while Kafka is, in my experience using it as a dumb pipe, rock solid, I'm not a fan of a tendency I've observed in its primary vendor to overpromise in the realm of distributed computing, while I've found Akka's primary vendor to be pretty up-front about there being no silver bullet.

A: You can argue that Apache Kafka is an alternative to Akka Cluster in some use cases.
Kafka itself runs as a cluster of brokers. Your Kafka topics are partitioned and distributed in that cluster. You can read off your topic with multiple consumers and that would be your vehicle for distribution of computation.


text:
Q: How to reorder dataframe series number after droping the null value >>> df
       name        toy       born
0    Alfred        NaN        NaN
1    Batman  Batmobile 1940-04-25
2  Catwoman   Bullwhip        NaN

# Serial number starts from 0

In this dataframe, we observe that the serial number (first column) is 0,1,2. After dropping the null value, we have:
     name        toy       born
1  Batman  Batmobile 1940-04-25

# Serial number starts from 1 (should start from 0)

I was wondering how can we reset Batman's serial number back to 0? Obviously, Pandas just delete the row with null value, but it did not reset the serial number. Are there any ways to solve this problem?

A: df.dropna(subset= ['toy', 'born']).reset_index()


text:
Q: How to properly use setw() to format output? I am trying to format my output as:
1 [tab] First Name: John [tab] Last Name: Smith [tab] Age: 20 [tab]daysInCourse: {35, 40, 55} Degree Program: Security
My current code is:
{
    cout << left << setw(15) << studentID;
    cout << left << setw(15) << "First Name: " << FN;
    cout << left << setw(15) << "Last Name: " << LN;
    cout << left << setw(15) << "Email " << studentEmail;
    cout << left << setw(15) << "Age: " << age;
    cout << left << setw(15) << "{" << days[0] << ", " << days[1] << ", " << days[2];
    cout << left << setw(15) << "Degree Program: ";
}

I have played around with each row's setw value and cant seem to get it right. Does the setw function need to only be used with specific values?

A:
Note: I am concerned that the data you posted contains actual e-mail addresses and information about real people, which may or may not be private and protected. If that is the case, I think this is a breach of privacy, which is illegal. Even with consent, there is no need to post private data on this forum; I would advise you to remove these data from your post, and to not do that again in the future.

As mentioned in comments, the setw manipulator only applies to the next string, so
cout << left << setw(15) << "{" << days[0] << ", " << days[1] << ", " << days[2];

will set a width of 15 only for the character { (similarly in the line with "First Name: ", etc.). It is also worth noting that if a string exceeds the specified width, then it will push the next contents and break the alignment of your columns; so you need to set the width thinking about the largest possible contents.
Here is a working example to implement what you want, using a stringstream to form the string before printing it (in order for setw to apply to the entire thing):
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>

// ------------------------------------------------------------------------

struct Student
{
    std::string ID, First, Last, Email, Degree;
    unsigned age;
    std::vector<unsigned> days;

    Student( std::string ID, std::string First, std::string Last, unsigned age,
        std::string Email, std::string Degree, std::vector<unsigned> days )
    : ID(ID), First(First), Last(Last), age(age), Email(Email), Degree(Degree), days(days)
    {}
};

std::ostream& operator<< ( std::ostream& os, const Student& s ) {
    std::ostringstream ss;

    ss << "First Name: " << s.First;
    os << std::left << std::setw(25) << ss.str();
    ss.str("");

    ss << "Last Name: " << s.Last;
    os << std::left << std::setw(35) << ss.str();
    ss.str("");

    ss << "Email: " << s.Email;
    os << std::left << std::setw(50) << ss.str();
    ss.str("");

    ss << "Age: " << s.age;
    os << std::left << std::setw(10) << ss.str();
    ss.str("");

    ss << "{" << s.days.at(0) << ", " << s.days.at(1) << ", " << s.days.at(2) << "}";
    os << std::left << std::setw(20) << ss.str();
    ss.str("");

    ss << "Degree Program: " << s.Degree;
    os << std::left << std::setw(30) << ss.str();
    ss.str("");

    return os << std::endl;
}

// ------------------------------------------------------------------------

int main() {
    std::cout << Student("A3","Robert","Smith",19,"example@foo.com","SOFTWARE",{20,40,33});
    std::cout << Student("A4","Alice","Smith",22,"example@bar.net","SECURITY",{50,58,40});
}

outputs:
First Name: Robert       Last Name: Smith                   Email: example@foo.com                            Age: 19   {20, 40, 33}        Degree Program: SOFTWARE
First Name: Alice        Last Name: Smith                   Email: example@bar.net                            Age: 22   {50, 58, 40}        Degree Program: SECURITY

Note that I have set different widths for each field, depending on the expected lengths of the contents. For example, e-mail addresses can be quite long, but the age will rarely exceed two digits.


text:
Q: C++ standard list and default-constructible types Why is that the single parameter constructor of std::list<T> requires T to be a default-constructible type? I mean the following code does not compile.
struct Foo { // does not have default constructor.
  Foo (int i) {}
}
int main(void) {
  std::list<Foo> l(10);
}

It seems possible to use the construct and destroy idioms as they have already done in the std::vector, albeit with more book-keeping the list class.
On a related note, why not have the capacity function in list? You can argue that such a function would pay memory allocation cost up-front and eliminate the overhead later on as you push_back objects. At least it will make the interfaces of two STL sequence containers slightly more consistent.

A: std::list doesn't have a capacity function because it makes no sense; it never has to resize like a vector does. It's capacity is only limited by the available memory, which is not easily determined.
From what you asked for, I think you actually want reserve(). That's a one-off for vector because it (badly) needs such a thing; there's no particular requirement to make all functions consistent across all STL containers, especially when they make little sense for others.
You can accomplish the same effect using a custom allocator. As Manuel suggested, look at boost.

A: There is no general requirement that the type be default constructible - it must be copyable and assignable. Your code does not work because you try to create  a list of 10 items - they have to be constructed somehow and so the default constructor must be used - but only in this specific case. If you created an empty list and added to it, there would be no such requirement.
The same is true for other containers - try compiling the following:
#include <vector>

struct A {
    A( int x ) : z(x) {}
    int z;
};

std::vector <A> a(10);

Regarding the second part of your question, I'd just observe that consistency of interface was not a prime design criterion for the standard containers - there is no intention, for example, that one type of container is a "drop-in" replacement for another. There is a good discussion of this in items 1 and 2 of Scott Meyers' book "Effective STL".

A: Neil already answered the main question.
Also note that you need a default constructor when calling resize().
You can circumvent this by having a STL list of pointers to objects but I guess this already was obvious to you.

On a related note, why not have the
  capacity function in list? You can
  argue that such a function would pay
  memory allocation cost up-front and
  eliminate the overhead later on as you
  push_back objects. At least it will
  make the interfaces of two STL
  sequence containers slightly more
  consistent.

I guess the problem here is that STL lists allow cross-list splicing. If you want to allocate memory upfront, have a look at the Boost Pool Allocator.

A: The reason is that, when you construct a list of n elements (where n is the parameter you used in the constructor), the list fills its structure of n elements with copies of T().
See sgi stl documentation for list.

A: So your question is really "why not have reserve and capacity functions in list?"
The answer to that is that there's no reason to reserve memory in advance for list - adding new elements never requires a realloc & copy for existing elements, there's no requirement that the memory holding the contents of a list be contiguous, and iterators don't get invalidated when doing a list::push_back().
All of those are the reason for the existence of vector<>::reserve(), and having memory in reserve for new elements is why a vector<> will perform placement new into raw memory.

A:
Why is that the single parameter
  constructor of std::list requires T
  to be a default-constructible type?

Because this contructor - creates list with elements (number which you pass as parameter). Value of each element will be default. Also you could use constructor with two parameters, for create list with elements which will be initialized with second element value.

On a related note, why not have the
  capacity function in list?

It doesn't have sense, because cost of adding new elements to list is much little than in case with vector.

std::vector does not have such a
  restriction. My question is why not
  use the same techniques
  (create/destroy idioms) in the
  std::list as well?

It is not restriction. Because if you don't use such constructor, default initializer will not required. Same thing true for vector.


text:
Q: Serving Angular content and HTML+CSS content from Node/Express backend I have one Node/Express server where I am serving both an Angular application and some static HTML. I serve the Angular application out of dist/angular and the static content out of static-content:
// This has to be in this order or else it doesnt work for some reason
app.use(express.static('./static-content'));
app.use(express.static('./dist/angular'));

app.use(parser.json());

// some other routes ...

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '/static-content/index.html'));
});

app.get('/app/*', function (req, res) {
  res.sendFile(path.join(__dirname, '/dist/angular/index.html'));
});

http.createServer(function (req, res) {
  let httpsHost = req.headers.host.replace('8081', '8443');
  res.writeHead(301, {"Location": "https://" + httpsHost + req.url});
  res.end();
}).listen(8081);

https.createServer(httpsOptions, app).listen(8443)

If you change the order of the express.static at the top, it will not serve the static-content so I am wondering if this is the correct way to serve both an Angular application and HTML+CSS content out of one Node/Express server?


text:
Q: fadeOut inside the onclick function I have written a code which shows question on click and also shows answer for certain period of time. The code works fine when there is no fadeOut function inside the code. As soon as I put the fadeOut function, the question and answer is shown only once. After that only question is shown . Why is this happening ?
Here is my code link :http://jsfiddle.net/sagesony/6qDap/1058/
and the code

Question:

Answer:

    <input id="start" type="button" value="start"/>
    <input id="show" type="button" value="show answer"/>

A: because fadeOut is setting your element to display:none; after fading.
so, you have to set this element visible again to fadeOut again.
just use:
.show()

to do this.
http://jsfiddle.net/Valtos/6qDap/1060/

A: You need to use a delay like
var verbs = ["play", "run", "go", "kill"];
var answers = ["golf", "dog", "school", "none"];
//register click handler
$('#start').click(function () {
    var i = Math.round(Math.random() * 3);
    $("#question").html(verbs[i]);
    $('#show').click(function () {
        $("#answer").html(answers[i]).delay(1000).fadeOut();
    })
})

A: You should show it again: http://jsfiddle.net/6qDap/1063/
 $("#answer").fadeOut(1000, function(){
        $(this).show().text('');
    });

A: This happens since after calling the fadeOut() method the answer span is hidden forever. You will have to do something to show it again like below:
var i = 0;
var verbs = ["play", "run", "go", "kill"];
var answers = ["golf", "dog", "school", "none"];

$('#start').click(function () {
    i = Math.round(Math.random() * 3);
    $('#question').html(verbs[i]);
});

$('#show').click(function () {
    $("#answer").html(answers[i]).show().fadeOut(1000);
});

FIDDLE DEMO


text:
Q: Getting new file name from FileIORename ETW event I am subscribing to the Kernel ETW Events using https://www.nuget.org/packages/Microsoft.Diagnostics.Tracing.TraceEvent/.
Is it possible to monitor file rename so that I know what was the previous and new file path?
I thought that it would simple require hooking to the FileIORename event, but the payload (FileIOInfoTraceData) contains only the previous file path in the FileName property.
kernelSession.Source.Kernel.FileIORename += FileIORename
...

private void OnFileIORename(FileIOInfoTraceData data)
{
    var prevFilePath = data.FileName;
    var newFilePath = ?
    ...
}

A: My solution in to use the FileIOFSControl event to get the new file name, I am using the FileKey property to link between the FileIORename event and the FileIOFSControl event.
Complete code in VB.NET
Imports System.IO

Imports Microsoft.Diagnostics.Tracing.Parsers
Imports Microsoft.Diagnostics.Tracing.Session
Imports Microsoft.Diagnostics.Tracing.Parsers.Kernel

Module Module1

    Private _etwSessionID As String
    Private _etwSession As TraceEventSession
    Private lstEvents As List(Of FileIOTraceEvent)

    Sub Main()

        lstEvents = New List(Of FileIOTraceEvent)

        _etwSessionID = "TestSession"

        _etwSession = New TraceEventSession(_etwSessionID) With {.StopOnDispose = True}
        _etwSession.EnableKernelProvider(KernelTraceEventParser.Keywords.DiskFileIO Or KernelTraceEventParser.Keywords.FileIO Or KernelTraceEventParser.Keywords.FileIOInit)

        AddHandler _etwSession.Source.Kernel.FileIORename, AddressOf FileIOTrace
        AddHandler _etwSession.Source.Kernel.FileIOFSControl, AddressOf FileIOTrace

        _etwSession.Source.Process()

        Console.Read()

    End Sub

    Private Sub FileIOTrace(data As FileIOInfoTraceData)

        Try

            If data.EventName = FileIOTraceEvent.EVENT_NAME_FILEIO_RENAME Then
                lstEvents.Add(New FileIOTraceEvent(data.ID, data.TimeStamp, data.EventName, data.ProcessID, data.ProcessName, data.FileName, data.FileKey))

            ElseIf data.EventName = FileIOTraceEvent.EVENT_NAME_FILEIO_FSCONTROL Then

                Dim fileEvent = lstEvents.FirstOrDefault(Function(ev) ev.EventName = FileIOTraceEvent.EVENT_NAME_FILEIO_RENAME AndAlso ev.FileKey = data.FileKey)

                If fileEvent IsNot Nothing Then
                    fileEvent.NewFileName = Path.GetFileName(data.FileName)
                    Console.WriteLine(fileEvent.ToString)
                End If

            End If

        Catch ex As Exception
        End Try

    End Sub

#Region "Classes"

    Private Class FileIOTraceEvent

#Region "Public Members"

        ''' <summary>
        ''' Event ID
        ''' </summary>
        Public ID As UShort

        ''' <summary>
        ''' Event date
        ''' </summary>
        Public Timestamp As Date

        ''' <summary>
        ''' Event name
        ''' </summary>
        Public EventName As String

        ''' <summary>
        ''' The process ID that raised the event
        ''' </summary>
        Public ProcessID As Integer

        ''' <summary>
        ''' The process name that raised the event
        ''' </summary>
        Public ProcessName As String

        ''' <summary>
        ''' File full path
        ''' </summary>
        Public FilePath As String

        ''' <summary>
        ''' The new file name
        ''' </summary>
        Public NewFileName As String

        Public FileKey As ULong

#End Region

#Region "Public Methods"

        Public Sub New(id As UShort, timestamp As Date, eventName As String, processID As Integer, processName As String, filePath As String, fileKey As ULong)

            Me.ID = id
            Me.Timestamp = timestamp
            Me.EventName = eventName
            Me.ProcessID = processID
            Me.ProcessName = processName
            Me.FilePath = filePath
            Me.FileKey = fileKey

        End Sub

        Public Overrides Function ToString() As String
            Return String.Concat("Event ID: ", ID, ", Date: ", Timestamp, ", Event Name: ", EventName, ", File Path: ", FilePath, ", New File Name: ", NewFileName)
        End Function

#End Region

#Region "Constants"

        Public Const EVENT_NAME_FILEIO_RENAME = "FileIO/Rename"
        Public Const EVENT_NAME_FILEIO_DELETE = "FileIO/Delete"
        Public Const EVENT_NAME_FILEIO_WRITE = "FileIO/Write"
        Public Const EVENT_NAME_FILEIO_SETINFO = "FileIO/SetInfo"
        Public Const EVENT_NAME_FILEIO_CREATE = "FileIO/Create"
        Public Const EVENT_NAME_FILEIO_FSCONTROL = "FileIO/FSControl"

#End Region

    End Class

#End Region

End Module


text:
Q: I am creating a Hash Table that uses nodes to chain. What is a collision? I can't seem to get an answer that I understand. What is a collision when you have a hash table that uses linked nodes?
Is the collision +1 for every index that you must pass to get to the index needed for that node you are adding?
I know that collisions are unavoidable, I have learned that much through my research but I haven't been able to figure out what constitutes a collision when dealing with a hash table that has linked nodes.
My program after finding its proper place in the array (array of pointers to nodes), sticks the new node at the front. Each element points at a node that points at another node, I have essentially multiple linked lists. So, does the collision count only include the first node of the element where the new node belongs because I stick it at the front, or does it include every single node in the linked list for that element.
for example, if the name "Smith" goes to the element [5], which also has 5 other nodes that are linked together, and I add it to the front, how would I decide what the collision count is?
Thanks for any help!

A: A collision is when 2 distinct entries produces the same output through the Hash function.
Say your (poorly designed) hash function H consists in adding all the digits of a number:

5312 -> 5 + 3 + 1 + 2 = 11
  1220 -> 1 + 2 + 2 + 0 = 5

So H(5312) = 11 and H(1220) = 5
H has a lot of collisions (this is why you should not use it):

H(4412) = 4 + 4 + 1 + 2 = 11
  H(9200) = 9 + 2 + 0 + 0 = 11
  etc...


text:
Q: LSTM accuracy not increasing more than 68% I am a newbie in the field of deep learning. I am trying to use LSTM with time series data with more than 300,000 datapoints. The target variable is a class with 7 unique values. I used one-hot encoding to covert it into numerical values. The final dataset looks as follows.
                      0    1    2    3    4    5    6
datetime
1970-01-09 03:32:31  0.0  1.0  0.0  0.0  0.0  0.0  0.0
1970-01-09 03:40:59  0.0  0.0  0.0  0.0  0.0  1.0  0.0
1970-01-09 04:14:28  0.0  0.0  0.0  1.0  0.0  0.0  0.0
1970-01-09 13:07:18  0.0  1.0  0.0  0.0  0.0  0.0  0.0
1970-01-09 15:44:40  0.0  0.0  0.0  0.0  0.0  0.0  1.0

My question is that after looking at multiple examples, I came up with the following LSTM but my training accuracy is not increasing more than 68%. Do you have any recommendations about what changes can help? I have tried changing the look_back value, epochs, batch size, number of hidden nodes, layers, etc. The accuracy changes only slightly with these modifications.
   X_train, y_train = preprocess_LSTM(train, look_back)
   X_train = np.reshape(X_train, (len(X_train), look_back, outputs))

   model = Sequential()
   model.add(LSTM(200, input_shape=(input_nodes, outputs)))
   model.add(Dense(100, activation='relu'))
   model.add(Dense(outputs, activation='softmax'))
   model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

   # fit network
   X_train = np.asarray(X_train)
   y_train = np.asarray(y_train)
   model.fit(X_train, y_train, epochs=5, batch_size=128)
   # evaluate model
   _, accuracy = model.evaluate(X_train, y_train, batch_size=128)
   print (accuracy)


text:
Q: Getting IE to replace a regex with the literal string "$0" I'm replacing a bunch of values in a regex with dollar amounts.  The problem is that in IE, if I attempt to replace with an amount of $0 (or, theoretically, $1--$9), the replace never occurs since the it's trying to replace a non-existant group:
'foo'.replace(/f/g, '$0');

I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).
Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1:
'foo'.replace(/(f)/g, '$1')

A: Write "$$0" to escape the $ sign.

A: In Chrome and Firefox you can workaround this limitation by using a function as the second argument of the replace function:
'foo'.replace(/(f)/g, function(){return '$1';}); // => $1oo

My own testing shows that IE8 is consistent with the other browsers on this issue.

A: The Problem:
'My Bank balance is {0} '.replace(/\{0\}/,'$0.22')
 results: "My Bank balance is {0}.22 "
 This is not what we want

The solution:
'My Bank balance is {0} '.replace(/\{0\}/,'$$0.22')
results: "My Bank balance is $0.22 "
'My Bank balance is {0} '.replace(/\{0\}/,"$0.22".replace(/\$/,'$$$$'))
result: "My Bank balance is $0.22 "

Explanation: I am trying to find '$' and replace by '$$'. To match '$' you have to escape it by '\$' and to replace '$$$$' you have to put four '$' as RegEx escape '$' for '$$'. Fun!!

A: @SLaks that should be more like: write "$$" for literal "$".
@cwolves getting a literal instead of a 'special' character (like "$" here) usually involves either doubling it or prefixing it with "\".


text:
Q: If the only self adjoint operators from $\mathcal H$ to $\mathcal H$ are $0$, what comment we can make on $\mathcal H$? If $\mathcal H$ is a Hilbert space over $\mathbb C $ or $\mathbb R$.
The only self adjoint operators from $\mathcal H$ to $\mathcal H$ are $0$ and $I$. --------------------------------(1)

*

*Then can we say that $\mathcal H$ is a one-dimensional space?

*What other comments we can make on (1).

A: The operator $2 \, I$ is always self-adjoint. Hence, $2 \, I = I$ or $2 \, I = 0$. This yields $I = 0$, hence, $\mathcal{H} = \{0\}$.
Edit: Since every orthogonal projection onto a subspace is self-adjoint, it is quite easy to reconstruct $\mathcal{H}$ from its self-adjoint operators.


text:
Q: How to create a read-only user for a particular schema After creating a user via CREATE USER... I want to give it access to my database and schema. Here is the way that is working:
EXEC sp_addrolemember 'db_owner', 'tom'
GRANT SELECT ON schema::dbo TO tom;

However, I'm having trouble doing this with the stored procedure, as the following doesn't give 'enough' privileges:
GRANT CONNECT TO tom;
GRANT SELECT ON schema::dbo TO tom;

What's wrong with using the CONNECT? What else do I need to grant such that they'll have select-all privileges on that schema?
Update: it seems I have to give it a more rigorous 'select'. Here is what worked:
GRANT CONNECT to tom;
GRANT SELECT to tom;
DENY SELET ON schema::other_schema to tom;
GRANT SELET ON schema::dbo to tom;
GO

Why do I need to add in the GRANT SELECT to tom ?

A: As we know, if we run EXEC sp_addrolemember 'db_owner', 'tom', the user will have the most privileges and can access all schemas of the current database.
I tried the following code, the user will only have the select privilege of the current database.
CREATE LOGIN bobby WITH PASSWORD = 'Password1'

CREATE USER bobby FOR LOGIN bobby;

GRANT CONNECT TO bobby;
GRANT SELECT ON schema::production TO bobby;

After I run this, I can access the specified database and the specified
schema(production) with the user bobby.

Then I run GRANT SELECT to bobby;, I can see the user bobby can access all the schemas in the current db.

So we can conclude that:

*

*GRANT SELECT to bobby; means grant all schemas to the user of the current database.

*GRANT SELECT ON schema::production TO bobby; means grant specified schema to the user of the current database.


text:
Q: A integral equation Prove that :
$$\displaystyle \int_0^{\frac{\pi}{2}}p(x)\cot x\text{d}x=2\sum_{k=1}^{\infty}\int_0^{\frac{\pi}{2}}p(x)\sin (2kx)\text{d}x$$
where $\displaystyle p(x)=x^n$

A: Using the formula for the sum of a geometric series:
$$
\begin{align}
2\sum_{k=1}^{m-1}\sin(2kx)
&=-i\sum_{k=1}^{m-1}(e^{i2kx}-e^{-i2kx})\\
&=-i\left(\frac{e^{i2x}-e^{i2mx}}{1-e^{i2x}}-\frac{e^{-i2x}-e^{-i2mx}}{1-e^{-i2x}}\right)\\
&=-i\left(\frac{e^{ix}-e^{i(2m-1)x}}{e^{-ix}-e^{ix}}-\frac{e^{-ix}-e^{-i(2m-1)x}}{e^{ix}-e^{-ix}}\right)\\
&=i\frac{e^{ix}+e^{-ix}}{e^{ix}-e^{-ix}}-i\frac{e^{i(2m-1)x}+e^{-i(2m-1)x}}{e^{ix}-e^{-ix}}\\[6pt]
&=\frac{\cos(x)}{\sin(x)}-\frac{\cos((2m-1)x)}{\sin(x)}\\[9pt]
&=\cot(x)-\frac{\cos((2m-1)x)}{\sin(x)}
\end{align}
$$
Therefore, if $p(x)/x$ is integrable, then by the Riemann-Lebesgue Lemma
$$
\begin{align}
2\sum_{k=1}^\infty\int_0^{\pi/2}p(x)\sin(2kx)\,\mathrm{d}x
&=\lim_{m\to\infty}2\sum_{k=1}^{m-1}\int_0^{\pi/2}p(x)\sin(2kx)\,\mathrm{d}x\\
&=\lim_{m\to\infty}\int_0^{\pi/2}p(x)\left(\cot(x)-\frac{\cos((2m-1)x)}{\sin(x)}\right)\,\mathrm{d}x\\
&=\int_0^{\pi/2}p(x)\cot(x)\,\mathrm{d}x-{\small\lim_{m\to\infty}\int_0^{\pi/2}\frac{p(x)}{\sin(x)}\cos((2m-1)x)\,\mathrm{d}x}\\
&=\int_0^{\pi/2}p(x)\cot(x)\,\mathrm{d}x
\end{align}
$$


text:
Q: Bash: Difference between paste command with Command Substiution vs. FIFO FDs I'm just trying to understand why when I use a couple FIFO FDs in a paste command I get a 'Broken Pipe' but when I use Command Substitution everything is all good.
A little background: I have a need to process a rather large array, looking for particular values, and finally do a litany of tasks a user could want. Speed is pretty important with this large dataSet.
What I've come up with so far is the idea of simply printing the array (subscripts and values in parallel as both subscripts and values will be used in user tasks), pasting them together so that every array item can be processed in sequence by the user in a 'stream' that'd mostly be accepted by a pipeline (the users tasks).
However, what I'm finding is that the first column for the paste command (the array subscripts) aren't making it.
Here's a very simplified example in commands (create_tmp_fifo does simply what it looks like, very simple. The 'cat' in the pipeline is just an abstract example of a user task):
fifo_pasteOutput=$(create_tmp_fifo) fifo_subscriptPrint=$(create_tmp_fifo) fifo_valuePrint=$(create_tmp_fifo);
printf '%s\n' "${!DATA_SET[@]}" >$fifo_subscriptPrint &
printf '%s\n' "${DATA_SET[@]}" >$fifo_valuePrint &
paste -d'|' <$fifo_subscriptPrint <$fifo_valuePrint | cat;
printf '\n';
rm $fifo_subscriptPrint $fifo_valuePrint $fifo_pasteOutput

Output:
[1] 117250
[2] 117251
#0,SYS[offset=0,ceiling=10]
#1,MSG[offset=11,ceiling=20]
#2,MISC[offset=21,ceiling=50]
[1]-  Broken pipe             printf '%s\n' "${!DATA_SET[@]}" > $fifo_subscriptPrint
[2]+  Done                    printf '%s\n' "${DATA_SET[@]}" > $fifo_valuePrint

Why is the first process showing a 'Broken Pipe'? If I do:
paste -d'|' <(printf '%s\n' "${!DATA_SET[@]}") <(printf '%s\n' "${DATA_SET[@]}")

Everything works as expected. From my reading of the Bash manual it's my understanding that process substitution is basically doing the same thing I'm doing with specified FIFO files. Am I misunderstanding something? I'm stumped.
Avoiding using process substitution in the paste command would be preferred as the function that prints the arrays for user consumption takes various options which format the output in many various ways, hence I'm trying to cut back on a paste command for every different variation.
Thanks in advance for any insight

A: I feel dumb.
Already found the answer.
paste -d'|' $fifo_subscriptPrint $fifo_valuePrint

Was looking at the command one last time and wondered if the arguments it takes are just the files themselves. Anyway, thanks for anyone's time.


text:
Q: Python: Control subprocess from calling thread I am working on a database interface to a MongoDB using Python Eve as an API.
The database stores several documents containing parameters and values needed for some calculations. I wrote a Python module containing all the calculation routines which need to have access to the desired data.
Since the calculations need some time to complete I would prefer multiprocessing instead of multithreading in order to use several cores for co-current simulations (doing calculations in parallel, one calculation per core, but with different input parameters, not splitting one calculation to several cores).
In order to start those parallel calculations as own (sub)processes I thought about using something like a parent thread which are observed by another thread called 'thread observer'. Since each of these calculation processes needs access to the database I thought about using the eve-API in combination with the requests module.
All in all these thoughts lead to the setup like the following:

Based on this concept I am not sure about how to control the subprocess from its parent thread. How can I make sure that Process 1 is terminated if Thread 1 terminates?
Note: The desired solution needs to work both on UNIX- and Windows-based machines. So using the returned pid of the started process in order to kill it using kill would not work since this would not be doable on a Windows machine.

A: Start with the Python 2 and Python 3 multiprocessing package having classes like Process with Queue and Pipe to exchange messages between them on all platforms where Python runs.  You seem to be interested in the Pool class of multiprocessing to control worker processes.  It is a different style of control than the usual fork/exec, wait, and signals.


text:
Q: echart cannot be visualized on DOM even though there is an instance on checking inspect element Hello i have a wird issue that the echarts is not loading even there is an instance on the DOM. I want to load it inside a widget. It works fine otherwise.
no chartdissplayed
chart displayed in html
My chart code:
var myChart = echarts.init(document.getElementById('displayarea'));
                    var option = {
                        title: {
                            text: 'ECharts '
                        },
                        tooltip: {},
                        legend: {
                            data:['aa']
                        },
                        xAxis: {
                            data: ["aa","bb","cc","dd","ee","ff"]
                        },
                        yAxis: {},
                        series: [{
                            name: 'rr',
                            type: 'bar',
                            data: [5, 20, 36, 10, 10, 20]
                        }]
                    };

                    myChart.setOption(option);

Can anyone guide on what could be the issue. Thanks in advance.


text:
Q: Rails 5.2.3 Blob Error with Active Storage when create file I'm using rails 5.2.3 and I am trying to use ActiveStorage for a new scaffolded agenda. I have followed this tutorial
I want to save files locally on the filesystem.
At the moment when I want to create a new object by web form, I get the following error:

Unable to autoload constant ActiveStorage::Blob::Analyzable, expected
  /home/vagrant/.rvm/gems/ruby-2.6.2/gems/activestorage-5.2.3/app/models/active_storage/blob/analyzable.rb
  to define it

From Mail-log:

[ERROR] blogs create (NoMethodError) "Cannot load Rails.config.active_storage.service:\nundefined method `fetch' for n

And when I refresh the page I get:

undefined method `fetch' for nil:NilClass

My Definitions
model:
has_one_attached :image

controller:
def create
  @blog = Blog.new(blog_params)
  .
  .
end

def blog_params
  params.require(:blog).permit(:name, :audit_comment, :image)
end

views:
= simple_form_for(blog) do |f|
  = f.error_notification
  .form-inputs
    = f.input :name, label: 'Name'

    = f.file_field :image

  = f.input :audit_comment
  .form-actions
    = f.button :submit

In development.rb:
config.active_storage.service = :local

What have I missed?
I've runned rails active_storage:install and migrations as this setup suggested
When I whole new rails app it works fine.


text:
Q: Whenever I watch a video the screen gets brighter when the cursor disappears Whenever I watch a video on my Windows 10 system,
the screen gets brighter when the cursor disappears.
I think it's an Intel® HD graphics card.
I searched it up and it said to turn off "adaptive brightness",
so I did, but it's still brightening.
I'll be watching a video and the background is a light gray, when I start watching the video.
When the cursor, along with the bottom bar disappears, the light gray will turn white; the screen just changes brightness.
If I move my mouse and the cursor appears again, the screen goes back to normal.
How can I prevent this?

A: First: we need to ensure the following two points:

*

*Download and install the latest graphics driver according to the graphics card or motherboard.

*Download and install the latest power management drivers according to the model of the machine.
Second: Do we use a video player to play video or use a browser to play video?
If we use a video player, we can use other video players, and then check if there is such a issue when playing, if not, it may be the setting issue of this video player. Check if there is a setting like "adaptive brightness" in this video player so that we can adjust the video brightness.
If we use a browser to watch videos, try another browser and see if other browsers have the same issue when playing videos. If only a browser has such a issue, we check the browser settings.
Third: If we use all the video players and browsers to watch the video, this issue may be an operating system problem.
We can refer to the articles: Windows 10 laptop keeps adapting brightness ("Adaptive Brightness" is disabled)

A: This is probably due to Intel® Display Power Saving Technology, here is a Github Script to disable it https://github.com/orev/dpst-control


text:
Q: Spliterator trySplit return type I have stumbled upon an interesting detail in java.util.Spliterator  (Java 8).
Method trySplit() is supposed to return an instance of Spliterator or null, if it can't be split. The java doc says the following:
 * @return a {@code Spliterator} covering some portion of the
 * elements, or {@code null} if this spliterator cannot be split.

It appears to me as a perfect place to use java.util.Optional. As per javadoc:
 * A container object which may or may not contain a non-null value.

Are there any reasons, why Optional was not used?
Googling did not help much, except this question in lambda-dev mailing list, which was not answered.

A: Spliterator is the part of internal stream implementation. It should not be used in business logic where Optional would be convenient. Its quite low-level interface which main goal is to be fast. So there's no reason for Optional there.
You might argue that Optional usually can be eliminated by JIT compiler. However that's not always the case. For example, default max depth of calls for inlining in Hotspot JIT compiler is 10 and usual stream processing has more stack frames, so even one additional stack frame may prevent optimization.

A: There are a couple of reasons it's the way it is. Of course, conceptually, trySplit could return Optional<Spliterator<T>>, but there are some design forces that pushed away from this.
One reason is that there's a difference between methods such as findFirst that return Optional vs. methods such as trySplit that return value-or-null.

*

*Methods like findFirst are called by and return values to application code.

*Methods like trySplit are called by and return values to library code.

A design aspect of the JDK class libraries is that the library APIs are (or should be) designed to make things easier for application code, and library code will often take on more complexity in order to make things simpler for applications.
One of the main reasons for Optional is to avoid passing nulls from the library to application code, because improper null handling is a common source of NullPointerExceptions. Instead of null, APIs like findFirst will return an empty Optional, which is supported by a rich set of methods such as orElse, map, filter, flatMap, etc. that provide a great deal of flexibility to applications for dealing with the not-found case.
Note that the nullable return value from trySplit is going in the opposite direction: from the application to the library.
Having application code pass or return a nullable value to the library is considerably less error-prone for the application than having it receive a nullable value from the library. If you're writing an application and the API says that you should pass or return a null to the library, there's no possibility that this will generate an NPE in your code. Indeed, there are a variety of places in the APIs (List.sort(null) comes to mind) where null has particular semantics in the API.
trySplit is called from relatively few places in the library, and the library maintainers are taking on the burden of dealing properly with null in all of those cases.
Another prime consideration is performance. Splitting is in the critical path of setting up a parallel pipeline. It's performed sequentially, before work is handed off to different threads to be executed in parallel. Per Amdahl's Law, in order to make parallelism as efficient as possible, you want to minimize the sequential setup overhead.
The fact is that an Optional is a box, and there is a cost to boxing and unboxing a value to and from an Optional. The JIT compiler might be able to optimize this away in some cases, but it might not. Even if it does, there's a period of time where the code is running but the Optional hasn't yet been optimized away. That's additional overhead. Since the library code is willing to bear the burden of handling null properly, we can guarantee there's no boxing overhead simply by not using Optional at all in this case.


text:
Q: Is there a way to distinguish mice in JavaScript? I am wanting to hook up several mice - each one used for different types of input.  Is there a way in JavaScript to distinguish between each mouse?
I know that JS may not seem like the right language for this, but I want to use one mouse for web navigation, and the other for Google-earth navigation.  Because the Google-API is already using JS, I figured I try to keep all the code together.

A: This is not possible with JavaScript. The JS would have to have low-level access to the clients machine to make this type of distinction. Obviously, this would be a huge security risk.


text:
Q: in kotlin do I have to set my class's nullable member variables to null after it goes out of scope? do I have to create a destructor if I have a nullable type as member variable of a class in Kotlin?
class Mesh{
      var tris:ArrayList<Int>?=null
      init{
           tris=arrayListOf<Int>()
      }
      fun initOneTri(tri:Int){
          tris?.add(tri)
      }
      fun destructor(){
          tris=null //Is this required?
      }

}

*

*Do I need a destructor for nullable types declared as member variable of a class in Kotlin?


text:
Q: Ribbon button still visible after hide from code I try to hide a button after click on it, i try following code :
btnEdit.Visible = false;

but the button still visible, it hide once i click on it
full code :
    void SwitchMenu(bool showEdit)
    {
        boxEdit.Visible = showEdit;
        foreach (var item in boxEdit.Items)
        {
            item.Visible = showEdit;
        }
        boxCreate.Visible = !showEdit;
        foreach (var item in boxCreate.Items)
        {
            item.Visible = !showEdit;
        }
    }

A: there are an issue with Box visibility, removed box solve my issue.


text:
Q: How to fix no Qt plugin initialized error for OpenCV People Counter tutorial script I am trying to get a working setup of the object detection and tracking algorithm talked about in this tutorial: https://www.pyimagesearch.com/2018/08/13/opencv-people-counter/
I am using a Mac and I have python 3.7.6 installed into a virtual environment named 'SARDroneV2' to keep installed packages from above tutorial isolated to just the virtual env.
I followed through the tutorial exactly, but when I try executing the code into Terminal I get the following error: (I included the command I entered into command line as well)
    (SARDroneV2) adammuzzarelli@Adams-iMac ~ % python /Users/adammuzzarelli/Desktop/SAR\ Tracker/Tracker\ Algo/people_counter.py --prototxt /Users/adammuzzarelli/Desktop/SAR\ Tracker/Tracker\ Algo/mobilenet_ssd/MobileNetSSD_deploy.prototxt --model /Users/adammuzzarelli/Desktop/SAR\ Tracker/Tracker\ Algo/mobilenet_ssd/MobileNetSSD_deploy.caffemodel

[INFO] loading model...
[INFO] starting video stream...

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in "" This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.


text:
Q: Can't connect to Oracle DB from within my dll I have an external dll (that written in c#) which is responsible of connecting to my DB.
I"m using this dll in my node.js application (Javascript).
 When connecting to MSS DB connection result is true, when connecting to Oracle db it constantly fails with no option to know what went wrong.
but if im connecting to the Oracle DB thru a test project (written in c#) in my visual studio ,  the result is true.
the problem accord only when i use the dll thru the nodejs.
How can I resolve this?

A: This are different databases and need different connection modules.
I would suggest writing a separate connection in node as it is really easy with the node-oracledb module:
var oracledb = require('oracledb');

oracledb.getConnection(
  {
    user          : "hr",
    password      : "welcome",
    connectString : "localhost/XE"
  },
  function(err, connection)
  {
    if (err) { console.error(err); return; }
    connection.execute(
      "SELECT department_id, department_name "
    + "FROM departments "
    + "WHERE department_id < 70 "
    + "ORDER BY department_id",
      function(err, result)
      {
        if (err) { console.error(err); return; }
        console.log(result.rows);
      });
  });

You need to install the module first using npm.
More info here: https://blogs.oracle.com/opal/entry/introducing_node_oracledb_a_node


text:
Q: Java keyboard input - game development I have a specific "problem" with a game I'm creating for class.
The game is an implementation of "Break it". To move the platform at the bottom I just used a key listener. The problem is that after the first key press there is a short "lag" or "stutter" before the platform starts moving. How could I prevent this to get a smooth response? Is there another way than KeyListener? KeyBindings?
Here is the key listener implementation
private class KeyControl implements KeyListener {

    private int dx = 20;

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
            if(dx < 0 )
                dx = -dx;
            gamePanel.movePlatform(dx);
        }

        if(e.getKeyCode() == KeyEvent.VK_LEFT) {
            if(dx > 0 )
                dx = -dx;
            gamePanel.movePlatform(dx);
        }

        if(e.getKeyCode() == KeyEvent.VK_SPACE) {
            System.out.println("space");
            gamePanel.play();
        }

        if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            gamePanel.pause();
        }

    }
}

and here is the method that moves the platform around
public void movePlatform(int dx) {
        int nextDX = dx;

        if(paused || init) {
            dx = 0;
        }

        // make sure platform doesnt exceed right border
        if(platform.getX() + platform.getWidth()  + dx> size.getWidth()) {
            if(nextDX < 0)
                dx = nextDX;
            else
                dx = 0;
        }

        // make sure platform doesnt exceed left border
        if(platform.getX() + dx <= 0) {
            if(nextDX > 0)
                dx = nextDX;
            else
                dx = 0;
        }

        platform.setFrame(platform.getX() + dx, platform.getY(), platform.getWidth(), platform.getHeight());
        platformIntervalX = new Interval((int)platform.getX(), (int)(platform.getX() + platform.getWidth()));
        platformIntervalY = new Interval((int)(platform.getY() - platform.getHeight()), (int)platform.getY());
        repaint();
    }

A: The solution is not to use the KeyListener's key press for moving your sprite. The key is not to rely on the hardware-specific key press frequency, to use a Swing Timer to create your own frequency. Instead use Key Bindings and a Swing Timer. Start the time on key press and stop it on key release.
For example, run this code and press and release the up-arrow key:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class KeyBindingEg extends JPanel {
   private static final String UP_KEY_PRESSED = "up key pressed";
   private static final String UP_KEY_RELEASED = "up key released";
   private static final int UP_TIMER_DELAY = 50;
   private static final Color FLASH_COLOR = Color.red;

   private Timer upTimer;
   private JLabel label = new JLabel();

   public KeyBindingEg() {
      label.setFont(label.getFont().deriveFont(Font.BOLD, 32));
      label.setOpaque(true);
      add(label);

      setPreferredSize(new Dimension(400, 300));

      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      KeyStroke upKeyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false);
      KeyStroke upKeyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true);

      inputMap.put(upKeyPressed, UP_KEY_PRESSED);
      inputMap.put(upKeyReleased, UP_KEY_RELEASED);

      actionMap.put(UP_KEY_PRESSED, new UpAction(false));
      actionMap.put(UP_KEY_RELEASED, new UpAction(true));

   }

   private class UpAction extends AbstractAction {
      private boolean onKeyRelease;

      public UpAction(boolean onKeyRelease) {
         this.onKeyRelease = onKeyRelease;
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         if (!onKeyRelease) {
            if (upTimer != null && upTimer.isRunning()) {
               return;
            }
            System.out.println("key pressed");
            label.setText(UP_KEY_PRESSED);

            upTimer = new Timer(UP_TIMER_DELAY, new ActionListener() {

               @Override
               public void actionPerformed(ActionEvent e) {
                  Color c = label.getBackground();
                  if (FLASH_COLOR.equals(c)) {
                     label.setBackground(null);
                     label.setForeground(Color.black);
                  } else {
                     label.setBackground(FLASH_COLOR);
                     label.setForeground(Color.white);
                  }
               }
            });
            upTimer.start();
         } else {
            System.out.println("Key released");
            if (upTimer != null && upTimer.isRunning()) {
               upTimer.stop();
               upTimer = null;
            }
            label.setText("");
         }
      }

   }

   private static void createAndShowGui() {
      KeyBindingEg mainPanel = new KeyBindingEg();

      JFrame frame = new JFrame("KeyBindingEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Edit
Or a better example, one that moves a sprite in any direction based on a key press of one of the arrow keys. No delay encountered:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.EnumMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class KeyBindingEg2 extends JPanel {
   enum Dir {
      LEFT("Left", KeyEvent.VK_LEFT, -1, 0),
      RIGHT("Right", KeyEvent.VK_RIGHT, 1, 0),
      UP("Up", KeyEvent.VK_UP, 0, -1),
      DOWN("Down", KeyEvent.VK_DOWN, 0, 1);

      private String name;
      private int keyCode;
      private int deltaX;
      private int deltaY;
      private Dir(String name, int keyCode, int deltaX, int deltaY) {
         this.name = name;
         this.keyCode = keyCode;
         this.deltaX = deltaX;
         this.deltaY = deltaY;
      }
      public String getName() {
         return name;
      }
      public int getKeyCode() {
         return keyCode;
      }
      public int getDeltaX() {
         return deltaX;
      }
      public int getDeltaY() {
         return deltaY;
      }
   }
   public static final int TIMER_DELAY = 10;
   public static final int DELTA_X = 2;
   public static final int DELTA_Y = DELTA_X;
   public static final int SPRITE_WIDTH = 10;
   public static final int SPRITE_HEIGHT = SPRITE_WIDTH;
   private static final String PRESSED = "pressed";
   private static final String RELEASED = "released";
   private static final int PREF_W = 800;
   private static final int PREF_H = 650;
   private Map<Dir, Boolean> dirMap = new EnumMap<>(Dir.class);
   private int spriteX = 0;
   private int spriteY = 0;
   private BufferedImage sprite;
   private Timer animationTimer = new Timer(TIMER_DELAY, new AnimationListener());

   public KeyBindingEg2() {
      for (Dir dir : Dir.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      sprite = createSprite();
      setKeyBindings();
      animationTimer.start();
   }

   private BufferedImage createSprite() {
      BufferedImage sprt = new BufferedImage(SPRITE_WIDTH, SPRITE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
      Graphics g = sprt.getGraphics();
      g.setColor(Color.RED);
      g.fillRect(0, 0, SPRITE_WIDTH, SPRITE_HEIGHT);
      g.dispose();
      return sprt;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (sprite != null) {
         g.drawImage(sprite, spriteX, spriteY, this);
      }
   }

   private void setKeyBindings() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();

      for (Dir dir : Dir.values()) {
         KeyStroke keyPressed = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, false);
         KeyStroke keyReleased = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, true);

         inputMap.put(keyPressed, dir.toString() + PRESSED);
         inputMap.put(keyReleased, dir.toString() + RELEASED);

         actionMap.put(dir.toString() + PRESSED, new DirAction(dir, PRESSED));
         actionMap.put(dir.toString() + RELEASED, new DirAction(dir, RELEASED));
      }

   }

   private class AnimationListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         int newX = spriteX;
         int newY = spriteY;
         for (Dir dir : Dir.values()) {
            if (dirMap.get(dir)) {
               newX += dir.getDeltaX() * DELTA_X;
               newY += dir.getDeltaY() * DELTA_Y;
            }
         }
         if (newX < 0 || newY < 0) {
            return;
         }
         if (newX + SPRITE_WIDTH > getWidth() || newY + SPRITE_HEIGHT > getHeight()) {
            return;
         }
         spriteX = newX;
         spriteY = newY;
         repaint();
      }
   }

   private class DirAction extends AbstractAction {

      private String pressedOrReleased;
      private Dir dir;

      public DirAction(Dir dir, String pressedOrReleased) {
         this.dir = dir;
         this.pressedOrReleased = pressedOrReleased;
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         if (pressedOrReleased.equals(PRESSED)) {
            dirMap.put(dir, Boolean.TRUE);
         } else if (pressedOrReleased.equals(RELEASED)) {
            dirMap.put(dir, Boolean.FALSE);
         }
      }

   }

   private static void createAndShowGui() {
      KeyBindingEg2 mainPanel = new KeyBindingEg2();

      JFrame frame = new JFrame("KeyBindingEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}


text:
Q: Core Data: deleteObject crashes application, NSPredicate the cause? I'm using a UICollectionView along with Core Data.
I can't seem to figure out why I can't remove an object from Core Data. It crashes at [self.managedObjectContext deleteObject:animation]; with an index 0 beyond bounds for empty array error. The following method is a delegate method that gets invoked from another viewcontroller. It gets a timestamp NSInteger and should create an NSPredicate with that timestamp.
The strange thing is that when I take the animationTimestamp NSInteger and hardcode it like:
[NSPredicate predicateWithFormat:@"timestamp == %i", @"1370169109"] it works and the object gets deleted without the error. However, when I want to pass the parameter as the argument it crashes. I've tried making it a string, NSNumber etc. Nothing works when I take the parameter, it only does when I hardcode it. I've logged animationTimestamp and it shows the correct value, so I'm stuck.
Thanks!
- (void)deleteAnimationWithTimestamp:(NSInteger)animationTimestamp {

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Animations" inManagedObjectContext:self.managedObjectContext];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp == %i", animationTimestamp];
    [fetchRequest setPredicate:predicate];

    [fetchRequest setEntity:entity];
    NSError *error;

    NSArray *animations = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (NSManagedObject *animation in animations) {
        [self.managedObjectContext deleteObject:animation];
    }

    // Save core data
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Couldn't save: %@", [error localizedDescription]);
    }

    [self.animationsCollectionView reloadData];
}

EDIT:
More info that might matter. The timestamp attribute in the model is a 64 bit integer (should it be by the way?). When I create the object I use:
NSNumber *timestampNumber = [NSNumber numberWithInt:timestamp];
[newAnimation setValue:timestampNumber forKey:@"timestamp"];

A: Get the NSInteger value from NSNumber
Like
NSInteger timestampNumber = [[NSNumber numberWithInt:timestamp] integerValue];
// then use this integer

[newAnimation setValue:timestampNumber forKey:@"timestamp"];

// or in
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp == %d", timestampNumber];


text:
Q: Parsing PGN string starts with number Hello everyone I am new to python and try to learn about parsing the string from PGN.
'[ECO "B08"]',
 '',
 '1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4',
 '9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+',
 '16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1  1-0',
 '',
 '[Event "Telechess ol1 7778"]',

The result that I want is just to put the move part into a list
1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4,9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+ 16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1

The approach that I take is by reading the PGN and split by '\n'. The output contains a list as the first block of code.
I want to detect by every list that started with a number (one digit or two-digit before the dot '.') should append into a new list.
rough code should be like
listmove = []
for i in pgn:
if i.startswith(1digitnumber or twodigitnumber before dot):
listmove.append[i]

Is it possible? Guidance will help a lot and will be appreciated.

A: Yes it's possible using regular expressions. The regex you need is ^\d+\. Demo
Explanation:

*

*^: Start of line / start of string

*\d+: One or more digit characters

*\.: One period

In python, you'd do:
import re

lines = ['[ECO "B08"]',
 '',
 '1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4',
 '9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+',
 '16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1  1-0',
 '',
 '[Event "Telechess ol1 7778"]']

regex = r"^\d+\."

movelines = []

for line in lines:
    if re.search(regex, line):
        # This line starts with digits and a period
        movelines.append(line)

print(movelines)

prints:
[
 '1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4',
 '9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+',
 '16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1  1-0'
]

You could also remove the ^ from your regex and use re.split() to get the different moves. You can use the fact that re.match() searches from the beginning of the line, so use that instead of re.search():
split_regex = r"\d+\."

all_moves = []

for line in lines:
    if re.match(split_regex, line):
        moves = re.split(split_regex, line)
        all_moves.extend(moves)

print(all_moves)

This prints
[
'', 'e4 d6 ', 'd4 Nf6 ', 'Nc3 g6 ', 'Nf3 Bg7 ', 'Be2 Nbd7 ', 'O-O O-O ', 'e5 dxe5 ', 'dxe5 Ng4',
'', 'e6 Nde5 ', 'Qxd8 Rxd8 ', 'Nxe5 Nxe5 ', 'Nb5 c6 ', 'Nc7 Rb8 ', 'f4 Ng4 ', 'Bxg4 Bd4+',
'', 'Kh1 Bb6 ', 'f5 Bxc7 ', 'fxg6 fxg6 ', 'Bh6 Be5 ', 'Rad1 Rxd1 ', 'Rxd1 Bd6 ', 'Rf1  1-0'
]

Notice the extra empty strings at the start of each line. This happens because of the way re.split() works, so you can simply ignore the first entry in each line with all_moves.extend(moves[1:]) to give
[
  'e4 d6 ', 'd4 Nf6 ', 'Nc3 g6 ', 'Nf3 Bg7 ', 'Be2 Nbd7 ', 'O-O O-O ', 'e5 dxe5 ', 'dxe5 Ng4',
  'e6 Nde5 ', 'Qxd8 Rxd8 ', 'Nxe5 Nxe5 ', 'Nb5 c6 ', 'Nc7 Rb8 ', 'f4 Ng4 ', 'Bxg4 Bd4+',
  'Kh1 Bb6 ', 'f5 Bxc7 ', 'fxg6 fxg6 ', 'Bh6 Be5 ', 'Rad1 Rxd1 ', 'Rxd1 Bd6 ', 'Rf1  1-0'
]

The win marker 1-0 is included in this because it's not separated by a move number, but it should be fairly trivial to remove that because it can only be one of three possibilities:

*

*1-0 (White wins),

*0-1 (Black wins)

*1/2-1/2 (draw)

A: The shortest intelligible line you might be interested in should be at least 4 characters (move number, move notation). So you can freely check those first characters for initial validity even up to moves of index 100 or more.
At some stage you might come across lines that start with a Black move, but they still start with a number I believe. ('15. ... Bd4+')
Since an earlier version caused a little confusion, this one splits out the first character test from those subsequent more explicitly:
def good_moves_start(pgnline):
    if len(pgnline) < 4:
        return False
    if pgnline[0] not in '123456789': # first char test
        return False
    for ch in pgnline[1:4]:
        if ch == '.':
            return True               # dot completes move #
        elif not ch.isdecimal():
            return False              # disqual characater
    return False                      # no dot in first 4 chars

This only identifies candidate move data of course; there is plenty more validation possible as the moves are read in. It would be interesting to consider how to allow for puzzle boards and chess variants - pieces, board, moves, # of players.


text:
Q: How to mask columns in Hive using REGEXP_REPLACE? I am trying to achieve the below requirement of masking of address fields in Hive using regexp_replace.
If I have an address field I need to retain characters in 1,4,8,12 ..etc (multiples of 4) position and replace remaining characters as 'X', Spaces should be retained.
I have achieved the result in Teradata but struggling with Hive SQL using the same function and arguments.
Teradata Code:
SELECT
RegExp_Replace(RegExp_Replace(
RegExp_Replace
('CHANGI COURT', '(.)(.)?(.)?(.)?', '(\1(\2[\3(\4', 2,0,'c'),'(\([^ ])', 'X', 1,0,'c'),'(\(|\[)', '', 1,0,'c');

Teradata Result working as expected:

CXXNXX CXXXT

Hive Code:
SELECT
RegExp_Replace(RegExp_Replace(
RegExp_Replace
('CHANGI COURT', '(.)(.)?(.)?(.)?', '(\1(\2[\3(\4', 2,0,'c'),'(\([^ ])', 'X', 1,0,'c'),'(\(|\[)', '', 1,0,'c');

Hive error

FAILED: SemanticException [Error 10014]: Line 1:37 Wrong arguments ''c'':
  No matching method for class org.apache.hadoop.hive.ql.udf.UDFRegExpReplace
  with (string, string, string, int, int, string). Possible choices:
  FUNC(string, string, string) (state=42000,code=10014)

I have attached the screenshots of the code and results for both Hive and Teradata as well.
Teradata Code:

Teradata Result:

Hive code:

Hive error:

Can this be achieved in HIVE?


text:
Q: Are SQL Reporting Services Hidden Parameters Secure? If a make a @UserID hidden parameter in my SSRS report and set that server side in a ReportViewer control is that parameter then secure or could it be altered by the end user?
I am using SSRS 2017.

A: The user would be able to run the report by passing in the parameter value in a URL to open the report. I wouldn't think most users have the technical skills to do so, but it is possible.
Here's a link to show you how they would have to create the URL.
https://myserver/Reportserver?/SQL+Server+User+Education+Team/_ContentTeams/folder123/team+project+report&teamgrouping2=xgroup&teamgrouping1=ygroup
Here's the Microsoft documentation:
https://learn.microsoft.com/en-us/sql/reporting-services/pass-a-report-parameter-within-a-url


text:
Q: How to start a populated listview to start at top with flutter? Populated listview pushes up container when I don't want it to When I make a listview that is populated and go to that view. It starts the view towards the bottom of the list with what was added most recently to that listview. I want to keep a box with relevant information at the top or within view initially. Then have the user scroll through the list. How can this be done? The listview is already populated.

The right is what happens, but I want the left. I currently have to scroll up to see what is at the top. It gets pushed off screen when the list gets large enough.

A: After some rewriting of my code to take advantage of showSearch and SearchDelegate. (You can find a good example of how to use those by watching this episode of the boring show.)
I solved my question by doing the following based on what balsanka suggested. Here is some pseudo code of what I did to fix. This future builder is within my Widget buildResults(BuildContext context) inside my SearchDelegate class.

FutureBuilder (
...
  builder: (BuildContext context, AsyncSnapshot<> snapshot) {
  ...
    ListView retList = ListView(
      ...
    )
    ...
    Column ret = Column(
      children: <Widget>[
        Container(
          child: Text('AYYYYY it worked'),
        ),
        Expanded(
          child: retList,
        )
      ],
    );
    return ret;
  }
)

Thanks for all the help guys!


text:
Q: How to translate "var a = collection?.First()?.somePropA ?? new A();" What is the purpose of single question mark on the right side of assignment in expression with null-coalescing operator? Example:
var a = collection?.First()?.somePropA ?? new A();

A: The single quotation mark (?.) is newly added in C# 6.0 and represents a null check.
So, for example, the following code is the same;
var foo = bar?.bar2;

Or
var foo = null;
if (bar != null)
    foo = bar.bar2;
else
    foo = null;

However, both can still return null. Therefore one can use the ?? check to assign a value if the result indeed is null.
That being said, one can write the following code;
var foo = bar?.bar2 ?? new Bar2();

which is basically the same as
var foo = null;
if (bar != null)
    foo = bar.bar2;
else
    foo = new Bar2();

Using ?. multiple times can really shorten your code. Consider, for example, the following line;
var foo = bar?.bar2?.bar3?.bar4?.bar5 ?? new Bar5();

this is syntactic sugar for
var foo = null;
if (bar != null)
{
    if (bar.bar2 != null)
    {
        if (bar.bar2.bar3 != null)
        {
            if (bar.bar2.bar3.bar4 != null)
            {
                if (bar.bar2.bar3.bar4.bar5 != null)
                    foo = bar.bar2.bar3.bar4.bar5;
                else
                    foo = new Bar5();
            }
            else
                foo = new Bar5();
        }
        else
            foo = new Bar5();
    }
    else
        foo = new Bar5();
}
else
    foo = new Bar5();

Of course, there are already way better ways to write the above (for example, by initializing foo = new Bar5() before doing all the checks), but for clarity I kept it this way.

A: ?. is a new operator that helps a developer to omit excessive checks for null.
You can read more here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

A: collection.First() takes the first item from the collection. If that is not null it will call somePropA. If it is null (here comes the purpose of this operator), it will return null: it is just a smart way to do a null check. It is called the null-conditional operator.
That single character prevents the need for checking each and every property or return value for null.
Another way to write this:
var a = ( collection != null && collection.First() != null
          ? collection.First().somePropA : null
        ) ?? new A();

Or:
A a;

if (collection != null && collection.First() != null)
{
    a = collection.First().somePropA;
}
else
{
    a = null;
}

if (a == null)
{
    a = new A();
}


text:
Q: How to assign new value array to old array inside method? There are a lot of mine methods with standard filter, map and so on to return a new array.
let array = [1, 2, 3, 4];
array = someFilter(array);
array = otherFilter(array);
array = someMap(array);

How can I do it without return new array?
let array = [1, 2, 3, 4];
someFilter(array);
otherFilter(array);
someMap(array);

For example
let x = [1, 2, 3, 4];
filter(x);
// x still 1, 2, 3, 4

function filter(array){
    let newArray = array.filter((item) => item % 2 == 0);
    array = newArray; // what do here?
}

Update
There is my solution
function replace(oldArray, newArray){
    oldArray.length = 0;
    push(oldArray, newArray);
}

function push(sourceArray, ...additionalArray) {
    additionalArray.forEach((array) => {
        if (array.length < 1000){
            sourceArray.push.apply(sourceArray, array);
        } else {
            array.forEach((item) => sourceArray.push(item));
        }
    });
    return sourceArray;
}

A: Use Array.splice() to remove all items from the original array, and add the items from the new array:

function filter(array) {
  const newArray = array.filter((item) => item % 2 == 0);
  array.splice(0, array.length, ...newArray);
}

const x = [1, 2, 3, 4];

filter(x);

console.log(x)

You also set the array's length to be 0 to remove all items, and then push the new items:

function filter(array) {
  const newArray = array.filter((item) => item % 2 == 0);
  array.length = 0;
  array.push(...newArray);
}

const x = [1, 2, 3, 4];

filter(x);

console.log(x)


text:
Q: Update values of a row based on id with sequelize gives 404 error I am currently working with nodeJS,expressJS and reactJS. I can currently access each data's id by clicking the edit button but I have issues actually updating the data everytime I click the button I get a 404 error in the console. I have looked through multiple questions and tutorials but none really helped with my confusion. I have a put route in my server.js to update the record based on the id:
app.put("update-list/:id", function (req, res, next) {
    Information.update({
        Name: req.body.name,
        Phone: req.body.phone,
        Email: req.body.email,
    }, { where: req.params.id }
    ).then(function (rowsUpdated) {
        res.json(rowsUpdated);
    }).catch(next)
});

Defined route in react:
<Route path="/edit/:id" component={Edit}/>

How I am getting the api:
 let [state, setState] = useState({
    name: "",
    phone: "",
    email: "",
  });
  let body = state;
  useEffect(()=>{
    handleSubmit(props);
  })
  function handleSubmit(props) {
    const id=props.match.id
    axios({
      method: "put",
      url: "http://localhost:5000/update-list/"+id,
      data: body,
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    console.log(state);
  }

On change function:
function handleChange(e, field) {
    e.preventDefault();
    const value = e.target.value;
    setState({
        ...state,
        [field]: e.target.value,
    });
}

The button click is calling the handleChange() function and the form is calling handleSubmit().
Am I missing something or is this completely the wrong way to do it? Let me know if you need any more details!

A: app.put("/update-list/:id", function (req, res, next) {
  db.Information.update({
    Name: req.body.name,
    Phone: req.body.phone,
    Email: req.body.email,
  }, { where: { id: req.params.id } } // This is fixed
  ).then(function (rowsUpdated) {
    res.json(rowsUpdated);
  }).catch(next)
});

React.js Project: https://github.com/nkhs/node-sequelize-react.js-client/tree/stack-66271022
API Project: https://github.com/nkhs/node-sequelize/tree/stack-66271022


text:
Q: Is it wrong to use line plots for discrete data? I've often seen discrete datasets plotted as line plots, but it occurs to me that the line infers a value at a point between the measurement intervals which is meaningless for discrete datasets. Is it therefore the case the using line plots for discrete data is wrong?
As an example, take two time-series datasets, one continuous (my weight, measured daily in the morning) and one discrete (the number of donuts I eat per day). It makes sense for the first dataset to be a line plot, as it is reasonable to infer that my weight in any given afternoon will be related to my weight the preceding and following mornings. However, if the number of donuts is represented as a line graph the lines between the dots no meaning can be inferred from that line.
EDIT
Here's another example: the Federal Hourly Minimum Wage Since Its Inception plot at http://mste.illinois.edu/courses/ci330ms/youtsey/lineinfo.html
Unless I'm mistaken, the minimum wage changes are discrete, and hence it's not possible to look up some arbitrarily selected time and establish the minimum wage at the point using the line interconnecting the dots.

A: Well, the donuts might be related to the weight :-)
While I see your point, I think this example is not so bad because time (on the horizontal axis, which is what the lines refer to) is continuous. The meaning of the line, to me, isn't so much that, at each time of day you ate a certain number of donuts, but that the number of donuts per day changes in some regular way. Thus, we might add something like a loess smoother to the line, and it would make sense. It is at least reasonable to think of donuts eaten at each hour, or even each minute (although this would be more sensible with a variable where the count per day was higher)
What is more worrisome is when the horizontal axis is discrete (and especially when it is nominal) but lines are drawn. This really makes no sense. E.g. if you are looking at (say) the % voting for Obama among (say) residents of different regions of the USA, it makes no sense to draw a line between Northeast and Midwest; especially since the order of the regions is arbitrary, but changing the order would change the lines. Yet I have seen graphs like this.

A: Connected line plots have proven too useful to limit to a single interpretation. A few prominent uses:

*

*Interpolated values. The case you mention where both variables are continuous and every interpolated point along the line as a meaningful interpretation.

*Rate of change. Even when the in-between values aren't meaningful, the slope of each line segment is a good representation of the rate of change. Note that for this interpretation, the X and Y values must be spaced appropriately, which is not the case in the wage plot you cite.

*Profile Comparison. When comparing small multiples or overlaid measures, lines can be useful even for categorical factors. In this case, the lines serve to connect groups of responses for limited pattern recognition. Here's an example from peltiertech.com with the factor on the Y (instead of the X) axis for label readability:


text:
Q: Java BufferedImage Slideshow i am trying to write a small slideshow application in java.
What works so far:

*

*Load the images from the drive

*Pick images randomly and don't pick one twice

*render the image in fullscreen

However, i display a new image every 3 seconds. Rendering the new image looks crappy becuase the display flickers while rendering loading the new image.
I haven't found a way to deal with that problem. I like to to a cool animation like "slide to the left and let the new image slide in from the right side" or "fade the old image out and the new one in".
Here is my rendering code so far:
private Frame frame;
private Component oldComponent = null;
private void display(final File file) throws IOException {
    Component c = new Component() {
        BufferedImage img = ImageIO.read(file);

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
        }
    };

    if(oldComponent != null)
        frame.remove(oldComponent);

    frame.add(c);

    oldComponent = c;

    GraphicsEnvironment ge = GraphicsEnvironment
            .getLocalGraphicsEnvironment();
    GraphicsDevice gs = ge.getDefaultScreenDevice();
    gs.setFullScreenWindow(frame);
    frame.validate();
}

As you can see, i create a new component and remove the old one, if there has been one.
I'm happy about any information code or links.
Thanks in advance!
Michael


text:
Q: Making PayPal API calls in PHP without cURL I can't use cURL as Google App Engine doesn't support it.
I am trying to get the access token in step 2 of: https://developer.paypal.com/docs/integration/direct/make-your-first-call
I'm not sure how I should be structuring my call. I have this so far:
$data = array(
    'grant_type' => 'client_credentials',
    'client_id' => $sandbox_client_id,
    'secret' => $sandbox_secret

);

$data = json_encode($data);

$context = [
  'http' => [
    'method' => 'POST',
    'header' => 'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
        'Accept: application/json' . "\r\n" .
        'Accept-Language: en_US' . "\r\n"
    ,
    'content' => $data
  ]
];
$context = stream_context_create($context);

$response = file_get_contents('https://api.sandbox.paypal.com/v1/oauth2/token', false, $context);

echo $response;

Which returns this:
Warning: file_get_contents(https://api.sandbox.paypal.com/v1/oauth2/token): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in C:\folder\php\paypal\test.php on line 28

Any insight is appreciated!

A: I figured it out.
The client id and secret have to be put into a string separated by : then base64 encoded. That is then sent in the header.
This works:
$auth_string = $sandbox_client_id . ':' . $sandbox_secret;
$encoded_auth = base64_encode($auth_string);

$data = array(
    'grant_type' => 'client_credentials'

);

$http_query = http_build_query($data);
$context = [
  'http' => [
    'method' => 'POST',
    'header' => 'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
        'Accept: application/json' . "\r\n" .
        'Accept-Language: en_US' . "\r\n" .
        'Authorization: Basic ' . $encoded_auth
    ,
    'content' => $http_query
  ]
];

$context = stream_context_create($context);

$response = file_get_contents('https://api.sandbox.paypal.com/v1/oauth2/token', false, $context);

echo $response;


text:
Q: Duration_in_traffic less than duration in google Distance Matrix API I am using both the "duration_in_traffic" and "duration" feature using the DistanceMatrix API.
For a given coordinate pair, I see the following results:
{
  "destination_addresses": [
    "Hamburg, Germany"
  ],
  "origin_addresses": [
    "85748 Garching, Germany"
  ],
  "rows": [
    {
      "elements": [
        {
          "distance": {
            "text": "761 km",
            "value": 760831
          },
          "duration": {
            "text": "7 hours 1 min",
            "value": 25242
          },
          "duration_in_traffic": {
            "text": "6 hours 42 mins",
            "value": 24145
          },
          "status": "OK"
        }
      ]
    }
  ],
  "status": "OK"
}

Here is my question:
How is it that the duration_in_traffic is less than duration?
From what i understood:
Duration: Duration of travel on a route... Not sure if it is without traffic
Duration_in_traffic: Duration of travel on a route under traffic conditions.
Any explanation on this will be greatly appreciated.

A:
Note: The durationInTraffic field is now deprecated. It was previously
  the recommended way for Google Maps API for Work customers to specify
  whether the result should include a duration that takes into account
  current traffic conditions. You should now use the drivingOptions
  field instead.

Duration seems to take an average of durations at different times/from historic data, while duration_in_traffic takes the given departure time (and live traffic) into account. So the route takes 7 hours 1 min in average, but with your given time it only takes you 6 hours 42 mins from Hamburg to Garching.
I don't know if Google has that detailed data, but it could be that during the day a part of the highway is most of the times limited to 60 km/h because of dense traffic, while your travel time is around 23:00 and due to that you are allowed to drive 120 km/h.
There are also the three values for traffic_model: best_guess, pessimistic and optimistic which can influence the duration_in_traffic value.


text:
Q: Measure, volume and cardinality on Minlos' book on statistical physics The following content was based on Minlos' book on statistical physics. Let $\Lambda \subset \mathbb{R}^{d}$ be fixed (Minlos takes $d=3$ but I think the ideas follow without change to $d \ge 1$). We denote by $\Lambda^{N}$ the $N$-fold cartesian product of $\Lambda$ with itself and $(\Lambda^{N})'$ $N$-uples $(x_{1},...,x_{N})$ in $\Lambda$ with different entries, i. e. $x_{i}\neq x_{j}$ if $i\neq j$. Also $\Gamma_{\Lambda, N}:=\{\omega \subset \Lambda, \hspace{0.1cm} \mbox{card}(\omega) = N\}$, where $\mbox{card}(\omega)$ is the cardinality of the set $\omega$. Define $\Pi: (\Lambda^{N})' \to \Gamma_{\Lambda, N}$ by $(x_{1},...,x_{N}) \mapsto \{x_{1},...,x_{N}\}$. For every subset $A$ of $\Gamma_{\Lambda, N}$, Minlos set:
$$ \mu_{\Lambda}^{(N)}(A) := \frac{\mbox{Vol}(\Pi^{-1}(A))}{N!} $$
Then, he states that
$\mu_{\Lambda}(\Gamma_{\Lambda, N}) = \frac{|\Lambda|^{N}}{N!}$. The problem is that he doesn't seem to define $\mbox{Vol}$ or $|\cdot|$ anywhere and it is getting me a little confused. At first, I thought $\mbox{Vol}$ was just the Lebesgue measure on $\mathbb{R}^{dN}$. But it would be a little odd because if I take $A = \{x_{1},...,x_{N}\}$ it seems that $\mu_{\Lambda}^{(N)}(\{x_{1},...,x_{N}\}) = 0$. Besides, how come does the second statement about $\mu_{\Lambda}(\Gamma_{\Lambda, N})$ follow? If $|\Lambda|$ is the cardinality of $\Lambda$ (which I don't know for sure), does it follow from de definition of $\mu_{\Lambda}$?

A: If $\text{Vol}$ denotes the Lebesgue measure on $(\mathbb R^d)^N$, if $|\cdot|$ denotes the Lebesgue measure on $\mathbb R^d$, and if $\mu_\Lambda=\mu_\Lambda^{(N)}$, then indeed $\mu_\Lambda(\Gamma_{\Lambda,N})=\frac{|\Lambda|^N}{N!}$. This follows because (i) $\Pi^{-1}(\Gamma_{\Lambda,N})=(\Lambda^N)'$ and (ii) (say, by the Fubini--Tonelli theorem) $\text{Vol}((\Lambda^N)')=\text{Vol}(\Lambda^N)=|\Lambda|^N$.
As for $\mu_\Lambda^{(N)}(A)$ with $A=\{x_{1},...,x_{N}\}$, it is undefined. Indeed, for $\mu_\Lambda^{(N)}(A)$ be defined, $A$ must be a subset of $\Gamma_{\Lambda,N}$, whereas $\{x_{1},...,x_{N}\}$ is a subset of $\mathbb R^d$ but not of $\Gamma_{\Lambda,N}$. On the other hand, if $A$ is the singleton set
$\{(x_{1},...,x_{N})\}$ with pairwise distinct $x_j$'s in $\mathbb R^d$, then indeed $\mu_\Lambda^{(N)}(A)=0$, and there is nothing odd about that.


text:
Q: How delete a folder when certain password is entered I want to remove a folder (or write on it by shred) when a specific password is entered. I don't want to use an encrypted OS like LUKS as this link says, or destroy the whole drive as lots of people say.
I have an idea. I can use 2 passwords to login to the system. 1st one is a usual password, but when I entered the second one, system logins but runs a script as startup like:
rm -rf /address/of/folder

or:
shred -u file.txt

Is this idea possible? (Can I use 2 passwords to login?)


text:
Q: The projective and injective modules of $End_A(V)$? Let A be a finite-dimensional k-algebra,where k is a fixed field. All modules of A are finitely generated left modules. Suppose X is an A-module. We denote by add(X) the full subcategory of A-modules consisting of all direct summands of direct sum of finitely many copies of X. $D$ is the usual k-duality $Hom_k(-,k)$, $\nu _A$ is the Nakayama functor $DHom_A(-,_{A}A)$
Recall that the module X is called a generator over A if $add(_{A}A) \subseteq add(X)$, a cogenerator if $add(D(A_A)) \subseteq add(X)$, and a generator-cogenerator if it is both a generator and a cogenerator over A.
Can anyone tell me how to get the following results:
1):Let V be a generator over A with $B := End_A(V)$.Then $Hom_A(V,I)$ is an injective B-module for every injective A-module I.
2): If V is a generator-cogenerator, then each projective-injective B-module is precisely of the form $Hom_A(V,I)$ with I an injective A-module.
Also I want to know is there any other results of the modules of $B=End_A(V)$ for a A-module V?


text:
Q: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*' I'm trying to recreate the vector class in C++
I obtain this error int the function at();
invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'
Isn't it possible to return a pointer as address even if the function is supposed to return a reference?
the code looks like:
template<typename T>
class Vector
{
public:

   explicit Vector(int initSize = 0);
   Vector(const Vector & rhs) throw (std::bad_alloc);
   ~Vector();
   const Vector & operator=(const Vector & rhs) throw (std::bad_alloc);
   void resize(int newSize);
   void reserve(unsigned int newCapacity);
   bool empty() const;
   int size() const;
   int capacity() const;
   T & operator[](int index);
   const T & operator[](int index) const;
   T & at(int index) throw (std::out_of_range);
   void push_back(const T & x) throw (std::bad_alloc);
   T pop_back();
   const T & back() const;
   typedef T * iterator;
   typedef const T * const_iterator;
   iterator insert(iterator it, const T& x) throw (std::bad_alloc);
   iterator begin();
   const_iterator begin() const;
   iterator end();
   const_iterator end() const;

private:
   int theSize;
   unsigned int theCapacity;
   T * objects;
};
#include "vector.hpp"
#endif /* VECTOR_HPP_ */

template<typename T>
Vector<T>::Vector(int initSize):theSize
(initSize),theCapacity(128),objects(0)
{

}

typename Vector<T>::iterator Vector<T>::begin()
{
    return objects;
}

template<typename T>
T & Vector<T>::at(int index) throw (std::out_of_range)
{
    //if (index<=theSize)
        return (begin()+index);
}

int main()
{
        Vector<int>* vec1=new Vector<int>(4);
    cout<<vec1->at(2)<<endl;
        return 0;
}

A: The expression begin()+index is of pointer type; you need to add a dereference to make it a reference:
template<typename T>
T & Vector<T>::at(int index) throw (std::out_of_range)
{
    return *(begin()+index);
}

Note that this may not be safe, because operations that re-allocate objects would invalidate the reference obtained through the at() function.


text:
Q: Getting 403 (Forbidden) React + Django when I try to delete or edit a task(todo), I get DELETE http://127.0.0.1:8000/api/tasks/4/ 403 (Forbidden). But, when I want just to get tasks, everything works. Maybe the problem in CORS. I have 'corsheaders' in INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE
serializers.py
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('pk', 'title', 'created_at', 'is_done')

settings.py
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:8000",
]

App.js
function removeTodo(id){
        axios.delete(`http://127.0.0.1:8000/api/tasks/${id}`)
    }

A: In views.py I didn't make a @api_view(['DELETE']) etc. And add it to urls.py
views.py
@api_view(['GET'])
def taskList(request):
    tasks = Task.objects.all().order_by('-id')
    serializer = TaskSerializer(tasks, many=True)
    return Response(serializer.data)

@api_view(['POST'])
def taskCreate(request):
    serializer = TaskSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

@api_view(['DELETE'])
def taskDelete(request, pk):
    task = Task.objects.get(id=pk)
    task.delete()

    return Response('Item successfully delete!')

A: In your settings.py just add:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',

    )
}

This works because with these settings we get to use Django's standard django.contrib.auth permissions or allow read-only access for unauthenticated users.