text:
Q: Identify which drives belong to a specific HP RAID 5 Group A total of 32 drives were removed from x4 decommissioned HP DL380 G6 servers (eight per server).
The setup of the eight drives per host was into two RAID Groups:
RAID 1 = SLOT 1, 2 = ESXi OS
RAID 5 = SLOT 3, 4, 5, 6, 7, 8 = VMFS Vol (hosting virtual machines)
Unfortunately there is some data that was not backed up prior to the removal of the drives, and now they are all in a pile mixed up.
What is the best way to put these drive back into the hosts without damaging the RAID groups the disks belong to?
Is there a tool that can be used to ready the RAID membership identifier on each drive?  Not sure if ACU supports this!
TIA
Danny

A: Probably the safest thing to do would be to send them all to a company like Kroll OnTrack. They understand the on-disk format of HP's RAID. Since all of the drives are operational, this probably wouldn't be too expensive but you'll have to talk to the right rep to get them to understand what you want: identify and group, but do not recover.
If you have access to a DAS shelf like an MSA 2000, you could load all of the drives in and let the controller auto-detect the existing RAID configuration of the drives. You would need multiple shelves all connected to a single controller to get this to work easily, although you could probably do it with a single shelf and a bit of musical hard drives.

A: The controller will erase the disks if you do this the wrong way...
Since HP Smart Array controllers store the array metadata on the actual drives, you can often move or relocate HP disk sets. However, there's some tolerance for drive displacement (slot reordering, etc).
So if the drives are moved together, the RAID is usaully intact. If you start doing that with multiple arrays with on-disk data... yeah. Not pretty.

An example from this weekend, trying to build a test environment from retired disks:


text:
Q: Simple front end for scientific code Currently I have a program where I pass some parameters and files to the main executable through the command line
e.g. Ill run a simulation through

./exe param1 param2 param3 .. etc

However to make this code more user friendly, I would like to have a system where you can load parameter files, and run a simulation on them, which seems to be a common with scientific code
Now I would like to move to a system where I can run something like

./exe simulation.params

I would think to create a class of all my parameters
class Parameter {
    //objects that are parameters
}

and then pass this around inside my main program, with something like a map from the variables in the file to the variables in the simulation. The main program just loops over each line in the input file, reading info and initialising this class.
Also it would be nice to either run the program in an interactive shell or just pass the file. Maybe just check if given a file (with some necessary checks) then runs, or just brings up an interactive session,
roughly
int main()
{
   if(argc== 1)
   {
    // run simulation on file
   }
   else
   {
     //bring up some menu
   }

}

Are these good practice? Most of the parameters are numbers, is there a recommended format? Are there any other useful libraries that help implement things like this? Would it be better to create the front end in something like python?

A: I would suggest you to introduce parameter names, one of which could be file name with settings. Also it would be better if you would not stick to only file-based or arg-based settings, but will allow file settings to be overridden by command line arguments. Basically you initialization would look like this:

*

*Process command line arguments

*Load configuration from file if present

*Apply configuration values from command line

There is a nice function getopt, defined in POSIX standard (which means - available in standard library). GNU provides extension called getopt_long, which allows you to have also "long" options like "--param". More information on getopt/getopt_long with examples available here

redpajama_set_name: RedPajamaStackExchange


text:
Q: SingleletterItalics placement I am trying to render a text on a graphics.
legend = Graphics[{
{White,
 Style[Text["laser pol.", Offset[{120, 50}]], FontSize -> 42,
  SingleLetterItalics -> False]},
{White,
 Style[Text["\!\(\*SuperscriptBox[\(H\), \(*\)]\)(N=3)",
   Offset[{285, 440}]], FontSize -> 42,
  SingleLetterItalics -> False]},
{White,
 Style[Text[
   "\!\(\*SubsuperscriptBox[\(H\), \(2\), \(+\)]\)(v=5-6)",
   Offset[{285, 525}]], FontSize -> 42,
  SingleLetterItalics -> False]}}];

I expected the H (in H2 and H+) to be straight but they render in italic. Am I using the directive in a wrong way?

A: Put the Style inside of the Text.
Text[Style[..., SingleLetterItalics -> False], ...]


text:
Q: how to display an array in ui-grid? I'm developping a hybride application i have an array with this structure
controller.js
 function getReference(fam, souFam, db, trans, $q) {

  var arr = [];
  var deferred = $q.defer();
  var query = null;

  if (trans == "fr") {
    query = "SELECT Reference + '_' + CAST(Durete AS TEXT) AS Reference, Charge, Fleche, Caoutchouc, Coerig, Epais, Durete, Flechemax FROM SUSPENSIONS WHERE Famille = ? AND Fixation = ? ORDER BY Charge";

  } else {
    query = "SELECT Reference + '_' + CAST(Durete AS TEXT) AS Reference, Charge, Fleche, Caoutchouc, Coerig, Epais, Durete, Flechemax FROM SUSPENSIONS WHERE Famille = ? AND Fixang = ? ORDER BY Charge";

  }

  db.executeSql(query, [fam, souFam], function(res) {
      for (var i = 0; i < res.rows.length; i++) {
        arr.push({
          {
          'Reference': res.rows.item(i).Reference,
          'Nominal load (daN)': res.rows.item(i).Charge,
          'Nominal static deflection (mm)': res.rows.item(i).Fleche
        }
        });
      }
      deferred.resolve(arr);
    },
    function(error) {
      console.error(error.message);
      console.log('SELECT error: ÷' + error.message);
    },
    function() {
      console.log('transaction ok');
    });

  return deferred.promise;
}

$scope.gridOptions= getReference(par1, par5,par3,par4,par5);

HTML
 <div ui-grid=" {data: gridOptions}" class="grid"> </div>

but in my ui-grid only 'reference' column data are displayed and for the others only header is displayed.
only


text:
Q: Sub-Query returned more than one value I inherited this SQL 7 Code that has run fine for years here. But at another location, in another country, they get this error: "Sub-Query returned more than one value".
SELECT
lc.LoadNum,
lc.ShipFromState,
lc.ShipToNum,
(SELECT ShippedStatus = CASE MAX(lc.Status)
WHEN 'Shipped' THEN 'LOADED'
WHEN 'Picked' THEN 'PICK UP'
WHEN 'Cancel' THEN 'PICK UP'
WHEN 'WtLoad' THEN 'PICK UP'
WHEN 'Released' THEN 'PICK UP'
WHEN 'Schedule' THEN 'PICK UP'
WHEN 'Loaded' THEN 'PICK UP'
WHEN 'WtPick' THEN 'PICK UP'
WHEN 'Picking' THEN 'PICK UP'
END) AS ShippedStatus,
tp.Description AS PlantDescription,
tp.Address,
tp.City,
tp.State,
tp.ZipCode,
sv.Description AS ShipViaDescription
FROM
vwLoadContents lc (nolock)
JOIN tblShipVia sv (nolock) ON lc.ShipVia = sv.Code
JOIN tblShipToCust sc (nolock) ON lc.ShipToNum = sc.ShipToNum
JOIN tblPlant tp (nolock) ON lc.ShipFromState = tp.Code
GROUP BY
lc.LoadNum,
lc.ShipFromState,
lc.ShipToNum,
tp.Description,
tp.Address,
tp.City,
tp.State,
tp.ZipCode,
sv.Description

How can the MAX(lc.Status) function be returning more than ONE value?
If I remove the entire "SELECT ShippedStatus = Case Max(lc.Status ...) as ShippedStatus"  Sub-Query then the error goes away!
I replaced the Sub-Query with this line of SQL code ...
MAX(Case lc.Status When 'Shipped' Then 'LOADED' else 'PICK UP' End) as ShippedStatus
The new line of SQL code "appears to" work at all locations (all databases) even though the MAX() function is now "outside the CASE" instead of "inside the CASE".
So, how does the original SQL script allow the MAX() function to return multiple values?
Thank You!


text:
Q: How can I do Null and empty check of arraylist using dw() function in mule? I tried the following way,
[dw('sizeOf payload.data.accts')>0] but hthis would just check if arraylist  is empty or not .So i need a help  to how do I null check on "accts" arraylist using dw() function.
I want both null and empty check in dw() function of mule so that I can use it in my choice router to proceed my flow.

A: I would do something like this in the choice router:
In the 'When' column:
#[payload.data.accts != empty]
In the Route Message to column:
yourFlow

A: Please refer How to Check null condition in Data weaver : Mule.
Should be applicable to Json as well - try out
Example:(payload.Records.*RecordsEntries.*RecordEntry default [])

A: You can combine default with sizeOf to achieve this:
#[dw('(sizeOf (payload.data.accts default [])) == 0']

We can break this down into two expressions. The first, payload.data.accts default [] will return an empty list if payload, payload.data or payload.data.accts is null. Otherwise it will just return whatever the value of payload.data.accts is.
The second, (sizeOf <expression>) == 0 will check if the list returned from the above expression is empty or not.


text:
Q: How do I react on user input during reactor.run() in twisted python? Im currently working on a client/server multi player cardgame solution in python using twisted libraries. Im pretty new to python, and this game actually is a proof of concept to myself, as i just want to show myself, that i can do such stuff. but im stuck ~8 hours on this problem now, and i need some advice.
following lines and the following description should let you know, what im trying to do here:
Description:

*

*Server ist started

*as soon as the demo client connects, server does some stuff in the background (registering, creating pile of cards for the player)

*the demo client now starts() the cardgame

*remote_start is called and calls function hoststart if its started by certain player (to be implemented)

*the cards from the players pile are sent to the client and print out

*the client should now be able to press a number (number of card), which then should be sent back to the server to print out the number (only printing doesnt make sense, but its the only thing that came to my mind right now :P)
now here starts the problem:

*

*as soon as the reactor.run() is started, it seems as whole script is executed (user registered, game started) and the input at the client is done after the whole script is executed. so the sending of the entered number is done, before the number is entered within the input function and therefore returns 0 to the server.

I think this is very complex to explain, so please ask any questions which may come up.
How can i resolve this problem?
Can i somehow make the server wait an amount of seconds so that the client is able to input the Number during that time?
Do i need to open a new connection which allways opens if have to wait for input on the client?

client.py:
PICK = 0

factory = pb.PBClientFactory()
reactor.connectTCP("localhost", PORT, factory)
def1 = factory.getRootObject()
def1.addCallbacks(got_obj1, err_obj1)
ret = reactor.run()

def got_obj1(obj1):
    def2 = obj1.callRemote("register","User A")
    def2 = obj1.callRemote("start","User A")
    def2.addCallback(show)
    obj1.callRemote("pick",PICK)  # Problem

def show(*var)
    data_string = json.dumps(var)
    decoded = json.loads(data_string)
    for card in decoded[0]:
        print(str(card['name'])
    PICK = Input("Which card do you want to pick?") # Problem

server.py:
print("Starting server on ", PORT)
rpc = RPCs()
reactor.listenTCP(PORT, pb.PBServerFactory(rpc))
reactor.run()

class RPCs(pb.Root):
     sessions = []
     def remote_pick(self,pick):
         print("picked: ", pick)
     def remote_start(self, username):
         for session in self.sessions :
             if (session.getName() == username):
                 ret = self.hoststart(username)
                 return ret
     def hoststart(self,username):
         pile4client = []
         card4pile {}
         for session in self.sessions:
             if (session.getName() == username):
                 ret = session.showpile(0)
            for card in ret:
                card4pile = { "name" : card.getName()}
                pile4client .append(card4pile)
            return pile4client
class Session():
     piles = []
     def showpile(self, num):
         return self.piles[num]

A: Pass obj1 to show and call its callRemote in show.  Something like this:
def got_obj1(obj1):
   ...
   def2.addCallback(show, obj1)

def show(value, obj1):
   ...
   PICK = Input("Which card do you want to pick?")
   obj1.callRemote("pick",PICK)


text:
Q: Qgis node tool not working due to unknown reasons my node tool stopped working appropriately. More precisely, I can select nodes just by selection window, not each node individually. Also, I can't move the nodes.
I attached a print screen with the snapping settings, in case the problem might be there.


text:
Q: Unable to download data from rubygems I don't know what this error means when trying to run gem update --system;
{9:29}[2.2.3]~ ➭ gem update --system
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)

I also get a similar error when trying;
{9:30}[2.2.3]~ ➭ gem install tunnelss
ERROR:  Could not find a valid gem 'tunnelss' (>= 0), here is why:
Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)

FYI - I can visit https://api.rubygems.org/specs.4.8.gz in the browser and it will start downloading so that's not the problem.
Don't really know what to try. Can anyone advise?

A: This is a known issue, see https://gist.github.com/luislavena/f064211759ee0f806c88 and/or https://gist.github.com/fnichol/867550 for solving it.
I stumbled over the same issue yesterday when I installed Ruby on Windows. So, personally, this https://superdevresources.com/ssl-error-ruby-gems-windows/ worked for me. The other guide mentioned a non-existent URL to the cacert.pem


text:
Q: Write Google Forms Answer to Sheet as soon as it is entered I have a Google Form with some questions for which the user has to choose an answer from dropdown. The answers in the dropdown lists are fed from a Google Sheet.
Because I would like those dropdowns to be dynamic, I was wondering if there was any way in which I could instantly get the answer given by the user on a dropdown written to a Google Sheet. That way, I could change what came up in the next dropdown list.

A: That it's not possible with Google Forms as there is no way to add a custom script to Google Forms respondent view.
Related

*

*How to repeat a section in Google Forms before submit?

*Google Forms Onclick Submit


text:
Q: Process.Start in BackgroundWorker I'm trying to start a new process when BackgroundWorker IsBusy.
Global.asax:
BackgroundWorker thread;
protected void Application_Start(object sender, EventArgs e)
{
     StartThread();
}
protected void StartThread()
{
     thread = new BackgroundWorker();
     thread.DoWork += new DoWorkEventHandler(DoWork);
     thread.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
     Process p = new Process();
     p.StartInfo.FileName = "exe.exe";
     p.Start();
     p.WaitForExit(10000);
}

But nothing was happened. Also there was no exceptions raised.
I've inserted a breakpoint at the p.Start() line. All works fine except that the process didn't started.
What could be the reason of this?
Also I've tried to use Thread class for this but I've got the same result.

A: You are starting a new thread from inside the BackgroundWorker's DoWork delegate. When you fire off the DoWork event, why not start the new process from the UI thread. This would be much better in terms of thread safty and concurrency - this could also be the root cause of you problem.


text:
Q: having trouble sending json data via http.get() request in flutter I am working on a flutter project, and I am trying to call a django based web-api, to retrieve posts that are relevant to a user in some way. Now my web-api works fine when I test it in outside of flutter app.
I am able to sign-in, sign-up, thus I have no problems with my connection.
there is an endpoint

.com/api/allBlogs/

this endpoint expects json data, {"uid": any_integer}
Now my question is

how can I call http.get() request in flutter and send uid along with
the request.

This is my code where I am trying to hit that endpoint to retrieve blogs.
  Future<void> loadPosts(String uid) async {
    final queryParameters = {
      'uid': uid,
    };
    final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
    final url = Uri.https(
        'beautyexperience.herokuapp.com', 'api/allBlogs/', queryParameters);
    try {
      List<Post> _tempPosts = [];
      final response = await http
          .get(
        url,
        headers: headers,
      )
          .then(
        (value) {
             .
             .
             .
    } catch (error) {
      print('**************************************************************');
      print('error: $error');
      throw (error);
    }
    //return [..._posts];
  }

This is the error message I am getting
error
W/DynamiteModule(10228): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(10228): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(10228): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/flutter (10228): inside pickup_layout > build > streamBuilder > builder: line 25
I/flutter (10228): **************************************************************
I/flutter (10228): error: FormatException: Unexpected character (at character 1)
I/flutter (10228): <!DOCTYPE html>
I/flutter (10228): ^
E/flutter (10228): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (10228): <!DOCTYPE html>
E/flutter (10228): ^
E/flutter (10228):
E/flutter (10228): #0      Posts.loadPosts
package:fyp_test/…/postsFolder/Posts.dart:110
E/flutter (10228): <asynchronous suspension>
E/flutter (10228):

update
This is what is returned in the body of the response, i.e. value.body
I/flutter (11594): extractedData: <!DOCTYPE html>
I/flutter (11594): <html lang="en">
I/flutter (11594): <head>
I/flutter (11594):   <meta http-equiv="content-type" content="text/html; charset=utf-8">
I/flutter (11594):   <meta name="robots" content="NONE,NOARCHIVE">
I/flutter (11594):   <title>KeyError
I/flutter (11594):           at /api/allBlogs/</title>
I/flutter (11594):   <style type="text/css">
I/flutter (11594):     html * { padding:0; margin:0; }
I/flutter (11594):     body * { padding:10px 20px; }
I/flutter (11594):     body * * { padding:0; }
I/flutter (11594):     body { font:small sans-serif; background-color:#fff; color:#000; }
I/flutter (11594):     body>div { border-bottom:1px solid #ddd; }
I/flutter (11594):     h1 { font-weight:normal; }
I/flutter (11594):     h2 { margin-bottom:.8em; }
I/flutter (11594):     h3 { margin:1em 0 .5em 0; }
I/flutter (11594):     h4 { margin:0 0 .5em 0; font-weight: normal; }
I/flutter (11594):     code, pre { font-size: 100%; white-space: pre-wrap; }
I/flutter (11594):     table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }

A: You can use Dio package and send your data as json in queryParameter. Here i provide example
Response response;
var dio = Dio();
response = await dio.get('https://beautyexperience.herokuapp.com/api/allBlogs',
queryParameters: {"uid": any_integer});

update
As i found, you have a server error. When you call api, the server returns to you an html response that say an error occurred and the error is <title>KeyError at /api/allBlogs/</title>. Can check your api service.
Anyway, i suggest using Dio is better and more comfortable.


text:
Q: Updating Xfce in Linux Mint beyond the standard version I'm running Linux Mint 20 Xfce and would like to update Xfce to the latest version (beyond the version offered in the Mint repos). Is there a PPA or something for this, and is it likely to cause any problems?

A: You are not running rolling release Linux distributive. Linux Mint has own release cycles, after a new release they update all system components and packages at once.
It's usually not a good practice to update components like an entire Desktop Environment (DE, which is Xfce) without an upgrading distro entirely to the new major version.
Linux packages are depend on each other, so updating a part from PPA could usually lead to unexpected bugs.


text:
Q: Error Llamada al método indefinido Base de datos :: prepare () Cordial saludo agradezco por favor su colaboración en el siguiente inconveniente que se me presenta, referente a la función prepare ():
Mi código es el siguiente,

*

*Mi archivo database.php, tiene la siguiente estructura:

    <?php
    class Database{
    private $host;
    private $db;
    private $usuario;
    private $contrasena;
    private $charset;
    private $pdo;
    public function __construct(){
    $this->host='localhost:3306';
    $this->db='grupo4s';
    $this->usuario='root';
    $this->contrasena='';
    $this->charset='utf8mb4';
    $this->connect();
    }
    function connect(){
    try{
    $connection = "mysql:host=" . $this->host . ";dbname=" . $this->db .";usuario=" . $this->usuario .";contrasena=" . $this->contrasena . ";charset=" . $this->charset;
    $options = [
         PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
         PDO::ATTR_EMULATE_PREPARES   => false,
       ];

    $this->pdo= new PDO($connection,$this->usuario, $this->contrasena, $options);
    print_r('Conexion satisfactoriua');
    }catch(PDOException $e){
      print_r('Error connection: ' . $e->getMessage());
      echo "Error connection";
    }
    }
    public function getConnection(){
          return $this->pdo;
         }
    }
    ?>

El archivo index.php, tiene la siguiente estructura:
    <?php
    require_once ('Conexion/database.php');
    session_start();

    if(isset($_SESSION['usuario'])){
    header("Location: admin.php");
       }
    if(isset($_GET['cerrar_sesion'])){
          session_unset();
          session_destroy();
    }

    if(isset($_SESSION['rol'])){
           switch($_SESSION['rol']) {
             case 1:
              header('location:admin.php');
             break;
             case 2:
              header('location:invitado.php');
             break;
             default:
            }
       }

    if(isset($_GET['usuario']) && isset($_GET['contrasena'])){
    $usuario=$_GET['usuario'];  //estaba _POST
     $contrasena= $_GET['contrasena'];
     $db= new Database();
    $query = $db->prepare("SELECT * FROM usuarios WHERE usuario=usuario AND contrasena=contrasena");
    $query->bind_param(['usuario'=> $usuario,'contrasena'=> $contrasena]);
    $query->execute();
          $query->store_result();

    if($query == true){
     $usuario = $row[1];
             $_SESSION['usuario']=$usuario;
            // validar rol
    $rol= $row[6];
    $_SESSION['rol']=$rol;
    switch($_SESSION['rol']) {
              case 1:
               header('location:admin.php');
              break;

              case 2:
               header('location:invitado.php');
              break;
           default:

            }
         } else{
    echo"El usuario o contraseña son incorrectos";
         }

        }

    ?>
    <!DOCTYPE html>

            <meta name="viewport" content="width=device-width, initial-scale=1.0">
                      <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Ingreso</title>
            <link rel="stylesheet" href="css/config1.css">

        <form action="#" methods="post">

Registro Usuarios

                  Usuario:
                  <input type="text" name="usuario" size=45 placeholder="Digite usuario">

                  Contraseña:
                 <input type="password" name="contrasena" id="contrasena" placeholder="Digite contraseña" >

              <input type="submit" name="submit" value="Ingresar" class="btn btn-success" name="btn1" id="btn1">

            Registrar usuario

El error que me muestra es:

Llamada al método indefinido Basededatos::prepare()

En la siguiente línea del archivo index.php:
$query = $db->prepare("SELECT * FROM usuarios WHERE usuario=usuario AND contrasena=contrasena");

He visto las demás ayudas acerca del mismo error en stackOverflow, pero son muy distintas al presente inconveniente.
Muchas gracias por su colaboración.


text:
Q: Angular combining Http Get response with conditional http post I am implementing a private message system in an app that uses angular 4.  When a user clicks on a unread message in their inbox (that may make up one of multiple messages in a thread that also may be unread) all the messages should be returned in the thread but I also want to check to see if any of the messages are unread, and mark them as read as part of this method.
The call to get the messages looks as follows:
getMessageThread(id: number, recipientId: number) {
  return this.authHttp.get(this.baseUrl + 'users/' + id + '/messages/' + recipientId)
    .map(response => response.json())
    .catch(this.handleError);
}

and in the component:
loadMessageThread() {
    const currentUserId = +this.authService.decodedToken.nameid;
    this.userService.getMessageThread(currentUserId, this.userId).subscribe(messages => {
      this.messages = messages;
    }, error => {
      this.alertify.error(error);
  });
}

I also have the following method in the service which should be called conditionally if any of the returned messages in the thread are marked as unread:
markAsRead(userId: number, messageId: number) {
  return this.authHttp.post(this.baseUrl + 'users/' + userId + '/messages/' + messageId, {}).subscribe();
}

So far I have tried a few different options.  If I try and call the user service from within the subscribe I get an error stating the user service is undefined:
loadMessageThread() {
  const currentUserId = +this.authService.decodedToken.nameid;
  this.userService.getMessageThread(currentUserId, this.userId)
    .subscribe(messages => {
      this.messages = messages;
      _.each(this.messages, function(message) {
        if (message.read === false && message.recipientId === currentUserId) {
          console.log(message) // works
      this.userService.markAsRead(currentUserId, message.id); // fails
      }
    });
  }, error => {
    this.alertify.error(error);
  });
}

If I try using a 'do' method prior to the subscribe this also fails to call the method in the service and goes straight to the error condition without hitting the subscribe method:
  loadMessageThread() {
const currentUserId = +this.authService.decodedToken.nameid;
this.userService.getMessageThread(currentUserId, this.userId)
  .do(messages => {
    _.each(messages, function (message: IMessage) {
      if (message.read === false && message.recipientId === currentUserId) {
    console.log(message) // works
        this.userService.markAsRead(currentUserId, message.id); // fails
      }
    });
  })
  .subscribe(messages => {
    this.messages = messages;
  }, error => {
    this.alertify.error(error);
  });
}

I'm not sure if I am overthinking this and am missing a more obvious approach to this.  Any help or suggestions would be appreciated.
Thanks, Neil

A:  _.each(this.messages, function (message) {

should be
 _.each(this.messages, (message) => {

otherwise this will not refer to the component.


text:
Q: TableView Cell appearance issue I have a tableVIew, where each cell is 90.0f tall (the height). my code;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90.0;
}

Now when i delete all the records in the table. the height of the cell shrinks to its default value which is 44 (i think).
1.) My problem is that, i need the height of the cell to remain as 90.0f even after the user deletes all the records. How can i do this programatically ?
2.) I have given 2 colours to my cell.
cell.contentView.backgroundColor = indexPath.row % 2 ? [UIColor whiteColor] : [UIColor blackColor] ;

When i delete the second cell, which is black, then both the 1st and 3rd cell is white. How can i re-arrange this to be black and white in an order.
EDIT:
Ok this works but when i try to delete the last record in the table and [tableview indexPathsForVisibleRows] i end up getting Assertion failure in
-[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:961 and
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. Attempt to delete more rows than exist in section.'
Why is this ?
CODE:
[self.tableView beginUpdates];

        [self.myArray removeObjectsInArray:discardedItems ];

        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]  withRowAnimation:YES];

[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]  withRowAnimation:YES];

        [self.tableView endUpdates];

A: 1) I don't think you can do that. One way around it would be to show x amount of blank cells to fill the page.
2) Call [tableView reloadData] upon cell deletion, or call [tableView reloadCellAtIndex...] on the rows before and after the deleted cell.

A: If the height of your rows is really static (like you showed), consider not implementing tableView:heightForRowAtIndexPath: but use the table-view's rowHeight property, instead.
This can be set either in code or in Interface Builder and should be the solution to your "the rows are shrinking if there are none" problem.
To your second problem:
Do you know about -[UITableView indexPathsForVisibleRows]?
You can use this to only reload the part of your table-view that needs to be updated. It would go like this:
- tableView:(UITableView *)table commitEditingStyle:(UITableViewCellEditingStyle)style forRowAtIndexPath:(NSIndexPath *)path
{
   NSArray *visibleCellPaths = [table indexPathsForVisibleRows];

   // replace this comment with whatever else needs to be done in any case...

   if (style == UITableViewCellEditingStyleDelete) {
      // replace this comment with the deletions of the model object

      NSUInteger affectedPathIndex = [visibleCellPaths indexOfObject:path];
      NSMakeRange updateRange = NSMakeRange(affectedPathIndex, [visibleCellPaths count] - affectedPathIndex);
      NSArray *cellPathsToReload = [visibleCellPaths subarrayWithRange:updateRange];

      // replace this comment with the bounds-checking.
      // e.g. if you only had one section and the backing store was an array, it may look like this:
      // while ([self.backingStore count] <= [[cellPathsToReload lastObject] row]) {
      //    NSUInteger remainingPathCount = [cellPathsToReload count];
      //    if (remainingPathCount) break;
      //    cellPathsToReload = [cellPathsToReload subarrayWithRange:NSMakeRange(0, remainingPathCount - 1)];
      // }

      [table reloadRowsAtIndexPaths:cellPathsToReload withRowAnimation:UITableViewRowAnimationFade];
   }

}

A: *

*set the rowHeight property of UITableView.

documentation states:

The height of each row (table cell) in the receiver.

*

*please provide you data source code


text:
Q: JavaScript onClick function to trigger ActionsScript3 Event Before I begin I will explain that I am relatively new to ActionScript, also newish to JavaScript but have a handle on what I can/need to do.
I have done some hunting online to find out what is needed to do this, however I am not 100% sure on how to do it.
The only tutorials I am able to find are about sending text from one to the other and vice versa.
What I am trying to achieve:

[JavaScript]

HTML element is clicked.

[ActionScript]

Performs an Event and passes Boolean back to JavaScript on success/error.

[JavaScript]

Dependent on true/false will have methods in place to continue.

I am NOT asking you to do this for me, however if you know of any good documentation/tutorials that you can point me to I would appreciate it. I am wanting to learn how to do this, not get shown/told how to do it.
Tutorials I have already read:

*

*tuts+

*circlecube
AGAIN thanks for any help / useful links that come my way :)

A: Well I have found a possible answer to my prayers!
A very nice gentleman on REDDIT pointed out the best way for me to achieve this.
Every tutorial / suggestion I could find was doing it the opposite way to what was required.
I needed [ACTIONSCRIPT] to have an Event fire when a [JAVASCRIPT] element was triggered onClick so that a function could be called.
The answer given to me was :

Register a handler in Flash with:
ExternalInterface.addCallback('jsFunction', asHandler);
After this I can call my function in JavaScript on the Flash Movie Object.

This appears to work, I will leave this question open for the next couple of days to see if anyone has any objections to this being the accepted answer.


text:
Q: ActionText blob partial not rendering extra elements I am using ActionText to render some richtext and for some reason I have restrictions in adding extra elements to the rendered partial using the partial provided by actiontext
I require attached images to be wrapped around a table element, so they can be rendered correctly for emails in Outlook.  ActionText seems to always ignore any extra elements in this partial I put in.  Anyone know why this is happening and if any ways to work around this?
This is my partial, where the table elements get ignored:
/views/active_storage/blobs/_blob.html.erb

      <figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %> text-center">
        <% if blob.representable? %>
          <%= image_tag rails_representation_url(blob.representation(resize_to_limit: [600, 400])) %>

          <% if caption = blob.try(:caption) %>

              <%= caption %>

          <% end %>
        <% end %>

A: I found the issue was to do with Action Text using inner method for sanitising strings before render.
I override the allowed attributes and tags in a initialiser:
ActionText::ContentHelper.allowed_attributes.add 'style'
ActionText::ContentHelper.allowed_attributes.add 'controls'

ActionText::ContentHelper.allowed_tags.add 'video'
ActionText::ContentHelper.allowed_tags.add 'source'

A: In my case, when I added a custom attribute (data-) to link_to helper in _blob.html.erb, it was not included in the rendered  link tag.
<% if blob.representable? %>
  <%= link_to image_tag(blob.representation(resize_to_limit:
local_assigns[:in_gallery] ? [ 800, 600 ] : [ 1024, 768 ]),
class: 'rounded'), rails_blob_path(blob), { 'data-fancybox': 'gallery' } %>
<% end %>

A: I want to know how to get action_name in _blob.html.erb file.
Because I want to show up or off the link to image according to the action name eg, show, edit.

A: # config/initializers/html_sanitation.rb

Rails::Html::WhiteListSanitizer.allowed_tags << 'h2'


text:
Q: Pattern Matching on GADTs I've created a GADT for expressions. When I pattern match on constructors that have constraints, the typechecker is unable to deduce constraints on the type variables used in the constructor's constraints. I think the code and error message are more elucidating.
{-# LANGUAGE GADTs, MultiParamTypeClasses #-}
import Data.Word

data Expr a where
  Value :: a -> Expr a
  Cast :: (Castable a b) => Expr a -> Expr b

class Castable a b where
  cast :: a -> b

instance Castable Word64 Word32 where
  cast = fromIntegral

instance (Show a) => Show (Expr a) where
  show (Cast e) = "Cast " ++ show e -- ERROR

The error I get:
gadt.hs:16:30:
    Could not deduce (Show a1) arising from a use of `show'
    from the context (Show a)
      bound by the instance declaration at gadt.hs:15:10-34
    or from (Castable a1 a)
      bound by a pattern with constructor
                 Cast :: forall b a. Castable a b => Expr a -> Expr b,
               in an equation for `show'
      at gadt.hs:16:9-14
    Possible fix:
      add (Show a1) to the context of
        the data constructor `Cast'
        or the instance declaration
    In the second argument of `(++)', namely `show e'
    In the expression: "Cast " ++ show e
    In an equation for `show': show (Cast e) = "Cast " ++ show e

Edit: If I comment out the Show (Expr a) instance and add the following code, it works fine:
eval :: Expr a -> a
eval (Value a) = a
eval (Cast e) = cast $ eval e

main = do
  let bigvalue = maxBound `div` 2 + 5 :: Word64
      e = Cast (Value bigvalue) :: Expr Word32
      v = eval e
  putStrLn "typechecks."
  print (bigvalue, v)

I would want the show instance to basically print something like Cast (Value bigvalue).

A: Cast :: (Castable a b) => Expr a -> Expr b

So here:
instance (Show a) => Show (Expr a) where
  show (Cast e) = "Cast " ++ show e -- ERROR

Cast e is of type Expr a. We have a Show a constraint, and by this very instance that implies Show (Expr a), so we can call show on things of type Expr a.
But e is not of type Expr a. Cast takes an argument of any type Expr a1 and gives you an Expr a (renaming the type variables to stay consistent with what we're talking about in the instance), so e is of type Expr a1. We don't have a Show constraint for the type a1, and we require Show a1 to imply Show (Expr a1), so there's no way to show e.
And there's no way to add such a constraint in the Show instance, because the type a1 doesn't appear in the type of Cast e. That seems to be the whole point of using a GADT here; you've deliberately thrown away all information about the type of the thing that Cast was applied to (other than the fact that Castable a1 a holds), and declared the result to simply be Expr a.


text:
Q: Footer not clearing Please can someone help, why is my footer not appearing at the bottom properly. I applied clear:both; yet noting.
http://www.vellosdesigns.com/newsite/build-2/
Please can you help?
Thanks to you all issue is now fixed.

A: If you want to use a clear:both; the footer need to have a parent that floats the elements. It's not your case.
The best way to do that is to use a clearfix
http://nicolasgallagher.com/micro-clearfix-hack/
Copy paste the code to your CSS. Then just add a class cf to your div
It will looks like

...

...

...

Hope this helps !

A: With the help i did this with the footer
<!DOCTYPE html>

<base href="http://www.vellosdesigns.com/newsite/build-2/" />

Whetstone - 020-8888-8888
Kensington - 020-8888-8888

Bespoke

Contemporary

Achitecture & Interiors

Management & Build

Contact Us

Bespoke

Contemporary

Achitecture & Interiors

Management & Build

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


text:
Q: Arrange table row in the basis of table data using javascript Suppose I have the code like this:

        name
        price

        a
        5

        b
        3

        b
        8

        b
        2

        b
        6

        b
        20

but it should be arranged this way:

        name
        price

        b
        2

        b
        3

        a
        5

        b
        6

        b
        8

        b
        20

Arranging the table data in basis of table data.
note: the class will be defined class="sort"
Thanks in advance
UPDATE:
I want the table to be arranged without any click of user.

A: Well it looks like you haven't tried anything due to a lack of code and you haven't told us how you are generating the pages / table (the question seems to ask us to do the work for you rather than help) but take a look at this: http://datatables.net/ it may give you the solution you want.

A: By converting rows to an array using $.makeArray you can use natve javascript sort() on the array. I sorted numerical since it seemed applicable
DEMO: http://jsfiddle.net/3MBPF/
function sortNum(a, b) {
   return 1 * $(a).find('.sort').text() < 1 * $(b).find('.sort').text() ? 0 : 1;
}

$(function() {
    var elems = $.makeArray($('tr:has(.sort)').remove())
    elems.sort(sortNum)
    $('table').append($(elems));
});

A: You can use jQuery Tinysort plugin available at http://tinysort.sjeiti.com/. That should cover most of your sorting needs.


text:
Q: Uniqueness of the maximum of a multi-dimensional function I have a somewhat complicated function of $M+1$ variables, which looks as follows.
$$f (x_0, x_1, x_2, \dots, x_M) = \sum_{i=1}^{N_A} \ln \left[1 - \text{erf}\left(x_0 + \sum_{j=1}^M a_{ij} x_j\right) \right] + \sum_{i=1}^{N_B} \ln \left[1 + \text{erf}\left(x_0 + \sum_{j=1}^M b_{ij} x_j\right) \right].$$
All is real here, but in in principle other than that there are no restrictions  on the possible values of the coefficients $a_{ij}$ and $b_{ij}$. $N_A$ and $N_B$ are in general some "larger" numbers (say, at least on the order of 100 or 1000), while $M$ tends to be pretty small, say for example 5 to 10 or so. Not that it should matter, but to add some context, this is actually a likelihood expression for some model.
Now my question is, is this a concave function with a unique maximum? Intuitively, the answer seems to be yes, and "numerical evidence" hints to the same direction, but I have a hard time proving it rigorously. I tried to calculate the Hessian, and eventually a general expression for its eigenvalues (which should all be negative in case my assumptions holds true), but it was just too much.
Any suggestions would be appreciated!
Thanks,
Lennex

A: A sum of concave functions is concave, and $\ln(1+\text{erf}(t))$ and $\ln(1-\text{erf}(t))$ are easily seen to be concave.  So your function is concave.
Moreover, since $\ln(1+\text{erf}(t))$ and $\ln(1-\text{erf}(t))$ are strictly concave,
the only way for a maximum of your function (assuming it exists) to be non-unique would be for all the $x_0 + \sum_j a_{ij} x_j$ and all the $x_0 + \sum_j b_{ij} x_j$ to be equal
at two different points, i.e. the matrix $\pmatrix{1 & A\cr 1 & B\cr}$ to have rank $< M+1$, where $A$ and $B$ are the matrices of coefficients $a_{ij}$ and $b_{ij}$, and the $1$'s are column vectors of all $1$'s.


text:
Q: Custom Layout not detecting in mainActivity class? I am a beginner at android.
I am using Android Studio 1.0. I am trying to make a custom layout for listView. I created custom layout files in the res/layout named row_layout. xml for layout is this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/cl_textView"
    android:textSize="30sp"
    android:textStyle="bold"
    android:padding="15dp"/>
</LinearLayout>

Code to implement that custom layout in the MainActivity class is:
  ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.row_layout,toDoList);

But activity class doesn't detect this custom layout and shows the error below while building.

A: You have to replace the android.R. with R. because R.* provides your application resources instead, android.R.* provides resources that ship with the Android SDK.
( R.* is actually shortcut for your.package.R.* )
Hope it helps.

A: R.layout denotes the resources which are provided by your application. All the variables, resource files (drawable, string, layout etc) which are defined by your application can be accessed by R.
Example R.layout.*, r.drawable.*, R.id.*, R.color.* etc
But android.R denotes the resources of your android SDK. all the resources which are not defined by you but are defined by android SDK will be available to you if you use android.R
In your code, you are using your own layout so replace android.R.layout with R.layout

A: It should be:
ListAdapter theAdapter = new ArrayAdapter<String>(this, R.layout.row_layout,toDoList);

android.R refers to those resources pre-built in the android sdk.
Since you have defined your own layout for the custom list view, you should use R file generated in your project.


text:
Q: For Each does not loop through sheets (without error) I need quick help to find my mistake.
The code below should loop through sheets and copy data to respective columns.
But it only copies from 1 sheet
I tried reseting varaiables but nothing helps..
I have similar macro where For each loop and the same If statement works with out problem.
Update:
It appears the problem is here no matter what kind of outer loop i write to jump to next row it does not jump, It just keeps overwriting cells..
For Each c In MyDataHeaders
i = Application.WorksheetFunction.Match(c.value, ColHeaders, 0) 'Finds the
matching column name Rng.Offset(, i - 1).value = Intersect(DataBlock.EntireRow,
c.EntireColumn).value 'Writes the values
Stop
Next c

Code below:
 Sub CopyDataBlocks()

 Dim sht As Worksheet
 Dim SourceSheet As Worksheet    'The data to be copied is here
 Dim TargetSheet As Worksheet    'The data will be copied here
 Dim ColHeaders As Range         'Column headers on Target sheet
 Dim MyDataHeaders As Range      'Column headers on Source sheet
 Dim DataBlock As Range          'A single column of data
 Dim c As Range                  'a single cell
 Dim Rng As Range                'The data will be copied here (="Place holder" for the first data cell)
 Dim i As Integer

 'Change the names to match your sheetnames:
'Set SourceSheet = Sheets("ws1")
Set TargetSheet = Sheets("Master")

With TargetSheet
Set ColHeaders = .Rows(1) '.Cells(1, 1), .Cells(1, .Columns.Count).End(xlToLeft) 'Or just .Range("A1:C1")
Set Rng = .Cells(.Rows.Count, 1).End(xlUp).Offset(1) 'Shoots up from the bottom of the sheet untill it bumps into something and steps one down

End With

For Each SourceSheet In ThisWorkbook.Worksheets
If SourceSheet.name Like "Sheet*" Then

With SourceSheet
Set MyDataHeaders = Intersect(.Rows(1), .UsedRange)

 For Each c In MyDataHeaders
    If Application.WorksheetFunction.CountIf(ColHeaders, c.value) = 0 Then
        MsgBox "Can't find a matching header name for " & c.value & vbNewLine & "Make sure the column names are the same and try again."
        Exit Sub
    End If
 Next c

'There was a match for each colum name.
'Set the first datablock to be copied:
    Set DataBlock = .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(xlUp)) 'A2:A & the last cell with something on it on column A

'Resizes the target Rng to match the size of the datablock:
Set Rng = Rng.Resize(DataBlock.Rows.Count, 1)

'Copies the data one column at a time:
For Each c In MyDataHeaders
    i = Application.WorksheetFunction.Match(c.value, ColHeaders, 0) 'Finds the matching column name
    Rng.Offset(, i - 1).value = Intersect(DataBlock.EntireRow, c.EntireColumn).value    'Writes the values
Next c

End With

Set MyDataHeaders = Nothing
End If
Next SourceSheet

End Sub

Thanks!


text:
Q: How to build and use flink-connector-kinesis? I'm trying to use Apache Flink with AWS kinesis. The document says that I have to build the connector on my own.
Therefore, I build the connector and added the jar file for my project and also, I put the dependency on my pom.xml file.
<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-connector-kinesis_2.11</artifactId>
    <version>1.6.1</version>
</dependency>

However, when I tried to build using mvn clean package I got an error message like this
[INFO] -----------------------< kkaldk:flink-kinesis >-----------------------
[INFO] Building Flink Quickstart Job 0.1
[INFO] --------------------------------[ jar ]---------------------------------
[WARNING] The POM for org.apache.flink:flink-connector-kinesis_2.11:jar:1.6-SNAPSHOT is missing, no dependency information available
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.458 s
[INFO] Finished at: 2018-12-19T17:45:43+09:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project flink-kinesis: Could not resolve dependencies for project kkaldk:flink-kinesis:jar:0.1: Failure to find org.apache.flink:flink-connector-kinesis_2.11:jar:1.6-SNAPSHOT in https://repository.apache.org/content/repositories/snapshots/ was cached in the local repository, resolution will not be reattempted until the update interval of apache.snapshots has elapsed or updates are forced ->
[Help 1]
[ERROR]

Could you help me to fix this?
---------added----------
This is what I've done (which is wrong procedure)

*

*started project following this document

*build connector from flink master source (which is 1.8-snapshot)

*add dependency with 1.6.1 version.

A: This is what I've done for solution.

*

*I downloaded 1.6.1 release from here.

*unzip the file (the archive will be unzip in .../flink-release-1.6.1/

*built it by mvn clean install -Pinclude-kinesis -DskipTests
Then I have flink-connector-kinesis_2.11 version 1.6.1 in my local maven repository
(for me, path was like this): ~/.m2/repository/org/apache/flink/flink-connector-kinesis_2.11
After then, I could use this connector at any project by adding dependency with this code. (I don't have to add the jar file anymore.)
<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-connector-kinesis_2.11</artifactId>
    <version>1.6.1</version>
</dependency>


text:
Q: Can not receive a response from a remote server I am trying to write a code that will allow me to connect to a remote server and receive a response from it.
The remote address is : www.euref-ip.net:2101
When trying to connect to it from a web page it works fine. However when i am trying to connect through my java code i cant get any response back.
Here is my code so far:
public class Client implements Runnable{
private String nServer = "";
private int nPort = 0;

public Client(String server, int port){
    this.nServer = server;
    this.nPort = port;
}

@Override
public void run() {
    try {
        SocketAddress sockaddr = new InetSocketAddress(nServer, nPort);
        Socket s = new Socket();
        s.connect(sockaddr, 10 * 1000);
        if (s.isConnected()) {
            s.setSoTimeout(20 * 1000);
            DataOutputStream out = new DataOutputStream (s.getOutputStream());
            DataInputStream in = new DataInputStream (s.getInputStream());
            while (true) {
                // send a message to the server
                String requestmsg = "GET / HTTP/1.0\r\n";
                requestmsg += "User-Agent: Client v1\r\n";
                requestmsg += "Accept: */* \r\n";
                requestmsg += "Connection: keep alive\r\n";
                out.write(requestmsg.getBytes());
                out.flush();

                // receive a response
                int ln = in.available();
                byte [] bytes  = new byte [ln];
                in.read(bytes);
                System.out.println(new String(bytes) + "\n");
                Thread.sleep(2000);
            }
        }
    }
    catch (UnknownHostException ex) {System.out.println(ex);}
    catch (IOException ex) {System.out.println(ex);}
    catch (InterruptedException ex) {System.out.println(ex);}
}}

Right now the ln variable is always 0 and I am reading empty response.
What am i doing wrong? Any suggestions?
Any help would be appreciated.

A: Your HTTP request is incomplete, you need to add an extra empty line at the end indicating the end of the header section which is also here the end of the request.
Try with this:
String requestmsg = "GET / HTTP/1.0\r\n";
...
requestmsg += "Connection: keep alive\r\n";
requestmsg += "\r\n";


text:
Q: react in controller, which and if action link is clicked in view In my view "EditUser" I have an action link which i click not always:
  <%= Html.ActionLink("Resend forgotten password", "EditUser", this.Model.UserName, null)%><br />

In my controller "AdministrationController" i have an EditUser ActionResult there i would like to call Method which send forgotten password. But I dont know how to react if i clicked an action link or not. I dont want to send Password each time when I call Action "EditUser".
My Action in AdministratorController:
[HttpPost]
        [ValidateInput(false)]
        public ActionResult EditUser(EditUserModel model)
        {
        try
        {
            Admin admin = new Admin();
            admin.SendForgottenPasswordToUser(model.UserName);

            if (!model.Validate())
            {
                ModelState.AddModelError("", "Please fill missed fields");
            }

            if (!model.Save())
            {
                ModelState.AddModelError("", "Error while saving data");
            }
            else
            {
                ModelState.AddModelError("", "Successufully edited.");
            }

            return View(model);

        }

A: You could create an extra action method and change the action link:
<%= Html.ActionLink("Resend forgotten password", "ResendPassword", this.Model.UserName, null)%>
The action method for resending the password then looks something like this:
[HttpPost]
[ValidateInput(false)]
public ActionResult ResendPassword(EditUserModel model)
{
    try
    {
        Admin admin = new Admin();
        admin.SendForgottenPasswordToUser(model.UserName);
        return View("EditUser", model);
    }
    catch (Exception ex)
    {
        // Error handling here.
    }
}


text:
Q: How can i use is not empty? How can i do a condition with is not empty, or has a value?
I tried but is not working
     <% if params[:search_num_letter].values.any?  and params[:search_letter_log].values.any? %>
          No data
     <% else %>
         <% if params[:search_num_letter] == ""  and params[:search_letter_log] == "" %>
            No data
         <% else %>
            my code
         <% end %>
     <% end %>

I will really appreciate help.

A: Instead of params[:search_num_letter].values.any? you probably want to drop the .values and just do params[:search_num_letter].any?.


text:
Q: In selenium, how can i track cursor movement on browser with any color? I am performing many task on one page.... i want to know where my cursor is , so is there any way that my cursor location will show in color on browser when i am running the script.
Thanks

A: There are several the cursor shape changing techniques using javascript, for example here. You can use it in your code (Java) using
((JavascriptExecutor) driver).executeScript

the details here


text:
Q: How to create long lived access tokens for published API in WSO2 API Manager I have created apis and published using this tutorials and it is working, i want to create long lived access tokens , is there any way to create long lived access tokens??? please help me to create long lived access tokens.

A: Setting token to a negative value will never expires the token. Found in this link.

A: It can be set as long as you want when you generate the token, 3600 secs is the default. If you set it to -1, the token will never expire.


text:
Q: Why List Box items are not update during Filtering? I`m writing a program to view product Information in a Listbox. I have a text box for searching that automatically filters the list as you typing by ProductName. I have run through my C# code numerous times and I can see the filter actually working but I cannot visually get it to filter or 'refresh' on the screen.
C# Code :
private ICollectionView _ProductInfoView;
    public ICollectionView ProductInfoView
    {
        get{return this._ProductInfoView;}
        set
        {
            this._ProductInfoView=value;
            this.onPropertyChnage("ProductInfoView");
        }
    }

 private void RibbonSetupProduct_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        this.hidePanels();
        new Task(() =>
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                ObservableCollection<ModelProductInformation> productInfoCollection   = new ObservableCollection<ModelProductInformation>(from ProductInfo in new GTS_ERPEntities().ProductInformations select new ModelProductInformation { ProductID = ProductInfo.ProductID,  ProductName = ProductInfo.ProductName , Remark=ProductInfo.Remark});
                this.ProductInfoView = CollectionViewSource.GetDefaultView(productInfoCollection);
                new ProductInfoSearch(ProductInfoView, this.TestTextBox);
            }
                ), DispatcherPriority.DataBind);
        }
        ).Start();

        this.PanelProducts.Visibility = Visibility.Visible;
    }

  class ProductInfoSearch
   {
      public ProductInfoSearch(ICollectionView filteredList, TextBox textEdit)
      {
        string filterText = string.Empty;

        filteredList.Filter = delegate(object obj)
        {
            if (String.IsNullOrEmpty(filterText))
            {
                return true;
            }
            ModelProductInformation str = obj as ModelProductInformation;
            if (str.ProductName==null)
            {
                return true;
            }
            if (str.ProductName.ToUpper().Contains(filterText.ToUpper()))
            {
                return true;
            }
            else
            {
                return false;
            }
        };
        textEdit.TextChanged += delegate
        {
            filterText = textEdit.Text;
            filteredList.Refresh();
        };
    }
}

XAML :
<dxe:ListBoxEdit x:Name="ProductInfoList" Margin="1.666,1,8,8" Grid.Column="2" Grid.Row="2" Grid.RowSpan="5"  DisplayMember="ProductName" DataContext="{Binding ProductInfoView, ElementName=window}" ItemsSource="{Binding}"/>

I guess my problem is either  Data Binding or inside Task().

A: i would make the ObservableCollection a private field and just create the instance once and also just create the ICollectionView once. to add new data you can use clear and add on your Collection - try it, it works for me.
 private ObservableCollection<ModelProductInformation> productInfoCollection;

 //ctor, just once in the constructor
 this.productInfoCollection =  new ObservableCollection<ModelProductInformation>();
 this.ProductInfoView = CollectionViewSource.GetDefaultView(productInfoCollection);
 new ProductInfoSearch(ProductInfoView, this.TestTextBox);

private void RibbonSetupProduct_Click(object sender, System.Windows.RoutedEventArgs e)
{
    this.hidePanels();
    new Task(() =>
    {
        this.Dispatcher.Invoke(new Action(() =>
        {
            var yourData = from ProductInfo in new GTS_ERPEntities().ProductInformations select new ModelProductInformation { ProductID = ProductInfo.ProductID,  ProductName = ProductInfo.ProductName , Remark=ProductInfo.Remark};
            //if you wanna change the collection, simple clear and add(or create AddRange extension)
           this.productInfoCollection.Clear();

           foreach(var data in yourData)
           { this.productInfoCollection.Add(data);}
        }
            ), DispatcherPriority.DataBind);
    }
    ).Start();

    this.PanelProducts.Visibility = Visibility.Visible;
}


text:
Q: I don't know why this app is shutting down(because of databinding,setOnClickListener) class day_1 : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var _binding: FragmentDay1Binding? = null
private val binding get() = _binding!!
private var mediaPlayer: MediaPlayer? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    arguments?.let {
        param1 = it.getString(ARG_PARAM1)
        param2 = it.getString(ARG_PARAM2)

    }
    binding.startbutton.setOnClickListener {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(activity, R.raw.days)
        }
        mediaPlayer?.start()
    }

    binding.pausebutton.setOnClickListener {
        if (mediaPlayer?.isPlaying == true) {
            mediaPlayer?.pause()
        } else {
            mediaPlayer?.start()
        }
    }

    binding.stopbutton.setOnClickListener {
        mediaPlayer?.stop()
        mediaPlayer = null
    }
     fun onStop() {
        super.onStop()
        mediaPlayer?.release()
        mediaPlayer = null
    }
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {

    // Inflate the layout for this fragment
    _binding = FragmentDay1Binding.inflate(inflater,container,false)
    return binding.root
}
companion object {
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment day_1.
     */
    // TODO: Rename and change types and number of parameters
    @JvmStatic
    fun newInstance(param1: String, param2: String) =
        day_1().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
}

what is above is my code. If I click the button, application was shutting down. First, I think that Media Player is problem. but application without setOnClickListener has no problem. Please help me masters.... Is it problem that setOnClickListener is in Fragment?
And Can I amend this code? or I restart project? Perhaps If you know why this problem exist, Please tell me resolution...

A: You can take a look for fragment lifecycles at here https://developer.android.com/guide/fragments/lifecycle
You are setting on click listener at onCreate method, in fragments views are created at onCreateView method so you are trying to access your view before it is created. So instead of onCreate method you need to set your click listener after your binding/view is ready, for example you can set your click listener before returning binding.root at onCreateView. Also you can set your click listener at onViewCreated method.


text:
Q: Specify column width + row height for one table I would like to increase the row height to properly show the fraction of N2O/SiH4 in the table (see attached image). Also, I would like the last column not to increase width according to the pagewidth. As I am using multiple tables in this report, I would like to be able to specifiy for each specific table. Please let me know if the question remains unclear to you after seeing my MWE.
\documentclass{report}
%\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{changes}
\usepackage{caption}
\usepackage[justification=centering]{caption}
\usepackage{amssymb}
\usepackage[gen]{eurosym}  %proper euro sign
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{bm} % for \bm macro
\usepackage{mhchem}  %allows chemical formulae
\usepackage{siunitx} %allow SI units
\usepackage{cleveref} %smart referencing, automatic sorting etc.
\usepackage{nomencl}
\usepackage{pdfpages}
\makenomenclature

\usepackage{tcolorbox}
\usepackage{tabularx}
\usepackage{array}
\usepackage{colortbl}
\tcbuselibrary{skins}
\tcbset{tab2/.style={enhanced,fonttitle=\bfseries,fontupper=\normalsize\sffamily,
colback=yellow!10!white,colframe=tudelft-sky-blue,
coltitle=black,center title}}

\begin{document}

    \begin{tcolorbox}[tab2,tabularx={Y||Y|Y|Y}]
        \caption{Oxide fraction estimated by weighing method}
    $\bm{\frac{\ce{N2O}}{\ce{SiH4}}}$   & \textbf{Deposition time(min)} & \textbf{Stoichiometry}                & \textbf{Oxygen fraction(\%)}  \\\hline\hline
            $\frac{200}{600}$           & 90                            &  SiO$_\textrm{\scriptsize 0.72}$      & 42                            \\\hline
            $\frac{200}{600} $          & 120                           &  SiO$_\textrm{\scriptsize 0.81}$      & 45                            \\\hline
            $\frac{250}{600} $          & 90                            &  SiO$_\textrm{\scriptsize 0.71}$      & 42                            \\\hline
            $\frac{250}{600} $          & 120                           &  SiO$_\textrm{\scriptsize 0.80}$      & 44                            \\\hline
            $\frac{300}{600} $          & 90                            &  SiO$_\textrm{\scriptsize 0.52}$      & 34                            \\\hline
            $\frac{300}{600} $          & 120                           &  SiO$_\textrm{\scriptsize 0.65}$      & 39                            \\\hline
            $\frac{350}{600} $          & 90                            &  SiO$_\textrm{\scriptsize 0.71}$      & 42                            \\\hline
            $\frac{350}{600} $          & 120                           &  SiO$_\textrm{\scriptsize 0.76}$      & 43                            \\
            \label{tab:oxidefraction_weighingmethod}
            \end{tcolorbox}

\end{document}

A: Not knowing what is the Y column type, nor the tudelft-sky-blue colour, I  propose an approximation with this solution  based on the \setcellgapes and \theadcommands from makecell. I also simplified your preamble, as some packages are already loaded by others.
\documentclass{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[dvipsnames, table]{xcolor}
\colorlet{tudelft-sky-blue}{SkyBlue}
\usepackage{changes}
\usepackage{caption}
\usepackage[justification=centering]{caption}
\usepackage{amssymb}
\usepackage[gen]{eurosym} %proper euro sign
\usepackage{mathtools, nccmath}
\usepackage{bm} % for \bm macro
\usepackage{mhchem} %allows chemical formulae
\usepackage{siunitx} %allow SI units
\usepackage{cleveref} %smart referencing, automatic sorting etc.
\usepackage{nomencl}
\usepackage{pdfpages}
\makenomenclature

\usepackage{tcolorbox}
\usepackage{tabularx}
\usepackage{makecell}
\tcbuselibrary{skins}
\tcbset{tab2/.style={enhanced,fonttitle=\bfseries,fontupper=\normalsize\sffamily,
colback=yellow!10!white,colframe=tudelft-sky-blue,
coltitle=black,center title}}

\begin{document}

\setcellgapes{3pt}\makegapedcells
\renewcommand{\theadfont}{\normalsize\bfseries}
    \begin{tcolorbox}[tab2,tabularx={>{\centering\arraybackslash}X||c|c|c}]
        \captionof{table}{Oxide fraction estimated by weighing method}
   \boldmath ${\mfrac{\ce{N2O}}{\ce{SiH4}}}$ & \thead{Deposition\\ time(min)} & \thead{Stoichiometry} & \thead{Oxygen\\ fraction(\%)} \\\hline\hline
            $\mfrac{200}{600}$ & 90 & SiO$_\textrm{\scriptsize 0.72}$ & 42 \\\hline
            $\mfrac{200}{600} $ & 120 & SiO$_\textrm{\scriptsize 0.81}$ & 45 \\\hline
            $\mfrac{250}{600} $ & 90 & SiO$_\textrm{\scriptsize 0.71}$ & 42 \\\hline
            $\mfrac{250}{600} $ & 120 & SiO$_\textrm{\scriptsize 0.80}$ & 44 \\\hline
            $\mfrac{300}{600} $ & 90 & SiO$_\textrm{\scriptsize 0.52}$ & 34 \\\hline
            $\mfrac{300}{600} $ & 120 & SiO$_\textrm{\scriptsize 0.65}$ & 39 \\\hline
            $\mfrac{350}{600} $ & 90 & SiO$_\textrm{\scriptsize 0.71}$ & 42 \\\hline
            $\mfrac{350}{600} $ & 120 & SiO$_\textrm{\scriptsize 0.76}$ & 43
            \label{tab:oxidefraction_weighingmethod}
            \end{tcolorbox}

\end{document}


text:
Q: Matlab comparation of two numbers not working I'm trying to compare three numbers in a if statement but they don't match even if they are the same.
here are the numbers from the command window,
>> a = (round2(final_aucscore(10, 1),1e-4))

a =

    0.9369

>> b = (round2(final_aucscore(10, 2),1e-4))

b =

    0.9598

>> c = (round2(final_aucscore(10, 3),1e-4))

c =

    0.9509

the function round2 can be found in the file echange here.
here's my code:
for mmm = 1:265

    a = (round2(final_aucscore(mmm, 1),1e-4));
    b = (round2(final_aucscore(mmm, 2),1e-4));
    c = (round2(final_aucscore(mmm, 3),1e-4));
    if   a == 0.9369 && b == 0.9598 && c == 0.9509
        auc_idx = idx(1:kk);
        save('auc_idx', 'auc_idx', 'mmm');
        break;
    end
end

shouldn't it stop and save when mmm = 10?

A: What every computer scientist should know about floating-point arithmetic. Read it and weep.

A: The problem you're facing here comes from rounding error.
Try this
foo = 0.9369;
bar = (round2(foo,1e-4));
disp(bar == foo)
disp(foo-bar)

You could instead make a function to compare only within a certain precision.


text:
Q: Relacionar matriz de String com um vetor de Float em C Preciso que o programa receba 20 nomes digitados pelo usuário, armazene em uma Matriz Char, e logo após receba os 20 salário dos usuários e armazene em um vetor Float. Consegui fazer até a parte em que o usuário deve utilizar o programa até requisitar a exibição de um Índice inválido (0 a 19 são os válidos); pois a matriz Char não aceita exibir os dados através do Index, ao menos não consegui de forma alguma exibir assim.
Alguém pode me ajudar?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
   float sal[20];
   char nom[21][16];
   int index, n, s;
   //recebe os nomes
   for(n = 0; n < 21; n++){
           printf("Insira o nome do funcionario [%d] \n", n);
           gets(nom[n]);
   }
   //exibe os nomes
   for(n = 0; n < 21; n++){
           printf("%s", nom[n]);
       printf("\n");
   }
   //recebe os salários
   for(s = 0; s < 20; s++){
       printf("Insira o salario do funcionario [%d] \n", s);
       scanf("%f", &sal[s]);
   }

   //exibe o nome e salário de acordo ao índice digitado pelo usuário
       while(index < 20)
   {
       printf("Indice escolhido: Funcionario %s %s ", nom[index][index]);
       printf("Salario %f ", sal[index]);
       printf("\n");
       printf("Qual o indice do Vetor que deseja consultar? \n");
       scanf("%d", &index);
   }

   return 0;
} ```


text:
Q: Updating files bigger then 1GB? Currently I am using xdelta to make the update files and send only the difference of the user current application version but I would like to know if there are better ways or other ways to approch this sort of situation and the advices the community could give me.
Our application is written in C# and our webserver is running on Linux with apache httpd.
Using xdelta new patchs shrink to the size difference between old and new file so the updates vary between 10mb to 500 mb avoiding the need to re-upload those 1GB each time we change something.

*

*What other options do I have that you could recommend me ?

*What else should I consider in this case ?

PS: I am really at loss with this to be honest, this is the first updater app I have made and I really don't know if I am doing it right.

if possible recommend open source or non-commercial applications

A: With the minimal amount of information provided, I dont see a problem with your approach.  If you need to patch a 1GB file you need to patch a 1GB file.  I assume it is a data file and therefore needs to be that size?  Is there any way you could split it into files that don't often change to possibly further reduce your patch size?

A: You might give bsdiff a try. It's the same thing as xdelta, with a somewhat different algorithm.
Getting started under Windows was not all that straighforward when I first tried (that may be different now, have not looked in a while), but once it worked, it worked ok.My mileage is that compression runs about 10 times slower than xdiff (but, who cares...) and generates patches that are usually about half the size. Obviously your mileage will depend a lot on your data, but for me it's big win. If you have some spare time, you could always give it a try.
The abysmal compress time may be a deterrent in some situations, but for my situation the fact that the patches are half the size excuses for everything, I wouldn't care if generating a patch ran over the entire weekend, if only that reduced the size again.


text:
Q: Can I remove an OTF macro from a Razer Deathstalker? I recently bought a Razer Deathstalker, and the other day I managed to activate the OTF macro recorder by accident, so now I have random gibberish and key presses bound to regular keys, so typing anything ends up being a pain, considering the backspace key prints "allallallallall", and so on.
The only way I've found of fixing this is reconnecting the keyboard or disabling Synapse, but that's only temporary, as it comes right back the next time I turn my PC on. Razer support mentions nothing related to removing them, and neither anywhere else I could imagine. There's also nothing in Synapse (god I hate Synapse).
How can I remove the macros?

A: I just figured it out myself.
Go to macro tab, within the macro tab there is a macro dropdown box. Click the arrow and choose one of them, then just delete any that you have.
It shows that none are there but you just have to go in and select one.

A: in the macro drop down box
Find a macro with a name like "new macro 1" or "new macro 2" and so on if you did not make the macros but there up in the box then just delete it.
you with see in the pic of the software all the keys being use by a macro are different looking in color

A: I had the same problem with all the gibberish.
Go to the first tab 'keyboard' then delete what ever profile you have and make a new one, that will remove any of the OTF macros you have.

A: My solution was to simply create a new macro and bind it to the gibberish key. Example:
I bound U key to asdlldsl
I record a new otf macro (fn+f9)
I hit u key, macros aren't recorded when recording macros, then bind it to you by hitting fn+f9 then u


text:
Q: Redirect to another servlets path through Java Method I have a method inside my doGet that starts a thread if the date is not equal to today. The scheduler will find the execute() method. Inside this method() I try to use the redirect.
Method 1:
I used the ScriptEngine to call my js method through Java but it always gives me the following error:
Js method:
function httpGet(theUrl){
window.open(theUrl)
}

Java Method:
ScriptEngine engine = manager.getEngineByName("js");
              // read script file

              engine.eval(Files.newBufferedReader(Paths.get(url), StandardCharsets.UTF_8));
              Invocable inv = (Invocable) engine;
              // call function from script file
              inv.invokeFunction("httpGet", "http://localhost:8080/myProject/StartScript?duration="+minutes);

Error:
javax.script.ScriptException: ReferenceError: "window" is not defined in <eval> at line number 3
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
at watering.WateringScheduler.execute(WateringScheduler.java:99)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)Caused by: <eval>:3 ReferenceError: "window" is not defined

Method 2:
I tried to use HttpUrlConnection but the problem is that it never redirects me to the page even though it connects.
 URL url;
              log.info("hi "+ minutes);
              url = new URL("http://localhost:8080/myProject/StartScript?duration="+minutes);
              HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
              urlConnection.setDoOutput(true);
              urlConnection.setRequestMethod("GET");
              urlConnection.connect();
              BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
              int responseCode = urlConnection.getResponseCode();
              System.out.println(responseCode);
              if(responseCode==200) {
                  urlConnection = (HttpURLConnection) url.openConnection();
                  System.out.println("Redirect to URL : " + url);
              }
              BufferedReader in = new BufferedReader(
                      new InputStreamReader(urlConnection.getInputStream()));
                String inputLine;
                StringBuffer html = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    html.append(inputLine);
                }
                in.close();

The problem is that everything I read online points to redirect through the doGet or doPost. I want to redirect through my execute() method.
Thanks!

A: The script engine in Java provides the ability to execute Javascript code, but does not provide an emulation of a browser.
Use HTTP clients like okhttp to download the raw HTML of the page.
For more information please visit
"document" is not defined in  java ScriptEngine


text:
Q: Gromacs: select residues from area I work on lipid and water structure. I have to select every water (group 1) that is below 4A from the lipid (group 2). I used this command:
gmx select -f input.gro -s input.tpr -n input.ndx -select 'group 1 and within 0.4 of group 2' -on output.ndx

Unfortunately it does the work, but program selects every ATOM in that area, leaving alone H or OH, what I cannot afford for that. I supposed to fix this by adding -seltype whole_res_com however the output values were totally nonsense.. Is the other way to select all water residues within 4A of lipid phase?
Thanks in advance!

A:
gmx select -f input.gro -s input.tpr -n input.ndx -select 'group 1 and
  same residue as within 0.4 of group 2' -on output.ndx

found out.


text:
Q: Azure (Synpase) Binary == Hex? I wonder how to get "real" binary dtypes in azure synpase.
If I use the following expression it seems to me that the function returns HEX values (see image) instead of binary type values:
toBinary(toInteger(zlm_flags))

Since my col of interest is a flag, I actually I want to have the first bit.

A: Thank you Conor Cunningham MSFT and Bohniti for your valuable discussions. Posting your discussions as answer to help other community members.

In the UI, the value is shown in HEX values but the data is Binary. To
obtain single bit, you can do COLUMN & 1 and cast it to bool. This
would be cheaper.

There is a function bin() in spark but I can't see the function in synapse. Is it not implemented yet or is there a sth else to it?

In all client drivers for Synapse SQL, selecting a binary column returns it as binary. There is no need for a function to do this as such. It seems like client tool that you are using is showing the hex values by default. For other types you can CAST to binary to see things in binary (or hex in your tool)


text:
Q: How user program and data is shared during fork() call and why child process runs complete not ahead of fork() call?    #include<stdio.h>
    main()
    {
     int a=9;
     printf(" %u hiii \n",&a);
     int p=fork();
     if(p==0){
             a=10;
             printf("\nChild  %u \n Value in child of a = %d\n",&p,a);
              }
     else
             printf("\nvalue of a = %d \n Parent with child process id = %d address of p = %u \n",a,p,&p);
     }

Ouptut of the above program According to ideone.com is - >
 3215698376 hiii

 value of a = 9

 Parent with child process id = 28150 address of p = 3215698380

3215698376 hiii

Child  3215698380

Value in child of a = 10

My question is if both are processes are giving same addresses of variable 'a' then if I change the value the value in one process why isn't the change reflecting in Parent process.
Moreover why the child process is running whole program else it should run with statements after fork().

A: The link in the question's comments answers the memory address question.
As for the "hiii" line being print out in both the parent and child application, the child is printing out the "hiii" line due to buffering of stdout. At the time of the fork() the line is still buffered in memory and not flushed to stdout until the next printf or the program exits. So the child really is starting execution at the fork line.
Try adding setvbuf(stdout, NULL, _IONBF, 0); as the first line of the program (or at least before the first printf) and see if the child still prints out the "hiii" line.


text:
Q: Python - OpenCV clean blurred image Is there a way I could clean a blurred image. I am using python 2.7.7. Suppose I have this image (Blurred):

Is there a way I clean this image to make it look like this?:

A: No. And yes. If you know about blur function then you can partialy restore image. The simplest example - Wiener filter.
And OpenCV has some more complicated deblur functions, for your case - out of focus image: https://docs.opencv.org/trunk/de/d3c/tutorial_out_of_focus_deblur_filter.html
Try it but do not expect magic results.


text:
Q: R: How do I calculate the maximum value seen so far in a variable for each ID I have the following data frame in R called df :
id<-c(1,1,1,1,2,3,3,3,3)
day<-c(1,2,4,5,2,2,3,6,8)
payment<-c(5,10,3,30,23,40,20,10,50)
df<-data.frame(id,day,payment)

 id  day  payment
  1   1       5
  1   2      10
  1   4       3
  1   5      30
  2   2      23
  3   2      40
  3   3      20
  3   6      10
  3   8      50

what I'm trying to do is creating a new variable called soFarMax, it represents the maximum payment that the associated id has made until that day:
  id  day   payment SoFarMax
  1   1       5       5
  1   2      10       10
  1   4       3       10
  1   5      30       30
  2   2      23       23
  3   2      40       40
  3   3      20       40
  3   6      10       40
  3   8      50       50

Would appreciate your help with this.

A: SoFarMax <- unlist(tapply(df[,3], df[,1], cummax))

if your order the days before it is not necessary that there already in your dataframe in order:
df_order <- df[order(df[,2]),]
SoFarMax <- unlist(tapply(df_order[,3], df_order[,1], cummax))

A: The key apparently was cummax thanks to @Frank. Here is what I managed to come up with:
library(data.table)
df<-data.table(df)
df<-df[,MaxSoFar:=cummax(payment),by=list(id)]

A: Using dplyr
df %>%
group_by(id) %>%
mutate(SoFarMax = cummax(payment))

A: I think you need to use window functions to group by this with IDs ( Use dplyr or subset for that )
and then use cummax(x) or you can use logic
df$sofarmax<-ifelse(df$payment[i]>df$payment[i-1],df$payment[i],df$payment[i-1])


text:
Q: Letter Tile Possibilities - Java solution Trying to solve the "Letter Tile Possibilities" problem
For a given input, require to calculate the number of possible sequences. Not sure what went wrong with my program.
The program works fine for the following input
Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Program fails when I change the input to this
Input: "AAABBC"
Expected Output: 188 (Correct Answer).
But the program is returning - 164
Code
    int[] factorial = new int[]{1,1,2,6,24,120,720};
    HashMap<String, Integer> map = new HashMap<String,Integer>();

    public int numTilePossibilities(String tiles) {
        char[] array = tiles.toCharArray();
        int total_sequences = 0;
        int total = array.length;
        for(int i=0; i<array.length; i++)
        {
            addToMap(array[i]);
        }
        for(int digit = 1; digit<=total; digit++)
        {
            int numerator = factorial[total];
            int denominator = (factorial[total-digit] * getRepetitions());

            total_sequences += Math.round((float)((float)numerator/(float)denominator));
            System.out.println("Digit "+digit+" Sequences "+Math.round((float)((float)numerator/(float)denominator))+" N "+ numerator+" D"+denominator+" Rep"+ getRepetitions() );
        }
        return total_sequences;
    }

    private Integer getRepetitions()
    {
        int denominator = 1;
            for(String key : map.keySet())
            {
                    if(map.get(key)==1)
                    {
                        continue;
                    }
                    denominator=  ((denominator)*factorial[map.get(key)]);
            }
        return denominator;
    }

    private void addToMap(char tile)
    {
        Integer counter = map.get(tile+"");
        if(counter == null)
        {
            counter = 0;
        }
        counter++;
        map.put(tile+"",counter);
    }

}


text:
Q: Power M query syntax to get the value for a named cell in Excel I am still learning about Power Query and Power M and I'm trying to get the value of a specific "named" cell in Excel and use this in Power M.  It is just a single cell and

=Record.Field(Excel.CurrentWorkbook(){[Name="weekone"]}[Content]{0},Excel.CurrentWorkbook(){[Name="weekone"]}[Content]{0})
Maybe I am not understanding the syntax of how to reach information in a particular field correctly, or I am getting mixed up on how to use the Record.Field() function.
Any help or guidance that can be provided would be greatly appreciated!  Thanks!

A: Record.Field gives the value of a field in a record.
It takes the record as the first argument and the name of the field as the second argument.
In a step by step approach it will be clearer:
let
    Source = Excel.CurrentWorkbook(){[Name="weekone"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type date}}),
    FirstRecord = #"Changed Type"{0},
    RecordValue = Record.Field(FirstRecord,"Column1")
in
    RecordValue

Or, in 1 line:
= DateTime.Date(Record.Field(Excel.CurrentWorkbook(){[Name="weekone"]}[Content]{0},"Column1"))

This would be an alternative:
= DateTime.Date(Excel.CurrentWorkbook(){[Name="weekone"]}[Content]{0}[Column1])

My preference would be:
= DateTime.Date(Table.FirstValue(Excel.CurrentWorkbook(){[Name="weekone"]}[Content]))


text:
Q: How does bash array slicing work when start index is not provided? I'm looking at a script, and I'm having trouble determining what is going on.
Here is an example:
# Command to get the last 4 occurrences of a pattern in a file
lsCommand="ls /my/directory | grep -i my_pattern | tail -4"

# Load the results of that command into an array
dirArray=($(echo $(eval $lsCommand) | tr ' ' '\n'))

# What is this doing?
yesterdaysFileArray=($(echo ${x[@]::$((${#x[@]} / 2))} | tr ' ' '\n'))

There is a lot going on here.  I understand how arrays work, but I don't know how $x is getting referenced if it was never declared.
I see that the $((${#x[@]} / 2}} is taking the number of elements and dividing it in half, and the tr is used to create the array.  But what else is going on?

A: I think the last line is an array slice pattern in bash of form ${array[@]:1:2}, where array[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1.
So for your case though you are taking the start index empty because you haven't specified any and length as half the count of array.
But there is a lot better way to do this in bash as below. Don't use eval and use the built-in globbing support from the shell itself
cd /my/directory
fileArray=()
for file in *my_pattern*; do
    [[ -f "$file" ]] || { printf '%s\n' 'no file found'; return 1; }
    fileArray+=( "$file" )
done

and do
printf '%s\n' "${fileArray[@]::${#fileArray[@]}/2}"


text:
Q: TypeError in JavaScript, Google Maps API I'm currently developing a Webapps using the Google Maps API. I want to plot X different routes simultaneosly to the same destination location.
If I plot one, it works, but when I work with arrays (Because I don't know how many routes I will plot finally) it shows me this type of errors. The code when calculating the routes is like these.
var rendererOptions = [];
var directionsDisplay = [];

for (var k = 0; k < carLatLng.length; k++) {

    rendererOptions[k] = {
        map: map
    };
    directionsDisplay[k] = new google.maps.DirectionsRenderer(rendererOptions[k]);

    var request = {
        origin: carLatLng[k],
        destination: place.geometry.location,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService = new google.maps.DirectionsService();
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay[k].setDirections(response);

        } else alert('Failed to get directions');
    });

}

The error tells me TypeError: directionsDisplay[k] is undefined. (It refers to the one inside the if() clause)
Hope guys you could help me. I have tried some options but none of them works. Only works when I eliminate the for loop (and the array-type)
Thank you

A: directionsService.route is asynchronous - by the time the last repsonse is received, the loop would've run it's course, and k == carLatLng.length - thus directionsDisplay[k] will be undefined
What you need is to change
directionsService.route(request, function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay[k].setDirections(response);

    } else alert('Failed to get directions');
});

to something like
function(directionsDisplay) {
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else alert('Failed to get directions');
    });
}(directionsDisplay[k]);

there's probably easier ways to make a closure, but my mind is addled at the moment
edit: for some clarity, maybe, hopefully -
function(captured_k) {
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay[captured_k].setDirections(response);
        } else alert('Failed to get directions');
    });
}(k);


text:
Q: Getting the week number as alias in sql analysis this is my first question here. Hopefully I´m clear enough what I´m searching for.
My problem is following:
On this analysis I want to get from the last 7 weeks, the summarized prices of each week. Its working with out any problems, but now I would like to add the weeks number of each week as alias.
In my tests I was using for example something like this:
DECLARE @week7 varchar(10)
SET @week7 = DATEPART(wk, GetDate())

One of my problems is, that I´m not allowed to work with "EXEC".
This is just an example of my analysis:
SELECT DISTINCT(
SELECT SUM(Price)
FROM tblBookingdata
WHERE(Datum BETWEEN DATEADD(wk, -7, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) AND DATEADD(wk, -6, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))))) AS '7 weeks ago', (
SELECT SUM(Price)
FROM tblBookingdata
WHERE(Datum BETWEEN DATEADD(wk, -6, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) AND DATEADD(wk, -5, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))))) AS '6 weeks ago'

I would like the column name to show the week number from each sub select. That the output would be for example for this week: 40 (as column name) and 900 as price summary.
So I tried to work here with DECLARE and assign @week7 for example with the current week number. But here I got stuck, due it seems like I need to work here with EXEC.
Is this only possible with "EXEC" or are there any other solutions to solve this? I was looking in the www, but currently I´m stucking a bit. Thankful for every help! :)

A: I think the DateDiff function is your friend here. Are you using SQL Server? This won't display a row for the week if there are zero records in that week, but this should be close to what you want.
select WeeksAgo, sum(Price) as Price from (
    select
        Price
        ,Datediff(wk, Datum, getDate()) as WeeksAgo
        ,Datum --not used
    from
        tblBookingdata
)DataByWeek
where WeeksAgo between 0 and 7 --should this be 0-6?
group by WeeksAgo

A: I think you're looking for something like this.  The prior 7 weeks are calculated from GETDATE based on a numbers table with 1, 2, 3, ... 7.  Then the booking Prices are summarized by week where the Datum is within the prior 7 weeks.  This will display NULL in price_sum if there were no sales that week.
drop table if exists #tblBookingdata;
go
create table #tblBookingdata(
    Datum        date not null,
    Price        int not null);
go

;with
weeks_cte(wk) as (
    select datepart(wk, dateadd(wk, w*-1,  getdate()))
    from (values (1),(2),(3),(4),(5),(6),(7)) v(w)),
bookings_cte(wk, price_sum) as (
    select datepart(wk, Datum), sum(Price)
    from #tblBookingdata
    where Datum>dateadd(wk, -7, getdate())
    group by datepart(wk, Datum))
select *
from weeks_cte wc
     left join bookings_cte b on wc.wk=b.wk;


text:
Q: Call to undefined function is_home() or any conditional tags Currently I am coding in my own custom plugin. For some reason I can't use conditional tags inside my function. For example
 function check_home() {
    if(is_home()) {
       $my_val=1;
    } else {
     $my_val=2;
    }
    return $my_val;
  }

It's returning following error

Fatal error: Uncaught Error: Call to undefined function is_home()

I checked and I found a solution & it is working fine.
It saying to add this add_action('wp', 'check_home');
But now I want to get the value of function to variable. But it is showing error.
 add_action('wp', 'check_home');
 function check_home() {
    if(is_home()) {
       $my_val=1;
    } else {
     $my_val=2;
    }
    return $my_val;
  }

  $my_ver = check_home();
  echo $my_ver;

Then it showing following error.

Fatal error: Uncaught Error: Call to undefined function is_home()

Now how can i solve this error ? What i am missing ?

A: It's a timing issue. This tries to call is_home() before that function exists.
$my_ver = check_home();

It works in the function called by add_action because then is_home() does exist because WP has fully loaded.
If you load php files in your plugin, then you can call check_home anytime in those files.
For example:
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
function ab_load_files() {
   require( MY_PLUGIN_PATH . '/ab-functions.php' );
}
add_action( 'init', 'ab_load_files' );

Then this code will work if placed in ab-functions.php
$my_ver = check_home();
echo $my_ver;


text:
Q: Alter namespaces on elements I have an xml document and an existing xslt transform (both of these are relatively large pre-existing code).
In various places through the XML, I have nillable fields declared like this:
<author i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>

However, I also already have this namespace declared in the xml element like so:
<message xmlns="http://www.mynamespace.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

I have had a request that the output for any nil node should look like the following:
<author xsi:nil="true" />

i.e. the i:nil should become xsi:nil and the namespace declared on the element be removed.
Ideally I would like to amend the existing transform to apply this to any node within the XML that would require this, however I am having some difficulty in phrasing a search to get any results as to how this would be done.  If anybody could help, that would be appreciated.
(I am unable to use any xslt 2.0 cleverness, just in case that affects the answer).
Slightly larger sample input:
<message xmlns="http://www.mynamespace.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <paper>
    <name>A name</name>
    <author i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
  </paper>
  <paper>
    <name>Another name</name>
    <author>
      Peter
    </author>
    <details>
      <publishDate i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
      <location>London</location>
    </details>
  </paper>
</message>

And desired output:
<message xmlns="http://www.mynamespace.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <paper>
    <name>A name</name>
    <author xsi:nil="true" />
  </paper>
  <paper>
    <name>Another name</name>
    <author>
      Peter
    </author>
    <details>
      <publishDate xsi:nil="true" />
      <location>London</location>
    </details>
  </paper>
</message>

A: Write an identity transform and two separate templates to handle

*

*attributes that are prefixed with i

*elements that have an attribute which is prefixed with i.

Stylesheet
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attribute::i:*">
    <xsl:attribute name="{concat('xsi:',local-name())}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

<xsl:template match="*[attribute::i:*]">
    <xsl:element name="{local-name()}" namespace="http://www.mynamespace.com">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

Output
Nillability attributes are now prefixed with xsi: and the Schema instance namespace is declared on the root element only.
<?xml version="1.0" encoding="UTF-8"?>
<message xmlns="http://www.mynamespace.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <paper>
      <name>A name</name>
      <author xsi:nil="true"/>
   </paper>
   <paper>
      <name>Another name</name>
      <author>
      Peter
    </author>
      <details>
         <publishDate xsi:nil="true"/>
         <location>London</location>
      </details>
   </paper>
</message>


text:
Q: Send cookies with node-fetch to bing I am trying to fetch bing search results with 50 searches per page. Simply editing the url to include "&count=50" doesn't work, and so I am sending a cookie to update the preference.
Right now I have:
const opts = {
    headers: {
      cookie: "SRCHHPGUSR; NRSLT=50",
    },
  };
const response = await fetch("https://www.bing.com/search?q=example", opts);

Which does not work. Any ideas on how to set the cookie, or another better way of achieving 50 results per page?