text:
Q: Angular - ngrx - Effect for continually getting data from server Setup

*

*Angular 13.2.0

*Ngrx 13.0.2

*Backend: Spring Boot

Goal
I want to continually get the data from the backend. The data is changing and i want to reflect those changes in the angular-app.
What works so far
pollingfetchEntities$ = createEffect(
    () => ({ scheduler = asyncScheduler, stopTimer = EMPTY } = {}) =>
      this.actions$.pipe(
        // Filter action type
        ofType(DoctransActions.fetchEntities),
        // Get the polling interval
        switchMap(() =>
          // Start polling
          timer(0, 3000, scheduler).pipe(
            // Stop the polling (used only in testing)
            takeUntil(stopTimer),
            switchMap(() =>
              this.http.get<DoctransResponse>(`${this.apiUrl}/someurl`).pipe(
                map(response => {
                  return action to set entities
                }),
                catchError((err) => {
                  return action for error
              )
            )
          )
        )
      )
  );

Question
Is there a better way for doing this? Maybe i am missing a complete other pattern?
Update 1
Investigating the websocket approach.
From here: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-websocket
it says

Latency alone is not a deciding factor. If the volume of messages is
relatively low (for example, monitoring network failures) HTTP
streaming or polling can provide an effective solution. It is the
combination of low latency, high frequency, and high volume that make
the best case for the use of WebSocket.
Blockquote

The angular-app will run in the spring-boot-backend. So there wont be any latency. But i dont need real time data (in ms or s). 1 update every 30 sek or every min is good enough.
So maybe HTTP streaming or polling is enough? Dont know this yet.
Anyone has some experience with it?
Solution
Solved with

*

*backend: spring webflux

*angular: EventSource

A: The best way is to use websocket.
import { webSocket } from "rxjs/webSocket";
const subject = webSocket('ws://localhost:8081');

subject.subscribe();

subject.next({message: 'blablabla'});

subject.complete();

You can create a websocket service to manage websocket in your Angular application, as well.
See rxjs documentation for more details.

A: This is fine if you want to poll for your data.
Another option is to use websockets that way the servers can send data to the client.

A: Websocket is the best way to achieve this but sometimes we can't able to use it in our projects because of backend is not supporting etc...
If the case is you can't use websockets, and you want to poll data from your server another way to achieve it is using interval from rxjs
loadEntities$ = createEffect(() =>
  this.actions$.pipe(
    ofType(fromEntityActions.loadEntities),
    switchMap(() => interval(1000)),
    map(() =>
      fromEntityActions.loadEntitiesSuccess({
        data: [
          {
            id: Math.random() > 0.5 ? 1 : 2,
            name: "Sefa",
            code: "Sefa"
          }
        ]
      })
    )
  )
);

You can try this code, Math.random is just for testing purposes to see if its really changing at 1000ms interval.


text:
Q: How to get inputs from multiple peers in a message-oriented microservice Here are two basic but related questions about distributed systems.  Suppose we are lucky enough to be writing microservices that will sit at the end of a queue (Azure Service Bus, AWS SQS, or Kafka).  Most or all of the services depend on inputs (messages) from other services to do their jobs.

*

*Should we strive to limit inter-service communication to the message queue?  There's always a temptation to make REST calls to other services (bypassing the bus) when you want something immediately.  But maybe this is a symptom of pre-microservice thinking.

*If the answer is yes--we should strive for total isolation--what do we do when service A needs messages from both B and C in order to do its job?  A has just seen a message from B that it should act on.  Does A wait around for the needed C message to come across the bus?
Maybe A could put a message on the bus asking C to do something and C could reply across the bus, but this is starting to feel awfully REST-like.

A:
Should we strive to limit inter-service communication to the message queue?

Not necessarily a message queue; but usually via indirect, asynchronous information transfer.
I push information to you by writing it into a information store that you can read, and I pull information from you by reading it out of an information store that you can write.  But you-the-service aren't necessarily running when I'm interacting with the information stores, and I'm not idle-blocking waiting on you to do your work.
Typically, when a service doesn't have all of the information that it needs to do some work, it will reschedule that work for later, or invoke some contingency measures to announce that it is not meeting its service level objectives for this unit of work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drawing Bijections for one set I just want to make sure I understand what to do when asked to draw bijections.
So when I am asked Draw the diagrams (as we did in class) for all bijections $f : A\to A$ when the set $A$ is $A = \{1, 2\}$
Do I make two columns of $1$ and $2$ because it is a bijection of one set, then draw the lines? But, I also do it four times because there can be four combinations.

A: I expect that what's wanted is something like this, with one diagram for each bijection:

Note that while there are two other functions from $A$ to $A$, neither of them is a bijection.


text:
Q: Consideration: Leave Read-only DB in Application resourcePath or copy to documents/library folder My App uses a read-only sqlite db. Now I am unsure, if it makes any sense to copy the db to the documents or library folder on the iphone or to leave it in the applications bundle ([[NSBundle mainBundle] resourcePath]).
Are there known issues with leaving the db in the resourcePath besides that it can only be used read only (e.g. is unpacking data an issue as the app itself is stored as a zip container and therefore frequent access is not recommended...)?
(There is a similar unanswered question, but my main point is the access of the db in the resource folder, not manipulating the resource folder.)

A: None I'm aware of. I would let the DB in the resource folder, save some space and prevent iTunes to include that db in every backup.


text:
Q: Gatling: For long term should we put one REST API in one simulation? We have decided to use Gatling as performance testing tool. But we are not able to figure how should we keep our simulations. Since we have around 25 API's as of now. So do I need to create 25 simulation for each API. This question is more on maintenance of code.

A: It depends on what you want to achieve. Do you want to only test each API in isolation? Or do you want to simulation real traffic that would be distributed over the different API calls with different weights?
I recommend extracting the calls to dedicated classes like it's being done in the tutorials and have multiple Simulations depending on your needs.


text:
Q: mail is not sending from azure portal webapp using sendgrid I have created the azure sendgrid account.Actually I can be able to send the mails in azureVM with my sendgrid credentials and we published the site in azure portal. In azure webapp the same email failed to send with the error as in below :
" Unable to read data from the transport connection:net_io_connectionclosed."
C# code I'm using to send mail:
At first i tried using smtp
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
var mail = new MailMessage();
var smtpServer = new SmtpClient(smtpSection.Network.Host);
mail.From = new MailAddress(smtpSection.Network.UserName);
mail.From = new MailAddress("john@example.com", "John Smith");
mail.To.Add(userId);
mail.Subject = subject;
mail.Body = body;
smtpServer.Port = smtpSection.Network.Port;
smtpServer.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtpServer.EnableSsl = false;
smtpServer.Send(mail);

Web config content:
<network defaultCredentials="true" host="smtp.sendgrid.net" port="25" userName="mysendgriduserid@azure.com" password="mysendgridpassword" />

it failed in azure webapp but works fine in azureVM. Then I tried using sendgrid api below:
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo(userId);
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = subject;
myMessage.Text = body;
var transportWeb = new Web("myapikey");
transportWeb.DeliverAsync(myMessage);

This also failed in azure webapp but works fine in azureVM. Both shows the same error as in image.
I'm completely clueless.Please help me to get rid of this error.
Thanks.
My apologies. I couldn't upload the image. I just share the stack trace in the image:
Server Error in '/' Application.

Unable to read data from the transport connection: net_io_connectionclosed.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[IOException: Unable to read data from the transport connection: net_io_connectionclosed.]
   System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) +1829453
   System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) +227
   System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) +16
   System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response) +54
   System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) +36
   System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) +88
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1661

[SmtpException: Failure sending mail.]
   Dme.Application.Repositories.<Dme-Application-Repositories-IIdentityRepository-SendEmailAsync>d__22.MoveNext() +259
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
   Dme.Application.Services.<Dme-Shared-Contracts-IIdentityService-CreateOrUpdateUserAsync>d__14.MoveNext() +5421
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
   Dme.Web.UI.Areas.Admin.Controllers.<SaveOrUpdate>d__13.MoveNext() +962
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +17
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +50
   System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.114.0

A: That's usually an error from within your own internal network. It's likely that the port you're trying to send through is closed - either by a firewall or your ISP.
Does telnet smtp.sendgrid.net 25 work for you ? Alternately you could try using port 465(SSL) or 587 (TLS/plain connection).

A: I think you might use the API wrongly, e.g pass wrong parameters into function
i created an empty Asp.net MVC app, and able to send email via SendGrid from Azure App Service
Here is the repo: https://github.com/shrimpy/SendGridSample
And below is the code snip from https://github.com/shrimpy/SendGridSample/blob/master/SendGridSample/Controllers/EmailController.cs
namespace SendGridSample.Controllers
{
    public class EmailController : ApiController
    {
        [HttpGet]
        [Route("api/SendMail")]
        public string SendMail(string email, string username, string password)
        {

            // Create the email object first, then add the properties.
            var myMessage = new SendGridMessage();

            // Add the message properties.
            myMessage.From = new MailAddress("hello@hello.com");

            // Add multiple addresses to the To field.
            List<String> recipients = new List<String> { email };

            myMessage.AddTo(recipients);

            myMessage.Subject = "Testing the SendGrid Library";

            //Add Text bodies
            myMessage.Text = "Hello World from " + Environment.MachineName;

            // Create a Web transport, using API Key
            NetworkCredential nc = new NetworkCredential(username, password);
            var transportWeb = new Web("This string is a SendGrid API key", nc, TimeSpan.FromSeconds(15));

            // Send the email.
            transportWeb.DeliverAsync(myMessage);

            return "done";
        }
    }
}

A: If using the SmtpClient class, try setting your Web config to (change defaultCredentials from true to false):
<network defaultCredentials="false" host="smtp.sendgrid.net" port="25" userName="mysendgriduserid@azure.com" password="mysendgridpassword" />

If trying the SendGrid classes trying awaiting the DeliverAsync call
await transportWeb.DeliverAsync(myMessage);


text:
Q: How to keep formatting of entered comments in Drupal? In my site: http://www.indiacustomercare.com which Drupal 6 and I've set default format as "Full HTML".
Now people are sometimes entering long comments and when published, all newlines get removed and multiple paragraphs coalesce to become single para.
So what I'm doing is to copy it and paste the comment in design view in Dreamweaver. This inserts  br element, as entered by the user.
Is there any way this could be handled automatically in Drupal?

A: "Full HTML" is "Full HTML". It doesn't have the "Line break converter" input format filter turned on because that would be incorrect behaviour. If you want automatic line breaking, I recommend that you create a new input format and give it the filters that you want - including Line break converter.


text:
Q: Local Source control repository - cross platform I am looking for a 'local' source control software, I don't need it to be necessarily available on network.. Its meant to be only for personal use..
What I am looking for is something like:
Need it to be cross platform. The biggest problem is, I need the same local repository to be available on both windows and Linux! (Is this even possible? :s ) I dual boot Windows 7 and Ubuntu and have managed to setup workspace that works in both OS without changes, now I need a source control software!
Easy installation, I have never installed one before! :)
And Has eclipse plugin..
I have used VSS for this purpose before, but that is only on Windows!
I looked for Mercurial, but I am not sure if I can use the same repository on both the OS!
Any suggestions are appreciated!
UPDATE: Thanks for your replies.. Yes I do want the same repository to be accessed from different operating systems.. Everyone has suggested an on-line repository but I 'need it to be local'.. Internet is not something I can depend on (I now know git takes care of this..! :)), I would not want version of, say my personal recordings of some home functions tweaked in audacity, to be hosted on-line! Right now, I am trying out git, as a local repository solution..

A: I'm pretty sure you can Mercurial, since the whole repository is in .hg folder.
 Try TortoiseHG - it's easy to install and use.

A: If you definitely want a repository that's always available on a local filesystem, I'd probably go for Mercurial or Git.  Most likely Mercurial, as it has the best windows support (including the TortoiseHg gui), but Git works similarly.
But there's two other issues:

*

*Do you make frequent backups?

*What file system type will you use for the shared repository?

In this particular case, I would not trust a single shared filesystem as the best basket to put your eggs in; In each boot environment, I would maintain working repositories separate from the shared one.  This would give you some redundancy.
Here's how this would work:
Two repositories U and W, for Ubuntu and Windows respectively, and one shared repository S, accessable frome either boot environment.
Assuming a stable situation, with all three repositories in sync:

*

*Commit any new code to repository U in Ubuntu.
$ hg commit -m 'changes from linux'

*Push the changes to S.
$ hg push

*Reboot into windows.
...

*Pull the latest changesets from S into W
W> hg fetch

*Update your code, commit frequently

*Push prior to rebooting into linux
W> hg push

*Reboot

*And repeat step 4, but now from linux
$ hg fetch       # performs an hg pull, followed by an update.

*Rinse, lather, repeat.
That's said, with both Mercurial and Git, you can synchronise your repositories across the net any time, so I would surely recommend you try that out some time.
And note: the best backup is having a copy of your data on a live file system on another computer, preferably at another location.

A: Why do you want it to be local? The benefit of source control, is that you can have multiple clients working on the same source, without worrying too much about conflicts etc.
Even though it doesn't really answer your question, this advices might solve your problem:
Just create a project for yourself at https://github.com/ or http://sourceforge.net/ any other free online repository hosting provider. SVN, CVS, GIT all come with excellent IDE integration and clients run on almost all operating systems.
Hope this helps. Regards.

A: Do you really want to have a duplicate repository on different operating systems?  That doesn't make sense to me. What would be the purpose of doing that?
I think you instead want to have a single repository that you can access from any operating system.
In this case, you can just install Subversion (or whatever source control system you prefer) on a server and access it from the operating systems you use.  There are plenty of client tools for Mac/Windows/Linux that can talk to subversion repositories, RapidSVN being free and cross-platform for one.
If you don't have your own server, there are plenty of places online that will host Subversion for you.


text:
Q: ASP.Net (3.5) MVC partial class for rule validation I have  2 projects. A data project, which contains my database and my Entity Framework model. I have table called 'User', and then have a generated EF class for user.
I am trying to add a partial class:
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;

namespace Data
{
    public partial class user
    {

        public bool isValid
        {
            get {
                return (GetRuleViolations().Count()==0);
            }
        }

        public IEnumerable<RuleViolation> GetRuleViolations()
        {
            yield break;
        }

        partialvoid OnValidate(ChangeAction action)
        {
            if (isValid)
                throw new ApplicationException("Rule violation prevents saving");
        }
    }

    public class RuleViolation
    {
        public string ErrorMessage { get; private set; }
        public string PropertyName { get; private set; }

        public RuleViolation (string errorMessage)
        {
            ErrorMessage = errorMessage;
        }

        public RuleViolation(string errorMessage, string propertyName)
        {
            ErrorMessage = errorMessage;
            PropertyName = propertyName;
        }
    }
}

This is following the MVC 1.0 NerdDinner example. However, I am getting a design time error on the OnValidate method:
    partial void OnValidate(ChangeAction action)
    {
        if (isValid)
            throw new ApplicationException("Rule violation prevents saving");
    }

No definining declaration found for implimenting declaration of partial method 'void OnValidate(ChangeAction action)'
What am I doing wrong?

A: There should be another file containing the rest of the user class.
In this file you have to declare that there might be a partial method called OnValidate.
public partial class user
{
    partial void OnValidate(ChangeAction action);
}

Some detail:
A partial method needs to have a signature specified somewhere.  Once the signature has been defined then an optional implementation can be specified.  Read http://msdn.microsoft.com/en-us/library/wa80x488.aspx for more information.


text:
Q: Security Center won't start after a malware attack Today, I got a virus/malware on my computer.  I first scan with my antivirus/malwarebytes/superantispyware to clean it.  I ended up cleaning all of it. No more ads pop up.
However, my security center service is disabled. I went into services, security center was disabled i enabled it and restarted computer it is now disabled again so i enabled it again an was able to turn security centre back on but after a minute or 2 it turns its self back off...
What can I do?  I tried sfc/scannow as well, but not finding any errors.
FYI, I'm running Windows 7 Pro SP1.
Please help

A: There is a high likelihood you still have traces on your system.
I would try using Kaspersky's TDSSKiller (free download) and run it in safe mode.
http://support.kaspersky.com/faq/?qid=208283363
I would look at the windows error logs to see if there is any error messages regarding the the security center service or service dependencies that are not behaving.
Right click on Computer>Manage> Expand "Event Viewer" > Select "System" and examine the error messages. That might help you get to the bottom of the issue.
BlackViper has a .reg file that will reset all your services to their default start states:
http://www.blackviper.com/Windows_7/registry.htm (scroll down the page a bit)
Lets start there for now, if nothing works... I have a few more steps.

A: Now that you are hopefully clean, I would do a system restore to a time before you became infected. That will not affect any documents you have, but will turn back the time on your registry, which was probably affected by the virus, and allow the service to start again.


text:
Q: How to print any variable value in xsl. bcoz we can not debug the xsl <xsl:if test="efile_format = 'PDF' or efile_format = 'Docume`efile_format = 'PDF' or efile_format = 'Document' ">

I want to check efile_format's value. because its always getting failed when I am trying to work but tried following if condition only for viewing that if the condition is affecting or not so that's affecting
<xsl:if test="1">

A: I am assuming you are missing second or condition :
<xsl:if test="efile_format = 'PDF' or efile_format = 'Docume`efile_format = 'PDF' or efile_format = 'Document' ">

Corrected syntex may be like one of these:
<xsl:if test="efile_format = 'PDF' or efile_format = 'Docume' or efile_format = 'PDF' or efile_format = 'Document' ">

OR
<xsl:if test="efile_format[(. = 'PDF') or (. = 'Document')]">

OR
<xsl:if test="efile_format=('PDF','Document')">


text:
Q: I guess this way of saying is old fashioned, wrong? This is a line of one of the Sherlock Holmes' stories and I guess the bold part would be old fashioned. May I check with you, please?

I could not help laughing at the ease with which he explained his process of deduction. "When I hear you give your reasons," I remarked, "the thing always appears to me to be so ridiculously simple that I could easily do it myself, though at each successive instance of your reasoning I am baffled until you explain your process. And yet I believe that my eyes are as good as yours."

Today, it would be, I guess,

the thing always appears me so ridiculously simple

Am I wrong?
Thank you.


text:
Q: Spoof IP address in Python There is a certain data API which I need to call to fetch some data. Imagine there are few million such records. For each such record, I construct the data URL (that returns a JSON response) from the record id and API key, fetch the response and put it to my local database. Now if I do it on my Mac, even with a 16 GB RAM, this will take months. Whereas if I try it on a 64 GB multicore EC2 desktop provided by AWS, it works lightning fast..except there is a problem.
There is a rate limit on the number of queries the API server can answer. If it goes beyond 40 any minute, it starts returning error messages in place of the JSON response. And on the EC2 machine, it ends up going upto 600 requests per minute. If it works correctly, I will have all the data in 2-3 hours. The funny thing is that the rate limit is imposed by IP, not by API key. So if I can somehow spoof the IP address (say from a list of 15 IPs in a round-robin manner) for the requests, it will stay within the limits. How do I do it? I am using urllib. Here's my sample code:
url = urltemplate % (list_of_params_including_API_key)
data = json.load(urllib.urlopen(url))
//parse the data and load it into database

A: Use the socket.bind method to specify the source address of the network connection.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind socket to a particular IP. port 0 allows it to select an unused local port
s.bind((spoofed_ip, 0))
s.connect((server_ip, 80))


text:
Q: Resources check hey I am frequently uploading my XCode iPhone projects to an svn repository to be build on another machine.
My problem is that when I add resources to my project sometimes I forget to add the resource as relative to the project.
I know one answer is to be more careful (not easy when your tired!) but if there was a way to run a script to check my resource paths are relative when I build and warn me if they are not it would be a great time saver for me.
How would I go about doing this?
Thanks
Chris

A: You can select all the files in your project and set the Path Type for all of them in one go. While this isn't a script this does save a lot of time over doing the files individually
I think the best approach to script this would be to look in the .xcodeproj file - the file paths are listed in there. If your project is called MyProject you need to open (either by using Show Package Contents in Finder or just the usual cd in Terminal) the MyProject.xcodeproj directory.
In here you'll find a file called project.pbxproj - open this in a editor that won't mess up your formatting and have a peek around the file. If you search for one of your files in the project you should be able to see how Xcode stores references to the project files.
Look for a section named /* Begin PBXFileReference section */. In here all your files are listed, along with where they are relative to the project, e.g.:
... path = Classes/MyClass.h; sourceTree = SOURCE_ROOT

If you can parse this file you should be able to acheive what you want - but remember to back up the file, otherwise you might corrupt your project.

A: How would it be if you instead write a script that asks the SCM if anything in the project is not committed?  For example, think of this scenario
Project Root

  Codex

    Project.xcodeproj
    …

  Design

    anImage.png

where anImage.png being outside of Codex, where the Xcode project sits (its path starts with a ../).  A strong .pbxproj parser would have to support all the variants in which Xcode references files to know exactly if there are stray files.
OTOH, the SCM knows where everything is all the time (you mentioned up-ping to a SVN server), so why not ask it instead.

*

*We have a Ruby script that prints a warning in Xcode's Build Log if anything in the project is not committed.


text:
Q: running 'msfconsole' command it throws error In termux while  "Could not find activerecord-6.1.4.7 in any of the sources", I tried running 'gem install activerecord' but still after installing this gem, it shows again same error. Plz help me!!

A: Delete the metasploit version already installed and install the official version of Metasploit from the official website according to the given procedure!
Metasploit Website :- Metasploit.com

And if this does not solve your problem then type these commands in terminal :-
sudo su
apt-get update
apt-get upgrade

After it's done again install the metasploit framework.
I hope this will solve your error.


text:
Q: Collection does not display on ListView I am creating an app in android that takes a data collection and displays the collection to a list view. I completed the code but nothing is displayed in the view. Here is the code:
public class Activity extends ListActivity {

protected  ArrayList<HashMap<String,String>> gameCollection = new ArrayList<HashMap<String, String>>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Populate view with data
    gameCollection.add(displayVideoGame("PlayStation","FIFA 14"));
    gameCollection.add(displayVideoGame("PlayStation","Thief"));
    gameCollection.add(displayVideoGame("PlayStation","Watch Dogs"));
    gameCollection.add(displayVideoGame("PlayStation","Battlefield 4"));
    gameCollection.add(displayVideoGame("PlayStation","Second Sun"));
    gameCollection.add(displayVideoGame("PlayStation","Mario Brothers"));
    gameCollection.add(displayVideoGame("PlayStation","Don't Starve"));
    gameCollection.add(displayVideoGame("PlayStation","Elder Scrolls Online Beta"));

    //Calling the Simple Adapter calling gameCollection List and setting the predefined layout
    SimpleAdapter adapter = new SimpleAdapter(this,this.gameCollection,android.R.layout.simple_list_item_1, new String[] {"Playstation"},new int[] {android.R.id.text1});
    //set adapter to collection
    setListAdapter(adapter);
}

//Create Private Method - Returns HashMap with key-value pairs
private HashMap<String, String> displayVideoGame(String key, String value)
{
    HashMap<String, String> videoGameHashMap = new HashMap<String, String>();
    videoGameHashMap.put(key,  value);
    return videoGameHashMap;

}


text:
Q: Newbie python script, odometry I was doing one online course where on page was special frame to run python script.
My task in this exercise was to compute the odometry, velocities are given.
This script on page looks: http://snag.gy/NTJGz.jpg
Now I would like to do the same using ROS:
there is nearly the same exercise but in ROS:
clear code looks: https://github.com/tum-vision/autonavx_ardrone/blob/master/ardrone_python/src/example1_odometry.py
There is information that I should add code from this online_course version to function callback, I try, but it doesn't work.
My code:
#!/usr/bin/env python

#ROS
import rospy
import roslib; roslib.load_manifest('ardrone_python')
from ardrone_autonomy.msg import Navdata
import numpy as np

def __init__(self):
    self.position = np.array([[0], [0]])

def rotation_to_world(self, yaw):
        from math import cos, sin
        return np.array([[cos(yaw), -sin(yaw)], [sin(yaw), cos(yaw)]])

def callback(self, t, dt, navdata):
        self.position = self.position + dt * np.dot(self.rotation_to_world(navdata.rotZ), np.array([[navdata.vx], [navdata.vy]]))
        print("received odometry message: vx=%f vy=%f z=%f yaw=%f"%(navdata.vx,navdata.vy,navdata.altd,navdata.rotZ))
        print(self.position)

if __name__ == '__main__':
    rospy.init_node('example_node', anonymous=True)

    # subscribe to navdata (receive from quadrotor)
    rospy.Subscriber("/ardrone/navdata", Navdata, callback(self, t, dt, navdata))

    rospy.spin()

Please correct me, I am totally newbie to python.
Now i got message:

Traceback (most recent call last):   File "./example1_odometry.py",
  line 28, in
      rospy.Subscriber("/ardrone/navdata", Navdata, callback(self, t, dt, navdata)) NameError: name 'self' is not defined

A: Just ommit the "self" argument, it is not needed. Try the next line:
rospy.Subscriber("/ardrone/navdata", Navdata, callback(t, dt, navdata))

The error you got is because self is a class member field (similar to the this pointer in java or c++), therefore it makes no sense to address it in your main function.

A: The direct error you posted:
Traceback (most recent call last): File "./example1_odometry.py", line 28, in rospy.Subscriber("/ardrone/navdata", Navdata, callback(self, t, dt, navdata)) NameError: name 'self' is not defined

is because in the line:
 rospy.Subscriber("/ardrone/navdata", Navdata, callback(self, t, dt, navdata))

self is undefined. You might mean rospy ?


text:
Q: Passing header parameters while loading Video in VideoJs I am trying to load a video into VideoJS player in a react project. The Video is returned from a web service taking specific token that authenticate the user.
Let's say the video is returned from the below API call:

localhost:8080/video/1/

In order to play this video, the user should be authenticated. In other words, the API takes the below header to return a successful result:

auth: token

My VideoJs player is built in a React component as below:

import React from 'react'
import videojs from 'video.js'

export default class VideoComponent extends React.Component {

  componentDidMount () {
      this.videoJsOptions = {
        sources: [{
           src: 'http://localhost:8080/video/1/',
          type: 'video/mp4',
        }],
      }
      let player = videojs(this.videoNode, this.videoJsOptions, function onPlayerReady() {
        console.log('onPlayerReady', this)
      })

      this.player = player
  }
  render () {
      return (
            <div data-vjs-player>
              <video ref={node => this.videoNode = node} className="video-js"></video>
            </div>
      )
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

How is it possible to let my video component take the token of the calling URL and pass it the request header?

A: I would put this component as a child of another component whose sole responsibility is to make the API call and render the VideoComponent if the user is authorized. Something along these lines.
You'll probably want some type of redirect or error message feedback to the user if they are not authorized. I did not incorporate that in my code snippet.
export default class VideoAuth extends React.Component {
    state = {
        isAuthorized: false
    }

    async componentDidMount() {
        const authRequest = await someAuthRequest()
        if (authRequest.ok) {// or however the data structure looks like
            this.setState({ isAuthenticated: true })
        }
    }

    render() {
        return this.state.isAuthenticated ? <VideoComponent /> : <div> Authorizing... </div>
    }
}


text:
Q: Batch Gradient descent algorithm showing 'int' not iterable error lr = 0.1
n_iterations = 1000
m = 5

theta = np.array([[1000],[989],[123],[3455]])

for iterations in n_iterations:
    gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
    theta = theta - lr * gradients

theta

After executing the code it says an error 'int' is not iterable.
More data:
X_b = np.asanyarray(df[['area', 'bedrooms', 'age']])

from a csv file
and Im using the three params(area,bedrooms,age) to predict the price i.e y
Please help me in that error

A: n_iterations is an int, which is not iterable like the error says. I think you want to loop n_iterations times.
Try range for that like this:
lr = 0.1
n_iterations = 1000
m = 5

theta = np.array([[1000],[989],[123],[3455]])

for iterations in range(n_iterations):
    gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
    theta = theta - lr * gradients

theta

A: You are using for iterations in n_iterations: where n_iterations is an integer value that shouldn't iterate. You can use range to overcome it
for iterations in range(n_iterations):


text:
Q: How to fix jQuery SlideToggle Animation hitch? I am trying to create a FAQ page and I want the question block to slide down on click. Although I have achieved what I wanted, when it slides back up, the animation has some sort of a hitch which is very obvious and annoying as the title of the second block snaps up towards the title of the first one.
I have searched all across stackoverflow for this topic, but despite having checked out many questions and their answers but not a single one worked for my case.
I have a made demo for you here.
HTML:

FAQ

Questions:

Questions:

jQuery:
// Show category on click
$(".eye-show-hide").on("click", function() {
    // Toggle eye icon and make the others default
    $(this).toggleClass("fa-eye fa-eye-slash");
    $(this).parent().siblings("h4").children().removeClass("fa-eye-slash").addClass("fa-eye");

    // Toggle category and close the others
    $(this).parent().next().slideToggle(500).css("display", "inline-block");
    $(this).parent().next().siblings(".questions").slideUp(500);
});

// Show answer on question click
$(".questions ol li p").on("click", function() {
    $(this).parent().next().slideToggle(500).css("display", "block");
    $(this).parent().next().siblings("p").slideUp(500);
});

A: slideToggle is animate by mathematical way, it'll control the element's height, padding, margin ... so it's difficult to maintian if your DOM tree is complex, sometimes will cause this problem(like forget to reset default margin or padding).
If you don't want to see that snap problem.
you need to use element to wrap it and set a min-height on it.
It just a dirty hack to prevent the animating element don't influence other element. There may be some padding or margin in these complex structure cause this problem. (on the animating element, its child or somewhere)
like this:
https://jsfiddle.net/9r5akuxt/8/
It'll be great by using css3 transform to animate it.

A: Is there a reason you add .css("display", "inline-block") after the call to slideToggle? I think this is what causes the hitch you're talking about.
See this fiddle: https://jsfiddle.net/9r5akuxt/7/


text:
Q: Htaccess redirect all requests to index (does not allow images) Wamp Server Please I need a help. I am working on a site and wants to redirect all requests to an index file while allowing access to images, css, javascripts and other documents that are not php scripts. I am working on a local server (WAMP). The problem I have is that it redirects all requests to the index file including images. Below is my htaccess rule.
<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /myapp
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\d{4})/(0?[1-9]|1[0-2])/([^/]+)/?$ app/$1-$2/$3 [R=301,L]
RewriteRule ^(.*)$ index.php [L]
</IfModule>

A: Is this not what you're aiming for?
RewriteRule ^(.*\.php)$ index.php [L]

You should also escape those slashes in your first rewrite rule

A: Thanks I have figured it out, I just modified the moved the first rewrite rule above the rewrite condition and it now working fine.
<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /myapp
RewriteRule ^(\d{4})/(0?[1-9]|1[0-2])/([^/]+)/?$ app/$1-$2/$3 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [L]
</IfModule>


text:
Q: How to determine number of occurences of a subtext in a text in Excel? As mentioned above, I would like to ask for help in writing a formula in Excel that would allow me to count all the specific String occurrences in a bigger String.
Let me show You exactly what do I mean by that:

I have a rather small database of products (around 150 different items), but their names are generally similar and because of that some words may repeat often and may be misleading when treated one-by-one.
I tried to fix the issue with MATCH and INDEX functions, but to be honest didn't really get the gist of them ...

A: Using TEXTJOIN:
=TEXTJOIN(" ",,INDEX(B:B,MATCH(FILTERXML(""&SUBSTITUTE(F2,CHAR(10),"")&"","//b"),A:A,0)))

Depending on ones version this is an array formula and may need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


text:
Q: I am using generalised mixed effects models family = binomial to determine difference between disturbed and undistubed substrate I am using a GLMM model to determine differences in soil compaction across 3 locations and 2 seasons in undisturbed and disturbed sites. I used location and seas as random effects. My teacher says to use the compaction reading divided by its upper bound as the Y value against the different sites (fixed effect). (I was previously using disturbed and undisturbed sites as 1,0 as Y against the compaction reading - so the opposite way around.) The random variables are minimal. I was using both glmer (glmer to determine AIC and therefore best model fit (but this cannot be done in glmmPQL)) while glmmPQL provides all amounts of variation which glmer does not. So while these outcomes are very similar when using disturbed and undisturbed as Y (as well as matching the graphs) only glmmPQL is similar to the graphs when using proportion of compaction reading. glmer using proportions is totally different. Additionally my teacher says I need to validate my model choice with a chi-squared value and if over-dispersed use a quasi binomial. But I cannot find any way to do this in glmmPQL and with glmer showing strange results using proportions as Y I am unsure if this is correct. I also cannot use quasi binomial in either glmer or glmmPQL.
My response was the compaction reading which is measured from 0 to 6 (kg per cm squared) inclusive. The explanatory variable was Type (diff soil either disturbed and not disturbed = 4 categories because some were artificially disturbed to pull out differences). All compaction readings were divided by 6 to make them a proportion and so a continuous variable bounded by 0 and 1 but  containing values of both 0 and 1. (I also tried the reverse and coded disturbed as 1 and undisturbed as 0 and compared these groups separately across all Types (due to 4 Types) and left compaction readings as original). Using  glmer with code:
model1 <- glmer(comp/6 ~ Type  +(1|Loc/Seas), data=mydata,
              family = "binomial")
model2 <- glmer(comp/6~Type +(1|Loc) , data=mydata, family="binomial")

and using glmmPQL:
mod1 <-glmmPQL(comp/6~Type, random=~1|Loc, family = binomial, data=mydata)
mod2 <- glmmPQL(comp/6~Type, random=~1|Loc/Seas, family = binomial, data=mydata)

I could compare models in glmer but not in glmmPQL but the latter gave me the variance for all random effects plus residual variance whereas glmer did not provide the residual variance (so was left wondering what was the total amount and what proportion were these random effects responsible for)
When I used glmer this way, the results were completely different to glmmPQL as in no there was no sig difference at all in glmer but very much a sig diff in glmmPQL. (However if I do the reverse and code by disturbed and undisturbed these do provide similar results between glmer and glmmPQL and what is  suggested by the graphs - but my supervisor said this is not strictly correct (eg: mod3 <- glmmPQL(Status~compaction, random=~1|Loc/Seas, family = binomial, data=mydata) where Status is 1 or 0 according to disturbed or undisturbed)  plus my supervisor would like me to provide a chi squared goodness of fit for the model chosen - so can only use glmer here ?). Additionally, the random effects variance is minimal, and glmer model choice removes these as non significant (although keeping one in provides a smaller AIC). Removing them (as suggested by the chi-squared test (but not AIC) and running as only a glm is consistent to both results from glmmPQL and what is observed on the graph. Sorry if this seems very pedantic, but I am trying to do what is correct for my supervisor and  for the species I am researching. I know there are differences.. they are seen, observed, eyeballing the data suggests so and so do the graphs.. Maybe I should just run the glm ? Thank you for answering me. I will find some output to post.


text:
Q: Servlet forward to jsp I have a servlet "ShowEvents", and I am trying to redirect to a jsp page "EventsOfClub.jsp" that is in WebContent folder. I am using Eclipse. But when I do the forward, nothing happens. I know this is a common mistake, but I browsed a lot of questions here and couldn't find the correct resource path (which I think is the problem). Please help.
ShowEvents:
request.getRequestDispatcher("EventsOfClub.jsp").forward(request, response);

EDIT: When the user logs in, I redirect (not forward) to ShowEvents servlet as:
response.sendRedirect("ShowEvents");

And then forward from ShowEvents to "EventsOfClub.jsp" as I said earlier. I thought the problem was I wasn't forwarding. But now when I forward from Login to ShowEvents as
request.getRequestDispatcher("ShowEvents").forward(request, response);

I am getting the same problem, that is, it stays at Login and displays a blank page. (Before, ShowEvents was showing a blank page)
EDIT:
Stack trace:
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.jsp.EventsOfClub_jsp._jspService(EventsOfClub_jsp.java:116)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at ShowEvents.doPost(ShowEvents.java:82)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at Login.doPost(Login.java:88)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Login servlet
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Login
 */
@WebServlet(description = "Enter credentials", urlPatterns = { "/Login" })
public class Login extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login()
    {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {   }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    //POST "localhost:8080/login"
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String name = (String) request.getParameter("username");
        String pass = (String) request.getParameter("password");

        Connection conn = null;
        String p="";

        try
        {
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://localhost:6666/Festeria", "postgres", "darthvedarvyas");

            HttpSession session = request.getSession();
            session.setAttribute("connection", conn);
            session.setAttribute("uname", name);

            Statement stmt = null;
            stmt = conn.createStatement();

                    //some DB code

            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(redirect);
            dispatcher.forward(request,response);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            String msg = "Oops! An error has occured!
 Please try again.";
            request.getSession().setAttribute("msg", msg);
            response.sendRedirect("Error.jsp");
        }
    }
}

A: Hej Darth Vedar,
i made a very simple demo for you:
Here is the Servlet
package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EventsOfClubServlet
 */
@WebServlet(name = "events", urlPatterns = { "/events" })
public class EventsOfClubServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public EventsOfClubServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        request.getRequestDispatcher("EventsOfClub.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

}

Login Servlet
package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "login", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        if((userName != null && userName.equalsIgnoreCase("demo")) && (password != null && password.equalsIgnoreCase("123456"))) {
            response.sendRedirect("events");
        } else {
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

}

Login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

    <form action="login" method="post">
        Username:
        <input type="text" name="username"/>

        Password:
        <input type="text" name="password"/>

        <input type="submit" value="Login">

    </form>

The JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

EventsOfClub.jsp

A: Try this code snippet,
class ShowEvents{
      //----
      doGet(HttpServletRequest request, HttpServletResponse response){
      doPost(request, response);
      }

      doPost(HttpServletRequest request, HttpServletResponse response){
      request.getRequestDispatcher(request.getContextPath()+"/EventsOfClub.jsp")
                                      .forward(request, response);
      }

}


text:
Q: How to modify local group policy and local security policy programatically? What I need to do is to modify local group policy and local security policy on different machine.It is very inconvenient to modify them each item, so I want to find out any way that can modify them through programming.
I have tried the way in this website,but it didn't work.
What I need to modify are shown as below:
1.Launch the Local/Group Policy Editor.

*

*Disable Windows update option at shutdown
Go to Computer Configuration -> Administrative Templates -> Windows Components -> Windows Updates, and double click on Windows Updates.
set "Do not display 'Install Updates and Shut Down'" to Enable.

*Set "Display Shutdown Event Tracker" in Group Policy Editor to Disabled.
Computer Configuration->Administrative Templates->System. Set "Display Shutdown Event Tracker" to Disabled.

*Computer Configuration->Windows Settings->Security Settings->Local Policies->Security Options.
Set the group policy option "Shutdown: Allow system to be shut down without having to log on" to Disabled.
2.Launch the Local Security Policy(run secpol.msc).

*

*Security Settings->Local Policies->Security Options.
Set the "Interactive logon: Do not display last username" option to Enabled.

*Security Settings->Local Policies->User Rights Assignment.
Add the user Administrator to "Deny logon through terminal services".

*Security Settings->Account Policies > Password Policy
Set the "Password must meet complexity requirements"
By the way, the windows operation is Windows server 2008r2 and windows server 2012r2.

A: PowerShell offers cmdlets to administer Group Policy. However, you normally don't need to modify local group policies on each machine. Just create a GPO and link it to the required computers.

A: There are very few things you can do programatically with settings in Group Policy. Administrative template settings, or any 'registry' data is within reach with the PowerShell cmdlets provided for set-gpregistryvalue and set-gpprefregistryvalue. You can reverse engineer the storage of each policy area and the general GP storage of each area but that is a bit of a chore unless you are an ISV looking to build tools. There is currently only 1 real interface available to read and write settings to GPOs. (full disclosure I am with the company that provides the solution). Google 'Group Policy Automation' and you will find it.
On another note, managing local policy is still a very important task for many reasons. Non domain joined systems, isolated systems, compliance between domain joined and non-domina joined boxes... lots of scenarios where this is important and necessary. Not to mention Windows Nano server.
so, I guess it depends on how deep you need to go or what your task is. If you are looking to build commercial solutions built on Group Policy start at MDSN (https://msdn.microsoft.com/en-us/library/windows/desktop/aa374177(v=vs.85).aspx). If you are looking for something simpler but third party let me know. If you are looking to manage just registry data look into the PowerShell cmdlets.


text:
Q: How to get result from TSQL to JavaSCript using old classic ASP page? We have a classic ASP page which has the below vbscript.
1) invoiceResult is a VB Array
2) invoiceSql: stored proc on SQL server
3) ricoh is company library which I cannot change (no access)
invoiceResult = ricoh.storedproc(invoiceSql)

Question: I need a javascript array instead of vb6. It does not matter how I get it. Can I somehow transform a vb6 array to a javascript array?
Or can I use Ajax to get SQL data from classic ASP?

A: You can access VBScript code from JavaScript. Somethin like this might work:
<SCRIPT LANGUAGE="VBSCRIPT">
 Function makeArrayVB()
   ' Creates a VBScript array
   dim anArray(1,1)
   anArray(0,0) = "0,0"
   anArray(0,1) = "0,1"
   anArray(1,0) = "1,0"
   anArray(1,1) = "1,1"
   makeArrayVB = anArray
 End Function

 <SCRIPT LANGUAGE="JavaScript">
 // Accesses a VBScript array within a JScript script
 function getVBArray()
 {
   var arrayObj;
   var jsArray;
   arrayObj = makeArrayVB();
   jsArray = VBArray(arrayObj).toArray();
   alert("VBScript array length = " + jsArray.length);
   // Displays the contents of the array
   for(i=1;i<=jsArray.length;i++)
   {
     alert(jsArray[i-1]);
   }
 }
 </SCRIPT>


text:
Q: javascript mileage calculation I am working on a mileage application where I will need to summarize the miles driven by day and employee. I also need to determine the first trip taken each day by each employee. Here is the sample array that includes the date, employee, miles driven, and beginning odometer reading:
var records = [
    ["2019-08-26", emp1, 110, 45878],
    ["2019-08-26", emp2, 79, 21561],
    ["2019-09-02", emp1, 111, 46900],
    ["2019-09-02", emp2, 59, 21789],
    ["2019-09-02", emp3, 22, 95781],
    ["2019-09-05", emp3, 26, 95835],
    ["2019-09-02", emp1, 12, 46971],
    ["2019-09-05", emp3, 50, 95895],
    ["2019-09-02", emp2, 49, 21812],
    ["2019-09-05", emp1, 69, 47011],
    ["2019-09-02", emp1, 42, 46950],
    ["2019-09-05", emp3, 21, 95911],
    ["2019-09-02", emp2, 101, 22017],
    ["2019-09-05", emp3, 78, 96001],
    ["2019-09-02", emp3, 35, 95421],
    ["2019-09-05", emp1, 47, 47065]
]

I am trying to create an object with the following output.
[
  {date: "2019-08-26", employee: emp1, miles: 111, firstTrip: 110},
  {date: "2019-08-26", employee: emp2, miles: 79, firstTrip: 79},
  {date: "2019-09-02", employee: emp1, miles: 65, firstTrip: 111},
  {date: "2019-09-02", employee: emp2, miles: 209, firstTrip: 59},
  {date: "2019-09-02", employee: emp3, miles: 57, firstTrip: 35},

etc

]

However, I can't seem to figure out how to identify the first distance traveled by analyzing the lowest odometer reading each day for each employee. Here is the using the reduce function that @Macarthurval helped me out with for everything but the "firstTrip":
var summary = records.reduce( function(total,record){
    var index = -1;
    total.forEach( function(s,i){
        if( s.date == record[0] && s.employee == record[1] ) index = i;
    });
    if( index == -1 ){
        total.push( {date: record[0], employee: record[1], miles: record[2]} );
    }else{
        total[ index ].miles += record[2];
        total[ index ].firstTrip = record[3];
    }
    return total;
},[]);

A: You could take a hash table and a combined key from date and employee and generate a new object of not exists and update miles.
At the end get the values from the object as result set.

var records = [['2019-08-26', 'emp1', 110, 45878], ['2019-08-26', 'emp2', 79, 21561], ['2019-09-02', 'emp1', 111, 46900], ['2019-09-02', 'emp2', 59, 21789], ['2019-09-02', 'emp3', 22, 95781], ['2019-09-05', 'emp3', 26, 95835], ['2019-09-02', 'emp1', 12, 46971], ['2019-09-05', 'emp3', 50, 95895], ['2019-09-02', 'emp2', 49, 21812], ['2019-09-05', 'emp1', 69, 47011], ['2019-09-02', 'emp1', 42, 46950], ['2019-09-05', 'emp3', 21, 95911], ['2019-09-02', 'emp2', 101, 22017], ['2019-09-05', 'emp3', 78, 96001], ['2019-09-02', 'emp3', 35, 95421], ['2019-09-05', 'emp1', 47, 47065]],
    temp = records.reduce(function (r, data) {
        var key = data[0] + '|' + data[1];
        r[key] = r[key] || { payload: { date: data[0], employee: data[1], miles: 0, firstTrip: data[2] }, odo: data[3] };
        r[key].payload.miles += data[2];
        if (data[3] < r[key].odo) {
            r[key].payload.firstTrip = data[2];
            r[key].odo = data[3];
        }
        return r;
    }, {}),
    result = Object.keys(temp).map(function (key) { return temp[key].payload; })

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: AVR photocell not working with Arduino UNO I was following a tutorial I found to get a photocell to light an LED as a first step to building a morse coder/decoder. I only have an arduino UNO available instead of the ATmega328P chip itself to work with. I have connected the photocell to pinout A0 and the LED to pinout D~9 on the UNO. I tried to rewrite the code to be used for my current setup but It comes up with three errors and four warnings that I can not figure out how to solve. Any help or advice would be greatly appreciated. I'm using Atmel Studio 7 Gcc C.
#ifndef F_CPU
#define F_CPU 16000000UL
#endif

#include <avr/io.h>
#include <util/delay.h>

#define PHOTO1 0 //sets photocell to PORTC pinout A0
#define LED1 9 //sets LED to PORTB pinout 9

void init_ports_mcu()
{
    DDRB = 0xFFu;  //set all pins at PORTB as output
    PORTB = 0x00u; // sets pins at PORTB as low - LED off

    DDRC = 0xFFu; //sets all pins at PORTC as output
    DDRC &= ~(1<<0); //Makes first pin at PORTC input
    PORTC = 0x00u; //sets all pins at PORTC as low-turning off Photocell
}

int map(int x, int in_min, int in_max, int out_min, int out_max)
{
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void ADC_init()
{
    //Enable ADC sampling freq to set prescaler to max value
    ADCSRA |= (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
    ADMUX = (1<<REFS0); //select required channel passed as input
}

uint16_t get_lightLevel()
{
    _delay_ms 10; //wait for line in channel to get selected
    ADCSRA |= (1<<ADSC); //start ADC conversion

    while (ADCSRA & (1<<ADSC)); //wait for conversion to complete

    _delay_ms 10;
    return (ADC);

}

int main(void)
{
    init_ports_mcu(); //setup microcontroller i/o ports
    ADC_init(); //initialize ADC

    while (1)
    {
        switch(map(get_lightLevel(), 0, 1023, 0, 3)){ //read and map ADC values
            case 0: //high light intensifies - LED is off
                PORTB &= ~(1<<LED1);
                PORTC &= ~(1<<PHOTO1);
            break;
            case 1: //middle light intensifies - LED is on
                PORTB = (1<<LED1);
                PORTC &= ~(1<<PHOTO1);
            break;
            case 2: //low light intensifies - LED is on
                PORTB = (1<<LED1);
                PORTC = (1<<PHOTO1);
            break;

        }
    }
    return (0);
}

Errors:
Recipe for target 'main.o' failed - Line 76
expected ';' before numeric constant - Line 44
expected ';' before numeric constant - Line 49

Warnings:
Statement with no effect [wunused values] - Line 44
Statement with no effect [wunused values] - Line 49
Larger integer implicitly turnicated to unsigned type [wover flow] - Line 69
Larger integer implicitly turnicated to unsigned type [wover flow] - Line 73

A: The formatting of your delays is incorrect.  According to util/delay.h (Convenience functions for busy-wait delay loops) here, two functions are available:
void    _delay_ms (double __ms)
void    _delay_us (double __us)

You should treat these as function calls, so you need to write:
_delay_ms(10);


text:
Q: Node Q - handle array with Q I have an  array of elements var arr = [1, 2, 3, 4, 5, 6, 7, 8]. What I want is to take every element, do some stuff, and take the other. I don't want the stuff to be done in parallel.
for example:
arr.forEach(function(d){
   //send 'd' through HTTP
   //if send is success wait 1000 resend the same.
});

How can I do this with Q ?

A: To turn an array of items into a sequentially processed array of promises, you can use reduce.
var Q = require('q');

var arr = [1, 2, 3, 4, 5, 6, 7, 8];

var lastPromise = arr.reduce(function(promise, item) {
    return promise.then(function() {
        return someFunc(item);
    });
}, Q.resolve())

lastPromise.then(function() {
    console.log('some message');
})
.catch(function(error) {
    console.log('some error');
});

Here someFunc is processing your item say like this
var item = 'item1';

someFunc(item).then(function(result) {
       console.log("The task finished.");
})
.catch(function(error) {
       console.log(error);
});

arr.reduce() takes two arguments, a callback and an initial value.If you notice they passed a second argument to reduce(), it will now call the given callback for each element in your array. The callback gets two arguments. The first time, the first argument is the initial value and the second argument is the first element of the array. Next time, the first argument is the return value of the previous time the callback was called, and the second argument is the next element of array.
For more details on this please take a look at
https://joost.vunderink.net/blog/2014/12/15/processing-an-array-of-promises-sequentially-in-node-js


text:
Q: How to delegate each() in jQuery It is possible to delegate .each() function in jquery? I want to bind my Div to li using delegate while using each(). Someone please help. Thanks in advance
I have this code
$('.calendar-container .item-list ul').each(function(){
    $(this).slick({
        slide: 'li',
        slidesToShow: 3,
        slidesToScroll: 3
    });
});

I want something like this but its not working
 $(document).delegate('.calendar-container .item-list ul','each',function(){
        alert('dd')
        $(this).slick({
            slide: 'li',
            slidesToShow: 3,
            slidesToScroll: 3
        });
    });

A: No.  You can't do this.  Delegation in jQuery is for handling events that bubble up the parent chain.  It appears you want to call .slick() on any newly created element that matches a selector.  You can't do that with delegation since it doesn't fit the above definition of how it works and what it does.  You aren't looking to handle an existing event that bubbles up the parent chain.
If you're looking for totally arbitrary monitoring of newly created objects or objects assigned matching classes, you'd probably have to use some sort of MutationObserver, though I suspect if we understood your entire situation, there's probably an easier and less generic way of solving your particular problem (like hooking into your code that modifies the DOM).


text:
Q: Magento_Checkout::js/components.phtml invalid template I get this error in the system.log:
   [2018-03-13 16:20:04] main.CRITICAL: Invalid template file: 'Magento_Checkout::js/components.phtml' in module: '' block's name: 'checkout_page_head_components' [] []

It's never good to see any error regarding the checkout, has anyone came across it and knows what is the cause and how to resolve it?
Running Magento ver. 2.1.8 and Varnish using Linux.
Also, found this which can be related:
[2018-03-14 09:03:15] main.CRITICAL: Broken reference: No element found with ID 'checkout.header.wrapper'. [] []

Edit:
This is the path to my components.phtml file in my custom theme:
/http/app/design/frontend/Venustheme/cricket_child/Magento_Checkout/templates/js/components.phtml

My layout/default.xml file:
    <referenceBlock name="head.components">
        <block class="Magento\Framework\View\Element\Js\Components" name="checkout_page_head_components" template="Magento_Checkout::js/components.phtml"/>
    </referenceBlock>

My layout/checkout_cart_configure.xml file:
    <referenceBlock name="head.components">
        <block class="Magento\Framework\View\Element\Js\Components" name="checkout_cart_configure_head_components" template="Magento_Checkout::js/components.phtml"/>
    </referenceBlock>

A: That error can appear when the Magento cannot find the template file. Please check if you have any typos in the folder names and check if the folders are the correct case.(Example: On linux "view" and "View" folders are different)
EDIT:
if you want to override the template "components.phtml" you can use the fallback system. You don't need the layouts. Just make sure you have the same paths.
Override templates
The fallback scheme for templates is the following (module context is always known for them):
Current theme templates:
 <theme_dir>/<Namespace>_<Module>/templates

Ancestors themes templates, recursively, until a theme with no ancestor is reached:
<parent_theme_dir>/<Namespace>_<Module>/templates

Module templates:
<module_dir>/view/frontend/templates

So if you need to customize a certain template, you need to create an overriding one with the same name in the ../templates/ directory in the theme module files. Where  is the path to the original template.
For example, if you must override the /view/frontend/templates/category/widget/link/link_block.phtml template, the  is category/widget/link/
Look here and here.


text:
Q: What are ways to solve Memory Leaks in C# I'm learning C#.  From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be.  I'm looking for wisdom learned over the years from you, the intelligent.
I'm coming from a C++ background and am VERY used to code-smells and development patterns.  I want to learn what code-smells are like in C#.  Give me advice!
What are the best ways to get things deleted?
How can you figure out when you have "memory leaks"?

Edit: I am trying to develop a punch-list of "stuff to always do for memory management"

Thanks, so much.

A: In general, the less you worry about memory allocation in C#, the better off you are.  I would leave it to a profiler to tell me when I'm having issues with collection.
You can't create memory leaks in C# in the same way as you do in C++.  The garbage collector will always "have your back".  What you can do is create objects and hold references to them even though you never use them.  That's a code smell to look out for.
Other than that:

*

*Have some notion of how frequently collection will occur (for performance reasons)

*Don't hold references to objects longer than you need

*Dispose of objects that implement IDisposable as soon as you're done with them (use the using syntax)

*Properly implement the IDisposable interface

A: The main sources of memory leaks I can think of are:

*

*keeping references to objects you don't need any more (usually in some sort of collection) So here you need to remember that all things that you add to a collection that you have reference too will stay in memory.

*Having circular references, e.g. having delegates registered with an event. So even though you explicitly don't reference an object, it can't get garbage collected because one of its methods is registered as a delegate with an event. In these cases you need to remember to remove the delegate before discarding the reference.

*Interoperating with native code and failing to free it. Even if you use managed wrappers that implement finalizers, often the CLR doesn't clean them fast enough, because it doesn't understand the memory footprint. You should use the using(IDisposable ){} pattern

A: C#, the .NET Framework uses Managed Memory and everything (but allocated unmanaged resources) is garbage collected.
It is safe to assume that managed types are always garbage collected. That includes arrays, classes and structures. Feel free to do int[] stuff = new int[32]; and forget about it.
If you open a file, database connection, or any other unmanaged resource in a class, implement the IDisposable interface and in your Dispose method de-allocate the unmanaged resource.
Any class which implements IDisposable should be explicitly closed, or used in a (I think cool) Using block like;
using (StreamReader reader = new StreamReader("myfile.txt"))
{
   ... your code here
}

Here .NET will dispose reader when out of the { } scope.

A: The first thing with GC is that it is non-deterministic; if you want a resource cleaned up promptly, implement IDisposable and use using; that doesn't collect the managed memory, but can help a lot with unmanaged resources and onward chains.
In particular, things to watch out for:

*

*lots of pinning (places a lot of restrictions on what the GC can do)

*lots of finalizers (you don't usually need them; slows down GC)

*static events - easy way to keep a lot of large object graphs alive ;-p

*events on an inexpensive long-life object, that can see an expensive object that should have been cleaned up

*"captured variables" accidentally keeping graphs alive

For investigating memory leaks... "SOS" is one of the easiest routes; you can use SOS to find all instances of a type, and what can see it, etc.

A: One other thing to consider for memory management is if you are implementing any Observer patterns and not disposing of the references correctly.
For instance:
Object A watches Object B
Object B is disposed if the reference from A to B is not disposed of property the GC will not properyly dispose of the object.  Becuase the event handler is still assigned the GC doesn't see it as a non utilized resource.
If you have a small set of objects you're working with this may me irrelevant. However, if your working with thousands of objects  this can cause a gradual increase in memory over the life of the application.
There are some great memory management software applications to monitor what's going on with the heap of your application.  I found great benefit from utilizing .Net Memory Profiler.
HTH

A: I recommend using .NET Memory Profiler
.NET Memory Profiler is a powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language.
.NET Memory Profiler will help you to:

*

*View real-time memory and resource information

*Easily identify memory leaks by collecting and comparing snapshots of .NET memory

*Find instances that are not properly disposed

*Get detailed information about unmanaged resource usage

*Optimize memory usage

*Investigate memory problems in production code

*Perform automated memory testing

*Retrieve information about native memory

Take a look at their video tutorials:
http://memprofiler.com/tutorials/

A: Others have already mentioned the importance of IDisposable, and some of the things to watch out for in your code.
I wanted to suggest some additional resources; I found the following invaluable when learning the details of .NET GC and how to trouble-shoot memory issues in .NET applications.
CLR via C# by Jeffrey Richter is an excellent book. Worth the purchase price just for the chapter on GC and memory.
This blog (by a Microsoft "ASP.NET Escalation Engineer") is often my go-to source for tips and tricks for using WinDbg, SOS, and for spotting certain types of memory leaks. Tess even designed .NET debugging demos/labs which will walk you through common memory issues and how to recognize and solve them.
Debugging Tools for Windows (WinDbg, SOS, etc)

A:

What are the best ways to get things deleted?

NOTE: the following works only for types containing unmanaged resources. It doesn't help with purely managed types.
Probably the best method is to implement and follow the IDisposable pattern; and call the dispose method on all objects implementing it.
The 'using' statement is your best friend.  Loosely put, it will call dispose for you on objects implementing IDisposable.

A: You can use tools like CLR profiler it takes some time to learn how to use it correctly, but after all it is free. (It helped me several times to find my memory leakage)

A: The best way to ensure that objects get deleted, or in .NET lingo, garbage-collected, is to ensure that all root references (references that can be traced through methods and objects to the first method on a thread's call stack) to an object are set to null.
The GC cannot, and will not, collect an object if there are any rooted references to it, no matter whether it implements IDisposable or not.
Circular references impose no penalty or possibility of memory leaks, as the GC marks which objects it has visited in the object graph. In the case of delegates or eventhandlers it may be common to forget to remove the reference in an event to a target method, so that the object that contains the target method can't be collected if the event is rooted.


text:
Q: zapier is unable to send challenge value to enable slack event api I'm using zapier with slack and want to catch an event when message_replied event was created as referred here.
To use event API, it needs URL verification, which is unable on zapier webhook catching. The following error occurs repeatedly; Request URL Your URL didn't respond with the value of the challenge parameter.
Are there any workarounds?
I'd really appreciate any help you can provide.
some related informations:

*

*app used in zapier : Webhooks by Zapier

*Event in zapier : Catch Hook

*feature used in slack bot : Event Subscriptions

A: This is not currently possible. "Webhooks by Zapier" will only respond with the default "success" response because it's intended to be used with any incoming webhook. For that product, there's not special cases for any particular service.
If you're trying to integration with the Slack Events API (something I implemented at Zapier), then I recommend writing your own web service to catch Slack hooks, do business logic, and then send relevant webhooks onto Zapier as needed. This will afford you much more control over the process.


text:
Q: How to display related group names for a particular Group member/ currently logged in user? I have a requirement to design a Visual force page and controller where I need to display list of groups Of the particular group member or currently logged in user. I mean for a currently logged in user, only display those list of group names where he is the member of the group. i.e. Only the Groups the Member has joined should appear on the list of groups.
My VF Code is:
<apex:page>
<apex:pageBlock id="pb1" mode="maindetail" title="Groups">

            <apex:pageBlockTable value="{!Groups}" var="g" id="pbt1" align="top" style="border:none; border-style:none;">
            <apex:column style="vertical-align:top;width:0.5em;">

                       <apex:image value="{!$Resource.greydot}" height="1" width="1"/>

                    </apex:column>
                <apex:column headerValue="" style="vertical-align:top;" headerClass="colHeadr">
                <input type="hidden" id="{!g.Name}" value="{!g.Id}"></input>

{!g.Name}

                </apex:column>
            </apex:pageBlockTable>

        </apex:pageBlock>

</apex:page>

Apex Class:
public with sharing class GroupsController {

    Map<Id,StringGroups = new Map<Id,String>();
    Map<Id,StringGroupLists = new Map<Id,String>();
    public Map<Id,StringgetGroups()
    {

        Set<IdGroupIds = new Set<Id>();
        for(CollaborationGroup g: [Select Id, Name, CollaborationType From CollaborationGroup WHERE IsArchived=false]){
            if(g.Name!=null){
                Groups.put(g.Id,g.Name);
                GroupIds.add(g.Id);
            }
        }

        for(CollaborationGroupMember cgm : [SELECT Id,MemberId,CollaborationGroupId FROM CollaborationGroupMember WHERE CollaborationGroupId IN : GroupIds AND MemberId = :UserInfo.getUserId()]){
            if(Groups.containsKey(cgm.CollaborationGroupId)){
                GroupLists.put(cgm.CollaborationGroupId,Groups.get(cgm.CollaborationGroupId));
                System.debug('Member - '+cgm);
            }
        }
        return GroupLists;
    }

}

A: Please try the below query for getting the Group Names where current loggedin user is a member.
[select id, Group.Name from GroupMember where UserOrGroupId =: UserInfo.getUserId()]


text:
Q: How to find the string match between 2 Excel files and return the match percentage in python? I have 2 Excel files which contains names as the only column:
File 1: file1.xlsx

Names
Vinay adkz
Sagarbhansali
Jeffery Jonas
Kiara Francis
Dominic

File 2: file2.xlsx

Names:
bhansali Sagar
Dominic
Jenny
adkzVinay

Sample Output:
I want to match the names in file 1 with names in file 2, and i am trying to get an output like the below :

Names         File2Matchname.  Match%
Vinay adkz.     adkzVinay.       98%
Sagarbhansali.  bhansali sagar   97%
Jeffery Jonas       NA            0%
Kiara Francis       NA            0%
Dominic          Dominic         100%

Is there any logic by which the above logic can be arrived in python ?
I tried to do this in Excel but vlookup doesn't help with match%. I know this is possible with python using cousine similarity but i am unable to get the logic in which the output can be arrived.
Any help would be much appreciated.

A: You can use Pandas and use python's built-in difflib library which has a function called difflib.SequenceMatcher() function to find the longest common substring between the two names.
Example code:
import pandas as pd
import difflib

#For testing
dict_lists = {"Names":["Vinay adkz", "Shailesh", "Seema", "Nidhi","Ajitesh"]}
dict_lists2 = {"Names":["Ajitesh", "Vinay adkz", "Seema", "Nid"]}

# Excel to  dataframes
df1 = pd.DataFrame(dict_lists) #pd.read_excel('file1.xlsx')
df2 = pd.DataFrame(dict_lists2) #pd.read_excel('file2.xlsx')

# Empty lists to stor matched name, match percentage
match_name = []
match_percent = []

# Iterate through the first dataframe
for i, row in df1.iterrows():
    name = row['Names']
    match = difflib.get_close_matches(name, df2['Names'], n=1, cutoff=0.8)
    if match:
        match_name.append(match[0])
        match_string = difflib.SequenceMatcher(None, name, match[0]).find_longest_match(0, len(name), 0, len(match[0]))
        match_percentage = (match_string.size / len(name)) * 100
        match_percent.append(match_percentage)
    else:
        match_name.append('NA')
        match_percent.append(0)

df1['File2names'] = match_name
df1['Match_per'] = match_percent
print(df1)

# Write in Excel
# df1.to_excel('output.xlsx', index=False)

I hope this helps you. This is the first time I am answering a question here.
Read also: How to use SequenceMatcher to find similarity between two strings?


text:
Q: Understanding calling one function inside another C I'd like to ask the following misunderstandings of C language, which I see I'm having.
I'm sorry if the code is not properly indented, I tried as much as I could but there are not so many guides on the internet.
The program asked given a starting number 'val' and a Even-Odd or Odd-Even alternating sequence (which stops whenever this rules is violated) to print the greater prime number with 'val'.
I tried with two functions and the main: one to control the GCD between two given numbers and the other to keep tracks of the greatest one, but I think I miss something in the code or in the conception of C function,
Because when compiled it returns me 0 or great number which I'm not entering.
One example to understand what I should do:
If my sequence was 10, 7, 8, 23 and my val was 3, I had to print 23, because it is the greatest integer prime with 3.
Here's the code :
#include <stdio.h>
int mcd(int a, int b)
{   // Gcd function
    if (a == 0)
        return b;
    else
        return mcd(b % a, b);
}

int valuta(int val, int h)  // Valuing Max function
{
    int temp = 0;
    if (mcd(val, h) == 1 && h > temp)
        temp = h;
    return temp;
}

int main()
{
    int val, d, x, y, z, t, contatore = 1;
    scanf("%d", &val);
    scanf("%d%d", &x, &y);
    if (x > y && mcd(val, x) == 1)
    {   // Two options
        t = x;
    }
    else if (y > x && mcd(val, y) == 1)
    {
        t = y;
    }
    if ((x % 2 == 0 && y % 2 == 0) || (x % 2 == 1 && y % 2 == 1))
    {   // Bad case
        if (x > y && mcd(val, x) == 1)
        {
            t = x;
            contatore = 0;
        }
        else if (y > x && mcd(val, y) == 1)
        {
            t = y;
            contatore = 0;
        }
    }
    else
    {
        while (contatore == 1)
        {
            scanf("%d", &z);
            t = valuta(val, z);
            if (x % 2 == 0 && z % 2 == 0)
            {   // Even- Odd - Even
                scanf("%d", &d);
                t = valuta(val, d);
                if (d % 2 == 0)
                {
                    contatore = 0;
                }
                else
                {
                    contatore = 0;
                }
            }
            if (x % 2 == 1 && z % 2 == 1)
            {   //Odd- Even- Odd
                scanf("%d", &d);
                t = valuta(val, d);
                if (d % 2 == 1)
                {
                    contatore = 0;
                }
                else
                {
                    contatore = 0;
                }
            }
        }
    }
    printf("%d\n", t);
    return 0;
}

PS.  Is there any way to reduce the number of lines of code or to reduce the effort in coding?  I mean, a straightforward solution will be helpful.

A: Your valuta() function is flawed in that it needs to return the maximum qualifying value so far but has no knowledge of the previous maximum - temp is always zero.  The following takes the previous maximum as an argument:
int valuta(int val, int h, int previous )
{
    return ( mcd(val, h) == 1 && h > previous ) ? h : previous ;
}

And is called from main() thus:
t = valuta( val, x, t ) ;

The test mcd(val, h) == 1 is flawed, because mcd() only ever returns the value of parameter b which is not modified in the recursion, so will never return 1, unless the argument b is 1.  Since I have no real idea what mcd() is intended to do, I cannot tell you how to fix it. It appear to be a broken implementation of Euclid's greatest common divisor algorithm, which correctly implemented would be:
int mcd(int a, int b)
{
    if(b == 0)
        return a;
    else
        return mcd(b, a % b);
}

But I cannot see how that relates to:

"[...] he greatest integer prime with 3 [...]

The odd/even even/odd sequence handling can be drastically simplified to the extent that it is shorter and simpler than your method (as requested) - and so that it works!
The following is a clearer starting point, but may not be a solution since it is unclear what it is it is supposed to do.
#include <stdio.h>
#include <stdbool.h>

int mcd(int a, int b)
{
    if(b == 0)
        return a;
    else
        return mcd(b, a % b);
}

int valuta(int val, int h, int previous )
{
    return ( mcd(val, h) && h > previous ) ? h : previous ;
}

int main()
{
    int val, x, t ;
    printf( "Enter value:") ;
    scanf("%d", &val);

    typedef enum
    {
        EVEN = 0,
        ODD = 1,
        UNDEFINED
    } eOddEven ;

    eOddEven expect = UNDEFINED ;
    bool sequence_valid = true ;

    printf( "Enter sequence in odd/even or even/odd order (break sequence to exit):\n") ;
    while( sequence_valid )
    {
        scanf("%d", &x);
        if( expect == UNDEFINED )
        {
            // Sequence order determined by first value
            expect = (x & 1) == 0 ? EVEN : ODD ;
        }
        else
        {
            // Switch expected odd/even
            expect = (expect == ODD) ? EVEN : ODD ;

            // Is new value in the expected sequence?
            sequence_valid = (expect == ((x & 1) == 0 ? EVEN : ODD)) ;
        }

        //  If the sequence is valid...
        if( sequence_valid )
        {
           // Test if input is largest qualifying value
           t = valuta( val, x, t ) ;
        }
    }

    // Result
    printf("Result: %d\n", t);

    return 0;
}


text:
Q: Emacs line number I am having problems obtaining a line number while within an emacs buffer. I have the following number in my initilization file: (setq line-number-display-limit 2000000), and I have verified that line number mode it turned on. When I first enter the (~500) line buffer, emacs provides me with a line number; however, it very quickly switched the line number reading to L??.
Any thoughts as to what could be wrong?
P.S. I have found searching for an answer to this problem nearly impossible as the key character string (L??) is seen by search engines as L(any character)(any character) -- does anybody know a way around this?
Any help will be much appreciated.  Thanks in advance!

A: Do you have very long (wide) lines?   Have you seen line-number-display-limit-width ?

line-number-display-limit-width is a variable defined in `C source code'.
  Its value is 200
Documentation:
  *Maximum line width (in characters) for line number display.
  If the average length of the lines near point is bigger than this, then the
  line number may be omitted from the mode line.

A: I had the same problem and setting line-number-display-limit-width solved it.  I set it using 'customize' and 'Save for future sessions'.  I thought that 'Save for future sessions' would include the 'Set for Current Session'.  But that seems not to be the case.  I had to quit and re-start emacs in order to make it take effect.  That was in a GNU Emacs 22.3.1


text:
Q: Remove first line separator of UItableView Cell How can I hide or remove the very first line separator of the tableViewCell programmatically?
I just need to remove cell 0 top line.
Something of this nature:
if(indexPath.row == 0){
   //remove top seperator
}

A: Within your cellForRowAt delegate function you can use:
if indexPath.row == 0 {
        cell?.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
    }


text:
Q: Normal tree with $\aleph_1$ nodes and no branch of cardinality $\aleph_1$ I am trying to understand how a normal tree with $\aleph_1$ node can fail to have a branch of cardinality $\aleph_1$.
Consider the tree of height $\omega_1$ whose nodes are $\mathbb{Q}$-valued strictly increasing $\alpha$-sequences.
This tree is normal : it has a single root; every node has a least to immediate successors; for every $\alpha < \beta < \omega_1$, if $x$ is on the $\alpha$-th level then there exist $y$ on the $\beta$-th level such that $x < y$.
This tree cannot have a branch of length $\omega_1$, for there would be an injection of $\omega_1$ into $\mathbb{Q}$.

Why does a proof in the style of König's Lemma break down for ω1? What is wrong with "Pick a node that has an uncountable number of successors as, if one doesn't exist, then you have a countable union of countable things which must (choice) be countable."?

This question is closely related to Aronszajn Trees and König's Lemma
but but I am not requiering that the tree be an Aronszajn tree.

A: How are you going to carry the recursive construction of a branch beyond the first $\omega$ steps? Every node has uncountably many successors at the next higher limit level, so you can easily construct a strictly increasing sequence $\langle x_n:n\in\omega\rangle$ of nodes, but if $\sup_n\sup x_n=\infty$, which is certainly possible, you won't be able to extend this sequence of nodes any higher in the tree.


text:
Q: Clear sheet button - Google Scripts I'm trying to clear a spreadsheet I have within Google.
I'm using the following code but can't seem to get it to work. The button is there but it doesn't do anything and gives me the error of can't find menubutton.
var activeSS = SpreadsheetApp.getActiveSpreadsheet();
var activeSh = activeSS.getActiveSheet();
var menubuttons = [ {name: 'Clear Sheet', functionName: 'Clearsheet'},]
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Clear Sheet')
      .addItem('Clear Sheet', 'menubuttons')
      .addToUi();
}

function menubuttons() {

  ss.addMenu('Clearsheet', 'menubuttons');

// note you also have to have functions called clearRange1 and clearRange2     as list below
function Clearsheet() { //replace 'Sheet1' with your actual sheet name

      sheet.getRange('A7:I100').clearContent();
}
  }

A: I've fixed it!! - The ] was on the wrong line.. Took days to figure it out!
function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var menubuttons = [ {name: "Clear Sheet", functionName: "clearRange1"},]
    ss.addMenu("Clear Sheet", (menubuttons)) ;
}

function clearRange1() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  sheet.getRange('A8:I73').clearContent();
}