text:
Q: What is stopping me from adding my own signature to things? there is something I am missing in understanding of digital signatures and was hoping someone could clear it up for me.
A digital signature is to verify something has not been modified and came from a person.
So say I somehow intercepted an xml file with a signature on it. I rip the signature out, then make some edits to the file. Then I generate a new signature for this file, and send it to who it was going to. They check the reference and yep it checks out. The file was not tampered with. But it was, only the signature was also tampered with. This must not be possible, so, what gigantic piece am I missing in this puzzle?

A: If the recipient would accept the document signed by anyone, then your approach would work. But the signature is usually used in conjunction with some other identification data, which makes replacing a signature meaningless.
Eg. when the user sends the signed report to the tax office, the report contains his name and the signature must contain his name. And this signature proves that John Doe has authorized or composed this report himself. If you replace the signature, it will contain your name, and the recipient of the report would compare the name in the report and the signature and reject the document.
Another example is SSL authentication of the server. The server presents the signed certificate that contains the domain name or IP address of the server (the procedure is more complicated, and I am omitting the details here). The client compares the data in the certificate with the address it connected to, and decides if he can trust the server or not.


text:
Q: Python easygui can't select file Here's my code:
import easygui
f = easygui.fileopenbox()
print f

Seems simple, but when I run it, I can't select any of the files, see figure in link. Sorry if this is dumb, but I am at my wit's end!
http://imgur.com/c20TvQ5

A: EasyGui isn't supported anymore. On OS X I don't have this problem with fileopenbox (it looks like what happens with diropenbox actually.) I'd recommend you try something like wxPython. Here's how to get a file open box in that (from https://stackoverflow.com/a/9319832/866271)
import wx

def get_path(wildcard):
    app = wx.App(None)
    style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
    dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)
    if dialog.ShowModal() == wx.ID_OK:
        path = dialog.GetPath()
    else:
        path = None
    dialog.Destroy()
    return path

print get_path('*.txt')

Tested on OS X with no problem. It's also cross-platform. If you're going to be doing GUI development, there's a lot of options to look at but wxPython is a good one because it uses the native widgets of whatever OS you're running. So everything looks pretty :)
For your case, you could instead call get_path('*.csv') if that's the type of file you're opening. Or just call get_path('*') to get all of them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java EE 5 programmatic authentication How I can authenticate a user from JSF action (or in servlet doGet/doPost methods)?
I mean something like:
Authenticator auth = ...;
if (!auth.authenticate("user","password"))
{
    FacesContext.getInstance().addMessage("Incorrect username or password", null);
}

Restrictions:

*

*This method must be compatible with container managed security. (i.e. `HttpServletRequest.getRemoteUser()` must return authenticated user)

*This method must work everywhere (i.e. on each application server).

Not using j_security_check or another J2EE authentication type (BASIC, DIGEST, etc...)
It is possible?
Or how to create captcha in this way?
Validate that login and password is not empty?
On single page and without JavaScript, of course...
Similar questions... but without answer on this question:
JSF authentication and authorization
Performing user authentication in Java EE / JSF using j_security_check
Edit 1:
I mean serlvet API at least 2.3.
Yes, I read about login in Servlet API 3.0, but it is supported only by new versions of application servers.
I think that here can be some solution that implements this authentication for each application server.
Sometimes via some hacks, sometimes via special classes designed for this purpose.
Like this:
private Class<?> tryClass(String name)
{
    try
    {
        return Class.forName(name);
    }
    catch (ClassNotFoundException e)
    {
        return null;
    }
}

public boolean authenticate(String username, String password) throws AuthenticationException
{
    try
    {

        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object request = context.getRequest();
        Object response = context.getResponse();

        Class<?> authClass = tryClass("com.sun.appserv.security.ProgrammaticLogin");
        if (authClass != null)
        {
            return (Boolean)authClass.getMethod("login").invoke(
                authClass.newInstance(), "user", "password", request, response);
        }

        authClass = tryClass("org.jboss.web.tomcat.security.login.WebAuthentication");
        if (authClass != null)
        {
            return (Boolean)authClass.getMethod("login").invoke(
                authClass.newInstance(), "user", "password");
        }

        // ... other hacks ...application servers

    }
    catch (Exception e)
    {
        throw new AuthenticationException("an error occured during user authentication", e);
    }

    return false;
}

A: Programmatic login is pretty darn tricky and seems to vary by application server.  I believe that going with the j_security_check is the most successful, and will allow your application to work across various application servers.
The hard part is getting the application server to accept the authentication.  On Tomcat, I've been able to do myLoginModule.login() and have the login module succeed, but the user wasn't authenticated with the container.  JBoss has some code to get programmatic authentication to work between JBoss and Tomcat (since Tomcat lives within JBoss).  Looking into this for Glassfish, I got the impression that programmatic login is very difficult and should be left to the pro's.
Glassfish documentation (http://docs.sun.com/app/docs/doc/820-4496/beacm?a=view) says:

Programmatic login is specific to the Enterprise Server and not portable to other application servers.

Edit
The j_security_check method takes a little getting used to, but once you learn to work around it, can be quite successful.  Basically you can have a welcome page that redirects the user in to your application; if the user has not logged in yet, they'll get sent to your login page.  Your login page can be your site's home page.  Once on the home page, the user can navigate to other "unsecure" pages of your site.  You can include login forms on those pages as well if you like.  You're not stuck with a single login page.
Edit 2
I've been using AJAX (via Richfaces) to check the user's username/password and showing an error message if needed.  If the credentials are correct, the form pointing to j_security_check is submitted to do the actual authentication.
Edit 3
The programmatic login method suggested by BalusC on the second linked question (http://stackoverflow.com/questions/2206911/best-way-for-user-authentication-on-javaee-6-using-jsf-2-0) doing request.login(...) looks great.  I'll be trying it out soon ;o)  Servlet 3 is supported by Glassfish 3 but not much else yet (will be part of Tomcat 7, probably JBoss 6).

A: Ah, it's J2EE 1.3 Java EE 5. Too bad, you're out of luck whenever you want to go ahead with container managed security. You have to grab containerspecific implementations from under the covers. By the way, "container managed security without j_security_check or BASIC/DIGEST" is self-contradicting. I would personally just forget about it all and homegrow security or grab a 3rd party implementation which is more configureable, like Spring Security.


text:
Q: Define Pin RX, TX Without SoftwareSerial Arduino Hi I did 2 diferent codes, then after verifying that they work i try to combine them and I got a problem. I used GSM.h to controle my GSM module, and to controle the GPS I used the SoftwareSerial.h.
I tryed to combine these to codes and this 2 libraries conflit with each other.
Can some one help me?
This is my code
//GSM
#include <GSM.h>
#define PINNUMBER "3805"
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;
//N de telefone de envio
char remoteNumber[20]= "914181875";
//Conteudo do SMS
char txtMsg[200]="Tester";
int val = 0;
//GPS
//#include <SoftwareSerial.h>
#include <TinyGPS.h>
TinyGPS gps;
SoftwareSerial ss(4, 3);

static void print_float(float val, float invalid, int len, int prec);

int button = 7;

void setup()
{
  // initialize serial communications
  pinMode(button, INPUT);
  Serial.begin(9600);

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
}

void loop()
{
val = digitalRead(button);
if (val == HIGH){
  sendSMS();
  }
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}

A: I would try using the AltSoftSerial library instead of SoftwareSerial:
https://github.com/PaulStoffregen/AltSoftSerial
The disadvantage of this library is it requires you to use specific pins for serial communication with your GPS hardware, which are different from the pins you're currently using:
// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

I don't have the hardware to test but the following code does compile:

//GSM
#include <GSM.h>
#define PINNUMBER "3805"
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;
//N de telefone de envio
char remoteNumber[20]= "914181875";
//Conteudo do SMS
char txtMsg[200]="Tester";
int val = 0;
//GPS
#include <AltSoftSerial.h>
AltSoftSerial ss;
#include <TinyGPS.h>
TinyGPS gps;

static void print_float(float val, float invalid, int len, int prec);

int button = 7;

void setup()
{
  // initialize serial communications
  pinMode(button, INPUT);
  Serial.begin(9600);

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
}

void loop()
{
val = digitalRead(button);
if (val == HIGH){
  sendSMS();
  }
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}


text:
Q: Error: Can't extract columns that don't exist. When using separate function from tidyr package Any help would be MUCH appreciated! I've included solutions I've tried at the end of this post after explaining the error I'm getting. Thank you in advance!
I'm trying to separate a newly added column into 4 separate columns based on a "_" separator as follows (code shows addition of column and separation of that column).
library(tidyverse)
library(openxlsx)
library(dplyr)
   ################### Formats raw data input into usable tibble that will be called throughout code ####################
# Adds a `meta` column to the tables with the filename of the file.
ldf_p <- mapply(function(x, y) mutate(x, meta = y),
               x = ldf_p,
               y = filenames_poin,
               SIMPLIFY = FALSE)

# Breaks up the meta column to separate meta information.
tbl_p <- bind_rows(ldf_p)

tbl_p <- tbl_p %>% separate(col = "meta",
                         sep = "_",
                         into = c("MUID", "Con", "State", "AirType")) %>%
 mutate(MUID = as_factor(MUID))

A snapshot of the head of tbl_p is included below, and you can clearly see the "meta" column included at the bottom. When tbl_p is open this column is present with the desired data.
# A tibble: 28,390 x 19
   ...1  `Baseline (V)` `TStart (s)` `TEnd (s)` `Width (ms)` `Height (V)` `SlopeRise (V/s…
   <chr> <chr>          <chr>        <chr>      <chr>        <chr>        <chr>
 1 1     0              1086.085     1086.244   158.9999999… 1.546670718… 0.0221479367068…
 2 2     0              1086.403     1086.565   162.0000000… 1.535335140… 0.0203560460742…
 3 3     0              1086.718     1086.883   164.9999999… 1.513617013… 0.0194694321866…
 4 4     0              1087.029     1087.19    161.0000000… 1.511392793… 0.0188157590977…
 5 5     0              1087.35      1087.517   167.0000000… 1.531234104… 0.0235031371974…
 6 6     0              1087.674     1087.829   154.9999999… 1.469163170… 0.0211227833350…
 7 7     0              1087.979     1088.144   164.9999999… 1.545739318… 0.0231538763150…
 8 8     0              1088.293000… 1088.46    166.9999999… 1.503279218… 0.0213396815432…
 9 9     0              1088.607     1088.788   181.0000000… 1.533299466… 0.0206839043055…
10 10    0              1088.928     1089.099   170.9999999… 1.491114158… 0.0172873396449…
# … with 28,380 more rows, and 12 more variables: `SlopeFall (V/s)` <chr>, `Sel
#   Duration` <chr>, Freq <chr>, `Avg Period` <chr>, `O2 Mean` <chr>, `CO2 Mean` <chr>, `Temp
#   Mean` <chr>, `Body Temp Linear C` <chr>, `Body Temp Avg C` <chr>, `TV cal mL` <chr>,
#   longname <chr>, meta <chr>

When running the final section of the code to separate the meta column in the R platform, it works perfectly. However, when this code is run in a pipeline through terminal, there is an error that I have traced down to the separate function. Below is the full error message with backtrace.
Error: Can't extract columns that don't exist.
✖ The column `meta` doesn't exist.
Backtrace:
     █
  1. ├─base::source("~/Desktop/papr/import_data.R")
  2. │ ├─base::withVisible(eval(ei, envir))
  3. │ └─base::eval(ei, envir)
  4. │   └─base::eval(ei, envir)
  5. ├─`%>%`(...)
  6. │ ├─base::withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
  7. │ └─base::eval(quote(`_fseq`(`_lhs`)), env, env)
  8. │   └─base::eval(quote(`_fseq`(`_lhs`)), env, env)
  9. │     └─`_fseq`(`_lhs`)
 10. │       └─magrittr::freduce(value, `_function_list`)
 11. │         └─function_list[[i]](value)
 12. │           ├─tidyr::separate(...)
 13. │           └─tidyr:::separate.data.frame(...)
 14. │             └─tidyselect::vars_pull(names(data), !!enquo(col))
 15
Execution halted

I have tried to rename the column, set an empty vector for "meta" before adding the column, setting empty vectors for the desired final columns, ungrouping just before the separate function, and checking for masked functions. Nothing has worked so far and I'm having trouble finding any other questions similar to this on this website to try and use the solutions from. Any help would be greatly appreciated! If more information is needed please let me know - I'm unsure if I have provided everything necessary for an answer as this is my first time asking a question! Thank you in advance!
Screenshot of format of ldf_p:
Screenshot of data format for ldf_p


text:
Q: Run a server-side exe from ASP (beginner) I have what should be a simple thing but my unfamiliarity with .NET and web programs is hindering me.  I'm a straight up old-school C programmer who has been programming ASP and ASP.NET lately for an ecommerce site.
I have an ASP program that synchronizes 2 databases.  I also have a VB.NET program compiled down to an EXE that fills the source database before the synch happens.  In the back of my mind I know I should be able to link the VB & ASP .NET programs together since that's the power of .NET.  Alternatively, if I could run the EXE from ASP it would be just as well for my project.  I do have the source to both programs.  The ASP script was written with a text editor - the VB was in VB 2008 Express.
Please assume I know nothing of linking assemblies and such because I don't - I just read that in an article. I'd prefer ASP but if necessary I could use the ASP.NET script to launch the EXE.  The code is legacy ASP with VBScript so all our ASP.NET stuff is the VB flavor as well.  C# makes my other programmer's head hurt so for his sake this will have to remain VB.
Is there a way I can relatively easily launch the EXE pre-sync program and have it run when the ASP synch script starts?
The server is MS Windows Server 2003 SP2 / IIS 6.0 / the .NET version is 2.0.50727.3603.  Thanks!
By the way - I'd love to "learn to use .NET properly" but time is short for this project and in-depth research will have to wait.
EDIT: Aaron's answer below gets me most of the way to the solution but I'm getting:
Exception Details:   System.ComponentModel.Win32 Exception: Access is denied
Source Error: Line 17: process1.Start();
Ideas anyone?
SOLUTION: Aaron's answer below plus the knowledge that ~/ in MapPath is the virtual root of the website and the file to run is relative to that.

A: // Create An instance of the Process class responsible for starting the newly process.
System.Diagnostics.Process process1 = new System.Diagnostics.Process();

// Set the directory where the file resides
process1.StartInfo.WorkingDirectory = Request.MapPath("~/");

// Set the filename name of the file you want to open
process1.StartInfo.FileName = Request.MapPath("foo.exe");

// Start the process
process1.Start();

A: If you have the source for both then you could open the project for the EXE and copy the functionality to a new class library, then reference this class library in the web app and call the method that does the database filling from the web app.


text:
Q: Get same completion candidates for IMain as would appear in a REPL I am trying to get the code completion for a Scala interpreter to work. Ideally it would work identically to the one provided by the REPL (ILoop). I am using a text document as source, so I do not want to instantiate an ILoop but just IMain.
In the following example, the completion only works for special cases:
import scala.tools.nsc.interpreter.{JLineCompletion, IMain}
import scala.tools.nsc.Settings

object CompletionTest extends App {
  val settings  = new Settings
  settings.usejavacp.tryToSetFromPropertyValue("true")
  val intp      = new IMain(settings)
  intp.initializeSynchronous()
  assert(intp.isInitializeComplete)
  val comp      = new JLineCompletion(intp)
  val completer = comp.completer()
  val buffer    = "val x = Indexe"
  val choices   = completer.complete(buffer, buffer.length)
  println("----BEGIN COMPLETION----")
  choices.candidates.foreach(println)
  println("----END COMPLETION----")
  intp.close()
}

The expected output would be IndexedSeq, but it is empty. If I set the buffer to just Indexe, it works. If I set the buffer to   Indexe (leading whitespace), the completion candidates are empty again.
So there must be an additional step involved in processing the buffer or invoking the completion. What exactly happens when <tab> is pressed in the REPL? It seems almost impossible to figure out which methods are called...

A: In JLineReader, you can see the wiring.  JLineConsoleReader sets up an ArgumentCompleter with the ScalaCompleter as the underlying completer.
So the completer wants just the argument, not the line.
apm@mara:~$ scalam
Welcome to Scala version 2.11.0-M7 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :power
** Power User mode enabled - BEEP WHIR GYVE **
** :phase has been set to 'typer'.          **
** scala.tools.nsc._ has been imported      **
** global._, definitions._ also imported    **
** Try  :help, :vals, power.<tab>           **

scala> val b = "Indexe"
b: String = Indexe

scala> completion.completer complete (b, b.length)
res0: scala.tools.nsc.interpreter.Completion.Candidates = Candidates(0,List(IndexedSeq))

In other keystrokes,
// paste your code

scala> val buffer    = "Indexe"
buffer: String = Indexe

scala> completer.complete(buffer, buffer.length)
res6: scala.tools.nsc.interpreter.Completion.Candidates = Candidates(0,List(IndexedSeq))

scala> import tools.nsc.interpreter.Completion.Candidates
import tools.nsc.interpreter.Completion.Candidates

scala> val Candidates(_, choices) = completer.complete(buffer, buffer.length)
choices: List[String] = List(IndexedSeq)

scala> choices foreach println
IndexedSeq

To hand it the full line:
scala> val argCompletor: ArgumentCompleter =new ArgumentCompleter(new JLineDelimiter, scalaToJline(comp.completer))
argCompletor: jline.console.completer.ArgumentCompleter = jline.console.completer.ArgumentCompleter@751222c7

scala> val maybes = new java.util.ArrayList[CharSequence]
maybes: java.util.ArrayList[CharSequence] = []

scala> val buffer    = "val x = Indexe"
buffer: String = val x = Indexe

scala> argCompletor.setStrict(false)

scala> argCompletor.complete(buffer, buffer.length, maybes)
res32: Int = 8

scala> maybes
res33: java.util.ArrayList[CharSequence] = [IndexedSeq]

The delimiter does the line parse.
Edit - some value-added analysis:
"Strict" mode for the completor exists because you can supply a completor for each token on the line, and require each previous argument to be completable.  For n completors, all args after nth arg are handled by the last completor.

A: Partial answer. I managed to drill a hole in that monster by overriding scalaToJline in JLineReader. That method is invoked with a pre-massaged string, following this trace:
at CompletionTest$$anon$1$$anon$2$$anon$3.complete(CompletionTest.scala:37)
at scala.tools.jline.console.completer.ArgumentCompleter.complete(ArgumentCompleter.java:150)
at scala.tools.jline.console.ConsoleReader.complete(ConsoleReader.java:1543)
at scala.tools.jline.console.ConsoleReader.readLine(ConsoleReader.java:1312)
at scala.tools.jline.console.ConsoleReader.readLine(ConsoleReader.java:1170)
at scala.tools.nsc.interpreter.JLineReader.readOneLine(JLineReader.scala:74)
at scala.tools.nsc.interpreter.InteractiveReader$$anonfun$readLine$2.apply(InteractiveReader.scala:42)
at scala.tools.nsc.interpreter.InteractiveReader$$anonfun$readLine$2.apply(InteractiveReader.scala:42)
at scala.tools.nsc.interpreter.InteractiveReader$.restartSysCalls(InteractiveReader.scala:49)
at scala.tools.nsc.interpreter.InteractiveReader$class.readLine(InteractiveReader.scala:42)
at scala.tools.nsc.interpreter.JLineReader.readLine(JLineReader.scala:19)
at scala.tools.nsc.interpreter.ILoop.readOneLine$1(ILoop.scala:568)
at scala.tools.nsc.interpreter.ILoop.innerLoop$1(ILoop.scala:584)
at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:587)

A: So this my "unwiring" which seems to be working as expected:
import scala.tools.nsc.interpreter._
import scala.tools.jline.console.completer.{Completer, ArgumentCompleter}
import scala.tools.nsc.interpreter.Completion.{Candidates, ScalaCompleter}
import scala.tools.nsc.Settings
import collection.JavaConverters._

object Completion2 extends App {
  val settings  = new Settings
  settings.usejavacp.tryToSetFromPropertyValue("true")
  val intp      = new IMain(settings)
  intp.initializeSynchronous()

  val completion = new JLineCompletion(intp)

  def scalaToJline(tc: ScalaCompleter): Completer = new Completer {
    def complete(_buf: String, cursor: Int, candidates: JList[CharSequence]): Int = {
      val buf   = if (_buf == null) "" else _buf
      val Candidates(newCursor, newCandidates) = tc.complete(buf, cursor)
      newCandidates foreach (candidates add _)
      newCursor
    }
  }

  val argCompletor: ArgumentCompleter =
    new ArgumentCompleter(new JLineDelimiter, scalaToJline(completion.completer()))
  argCompletor.setStrict(false)

  val jlist: java.util.List[CharSequence] = new java.util.ArrayList

  val buffer = "val x = Indexe"

  argCompletor.complete(buffer, buffer.length, jlist)

  val list = jlist.asScala

  println("----BEGIN COMPLETION----")
  list.foreach(println)
  println("----END COMPLETION----")
  intp.close()
}

Edit: This has problems with wildcard imports for some reason. Like if I execute
import mypackage.MySymbol

Then MySymbol is found by the completer. But if I execute instead
import mypackage._

Then none of the contents of mypackage are found. Any ideas?


text:
Q: How to shrink large python package for AWS Lambda Layer? I'm trying to deploy a python package with large binary dependencies such as numpy, scipy, astropy, pandas, etc... The zip file is more than 400MB, so I have to shrink his size below 250MB to be able to deploy it to a lambda layer from S3.
I know I can delete tests, docs and pycache directories with something like
find -name "tests" -type d | xargs rm -rf
find -name "docs" -type d | xargs rm -rf
find -name "__pycache__" -type d | xargs rm -rf

but this is not sufficient...
Is it theoretically possible to delete *.pyc and *.so files? I know that, for example, the serverless-framework with serverless-python-requirements offer the slim option to package dependencies removing all *.pyc and *.so files. But I think Lambda environment needs these files... I don't want to use any framework if possible and I can run eventually docker to build binaries from a lambda compatible image (I'm working from WSL now). I tried many things but they are not working, I'm not sure why...
I really appreciate any help to understand what it's possible and what it's not to deploy such a huge package to Lambda...

A: As a workaround when I've run into this, I did what @jordanm suggested and switched to a Fargate task.
A simpler solution as of December 2020 is to use a container image for your Lambda.


text:
Q: CSV Parsing, trying to understand some code Here's the code
import csv

def csv_dict_reader(file_obj):
    """
    read a CSV file using csv.DictReader
    """

    reader = csv.DictReader(file_obj, delimiter=',')
    for line in reader:
        print(line['first_name']),
        print(line['last_name']),

if __name__== "__main__":
    with open("dummy.csv") as f_obj:
        csv_dict_reader(f_obj)

I wanted to try and do a quick breakdown, to see if I understand how exactly this works. Here we go:
1) import csv brings in the csv method
2) We define a function, which takes 'file_obj' as its argument
3) the reader variable makes a call to a function within csv called "DictReadre", which subsequently takes arguments from 'file_obj' and specifies a 'delimiter'
4) I get confused with this for loop, why is that we don't have to define line beforehand? Is it that line is already defined as part of 'reader'?
5) I'm really confused when it comes to 'name' and 'main', are these somehow related to how we specify a 'file_obj'? I'm equally confused with how we end up specifying the 'file_obj' in the end; I've been assuming 'f_obj' somehow manages to fill this role.
--edit--
Awesome, this is starting to make a whole lot more sense to me. So, when I make a 'class' call to DictReader(), I'm creating an instance of it in the variable 'reader'?
Maybe I'm going too far off the beaten path, but what in the DictReader() class allows for it to determine the structure of fields like 'last_name' or 'first_name'? I'm assuming it has something to do with how CSV files are structures, but I'm not entirely certain.

A:
1) import csv brings in the csv method

Well, not quite; it brings in the csv module.*
* … which includes the csv.DictReader class, which has a csv.DictReader.__next__ method that you call implicitly, but that's not important here.

2) We define a function, which takes 'file_obj' as its argument

Exactly.*
* Technically, there's a distinction between arguments and parameters, or between actual vs. formal arguments/parameters. You probably don't want to learn that yet. But if you do, formal parameters go in function definitions; actual arguments go in function calls.

3) the reader variable makes a call to a function within csv called "DictReadre", which subsequently takes arguments from 'file_obj' and specifies a 'delimiter'

Again, not quite; it makes a call to the class DictReader. Calling a class constructs an instance of that class. Arguments are passed the same way as in a function call.* You can see the parameters that DictReader takes by looking it up in the help.
* In fact, constructing a class actually calls the class's __new__ method, and then (usually) its __init__ method. But that's only important when you're writing new classes; when you're just using classes, you don't care about __new__ or __init__. That's why the documentation shows, e.g., class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds).

4) I get confused with this for loop, why is that we don't have to define line beforehand? Is it that line is already defined as part of 'reader'?

No, that's exactly what for statements do: each time through the loop, line gets assigned to the next value in reader. The tutorial explains in more detail.
A simpler example may help:
for a in [1, 2, 3]:
    print(a)

This assigns 1 to a, prints out that 1, then assigns 2 to a, prints out that 2, then assigns 3 to a, prints out that 3, then it's done.
Also, you may be confused by other languages, which need variables to be declared before they can be used. Python doesn't do that; you can assign to any name you want anywhere you want, and if there wasn't a variable with that name, there is now.

5) I'm really confused when it comes to 'name' and 'main'

This is a special case where you have to learn something reasonably advanced a little early.
The same source code file can be used as a script, to run on the command line, and also as a module, to be imported by other code. The way you distinguish between the two is by checking __name__. If you're being run as a script, it will be '__main__'. If you're being used as a module by some other script, it will be whatever the name of your module is.
So, idiomatically, you define all your public classes and functions and constants that might be useful to someone else, then you do if __name__ == '__main__': and put all the "top-level script" code there that you want to execute if someone runs you as a script.
Again, the tutorial explains in more detail.


text:
Q: Difference Between Pointer(*) And Reference(&) I use Reference(&) here,but the a didn't change.Why?
While i use Pointer(*) the value have changed.
int all=0;
void call_from_thread(int & a)
{
   a = 5;
}

int main()
{
    thread s = thread(call_from_thread, all);
    s.join();
    return 0;
}

Another program,in this case, i also use Reference(&),but the value have changed. Why the value a in thread didn't change?
void Func3(int &x)
{
    x = x + 10;
}

int main() {

    int n = 0;
    Func3(n);
    cout << "n = " << n << endl; // n = 10
}

A: The std::thread constructor makes copies of its parameters during the thread creation step.... ordinary references don't survive the trip, and the call_from_thread function receives a reference to the copy.
Details can be found in the Standard.  The thread::thread constructor behavior is described as

Constructs an object of type thread. The new thread of execution executes INVOKE(DECAY_COPY(std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...) with the calls to
  DECAY_COPY being evaluated in the constructing thread.

The exact definition of DECAY_COPY is quite complex, but as the name suggests, it ignores references and makes a value copy.
A simple workaround is to use std::ref.
thread s = thread(call_from_thread, std::ref(all));

This keeps a pointer through the copies, and only resolves to the actual target when the reference parameter is bound.


text:
Q: ECMAScript 5 'for' loop, with 'i' overwritten, vs. ECMAScript 6 'for' loop I was interviewed for a JavaScript frontend developer position. I failed because I didn't know a few advanced questions. Please help me to understand at least this one.
My problem was on ECMAScript 6 knowledge, not the for loop in ECMAScript 5 or the closure. I didn't understand what is doing for/of or who is doing the magic in this ECMAScript 6 code to not overwrite the i.
The question was like:

To display numbers from 1 to 5 in the for loop, every time we click on a button, we have to wrap the console in a closure, to have the right output, so the i variable will not be overwritten if we use this closure.
In ECMAScript 6, in a for loop we only have the callback function, and i is not overwritten. Why?
// ECMAScript 5
for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click',
    function(x) {
      return function() {
        console.log(x);
      };
    }(i)
  );
  document.body.appendChild(btn);
}

// ECMAScript 6
const ps = Array.from(document.querySelectorAll('p'));

for (const [i, paragraph] of ps.entries()) {
  paragraph.addEventListener('click', function() {
    return console.log(`${i+1}: ${this.textContent}`);
  });
 }

A: This is just a matter of scope. It has nothing to do with the for...of loop...
Take a look at these scenarios:
var is global

// "i" is global
for (var i = 0; i < 5; i++) {}

console.log(i);

var is still global

// "i" is global
var i;
for (i = 0; i < 5; i++) {}

console.log(i);

let is local

// "i" is local
for (let i = 0; i < 5; i++) {}

console.log(i); // ReferenceError

let is global

// "i" is global
let i;
for (i = 0; i < 5; i++) {}

console.log(i);


text:
Q: Relationship not being created, match by Id not returning results I'm just getting started with Neo4j.
I'm trying to do a complex LOAD FROM CSV but I don't seem to be getting the relations part right.
LOAD CSV WITH HEADERS FROM "file:/Users/brestrepo/Krossover/neo4j/access_control_games.csv" AS csvLine
MERGE (game:Game
    {
        id: toInt(csvLine.id),
        datePlayed: csvLine.date_played,
        type: csvLine.type,
        createdAt: csvLine.created_at,
        updatedAt: csvLine.updated_at
    }
)
FOREACH(ignoreMe IN CASE WHEN trim(csvLine.deleted_at) <> "" THEN [1] ELSE [] END | SET game.deletedAt = csvLine.deleted_at)
WITH csvLine, game
MATCH (team:TEAM { id: toInt(csvLine.created_by_team_id)}),(game:Game { id: toInt(csvLine.id)})
CREATE (team)-[:OWNER_TEAM { }]->(game)
WITH csvLine, game
MATCH (user:User { id: toInt(csvLine.created_by_user_id)}),(game:Game { id: toInt(csvLine.id)})
CREATE (user)-[:OWNER_USER { }]->(game)
WITH csvLine, game
MATCH (team_away:TEAM { id: toInt(csvLine.team_away_id)}),(game:Game { id: toInt(csvLine.id)})
CREATE (team_away)-[:AWAY_TEAM { }]->(game)
WITH csvLine, game
MATCH (team_home:TEAM { id: toInt(csvLine.team_home_id)}),(game:Game { id: toInt(csvLine.id)})
CREATE (team_home)-[:HOME_TEAM { }]->(game)
RETURN game

I think that the MATCH is that's causing this problem. The Match is unable to find a game.
I do get games when I do:
MATCH (game:Game) return game LIMIT 1
{
  "records": [
    {
      "keys": [
        "game"
      ],
      "length": 1,
      "_fields": [
        {
          "identity": {
            "low": 31891,
            "high": 0
          },
          "labels": [
            "Game"
          ],
          "properties": {
            "createdAt": "2014-07-18 19:38:32",
            "deletedAt": "NULL",
            "id": {
              "low": 285,
              "high": 0
            },
            "type": "2",
            "datePlayed": "2013-10-12 04:00:00",
            "updatedAt": "2016-03-25 15:28:41"
          },
          "id": "31891"
        }
      ],
      "_fieldLookup": {
        "game": 0
      }
    }
  ],
}

But then, when I do
MATCH (game:Game {id: 31891}) return game;

(no changes, no records)

Can anyone point me in the right direction?


text:
Q: when to roll back a jdbc transaction I have been reading an interesting statement in http://download.oracle.com/javase/tutorial/jdbc/basics/transactions.html
The interesting part is: "Catching an SQLException tells you that something is wrong, but it does not tell you what was or was not committed. Since you cannot count on the fact that nothing was committed, calling the method rollback is the only way to be sure."
Is that really so? If I don't call commit but I got an SQLException then can I not count on nothing being committed? What if my program exits without calling commit or rollback? I thought the transaction will be rolled back automatically for me but this statement takes away my certainty.

A: Basically any modern database you would consider using in its default isolation level would not exhibit this behavior.  But ultimately, what happens down there is out of JDBC's control and for all it knows you might be using Informix 5 or a 1988 Sybase with an adaper layer under the hood.
Hence, from the high level language API specification point of view, they have to make the statement that nothing is guaranteed if you don't use it properly.  Basically it's saying that it would not be considered a bug at the JDBC level if the result of abandoning a connection with neither a commit nor a rollback results in some executed statements showing up in the database level.  (Usually for most databases we'd consider that  bug at the database level, but again, JDBC is a high level API.)

A: you can test it out to see what happens.
I would recommend using Spring for this stuff.  It will automatically handle your tx rollbacks for you.


text:
Q: unknown type name "pthread_barrier_t" I am trying to parallelize an algorithm in C. I want to use pthread_barrier_t but my Ubuntu wsl can't find it for some reason. I have pthread.h included and I can use the rest of the pthread functions. libthread.a is installed.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

/* Error occurs here */
pthread_barrier_t barrier;

Exact error is: "identifier pthread_barrier_t is undefined"
I saw elsewhere it could be the way I'm compiling.
Compiling as follows:
gcc -o test test.c -Wall -std=c99 -lpthread -lm

Also, VS Code can't identify the function.

A: The problem is your -std=c99 option. Using strict C mode disables a bunch of stuff, including something that stops pthread_barrier_t from getting defined. If you use -std=gnu99 instead, it should compile. (Tested on Ubuntu 16.04 on WSL).
Alternatively, add
#define _XOPEN_SOURCE 600 /* Or higher */

or
#define _POSIX_C_SOURCE 200112L /* Or higher */

before the first #include in your source. See man 7 feature_test_macros for the acceptable values of these macros and more information.


text:
Q: Append to a JSON File (Node.JS, Javascript) I currently have a json file setup with the following format:
{
   "OnetimeCode" : "Value"
}

And I'd like to be able to do two things:

*

*Append to the file (change the values in the file)

*Add New Items to the File (In the same format)

I have been searching for almost an hour trying to find either a module (for Node) or just easy sample code that would allow me to accomplish this.
I have tried using several plugins already, but rather than appending to the file, they completely rewrite it.
One of the plugins is called "jsonfile" (npm install jsonfile)
var jf = require('jsonfile'); // Requires Reading/Writing JSON
var jsonStr = WEAS_ConfigFile;
        var obj = JSON.parse(jsonStr);
        obj.push({OnetimeCode : WEAS_Server_NewOneTimeCode});
        jf.writeFileSync(WEAS_ConfigFile, obj); // Writes object to file

But that does not seem to be working.
Any help is appreciated! But Please, keep it simple.
Also: I cannot use jQuery

A: The code you provided with the jsonfile library looks like a good start: you parse the json into an object, call .push(), and save something.
With raw Node calls (assuming the json file is a representation of an array):
var fs = require('fs');
function appendObject(obj){
  var configFile = fs.readFileSync('./config.json');
  var config = JSON.parse(configFile);
  config.push(obj);
  var configJSON = JSON.stringify(config);
  fs.writeFileSync('./config.json', configJSON);
}

appendObject({OnetimeCode : WEAS_Server_NewOneTimeCode});


text:
Q: Visual Studio 2017 xaml designer not available Using Visual Studio Professional 2017 (Release 15.2 26430.16), when I open a xaml file for a desktop UI that I have developed, I can no longer see the xaml designer (I only see the raw xaml code). This is new behaviour and may be due to me having a system clean-out, so maybe I removed an SDK that I need or something like that?
Are there any Visual Studio error logs I can check for warnings etc?

A: Make sure XAML Designer is enabled.
Tools -> Options -> XAML Designer -> General -> Enable XAML Designer

A: I couldn't get the designer to work, but I found an alternate solution posted here, posted by @DamianSuess

Use the View > Other Windows > Xamarin.Forms Previewer menu in
Visual Studio to open the preview window. Use the Window > New
Vertical Tab Group menu to position it side-by-side.

forms-not-show-in-visual-studio

A: I know this issue is tagged as WPF but I had a similar issue for Xamarin Forms.
What solved this issue for me:

*

*Right Click the xaml file

*Select "Open With..."

*Select Xamarin.Forms Previewer

*Click OK

*Optionally, you can set the Xamarin.Forms Previewer as the default for xaml files

A: Frankly, your situation is different than mine. In my situation, it was because of Resharper. Maybe this may useful for someone else.
What to do is checking Resharper Options > Enviroment > Performance Guide > Disable XAML Designer.
It must be set to "Ignore" or "Show in Status Bar". Otherwise, it will always disable XAML Designer.

A: make sure you have correctly installed the Windows 10 SDK, there are 3-4 versions of the SDK, the error you are talking about can also be a consequence of a incompatible sdk,
also reinstall the sdk related to your app, close every process related to Visual studio running in background while reinstalling the SDK.
Can you share a screenshot of the xaml designer page?

A: In the Visual Studio 2017 Installer, I selected all of the SDKs and installed the missing ones. This did not fix the problem by itself, but a subsequent 'repair' from the Visual Studio 2017 Installer (available from the 'hamburger' drop-down) did.
Sometimes, adding or removing SDKs from the Installer toggles the 'Enable XAML Designer' check box under Tools -> Options -> XAML Designer -> General (or perhaps it was the repair step that turned this back on), so ensure that this is checked.

A: I had the same, I found that opening the XAML in VS community did not work. However, if I choose file -> open -> project/solution and open the corresponding sln file, it works.


text:
Q: How to get a div to resize its height to fit container? How can I get the nav div to have expand down or have the height the same as its parent div?

*   {
    border:0;
    padding:0;
    margin:0;
}
#container {
    margin-left: auto;
    margin-right: auto;
    border: 1px solid black;
    overflow: auto;
    width: 800px;
}
#nav {
    width: 19%;
    border: 1px solid green;
    float:left;
}
#content {
    width: 79%;
    border: 1px solid red;
    float:right;
}

Menu

Menu

Menu

Menu

Menu

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.

A: Simple Way
You can achieve this with setting both the top and bottom attributes of the nav to 0 and the position: absolute. Set the container to position: relative.
See how this is done
Modern Way (Flexbox)
IE11+ and all modern browsers support flexbox.
.container {
  display: flex;
  flex-direction: column;
}

.child {
  flex-grow: 1;
}

A: you would possibbly need to specify the height of container and then set the nav's height to 100%.
Edit: had a quick look around and it seems that the height property applies to the parents height so you will indeed need to set the containers height.
NB: setting the height of the body element to 100% only scales it to the height of the browser window. Any content which goeds over one page will not have the same background etc.

A: I had the same issue, I resolved it using some javascript.

A: Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.
One way to do the following without using JavaScript is via a technique called Faux-Columns.
It basically involves applying a background-image to the parent elements of the floated elements which makes you believe that the two elements are the same height.
More information available at:

A List Apart: Articles: Faux Columns

A: If the trick using position:absolute, position:relative and top/left/bottom/right: 0px is not appropriate for your situation, you could try:
#nav {
    height: inherit;
}

This worked on one of our pages, although I am not sure exactly what other conditions were needed for it to succeed!

A: Another one simple method is there. You don't need to code more in CSS. Just including a java script and entering the div "id" inside the script you can get equal height of columns so that you can have the height fit to container. It works in major browsers.
Source Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title></title>

Menu

Menu

Menu

Menu

Menu

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.

You can include any no of divs in this script.
ddequalcolumns.columnswatch=["nav", "content"]
modify in the above line its enough.
Try this.

A: You probably are going to want to use the following declaration:
height: 100%;
This will set the div's height to 100% of its containers height, which will make it fill the parent div.

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>


text:
Q: How to convert all float columns in dataframe but except the first column? I have searched but not found excatly what I need. I have a dataframe which has 50 columns. The first one is a date dtype, the rest are floats dtypes.
Now I want to convert ONLY the float columns into integer but NOT the date column.
Can someone guide please?
When I slice the df like this df_sub1=df_sub.iloc[:, 1:].apply(np.int64) and then concat with the date column after, it crashes my laptop and did therefore not work. I hope there is a better way.

A: Well assuming that date is your first column
import pandas as pd

cols = df.columns
df[cols[1:]] = df[cols[1:]].apply(pd.to_numeric, errors='coerce')

A: you can do it like this.
new_df = df.drop(nameoffirstcolumn,1)
new_df.apply(np.int64)

then you can do something like.
final_df = pd.concat([df1['nameoffirstcolumn'],new_df], axis=1)


text:
Q: What is the Pythonic way to check if a list of strings is sorted or not? I have a list of strings
my_string_list = ['Banana', 'Apple', 'Sorry']

How can I check if this my_string_list is sorted or not?
One obvious way is to sort this list and compare it against the original list. But I do not want to iterate over the whole original list to decide that the list is not sorted.
sorted_list_of_strings = sorted(my_string_list)
if my_string_list != sorted_list_of_strings:
    print(f'The list {my_string_list} is not sorted.')

I am wondering if there is any other way to do this?

A: Typically, I'd use your solution (if x == sorted(x):) and accept the cost; it's easy to write, and if it's not a hot code path, it hardly matters if you're doing it somewhat inefficiently (for the already-sorted case, it'll be roughly O(n) anyway thanks to Python's TimSort, so you only pay O(n log n) general sort costs for the "not sorted" case). It's also easy to customize when you need to handle reverse sorting, keyed sorting, etc., while remaining easy to write and easy to verify by inspection.
If you want a more efficient solution using Python builtins, you could do something along the lines of (with from operator import le at the top of the file):
if all(map(le, my_string_list, my_string_list[1:])):

which compares each element to the following element, returning False on the first mismatch, and True if they're all less than or equal to the following element. Replace my_string_list[1:] with itertools.islice(my_string_list, 1, None) if you have concerns about the cost (computational or memory cost) of building the temporary list with the plain slice.


text:
Q: How to split an existing webApi project? I have an existing legacy .Net webApi project with ~20 controllers and ~10 methods each.
The traffic is 15 requests per sec.
I'm wondering if it's a smart thing to do to take microServices approach and split it into few hosted projects.
Since i don't have access to the clients (android, ios, WebSite and third parties) i will have to keep the existing API URL working (http://domainName/API).
My quick and dirty architecture is:
1) Build new hosted API process http://domainName/API1, http://domainName/API2, http://domainName/API3...
2) Ask kindly from the clients to use the new URLs
3) http://domainName/API will act as router to the new processes for background competitively
Ideas ? Is there any existing pattern for that?

A:
I'm wondering if it's a smart thing to do to take microServices approach and split it into few hosted projects.

This strongly depends on the amount of organizational pain you are experiencing today. Is your development team losing a lot of time by coordinating the monolith development and issues arising from dependencies between the different parts of your monolith? Is your monolith taking hours to build? Would your business benefit greatly from faster releases? If the answers are yes, then you should consider switching to microservices. If the answers are no or maybe, then you either have a well designed/working monolith and/or the pressure to change is low. Refactoring a monolith to microservices is most likely very expensive and you have to make a cost/benefit calculation. This is a good read and this too.

Ideas ? Is there any existing pattern for that?

I found this article to be a good general guide about how to change a monolith. Additionally here are some resources about the experiences of some large companies (Amazon1, Amazon2, Soundcloud, Netflix).
In short:

*

*You want to avoid a big bang refactoring that tries to change the whole monolith or large portions in one shot.

*Identify the modules from your monolith that will give the biggest benefit when refactored into microservices.

*Start by changing the interfacing to your application without changing the underlying implementation (for the highest value module/service) to reflect a independent service.

*The changed interfacing gives you the freedom to refactor the actual implementation at your own pace.


text: Q: Funcionalidad de ataques dns spoofing (medidas de proteccion) Mi pregunta es entorno a la funcionalidad de el ataque dns spoofing actualmente, ya que con determinadas dominios reconocidos como lo son facebook youtube he estado haciendo pruebas con maquinas virtuales con herramientas como bettercap y ettercap, el ataque no funciona eficientemente por lo que no suplanta el dominio ni lo redirige mientras que en otros dominios si lo hace. En concreto la pregunta seria hoy en dia existen medidas de proteccion por parte de esos sitios web o estoy haciendo el procedimiento mal?.


text:
Q: Different Servers for incoming mails not sure if what I want is possible so I´d appreciate any pointers.
I have full control over the infrastructure (DNS and servers)
Currently I receive mails for domain.tld.
MX record for domain.tld is  gw.domain.tld.
gw then does some spam and virus checking and forwards the mails to the internal exchange server. GW is a Proxmox Mail Gateway Box (Free license)
Now what I want is to distribute mails for different recipients to other mail servers.
Basicly I only want user1@domain.tld and user2@domain.tld to go to the exchange as before, but all others go to a different mail server (based on linux).
Any idea how I could achieve this?

A: The easiest way to complete this would probably be to direct the MX record at the Linux server and have it forward the mail for the users in question onto the Exchange server. This can be done either using an .forward in the user's home, or in /etc/aliases if the user doesn't need to exist on the system.
For this to work, you need to have the Exchange server listening for an alternative domain, for example user@exchange.company.com or user@company.local.
There's other ways to do it was well, for example putting a smart smtp proxy server in front of both, but that will just add to the complexity.


text:
Q: How to Get Index value from list in C#?
I have following code that i am getting a index and value for example
index[0] value[0]"example"[1]"example" [2]"example" i want to access only one index all value at a time
foreach (var pair in profession.Professions.Select((x, i) => new { Index = i, Value = x }))
{
    Console.WriteLine(pair.Index + ": " + pair.Value);
}

For example: when user will select first item in list box and that item index is [0] and value is [0]1 [1]480[2]749[3]270 i want to show all the value in messagebox.

A: Since your code is only partial and not very clear, I'm giving this a shot based on the image you provided:
//Defining the structure like in your example
static List<int[]> rootArray = new List<int[]>{
        new int[]{1,5,7,10},
        new int[]{2,4,6,8},
        new int[]{3,6,9,12}
    };

static void Main(string[] args)
    {
        //Same loop you posted in your OP, only added a .Where after the initial .Select just to get elements with Index == 0
        foreach(var p in rootArray.Select((x,i) => new {Index = i, Value = x}).Where(f => f.Index == 0).Select(x => x.Value))
        {
            //Since this is a List<int[]> your values are int arrays hence you need a loop to display all the values in it.
            foreach(var i in p)
            {
                Console.WriteLine(i);
            }
        }

        Console.ReadLine();
    }

Hope this helps.


text:
Q: Cant import a PushKit framework into pyobjus I am trying to import UserNotifications from the PushKit framework but i don't know how to call it because the only Include function i know of in pyobjus is AppKit. I have not seen of any way to call frameworks from the PushKit when i try to call it from the AppKit. it returns an error. Below is my code and the error. I would appreciate any help.
from pyobjus import autoclass
from pyobjus.dylib_manager import load_framework, INCLUDE
load_framework(INCLUDE.AppKit)
UserNotifications = autoclass('UserNotifications')

Traceback
Traceback (most recent call last):
  File "/Users/temitayoadefemi/PycharmProjects/test7/mainfile.py", line 5, in <module>
    UserNotifications = autoclass('UserNotifications')
  File "pyobjus/pyobjus.pyx", line 726, in pyobjus.autoclass
  File "pyobjus/pyobjus.pyx", line 85, in pyobjus.MetaObjcClass.__new__
  File "pyobjus/pyobjus.pyx", line 116, in pyobjus.MetaObjcClass.resolve_class
pyobjus.ObjcException: Unable to find class b'UserNotifications'

A: AppKit doesn't have a class called UserNotifications. You could use UNNotificationSettings for normal Push Notification or PKPushRegistry for VoIP Push Notification.
References:
https://developer.apple.com/documentation/pushkit?language=objc
https://developer.apple.com/documentation/usernotifications?language=objc


text:
Q: Copy text to clipboard from a specific data cell in a table. I am trying to use a JavaScript Function in my php file to copy data from specific cells in the table. Each row has a column for Project, Description and link to the project.
I want to be able to copy the the links to my clipboard on a button click.  However, no matter what row I click to copy the link, it only copies the last one.
My Javascript function only takes in the last ID variable that was displayed on the table, and not the ID of the variable i wanted to copy...
        while ($row = $result->fetch_assoc()) {
        $id = $row['id'];
                echo '

                        '.$row["pid"].':
'.$row["pname"].'
                        ' .$row["URLdescription"].'

                                <input type="text" value="'.$row['directionsURL'].'" id="'.$id.'">
                                <button onclick="myFunction()" name="copy"> Copy </button>

';
    };   //  END WHILE

^^ this is my while loop

^^here's my JavaScript function.

A: First of all, you can clean up that loop a bit:
while ($row = $result->fetch_assoc()) {
   extract($row);
   echo "

       $pid:
$pname
       $URLdescription

           <input type='text' value='$directionsURL'>
           <button class='copy'> Copy </button>

";
};   //  END WHILE

By wrapping the string in double quotes ", you can use variables inside it. We get those from calling extract() on the row array.
Next, we assign the click handlers to the buttons:
// get all buttons, turn NodeList into Array
const buttons = Array.prototype.slice.call(document.querySelectorAll(".copy"));

// click handler
const handleCopyClick = evt => {
  // grab the <input> via button's parent
  var input = evt.target.parentNode.querySelector('input');
  input.select();
  document.execCommand("copy");
  input.blur(); // remove selection
};

// finally, assign the function as handler for each button
buttons.forEach(button => {
  button.addEventListener('click', handleCopyClick);
});

Finally, if those <input>s are only <input>s because you need that for the clipboard functionality, you should probably use a hidden input and show the URL using a .

A: html
<input type="text" value="
<?php echo $row['account']; ?>" id="
<?php echo "myInput".$id ;?>">

<button class = "abc btn-sm btn-success" data-id1="
    <?php echo "myInput".$id ;?>">
            Copy

</button>

JS
  $(document).on('click', '.abc', function(){
    var id = $(this).data("id1");

    var copyText = document.getElementById(id);

    /* Select the text field */
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");

    /* Alert the copied text */
     alert("Copy: " + copyText.value);

});


text:
Q: Access Denied 403 forbidden I'am trying to encrypt password in sign up and its work, when i post sign up it saved in db and the password encrypted.
But the other api becomes access denied, for example when i try to login or get all user it give me forbidden 403 "access denied" what the wrong in my code?
this is my security class
package com.user.user.config.security;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
private final UserDetailsService userDetailsService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;

public static final String SIGN_UP_URL = "/registration";
public WebSecurityConfig(UserDetailsService userDetailsService,
BCryptPasswordEncoder bCryptPasswordEncoder) {
    this.userDetailsService = userDetailsService;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers
(HttpMethod.POST,
SIGN_UP_URL).permitAll().anyRequest().authenticated();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws
Exception {

auth.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
 }
}

and this is method in class services
public List<Users> getAllUsers() {
    List<Users> users = new ArrayList<>();
    userRepository.findAll()
            .forEach(users::add);
    return users;
}

 public void registration(Users users) {
    //
 users.setPassword(bCryptPasswordEncoder
.encode(users.getPassword()));
 users.setPassword(bCryptPasswordEncoder
.encode(users.getPassword()));
 userRepository.save(users);
 }

and i added this method in main class
 @Bean
  public BCryptPasswordEncoder bCryptPasswordEncoder() {
     return new BCryptPasswordEncoder();
  }

what i should to do to fix my problem ??

A: Its work when i Edit this function
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests().antMatchers( "/registration","/users","/login")
            .permitAll().anyRequest().authenticated();
}

but swagger not work what i should add to make it work?
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback.

Wed Dec 26 18:31:49 EET 2018
There was an unexpected error (type=Forbidden, status=403).
Access Denied


text:
Q: How do we combine multiple row values into single delimited row using Apache Drill How do we combine multiple row values into single row using Apache Drill?
Example :
Input:
a
b
c

Output:
a,b,c

In oracle or any other database we have listagg function  to achieve this. How do we achieve this using Apache Drill?

A: *

*Drill hasn't listagg function, since it is not a standard SQL ANSI
function. But you can create your own UDF for this purpose [1].

*Also you can contribute to Drill to create this function or similar PIVOT
function.

*A case statement along with aggregation might do the trick
[2].

*Also consider the similar approach like in Hive [3]

[1] https://drill.apache.org/docs/adding-custom-functions-to-drill-introduction/

[2] http://mail-archives.apache.org/mod_mbox/drill-user/201606.mbox/%3CCAAOiHjHyCajBDVerE9fFbgHUyQ+3wYAcX84ZaoUVbAyj0LpjBw@mail.gmail.com%3E

[3] http://hadoopmania.blogspot.com/2015/12/transposepivot-table-in-hive.html


text:
Q: Delete Hidden Rows In Excel 2010 I have data in excel 2010 where data in one cell is hidden which is not visible but when I copy and paste special that part the data appears in that cell.
How to view and delete that hidden data/rows from excel 2010.

A: If you don't mind a 2 step approach, you can do "Find and Select...", then "Go To Special..." and then pick "Visible Cells Only". This highlights only the visible cells, you can ctrl+C and paste it to another sheet. The shorthtcut for highlighting the visible cells is also:  "alt+;"
For the future you might want to move to Stackexchange forum for Excel related questions, as SOF is focused on coding.


text:
Q: Reactor vs thread My question is very simple in Java reactive programming
Thread Model:

*

*User A (Lets say Thread 1), sends GET request to application.

*Thread 1 will wait/blocked until it gets response from DB(IO request).

*Once response received, block is removed and Thread_1 returns response to user.

Reactive Programming model:

*

*User A (Lets say Thread 1), sends GET request to application.

*In reactive thread_1 will have one call back to run. So it won't wait/blocked.

Question:

*

*Who will run that call back? That is, which thread will run that call back?

*What is event loop mechanism in reactor? Provide example in layman terms.

*How to make use of multiple core CPU in reactive programming for NIO tasks?

A: Spring WebFlux has an event loop thread group which by default consists of as many threads as many CPU cores the machine running the application has. The callback is run by one of the threads from the group. If you use Spring WebFlux and WebClient (or any other reative data access library) then you get this multi-threaded behaviour out of the box.


text:
Q: TensorFlow: are all the basic operations in python overidden in Tensorflow I am new to tensorflow, and trying to write loss function(squared loss) using basic python operators, but it is not working. Can anyone tell me where I went wrong. Thanks in adavnce
n = x_data.shape[0]
L = (Y_pred-y)**2
loss = (1/n)*tf.reduce_sum(L)

I get loss=0.0 when I run the corresponding session
_ ,_m, _c, _l = session.run([optimizer,m,c,loss], feed_dict={x: x_data, y: y_data})

y is a placeholder
loss = tf.reduce_mean(tf.squared_difference(Y_pred,y))

this works just fine?
Complete Code:
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#downloading dataset
!wget -nv -O /resources/data/PierceCricketData.csv https://ibm.box.com/shared/static/reyjo1hk43m2x79nreywwfwcdd5yi8zu.csv

df = pd.read_csv("/resources/data/PierceCricketData.csv")
df.head()

%matplotlib inline

x_data, y_data = (df["Chirps"].values,df["Temp"].values)

plt.plot(x_data, y_data, 'ro')
# label the axis
plt.xlabel("# Chirps per 15 sec")
plt.ylabel("Temp in Farenhiet")

x = tf.placeholder(tf.float32, shape=x_data.shape)
y = tf.placeholder(tf.float32, shape=y_data.shape)
m = tf.Variable(3.0, name='m')
c = tf.Variable(2.0, name='c')

Y_pred = m*x+c

n = x_data.shape[0]
L = (Y_pred*nf-y*nf)**2
loss = (1/n)*tf.reduce_sum(L)

# loss = tf.reduce_mean(tf.squared_difference(Y_pred,y))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)

session = tf.Session()
session.run(tf.global_variables_initializer())

convergenceTolerance = 0.0001
previous_m = np.inf
previous_c = np.inf

steps = {}
steps['m'] = []
steps['c'] = []

losses=[]

for k in range(100000):
    _ ,_m, _c, _l = session.run([optimizer,m,c,loss], feed_dict={x: x_data, y: y_data})

    steps['m'].append(_m)
    steps['c'].append(_c)
    losses.append(_l)
    if (np.abs(previous_m - _m) <= convergenceTolerance) or (np.abs(previous_c - _c) <= convergenceTolerance):

        print "Finished by Convergence Criterion"
        print k
        print _l
        break
    previous_m = _m,
    previous_c = _c,
print(losses)

Output I get is [0.0, 0.0]
Why?

A: Here is the official TensorFlow implementation of mean_squared_error :
from tensorflow.python.framework import ops, math_ops
@tf_export("losses.mean_squared_error")
def mean_squared_error(labels, predictions, weights=1.0, scope=None,
                       loss_collection=ops.GraphKeys.LOSSES,
                       reduction=Reduction.SUM_BY_NONZERO_WEIGHTS):
    if labels is None:
        raise ValueError("labels must not be None.")
    if predictions is None:
        raise ValueError("predictions must not be None.")
    with ops.name_scope(scope, "mean_squared_error",(predictions, labels, weights)) as scope:
        predictions = math_ops.to_float(predictions)
        labels = math_ops.to_float(labels)
        predictions.get_shape().assert_is_compatible_with(labels.get_shape())
        losses = math_ops.squared_difference(predictions, labels)
        return compute_weighted_loss(losses, weights, scope, loss_collection, reduction=reduction)

As you can see in their source code you should make sure that the tensors have the same dtype. Hope that answers your question.


text:
Q: Android: I receive the same message several times with SOCKET.IO and SERVICE I want to use a socket in a service with AsyncTask. I put the socket initializing and callback socket.on in the onCreate(it is called only once) and I receive the same message several times. I don't know what can I do to receive message only once.In the service onCreate is called only once and I use thread in the service.  This is my code:
public class SocketService extends Service {

final String TAG = "SocketService";
JSONObject sendMessage;
JSONObject sendUserPhone;
protected Socket socket;
String msg;

SessionManager session;

Handler handler;

private final IBinder mBinder = new MyBinder();
public class MyBinder extends Binder {

    SocketService getService() {

        return SocketService.this;
    }
}

@Override
public void onCreate(){

    handler = new Handler();
     super.onCreate();

    Connection connection = new Connection();
    connection.execute();

    Identification identification = new Identification();
    identification.execute();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    session = new SessionManager(getApplicationContext());

    Bundle extras = intent.getExtras();

    if(extras!= null) {
        String emtr_phone =  session.getPhoneSession();
        String msg = extras.getString("message");
        String encPth = extras.getString("encodeImagePath");
        String dest1_phone =  extras.getString("dest1 phone");
        String dest2_phone =  extras.getString("dest2 phone");
        String dest3_phone =  extras.getString("dest3 phone");
        String dest4_phone =  extras.getString("dest4 phone");
        String dest5_phone =  extras.getString("dest5 phone");
        String dest6_phone =  extras.getString("dest6 phone");
        String dest7_phone =  extras.getString("dest7 phone");
        String dest8_phone =  extras.getString("dest8 phone");
        String dest9_phone =  extras.getString("dest9 phone");
        String dest10_phone =  extras.getString("dest10 phone");
        String dest11_phone =  extras.getString("dest11 phone");
        String dest12_phone =  extras.getString("dest12 phone");
        String dest13_phone =  extras.getString("dest13 phone");
        String dest14_phone =  extras.getString("dest14 phone");
        String dest15_phone =  extras.getString("dest15 phone");

          Send send = new Send();
        send.execute(emtr_phone, msg, encPth, dest1_phone,dest2_phone,dest3_phone, dest4_phone, dest5_phone, dest6_phone,dest7_phone,dest8_phone, dest9_phone, dest10_phone, dest11_phone,dest12_phone, dest13_phone, dest14_phone, dest15_phone);

    }

    return Service.START_NOT_STICKY;

}

private String encodeImage(String path) { // Bitmap bm

    File imagefile = new File(path);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

    Bitmap bm = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);

    return encImage;
}

@Override
public IBinder onBind(Intent intent) {

    // TODO: Return the communication channel to the service.
    //  return mBinder;
    //throw new UnsupportedOperationException("Not yet implemented");
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
   // socket.disconnect();
       Disconnection disconnection = new Disconnection();
     disconnection.execute();
}

class Connection extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... voids) {
        try {

            //       socket = IO.socket("http://192.168.18.1:8080/");

            socket = IO.socket("http://ec2-52-17-48-90.eu-west-1.compute.amazonaws.com:8080"); // http://169.254.110.170:5000/

        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        socket.connect();

        Log.d(TAG, "onCreate");

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                Log.d(getClass().getCanonicalName(), "Connected to server");
            }

        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... arg0) {
                Log.d(getClass().getCanonicalName(), "Disconnected from server");
            }

        });

        socket.on("message", new Emitter.Listener() {
            @Override
            public void call(Object... args) {

                JSONObject data = (JSONObject) args[0];
                Log.d(TAG, "Handling friendcall");
                //    String msg;
                //                          String imageText = null;

                try {
                    if (data.getString("image") != null) {

                        String message = data.getString("text").toString();
                        String imageText = data.getString("image");

                        Intent in = new Intent();
                        Bundle extras = new Bundle();
                        extras.putString("MsgWithImag", message);
                        extras.putString("Imag", imageText);
                        in.putExtras(extras);
                        in.setAction("NOW");

                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in);
                        Log.d(TAG, "Call from : " + message + imageText);
                    }

                } catch (JSONException e) {
                    //  Log.d(TAG, "friend call object cannot be parsed");
                    e.printStackTrace();
                }

                try {
                    if (data.getString("sansPhoto") != null) {

                        String message = data.getString("text").toString();

                        Intent in = new Intent();
                        in.putExtra("Msg", message);
                        in.setAction("NOW");

                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in);

                    }
                } catch (JSONException e) {
                    //  Log.d(TAG, "friend call object cannot be parsed");
                    e.printStackTrace();
                }
            }
        });

        Log.d(TAG, "onStartCommand. Socket should be up");

        return null;
    }
}

class Disconnection extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... voids) {

        socket.disconnect();

        return null;
    }
}

class Identification extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        // Session class instance
        SessionManager session = new SessionManager(getApplicationContext());

        String phone_session = session.getPhoneSession();
        sendUserPhone = new JSONObject();
        try {
            sendUserPhone.put("nbrphone", phone_session);
            socket.emit("adduser", sendUserPhone);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

}

class Receive extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {

        Log.d(TAG, "onCreate");

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                Log.d(getClass().getCanonicalName(), "Connected to server");
            }

        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... arg0) {
                Log.d(getClass().getCanonicalName(), "Disconnected from server");
            }

        });

        socket.on("message", new Emitter.Listener() {
            @Override
            public void call(Object... args) {

                JSONObject data = (JSONObject) args[0];
                Log.d(TAG, "Handling friendcall");
                //    String msg;
                //                          String imageText = null;

                try {
                    if (data.getString("image") != null) {

                        String message = data.getString("text").toString();
                        String imageText = data.getString("image");

                        Intent in = new Intent();
                        Bundle extras = new Bundle();
                        extras.putString("MsgWithImag", message);
                        extras.putString("Imag", imageText);
                        in.putExtras(extras);
                        in.setAction("NOW");

                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in);
                        Log.d(TAG, "Call from : " + message + imageText);
                    }

                } catch (JSONException e) {
                    //  Log.d(TAG, "friend call object cannot be parsed");
                    e.printStackTrace();
                }

                try {
                    if (data.getString("sansPhoto") != null) {

                        String message = data.getString("text").toString();

                        Intent in = new Intent();
                        in.putExtra("Msg", message);
                        in.setAction("NOW");

                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in);

                    }
                } catch (JSONException e) {
                    //  Log.d(TAG, "friend call object cannot be parsed");
                    e.printStackTrace();
                }
            }
        });

        Log.d(TAG, "onStartCommand. Socket should be up");

        return null;
    }
}

class Send extends AsyncTask<Object, Void, Void> {

    String emetr_phone, msg, encPth, sansPhoto, dest1_phone, dest2_phone, dest3_phone, dest4_phone, dest5_phone, dest6_phone, dest7_phone, dest8_phone, dest9_phone, dest10_phone, dest11_phone, dest12_phone, dest13_phone, dest14_phone, dest15_phone;

    @Override
    protected Void doInBackground(Object... params) {

        emetr_phone = (String) params[0];
        msg = (String) params[1];
        encPth = (String) params[2];
        sansPhoto = "g";
        dest1_phone = SupprCaractDest((String) params[3]);
        dest2_phone = SupprCaractDest((String) params[4]);
        dest3_phone = SupprCaractDest((String) params[5]);
        dest4_phone = SupprCaractDest((String) params[6]);
        dest5_phone = SupprCaractDest((String) params[7]);
        dest6_phone = SupprCaractDest((String) params[8]);
        dest7_phone = SupprCaractDest((String) params[9]);
        dest8_phone = SupprCaractDest((String) params[10]);
        dest9_phone = SupprCaractDest((String) params[11]);
        dest10_phone = SupprCaractDest((String) params[12]);
        dest11_phone = SupprCaractDest((String) params[13]);
        dest12_phone = SupprCaractDest((String) params[14]);
        dest13_phone = SupprCaractDest((String) params[15]);
        dest14_phone = SupprCaractDest((String) params[16]);
        dest15_phone = SupprCaractDest((String) params[17]);

        sendMessage = new JSONObject();

        //  String phone_emmet = SupprCaractEmmet(emetr_phone);
        try {

            sendMessage.put("emetr_phone", emetr_phone);

            if (msg != null) {

                sendMessage.put("text", msg);

            }

            if (encPth != null) {  //ImageBmp

                sendMessage.put("image", encodeImage(encPth));
                //  sendMessage.put("image", encodeImage(ImageBmp));

            } else {
                sendMessage.put("sansPhoto", sansPhoto);
            }

            sendMessage.put("dest1_phone", dest1_phone);
            sendMessage.put("dest2_phone", dest2_phone);
            sendMessage.put("dest3_phone", dest3_phone);
            sendMessage.put("dest4_phone", dest4_phone);
            sendMessage.put("dest5_phone", dest5_phone);
            sendMessage.put("dest6_phone", dest6_phone);
            sendMessage.put("dest7_phone", dest7_phone);
            sendMessage.put("dest8_phone", dest8_phone);
            sendMessage.put("dest9_phone", dest9_phone);
            sendMessage.put("dest10_phone", dest10_phone);
            sendMessage.put("dest11_phone", dest11_phone);
            sendMessage.put("dest12_phone", dest12_phone);
            sendMessage.put("dest13_phone", dest13_phone);
            sendMessage.put("dest14_phone", dest14_phone);
            sendMessage.put("dest15_phone", dest15_phone);

            socket.emit("message", sendMessage);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}

public String SupprCaractDest(String dest_phone) {
    String carAsup = "+";
    dest_phone = dest_phone.replace(carAsup, "");

    return dest_phone;
}

}


text:
Q: Angular reactive form filter list of checkboxes I have a list of checkboxes and an input field.
The checkboxes each have a name.
I want to filter the list by name, using the value from the input field.
The expected result is that only those checkboxes are visible, which name contains the text typed in the input field.
This is super trivial in AngularJS, and it's also easy to do with Angular's template-driven forms.
But I need to do it in a reactive form.
How on Earth do I do that?
Example with code: https://stackblitz.com/edit/angular-checkbox-list-filter

A: You can either make your list of checkboxes an Observable and change the value of the obsverable every time the user searches. or you can store two copies. the first would hold the master list of checkboxes, and the second would hold the filtered results based on the search term.
Made a few adjustments to get you started based on approach 2. seen here

*

*I adjusted the HTML to loop through the "filtered_data" variable.

*this variable gets updated in the form control value changes.  using
a regexp "case insensitive' pattern to match against the name of each
box

*I also added logic so all controls are reset when you clear out
the input field.

hopefully that is enough to get you started.
If you need to make this an observable, reach out.

A: Create one more name form control in form array. With that you will know that which box is checked or not by name.
Angular Code with checkboxes


text:
Q: How to properly change target framework to .NET 4.0 I built an application with target framework .NET 4.6 using MVC 5 and Entity Framework 6 using Visual Studio 2017 on my Windows 7 machine. I'm now being told that I should have built the application to target .NET 4.0 because the production environment only has 4.0 installed. So I changed the target framework to 4.0 but now the application will not build on my machine.
I'm guessing I also need to downgrade MVC and EF. How is the proper way of doing this?
And which versions of MVC and EF should I install?
Do I need to make any manual changes to web.config?

A: There is no "proper" way, you have 3 options, in my favorite order:

*

*Update the server and install the latest .net version. (at the time .net 4.6). Make sure used libraries are up to date and not end of life.

*Start over in a new project and make sure you target version 4.0: you can copy most of your source files. You'll probably get some compiler errors, but usually they are easily fixed. This way you'll have the benefit that the used template matches the framework and packages version(s).

*Re-target the used framework in the project properties and replace the packages which are installed and hope for the best (sometimes you need other packages). Hopefully you used the package manager to install those packages. Maybe the update-packages command helps, but be sure to backup your project first. Some packages become obsolete after time, some are renamed. This is what will cause issues. Also, some of the Methods/API calls will be different, so some rework will be needed.

As for the rest of your questions:

I'm guessing I also need to downgrade MVC and EF. How is the proper way of doing this?

Use the nuget package manager

And which versions of MVC and EF should I install?

The nuget package manager will fix this for you.

Do I need to make any manual changes to web.config?

Sometimes: yes.


text:
Q: Bootstrap collapse list hiding on bottom of box When I click on the last listed category, it opens the bottom of the box and gets hide. I want it to scroll up automatically on click.
here is my code:
When I click on the last listed category, it opens the bottom of the box and gets hide. I want it to scroll up automatically on click.

.browse-category-seeker {
    float: right;
    width: 100%;
    padding: 0;
}
 .panel-body a {
    display: inline-block;
    width: 100%;
    padding: 2px 0;
    color: #878689;
    cursor: pointer;
}
.right-bottom-db .panel-body {
    padding: 0px 15px;
    padding-left: 40px;
    max-height: 120px;
    overflow: auto;
    margin-right: 10px;
}
.right-bottom-db .panel-title a {
    color: #818181 !important;
    text-decoration: none !important;
    background: rgba(226, 226, 227, 0.3);
}
.panel-title {
    margin-top: 0;
    margin-bottom: 0;
    font-size: 16px;
    color: inherit;
}
.right-bottom-db .panel-default > .panel-heading {
    background: none;
    border: none;
}
.right-bottom-db .panel.panel-default {
    border: none;
}
 h4.browse-title-c {
    border-bottom: none;
    font-size: 14px;
    background: #f6f6f6;
    border-bottom: 2px solid #fff;
}
 .right-bottom-db.services-list-main {
    border: none;
    box-shadow: 0px 1px 21px -9px #504e4e;
}
.right-bottom-db.services-list-main {
    margin-top: 20px;
    max-height: 350px;
    overflow: auto !important;
        max-width: 300px;
}
.services-list-main {
    width: 100%;
    border: 2px solid #d5cbf8;
    margin-top: -2px;
    border-radius: 10px;
    padding-bottom: 10px;
}
.right-bottom-db .panel-title > a, .panel-title > small, .panel-title > .small, .panel-title > small > a, .panel-title > .small > a {
    color: inherit;
    padding: 10px 15px;
    display: inline-block;
    width: 100%;
    font-size: 14px;
}
h4.browse-title-c {
    padding: 10px 15px;
    color: #818181 !important;
    border-bottom: 2px solid #e2e2e3;
    font-size: 14px;
    margin: 0;
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    background: #fff;
    z-index: 1;
}

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

Browse by category

          Art

                       Art Lessons
                           Artwork
                           Fashion
                           Graphic Design
                           Interior Design
                           Landscape Painting
                           Logo Design
                           Marketing Materials Design
                           Painting
                           Portrait Painting
                           Tattoo
                           Tattoo Removal
                           Home Inspection

          Automotive

                       Auto Detailing
                           Auto Painting
                           Body Work
                           Car Wash
                           Chauffeur Services
                           Dent Repair
                           Driving Lessons
                           Mechanic
                           Oil Change
                           Plug-in Vehicle Charger
                           Rentals
                           Sales
                           Smog Check
                           Tire Repair
                           Towing
                           Transportation

          Beauty

                       Eyebrows/Lashes
                           Facial Treatment
                           Fashion
                           Foot Care
                           Hair
                           Jewelry
                           Makeup
                           Manicure
                           Massage
                           Modeling
                           Nails
                           Pedicure
                           Skin Care
                           Spa
                           Tanning
                           Tattoos
                           Waxing & Hair Removal

          Delivery

                       Bulk Delivery
                           Courier
                           Food Delivery
                           Luggage Delivery
                           Shopping

          Education

                       Academic Counseling
                           Academic Preparation
                           After-school Care
                           Assistive Teaching
                           Child Care
                           Coding Workshop
                           Communications Seminars
                           Cooking Lessons
                           Design Class
                           Digital Education
                           Early Childhood
                           Financial Management
                           Group Study
                           Health Education/Workshops
                           Home Schooling
                           Language Lessons
                           Meeting Room Space
                           Music Lessons
                           Post Graduate Advisement
                           Safety Education
                           SAT/MCAT Lessons
                           Scholarship/Financial Aid Advisement
                           Student Aid
                           Student Transportation
                           Teaching Certification
                           Technology Education
                           Tutoring
                           Writing Workshops

          Electronics

                       Computer Sales
                           Computer Training
                           Electronic Assembly
                           Gadget Repair & Services
                           Home Stereo/Videos
                           Software Training
                           Virus/Malware Removal

          Events

                       Bartender
                           Cake Decoration
                           Catering
                           Chefs
                           Dancers
                           DJ's
                           Entertainment
                           Event Decoration
                           Event Photography
                           Event Planner
                           Event Transportation
                           Face Paint
                           Fashion
                           Florist
                           Live Music
                           Locations
                           Makeup
                           Party Bus
                           Photo Booth
                           Tables and Chairs
                           Wedding Officiant

          Family

                       Assistant Services
                           Babysitter
                           Child Care
                           Counseling
                           Family Care
                           Family Cook
                           Family Doctor
                           Family Portraits
                           Geriatric Services
                           Home Care
                           Home Security
                           House Sitting
                           Law Attorney
                           Pet Sitter
                           Small Pet Care

When we click on the last listed category, it opens the bottom of the box and gets hide. I want it to scroll up automatically on click.


text:
Q: A problem about positive-define Suppose $A$ is a real symmetric matrix, and let $h$ be the maximal eigenvalue of $A$.
Claim: $hE-A$ is positive-define, where E is the identity matrix.
I know that if $x$ is a eigenvector of $A$, then $x^T(hE-A)x \ge 0.$
But I have no idea that how to prove the case when $x$ is not a eigenvector.
Can someone give me a hint or a solution to this problem? Thanks a lot.

A: If you look at the characteristic polynomial of $hE-A$, you have
$$\det(hE-A-\lambda E)=\det((h-\lambda )E-A).$$ So the eigenvalues of $hE-A$ are of the form $h-\lambda$, where $\lambda$ is an eigenvalue of $A$.
Thus $hE-A$ is symmetric and all its eigenvalues are nonnegative.

A: Since $A\in\mathbb{R}^{n\times n}$ is symmetric, there exists a orthogonal basis of eigenvectors of $A$ so every vector $x\in\mathbb{R}^n$ can be written as the linear combination of eigenvectors of $A$. This follows from the spectral theorem for symmetric matrices.


text:
Q: Tensorflow with GPU speeds Is there anything that affects speed other than RAM? I'm running an experiment on two different laptops, one that allocates just 300MB and another that allocates 4GB and somehow the 300MB is running faster despite being allocated less than 1/10th of the memory.
Are there potentially allocation issues for different types of nvidia cards? It's the same LSTM for both.

A: Yes, Tensorflow is affected by the clock speed of your CPU or the characteristics of your GPU if you are running tensorflow-gpu (which parallelizes your code to run much, much faster).  Everything from the single-core performance of your GPU to its video RAM can affect your NN training speed, though it can be nonlinear -- for example, high bandwidth GPUs may not have much of a performance increase over low bandwidth GPUs on a small feedforward network.  Unless you are running multiple GPUs and if you're not trying to allocate memory to fill more than 80% of your VRam (I find usually the top 20% is full), I don't know why this would be a memory allocation issue -- lastly, I know it's been a while, so if you're still having the issue, maybe update your CUDA drivers.


text:
Q: Node Login Error: Cannot GET /users/auth/login i am getting this error while trying to login on my Node Applications:
Cannot GET /users/auth/login
after setting my view, controller and routes appropriately.
please help guys>
see my controller file below

const bcrypt = require('bcrypt')
const User = require('../database/models/User')

module.exports = (req, res) => {
    const {email, password} = req.body;
    //try to find user
    User.findOne({ email }, (error, user) => {
        if (user) {
        bcrypt.compare(password, user.password, (error, same) => {
            if (same) {
                res.redirect('/')
            } else {
                res.redirect('auth/login')
                }
            })
        } else {
            return res.redirect('/auth/login')
        }
    })

};

and my Html below

              <form action="/users/login" method="POST" enctype="multipart/form-data">

likewise my route:
const loginUserController = require('./controllers/loginUser')
app.get("/auth/login", loginController);
app.post("/users/login", loginUserController);

and i still get this as my output when this login button is clicked>
enter image description here
and i don't know what i am still getting wrong as i am not supposed to be getting that callback link

A: Be careful while using res.redirect you had put auth/login instead of /auth/login
const bcrypt = require("bcrypt");
const User = require("../database/models/User");

module.exports = (req, res) => {
const { email, password } = req.body;
//try to find user
User.findOne({ email }, (error, user) => {
    if (user) {
    bcrypt.compare(password, user.password, (error, same) => {
        if (same) {
        res.redirect("/");
        } else {
        res.redirect("/auth/login");
        }
    });
    } else {
    return res.redirect("/auth/login");
    }
});
};

This should fix your problem, let me know if any problems


text:
Q: Working with a sql database on SQL Server 2012 and work with the same database on SQL Server Express 2012 is the same? I have this question about the SQL Server and SQL Server Express.
In my client machine, the database that he's using is SQL Server 2012 and in my machine i have SQL Server 2005.. so i want to install another instance and a friend told me that i dont need to install the SQL Server 2012 Standard (the one that they have) and with the SQL Server 2012 Express will work.. is that ok?
I really don't know the real difference in working with SQL Server Express 2012 and SQL Server Standard 2012 (with the same database).

A: On of the major differences is that with express you not be able to back ups over the network.  Local backups only.  When I do back ups from the SqlExpress Server Manager Studio it doesn't recognize mounted drives.  Check out this for a more formal approach to your question
[http://msdn.microsoft.com/en-us/library/cc645993.aspx][1]

A: Check through this document:
Features supported by the editions of SQL Server 2012
You will soon be able to see if there are any features that you are using in standard that are not available in express.