text:
Q: Creating a cloudfront distribution using aws cli json Hi i am trying to create a new custom origin cloudfront distribution from aws cli. But i am getting the following error. I ve checked my json file. no errors found but aws cli is throwing the below error
[ec2-user@ip-172-31-20-146 ~]$ aws cloudfront create-distribution --distribution-config "$(
Here is my json file

{
  "DistributionConfig": {
    "CallerReference": "fucking16483256",
    "Aliases": {
      "Quantity": 1,
      "Items": [
        "cdn.nammacloud.com"
      ]
    },
    "Origins": {
      "Quantity": 1,
      "Items": [
        {
          "origin": {
            "CustomOriginConfig": {
              "OriginProtocolPolicy": "match-viewer",
              "HTTPPort": 80,
              "HTTPSPort": 443
            },
            "Id": "Custom-www.nammacloud.com",
            "DomainName": "www.nammacloud.com"
          }
        }
      ]
    },
    "DefaultCacheBehavior": {
      "TargetOriginId": "Custom-www.nammacloud.com",
      "ViewerProtocolPolicy": "allow-all",
      "MinTTL": 3600
    },
    "Comment": "new distribution",
    "Logging": {
      "Bucket": "",
      "Prefix": "",
      "Enabled": false,
      "IncludeCookies": false
    },
    "PriceClass": "PriceClass_All"
  }
}

A: Try removing the wrapping "DistributionConfig" object, so:

{
  "CallerReference": "f***ing16483256",
  "Aliases": {
    "Quantity": 1,
    "Items": [
      "cdn.nammacloud.com"
    ]
  },
  "Origins": {
    "Quantity": 1,
    "Items": [{
      "origin": {
        "CustomOriginConfig": {
          "OriginProtocolPolicy": "match-viewer",
          "HTTPPort": 80,
          "HTTPSPort": 443
        },
        "Id": "Custom-www.nammacloud.com",
        "DomainName": "www.nammacloud.com"
      }
    }]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "Custom-www.nammacloud.com",
    "ViewerProtocolPolicy": "allow-all",
    "MinTTL": 3600
  },
  "Comment": "new distribution",
  "Logging": {
    "Bucket": "",
    "Prefix": "",
    "Enabled": false,
    "IncludeCookies": false
  },
  "PriceClass": "PriceClass_All"
}


text:
Q: What is the best way to secure your program I searched a lot about what is the best way to secure your program and I found many results and there were two good ways.
The first one is to hash the mac address of the computer and link it with an activation code but it's still vulnerable.
And the second one is to use a usb device but I didn't find any detail so can anybody tell me in details what is the best way and how to implement it please.

A: First of all, you need to consider that it doesn't matter what you do, someone will be able to crack it, and because of this is that you need to consider a balance between the security of your application and how hard you will make it for legitimate users (since you don't want to punish a user who already paid for your product, just because you want to protect your applications from the guys who don't want to pay).
Having this in mind, you could go with digital signatures using asymmetric encryption, where you'll sign your license "activation" with your private key, and then your application will use its public key to verify that the received license was submitted by you. You should also take a look at this discussion (I recommend you to focus on the 2nd answer, not the selected one) and this one.
But again, your objective should be to just make things hard for bad guys, but without punishing your legitimate users, because for an attacker, it could be as easy as de-compiling your program and removing your logic to validate the license (unless you're creating an "always online" application, but usually users don't like that, and I'm saying this as a user).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax post request causes 500 internal server error - Laravel In short: 500 internal server error when trying to do a POST request using ajax to a resource controller's method.
Resource CurrencyController:
public function ajaxDeleteImage() {
    if ($request->isMethod('ajax')) {
        $path = $request->input('imgUrl');
        $id = $request->input('id');

        $currency = Currency::findOrFail($id);
        $currency->cur_icon = '';
        $currency->save();
        Storage::delete($path);

        return 'Deleted image!';
    }

    return App::abort(404);
}

Here's my routes:
/**
 * ajax requests
 */

Route::any('ajax-delete-image-currency', 'CurrencyController@ajaxDeleteImage');

/**
 * admin prefix
 */

Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
    Route::resource('request', 'ReqController');
    Route::resource('currency', 'CurrencyController');
});

edit.blade.php - where i created a form with multipart/form-data:
here are some form html code...

@section('custom_scripts')
<script type="text/javascript">
(function($) {

    var thisUrl = $('input[name="image-hidden"]').val();
    var currencyId = $('input[name=id]').val();

    // console.log(thisUrl);

    $('.del-image').click(function() {
        $.ajax({
            method: 'post',
            url: '/ajax-delete-image-currency',
            data: {imgUrl: thisUrl, id: currencyId},
            success: function(data) {
                console.log("removed image");
                window.location.reload();
            },
            error: function(e) {
                alert('Error' + e);
            }
        });
    });

})(jQuery);
</script>
@endsection

The problem is - i am getting internal server error 500 whenever i press on a button with class .del-image (sending post request with ajax).
Also i tried to delete whole method ajaxDeleteImage from a controller at all. Nothing happened, same 500 error. Seems like post request cannot reach that method in a CurrencyController.
Maybe i have a problem in my routes? Wrong sorting? I read that i have to move certain methods above resource controllers, so it would work correctly, but that it's not my case.
Please advice something.

A: It was issue with TokenMismatchException in VerifyCsrfToken.php line 67
So you have to send csrf token with your Ajax request.
Found it with Dev tools -> Network -> then click on the error -> it will show actual response.
Or if you're using Postman - you will see that error in a response.


text:
Q: Get First (specific) node with random (optional) subnodes I need the first node of a complex xml by a deep deep subnode with random nodes between.
My XML:
<abc>
    <bcd id="1">
        <cde>
            <bcd id="100">
                <cde>
                    <xxx id="998">
                    </xxx>
                </cde>
            </bcd>
        </cde>
    </bcd>
    <bcd id="2">
        <cde>
            <bcd id="101">
                <cde>
                    <bcd id="102">
                        <cde>
                            <xxx id="999">
                            </xxx>
                        </cde>
                    </bcd>
                </cde>
            </bcd>
        </cde>
    </bcd>
</abc>

With this XPATH I get only with this design a correct result. the grade of nested is variabel.
"//bcd/cde/bcd/cde/xxx[@id='998']"

I want a XPATH like that where I get the first bcd (id='1') node:
"//[bcd/cde]+/xxx[@id='998']"

or first bcd (id='2') node:
"//[bcd/cde]+/xxx[@id='999']"

regards Chris

A: The following xpath works for me:
/*/bcd[.//xxx/@id='998']


text:
Q: Sequence processing texts - why is padding 'pre' the default? What's the intuition behind adding padding at the start of the text strings in preprocessors such as keras.preprocessing.sequence.pad_sequences ?
Would I be correct to assume that it is related to the fact that default truncation removes the start of strings? On that point, I guess I also don't understand why we think that ends of text strings would be more meaningful than the start.


text:
Q: ¿Cómo utilizar inyección de dependencias en TypeScript? Soy relativamente nuevo en TypeScript y pues me gustaría implementar inyección de dependencias en mi proyecto sin usar módulos. La cuestión es que soy alguien que tiene más experiencia en lenguajes que son más orientados a objetos como C# o Java.
Busqué en internet sobre cómo hacer esto pero lo único que obtuve es usar módulos, algo que no quiero usar aún sin primero intentarlo.
Ésta es mi clase base:
class Motor {
Acelerar(): void {
}
GetRevoluciones(): number {
let currentRPM: number = 0;
return currentRPM;
 }
}
export {Motor};

La clase que usa a Motor:
import { Motor } from "./1";
class Vehiculo {
private m: Motor;
public Vehiculo(motorVehiculo: Motor) {
    this.m = motorVehiculo;
}
public GetRevolucionesMotor(): number {
if (this.m != null) {
    return this.m.GetRevoluciones();
}
else {
    return -1;
}
}
}
export { Vehiculo };

La interface y el tipo de motor:
interface IMotor {
Acelerar(): void;
GetRevoluciones(): number;
 }
class MotorGasoline implements IMotor {
private DoAdmission() { }
private DoCompression() { }
private DoExplosion() { }
private DoEscape() { }
  Acelerar() {
   this.DoAdmission();
   this.DoCompression();
   this.DoExplosion();
   this.DoEscape();
 }
 GetRevoluciones() {
    let currentRPM: number = 0;
    return currentRPM;
  }
}
class MotorDiesel implements IMotor {
  Acelerar() {
   this.DoAdmission();
   this.DoCompression();
   this.DoCombustion();
   this.DoEscape();
}
GetRevoluciones() {
  let currentRPM: number = 0;
  return currentRPM;
}
 DoAdmission() { }
 DoCompression() { }
 DoCombustion() { }
 DoEscape() { }
 }

Y aquí es donde el error aparece:
 import { Vehiculo } from "./2";
 enum TypeMotor {
   MOTOR_GASOLINE = 0,
   MOTOR_DIESEL = 1
 }
 class VehiculoFactory {
 public static VehiculoCreate(tipo: TypeMotor) {
  let v: Vehiculo = null;
   switch (tipo) {
      case TypeMotor.MOTOR_DIESEL:
          v = new Vehiculo(new MotorDiesel()); break;
      case TypeMotor.MOTOR_GASOLINE:
          v = new Vehiculo(new MotorGasoline()); break;
      default: break;
  }
  return v;
  }
 }

He oído que se puede hacer en JavaScript así que he intentado implementarlo con TypeScript. Por el momento no estoy interesado en usar ningún módulo; sólo quiero implementarlo correctamente sin depender de ellos.
Actualizado
Me olvidé de poner el error. IntelliSense me muestra un error de este tipo:

Supplied parameters do not match any signature of call target.

A:
La cuestión es que soy alguien que tiene más experiencia en lenguajes que son más orientados a objetos como C# o Java.

JavaScript es orientado a objetos también, pero no de la forma tradicional que implementan C# y Java; JavaScript implementa un estilo de orientación a objetos protipado.
Lo que estás hanciendo se llama inversión de control (IoC) y es una técnica que consiste en inyectar las dependencias desde fuera de la clase. El modo que usa en Java por ejemplo, es por medio de un contenedor de dependencias que se resuelven en tiempo de ejecución por medio de calificadores, por ejemplo: @Diesel, @Gasoline para que no haya ambiguedad al inyectarlas.
Tu problema es que defines en el constructor que la clase Vehiculo acepta una instancia de tipo Motor, pero lo que estás pasando es una implementación de IMotor. Lo que debes hacer es cambiar la firma del constructor de Vehiculo para que acepte cualquier implementación de IMotor:
public Vehiculo(motorVehiculo: IMotor) {
    this.m = motorVehiculo;
}

De esta manera podrás pasar instancias de MotorDiesel y MotorGasoline.

Cómo funciona el tipado estático en JavaScript/Typescript
El tipado estático en estos lenguajes funciona similar a C# y Java. El tiempo de ejecución se evalúa si la instacia que se ha pasado es del tipo definido:

*

*Instancia recibida en el constructor.

*Evaluación de tipos.

*¿Es del tipo especificado?

*

*Sí: continuar.

*No: lanzar error.

En el paso dos se hace una especie de typeof para saber si el parámetro en realidad cumple los requisitos de la firma del método, de esta manera, Typescript puede "saber" si se ha cumplido la firma o no.
Ten en cuenta que Typescript es casi una implementación básica de C# para el lado cliente, y por ende, se trata de emular su comportamiento. Si sabes como funciona C#, entonces sabrás como funciona Typescript con mayor facilidad.


text:
Q: Area 51 should have its own privileges pages On all main Stack Exchange sites, clicking on your reputation score at the top of the screen directs you to the privileges page. On Area 51, however, that is not the case. In fact, the page does not even exist. Instead, you have to check the FAQ to find the information you're looking for.
I think Area 51 should function like every other site on the network and have its own privileges pages. It'd be more intuitive and easy to find than it currently is.

A: Area 51 now has its own privileges pages.

A: Since the privledge list is so small on the Area 51 FAQ.  I can understand why it might not need its own page.
However I agree that the user experience would be more consistent and easier to follow if it lined up closer with other sites.


text:
Q: How can  I get an image to appear then fade out then fade into home page? I'm new to Jquery and I believe it is required to do what I need to do here.
A client wants their home page to begin with only the logo image visible and then fade into the navigation and content of the home page after a second or so. The logo image would appear in the center (vertical and horizontal).  At the same time while the logo is shown the home page to appear in the background as a grey scale.

A: Create an image on top of everything else. This can be done by making the position: absolute, and maybe adjust the z-index. Give the image and id.
You can chain animate() functions and put whatever effect you want in there.
$( "#block1" ).animate({opacity: 100%;},1000).animate({opacity: 0%;},1000);

Because after the animation you want to remove the image so that it isn't displayed (or you can't click on anything underneath the image).
So can use toggle instead of animate (but toggle also adjusts height and width as part of its effect):
$( "#block1" ).toggle(1000);

To make only the image display initially, put everything else inside a div, and set it to display: none in css. Then set a callback ( .toggle( [duration] [, callback] ) at http://api.jquery.com/toggle/). And for the callback declare a function to set the display back on for everything else:
$( "#block1" ).toggle(1000, function () {
  $("#everythingelse").css("display: inline");
});

Or you can set the display to none with an animate function:
$( "#block1" ).animate({opacity: 0%;},1000,"linear", function () {
  $( "#block1" ).css("display: none");
  $("#everythingelse").css("display: inline");
});

With animate (more information at http://api.jquery.com/animate/), you have more custom control over its effects

A: use a callback function inside animate function, look at this tutorial ... http://cdmckay.org/blog/2010/03/01/the-jquery-animate-step-callback-function/


text:
Q: Read Json from request in Spark I'm strating with Spark, and I'm trying to get a request with a Json as parameter.
This is how I send it:
  let data = {
    req: this.state.results
  }

  const apiAddress = 'http://localhost:4567/results';
  fetch(apiAddress, {
    method: 'post',
    body: data
  }).then( (res) => {
      console.log(res);
      return res
  });

And I'm getting this on the server side calling request.body():
Request ------WebKitFormBoundaryBvud3Cn7ZmzAtAXt
Content-Disposition: form-data; name="data"

[object Object]
------WebKitFormBoundaryBvud3Cn7ZmzAtAXt--

But I cant find a way to know what's in that Object or how to get to its parameters.


text:
Q: Fashion color matching or fashion matching colors I am working on an app that gives suggestions on how to match colors for your clothes and I am looking for a tagline for the app.
Which is better? "Fashion color matching" or "Fashion matching colors" or "Matching fashion colors"? Or is there a better choice of words? I am not a native English speaker so I don't know which formulation sounds more natural.

A: How about making the tagline sound more active by having the verb in front? ie "Matching colors in style," "Matching colors for fashion"

A: How about "Matching colors fashionably"?
Or "Fashionable color matching."

A: You can use below tag lines for your app,

*

*A style for every story.

*Be your own label.

*Designed for fit. Loved for style.

*Fashion is nothing without people.


text:
Q: How to make html file encrypted? I want to know, how to make my html file code to encrypted?
So that if normal user see the code,
then they don't understand the code?

A: You can't. If the user can't see it, the browser wouldn't be able to either!

A: This is called obfuscation, but it's pointless.  People can still view your complete DOM tree in DOM Inspector or Firebug.  As this Yahoo blog entry says, "If you don't want people to see your programs, unplug your server."  This applies equally to HTML.

A: Don't bother. All encryption will do for you is slow down your site. It's not worth 'hiding' it. Any moron can just open up Firebug and see everything without even having to decrypt the source code anyways.

A: This might be good:  http://www.iwebtool.com/html_encrypter
it's free and online makes your code into unicode hope less to copy and edit!

A: I don't remember how I did it, but I was just reading some of my own code recently and I couldn't even understand it.  A normal user would not have a chance.  I don't thing encryption was involved however.

A: You may try disable the mouse right click.
JS (jQuery):
$(document).bind('contextmenu',function(){return false;});

Again as shown in other posts this is actually meaningless because if someone want to view the source they can just press F12 to open the console and view all the codes.
Also, I don't think a normal user will want to see this kind of things. If they see that, they just think they're pressing the wrong button and close it.

A: You can use StatiCrypt to encrypt your HTML file using AES-256 encryption. You then get a simple HTML page with a password prompt, see example.
Two cautionary notes from the project's repository:

Disclaimer if you have extra sensitive banking data you should probably use something else!
...
AES-256 is state of the art but brute-force/dictionary attacks would be trivial to do at a really fast pace: use a long, unusual passphrase.

A similar tool is clientside-html-password. There might be others as well, but the bottom line is that you can make an HTML file encrypted.

A: I've written a tool to encrypt HTML files called PageCrypt. The tool asks for a password at the time of encryption, then spits out an encrypted HTML file. Then, when a user views the encrypted file, they need to input the set password to be able to unscramble and view it.
The tool is hosted here:
https://www.maxlaumeister.com/pagecrypt/
with source code available here:
https://github.com/MaxLaumeister/pagecrypt

Description of the project, from the project page:

PageCrypt - Password Protect HTML
This tool lets you securely password-protect an HTML file. Unlike other password-protection tools, this tool:

*

*Has no server-side components (this tool and its password-protected pages run entirely in javascript).

*Uses strong encryption, so the password-protection cannot be bypassed.
All you need to do is choose an HTML file and a password, and your page will be password-protected.

A: You can try DRM-X 4.0, it supports protect HTML JS CSS and Images. it also supports protect Dynamic Website.
https://www.haihaisoft.com/HTML-Encryption.aspx
https://www.haihaisoft.com/Dynamic-Website-DRM-Protection.aspx


text:
Q: Combine two colors together I want to combine the values of two colors. For example:
// color 1:
int aa = 255;
int rr = 255;
int gg = 0;
int bb = 0;

// color 2:
int aa = 128;
int rr = 0;
int gg = 0;
int bb = 0;

The first color is pure red at 100% alpha. The second color is black at 50% alpha. I want to find the final combined color, as if I layered the second color on top of the first, as you could do in photoshop via layers.
What is the formula for doing this? I'm not sure of the correct terminology here, so getting search results that I don't think are what I want.
Thanks

A: Have yo tried adding the two colors to see if the results is what you expect?
Class Color
{
int aa ;
int rr ;
int gg ;
int bb;
}

 Color Combined( Color a, Color b)
 {
    Color result=new Color();
    result.aa=(int)((a.aa+b.aa)/2);
    result.rr=(int)( (a.rr+b.rr)/2);
    result.gg=(int)( (a.gg+b.gg)/2);
    result.bb=(int)( (a.bb+b.bb)/2);
    return result;
 }


text:
Q: Issue with Intellij 13.1 when working with a project (java + scala) with multiple source folder I have a project (java + scala) which has multiple source folders.
When I exclude all source folders except one, intelliJ resolves java references properly.
But when I include other source folders, somehow intelliJ resolves only java references in the first occuring source folder only.
Am I missing something here ?
Can someone please help me with this ?
Thanks
Ganesh


text:
Q: File runs from python.exe I just switch laptops and everything seems to be normal except this. When I open CMD and try to run a file like py filename.py
it comes up with an error
C:\Users\john\AppData\Local\Programs\Python\Python37\python.exe: can't open file 'filename.py': [Errno 2] No such file or directory
It defaults to the python.exe file. It does it for every file that I try to run as well. I am in the correct directory (the directory where the actual file is in) but it keeps defaulting to that error. I am running windows 10 with python 3.7.3.

A: You may have to change the default directory where your terminal looks for the python.exe file and its packages. You must change both. One variable points to the python[version] folder and the other points to the python[version]\scripts folder.
This page shows you how to redirect your terminal in windows:
https://superuser.com/questions/1399544/how-to-change-default-python-executable-on-windows-10/1399546
Another tip is that you must change these two identical directories for both the "user variables" and the "system variables" listed in the section below it. I believe the Python installation has probs with this, especially if it's a reinstall or a failed update. And on Windows in general.
Best,


text:
Q: Android buttons in relative view - Have buttons fill available width I have a 9 buttons labeled 1 through 9 in a 3 by 3 Calculator like configuration. These are all contained in a relative view. I would like to have the buttons grow wider than they need to be and fill the available width of the relative view. The relative view is set to fill parent. I would also like to leave at least a small gap between the buttons so that they are not touching. What is the best way to approach this?

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn0"
        android:id="@+id/btn0"
        android:layout_above="@+id/btnStart"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="btnNumber_Click"
        android:tag="0" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn1"
        android:id="@+id/btn1"
        android:layout_above="@+id/btn0"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:tag="1"
        android:onClick="btnNumber_Click" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn2"
        android:id="@+id/btn2"
        android:tag="2"
        android:onClick="btnNumber_Click"
        android:layout_above="@+id/btnNegative"
        android:layout_alignLeft="@+id/btnNegative"
        android:layout_alignStart="@+id/btnNegative" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn3"
        android:id="@+id/btn3"
        android:layout_above="@+id/btn0"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:tag="3"
        android:onClick="btnNumber_Click" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn4"
        android:id="@+id/btn4"
        android:layout_above="@+id/btn1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:tag="4"
        android:onClick="btnNumber_Click" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn5"
        android:id="@+id/btn5"
        android:tag="5"
        android:onClick="btnNumber_Click"
        android:layout_below="@+id/btn8"
        android:layout_alignLeft="@+id/btn2"
        android:layout_alignStart="@+id/btn2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn6"
        android:id="@+id/btn6"
        android:layout_alignBottom="@+id/btn5"
        android:layout_alignLeft="@+id/btn3"
        android:layout_alignStart="@+id/btn3"
        android:tag="6"
        android:onClick="btnNumber_Click" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn7"
        android:id="@+id/btn7"
        android:layout_above="@+id/btn4"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:tag="7"
        android:onClick="btnNumber_Click" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn8"
        android:id="@+id/btn8"
        android:tag="8"
        android:onClick="btnNumber_Click"
        android:layout_alignTop="@+id/btn7"
        android:layout_alignLeft="@+id/btn5"
        android:layout_alignStart="@+id/btn5" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn9"
        android:id="@+id/btn9"
        android:layout_alignTop="@+id/btn8"
        android:layout_alignLeft="@+id/btn6"
        android:layout_alignStart="@+id/btn6"
        android:tag="9"
        android:onClick="btnNumber_Click" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnEnter"
        android:id="@+id/btnEnter"
        android:layout_alignTop="@+id/btn0"
        android:layout_alignRight="@+id/btn3"
        android:layout_alignEnd="@+id/btn3"
        android:onClick="btnEnter_Click"
        android:layout_alignLeft="@+id/btn3"
        android:layout_alignStart="@+id/btn3"
        android:singleLine="false" />

Thanks,
David

A: This is how you layout should be,
And also set margin to all buttons to have some space between them.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal">

    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

</LinearLayout>
<LinearLayout
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal">

    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

</LinearLayout>
<LinearLayout
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal">

    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

</LinearLayout>
</LinearLayout>


text:
Q: Union between sets I am taking a Coursera Functional Programming in Scala class. This is the second week and I hit a wall. In the assignment we are working with Sets, but not the kind of Set we all meet in Java, for example. It is a Set that returns true if the value is in there and false otherwise. They say it's not a container, it's just a function.
To get it clear, I need your help. I don't want you to solve my assignment, it's just an example that I want to get the idea of what I should do.
/**
   * We represent a set by its characteristic function, i.e.
   * its `contains` predicate.
   */
  type Set = Int => Boolean

 /**
   * Indicates whether a set contains a given element.
   */
  def contains(s: Set, elem: Int): Boolean = s(elem)

 /**
   * Returns the set of the one given element.
   */
  def singletonSet(elem: Int): Set = Set(elem)

 /**
   * Returns the union of the two given sets,
   * the sets of all elements that are in either `s` or `t`.
   */
  def union(s: Set, t: Set): Set = ???

This is the code. In the singletonSet I guess the way to solve it is to return the Set(elem), right?
If that is good, how am I supposed to make the union between the two? I am not new to programming but I can't see any way to do it. Since I shouldn't return a "set" of numbers.
This is what another student told me about sets: "But all a "Set" is is a function that takes an Int and returns a Boolean (Int => Boolean). Any function that takes an Int and returns a Boolean fits the type 'Set'."
What I tried in the union function is to have something like:
def union(s: Set, t: Set): Set = (s | t) //value | not a member of Int => Boolean

Any help would be appreciated :)

A: A possible hint is to look at the types. Look at the Set type. It is actually a type alias to a function from Int into Boolean.
Thus, when you have two sets, you actually have two functions. How can you use them to provide a function that represent the union of these Set? It must be your starting point.

A: It seems the wall you are hitting is that you are unfamiliar with defining functions in Scala. In this particular case you need to define functions of type Int => Boolean, they take an Int and return a Boolean.
Here are some examples of function literals of type Int => Boolean. Try them in the Scala console or the Scala IDE worksheet:
(x: Int) => true
(x: Int) => false
(x: Int) => x == 2
(x: Int) => x == 10
(x: Int) => x == 2 || x == 10
(x: Int) => x % 2 == 0

Then all you have to do for the assignment is to use the same syntax, starting with (x: Int) => and then translate the meaning of union, intersect, ... into the right hand side of the expression.
Part of learning is giving it a genuine effort. I believe you can resubmit the solution multiple times, so don't hesitate to submit and iterate if you don't get 10/10 on the first try. All you need is compiling code. Good luck!


text:
Q: Expressing the solution to a rational expression in radical form I'm trying to find the solution to this equation
$$
-\frac{3}{r} + \frac{8}{r^3} = \frac{\sqrt{2}-1}{2}
$$
but I haven't been able to find a solution in radical form. Although I've found the solutions as decimals, I am looking for a solution in radical form. What are the solutions to this equation expressed as radicals?


text:
Q: Python smtplib - not sending with variables I am trying to send an email using the smtplib library. It works fine, but if my message includes a fixed string + variable, it doesn't work.
Here is my code:
destinationEmail = 'destination@gmail.com'
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login("me@gmail.com", "password")
message = f"I am sending this variable: {variableName}"
server.sendmail("me@gmail.com", destinationEmail, message)

Using the above code does not work. I've tried using this format for the message as well:
message = "I am sending this variable: " + variableName

It also does not work. If my message has no variables, it sends successfully, like:
message = "testing"

Another thing I've tried is sending the variable alone, like:
message = variableName

And that works! So I'm really confused what is wrong here. It seems like it doesn't wanna send messages that has a fixed string + variable. BTW the variable I am using is of type string. Even when I use str( ) around the variable, it doesn't work.

A: This is usually a version problem, but you can always substitute your f-string for message = "I am sending this variable: {}".format(variable_name) which worked for me.

A: The answer is here: How to send variable value via email with smtplib in python3?
Use MIMEText to construct the message (with 'subject' 'from' and 'to'). @tax evader was right about the subject thing. I guess it requires a subject.


text:
Q: MPI_Isend reusing internal buffer I have a Finite Element code that uses blocking receives and non-blocking sends. Each element has 3 incoming faces and 3 outgoing faces. The mesh is split up among many processors, so sometimes the boundary conditions come from the elements processor, or from neighboring processors. Relevant parts of the code are:
std::vector<task>::iterator it = All_Tasks.begin();
std::vector<task>::iterator it_end = All_Tasks.end();
int task = 0;
for (; it != it_end; it++, task++)
{
  for (int f = 0; f < 3; f++)
    {
        // Get the neighbors for each incoming face
        Neighbor neighbor = subdomain.CellSets[(*it).cellset_id_loc].neighbors[incoming[f]];

        // Get buffers from boundary conditions or neighbor processors
        if (neighbor.processor == rank)
        {
            subdomain.Set_buffer_from_bc(incoming[f]);
        }
        else
        {
            // Get the flag from the corresponding send
            target = GetTarget((*it).angle_id, (*it).group_id, (*it).cell_id);
            if (incoming[f] == x)
            {
                int size = cells_y*cells_z*groups*angles*4;
                MPI_Status status;
                MPI_Recv(&subdomain.X_buffer[0], size, MPI_DOUBLE, neighbor.processor, target, MPI_COMM_WORLD, &status);
            }
            if (incoming[f] == y)
            {
                int size = cells_x*cells_z*groups*angles * 4;
                MPI_Status status;
                MPI_Recv(&subdomain.Y_buffer[0], size, MPI_DOUBLE, neighbor.processor, target, MPI_COMM_WORLD, &status);
            }
            if (incoming[f] == z)
            {
                int size = cells_x*cells_y*groups*angles * 4;
                MPI_Status status;
                MPI_Recv(&subdomain.Z_buffer[0], size, MPI_DOUBLE, neighbor.processor, target, MPI_COMM_WORLD, &status);
            }
        }
    }

    ... computation ...

    for (int f = 0; f < 3; f++)
    {
        // Get the outgoing neighbors for each face
        Neighbor neighbor = subdomain.CellSets[(*it).cellset_id_loc].neighbors[outgoing[f]];

        if (neighbor.IsOnBoundary)
        {
            // store the buffer into the boundary information
        }
        else
        {
            target = GetTarget((*it).angle_id, (*it).group_id, neighbor.cell_id);
            if (outgoing[f] == x)
            {
                int size = cells_y*cells_z*groups*angles * 4;
                MPI_Request request;
                MPI_Isend(&subdomain.X_buffer[0], size, MPI_DOUBLE, neighbor.processor, target, MPI_COMM_WORLD, &request);
            }
            if (outgoing[f] == y)
            {
                int size = cells_x*cells_z*groups*angles * 4;
                MPI_Request request;
                MPI_Isend(&subdomain.Y_buffer[0], size, MPI_DOUBLE, neighbor.processor, target, MPI_COMM_WORLD, &request);
            }
            if (outgoing[f] == z)
            {
                int size = cells_x*cells_y*groups*angles * 4;
                MPI_Request request;
                MPI_Isend(&subdomain.Z_buffer[0], size, MPI_DOUBLE, neighbor.processor, target, MPI_COMM_WORLD, &request);

            }
        }

    }
}

A processor can do a lot of tasks before it needs information from other processors. I need a non-blocking send so that the code can keep working, but I'm pretty sure the receives are overwriting the send buffers before they get sent.
I've tried timing this code, and it's taking 5-6 seconds for the call to MPI_Recv, even though the message it's trying to receive has been sent. My theory is that the Isend is starting, but not actually sending anything until the Recv is called. The message itself is on the order of 1 MB. I've looked at benchmarks and messages of this size should take a very small fraction of a second to send.
My question is, in this code, is the buffer that was sent being overwritten, or just the local copy? Is there a way to 'add' to a buffer when I'm sending, rather than writing to the same memory location? I want the Isend to write to a different buffer every time it's called so the information isn't being overwritten while the messages wait to be received.
** EDIT **
A related question that might fix my problem: Can MPI_Test or MPI_Wait give information about an MPI_Isend writing to a buffer, i.e. return true if the Isend has written to the buffer, but that buffer has yet to be received?
** EDIT 2 **
I have added more information about my problem.

A: So it looks like I just have to bite the bullet and allocate enough memory in the send buffers to accommodate all the messages, and then just send portions of the buffer when I send.


text:
Q: Jquery-ползунок с маркером Подскажите, как добавить маркер к jquery.slider ?

т.е. там где надпись 50км, как можно добавить этот блок?

A: Вот один из вариантов решения на основе документации, только нормально стилями подправить.

$(function() {
  var handle = $("#custom-handle .value-output");
  $("#slider").slider({
    create: function() {
      handle.text($(this).slider("value"));
    },
    slide: function(event, ui) {
      handle.text(ui.value);
    }
  });
});
#custom-handle {
  width: 3em;
  height: 1.6em;
  top: 50%;
  margin-top: -.8em;
  text-align: center;
  line-height: 1.6em;
  position: relative;
}

.value-wrapper {
  display: block;
  position: absolute;
  top: 34px;
  left: -4px;
  border: 1px solid grey;
  right: -13px;
  color: #000000;
}

.value-wrapper::before {
  content: '';
  position: absolute;
  display: block;
  left: 20px;
  top: -16px;
  border: 5px solid transparent;
  border-bottom: 10px solid grey;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

 км/ч


text:
Q: Zend Framework, passing variables to view I have a problem with displaying a view. When I pass var to view, view doesn't render.
Controller:
public function indexAction()
{
    $branchModel = new Application_Model_Branches();
    $branches = $branchModel->getAllBranches();
    $this->view->menu = $branches;
}

View (index.phtml):

Menu

<?php
    $this->htmlList($this->menu);
?>

When I try debug $branches without assign it to view, all seems to be ok, but when I try push it to view,index.phtml don't appear.
Regards

A: You're just missing an echo in your code, the htmlList view helper returns a value - it doesn't echo it. Some examples of the various form view helpers can be seen here

Menu

<?php
    echo $this->htmlList($this->menu);
?>

A: controller
    $this->view->variableName = "Hello World!";//assign here

    $this->view->assign('variableName1', "Hello new World!");//assign here

view
    echo $this->variableName;//echo here

    echo $this->variableName1;//echo here


text:
Q: Why does assigning a member raise NullReferenceException? I've been trying to get this code to work for quite a while now and unfortunately, I've always gotten NullReferenceException. I've found that this code works if one doesn't use pointers to the class but I don't see why pointers could cause this exception.  By the way, I'm not very experienced with c++ so it would be kind of you to explain this in a simple manner.  Thanks in advance.
class Box
{
    public: char* data;
};
int Main()
{
    Box* a;
    a->data = "Hello World";
    return 0;
}

A: Box* a; declares a pointer to a Box object. You don't ever create a Box object so a doesn't point to anything.
The behaviour writing a->data is therefore undefined.
Either drop the pointer so you get Box a;, or use Box* a = new Box();. In the latter case, don't forget to call delete a; at some point else you'll leak memory.
Finally, writing a->data = "Hello World"; could be problematic: a->data will then be a pointer to a read-only string literal; the behaviour on attempting to modify the contents of that buffer is undefined.
It's far better to use a std::string as the type for a.

A: A pointer to a Box object is not a Box object. The pointer Box* a points to a non-existing object, that's why you get an error when you try to assign "Hello World" to a member.
You should create a Box object either by creating it "on the stack" with automatic storage duration:
Box a;

or by creating it "on the heap" with dynamic storage duration:
Box* a = new Box;

and delete it after use:
delete a;

A: A pointer just points to a (hopefully) allocated chunk of memory. In your example, the pointer is uninitialized, and so you're trying to set memory which you don't have access to.
You should ensure that it points to something valid, like this:
int Main()
{
    Box box; // stack allocation
    Box* a = &box; // you could also call new Box; here
    a->data = "Hello World";
    return 0;
}

A: The value of a is undefined because you never set it to anything. Therefore, anything can happen. The most likely thing is that you access memory that is not yours, triggering a segmentation fault or a similar access exception. This is what happened.
Don't do this. Define your address in terms of the address of a variable of the same type that is already defined.

A: a isn't initialized (or assigned), it's just a dangled pointer. Any dereference on it will be Undefined behavior.
You could Box* a = new Box, or Box b; Box* a = &b to make the pointer valid. e.g.
Box* a = new Box;
a->data = "Hello World";
...
delete a;


text:
Q: Assigning names and types to the columns of an empty data frame I found the following command to create an empty data frame whose columns have a name and a type:
dataFrameMio = data.frame("col1" = character(0), "col2" = numeric(0), "col3"= numeric(0))

class(dataFrameMio$col1)  # character OK
class(dataFrameMio$col2)  # numeric OK
class(dataFrameMio$col3)  # numeric OK

And I found this code where the type is automatically set to logical. Is it possible to specify the type also in this case?
colonne = c("col4", "col5", "col6")
dataFrameMio2 = data.frame((matrix(nrow = 0, ncol = length(colonne))))
colnames(dataFrameMio2) = colonne
print(dataFrameMio2)

class(dataFrameMio2$col4)  # logical
class(dataFrameMio2$col5)  # logical
class(dataFrameMio2$col6)  # logical

A: It is just that matrix cannot have more than one type.  It may be either better to create a list and wrap to data.frame as list can have multiple types.  Or if we want to change the type
dataFrameMio2[] <- Map(`class<-`, dataFrameMio2,
   c("character", "numeric", "numeric"))

-checking
> str(dataFrameMio2)
'data.frame':   0 obs. of  3 variables:
 $ col4: chr
 $ col5: num
 $ col6: num
> class(dataFrameMio2$col4)
[1] "character"
> class(dataFrameMio2$col5)
[1] "numeric"
> class(dataFrameMio2$col6)
[1] "numeric"


text:
Q: returning a zero from a mysql count even it there is no result for that month i have a logs table that i want to show the details in a chart, so i wanted a query that will show all the records from January to the current month and if the activities in that month are zero, it should return zero so that the chart may flow,
may table looks like this:
id      user_id  action                 date_added
75      56      Base Adding            2017-02-29 11:52:35
76      56      Base Adding            2017-02-29 11:59:28
77      61      Fuel Adding            2017-02-29 12:05:16
78      56      Update details         2017-02-29 12:17:08
79      57      Logged In              2017-02-29 12:25:41
80      56      Base Adding            2017-03-29 12:40:56
81      55      Logged In              2017-02-29 12:51:31
82      56      Base Adding            2017-05-29 12:53:25

the results that i wanted top see is something like this:
MonthAdded         Totalcount
2017-01              0
2017-02              2
2017-03              1
2017-04              0
2017-05              1

My query looks like this and its not giving me the output, please help me.
SELECT DATE_FORMAT(date_added, '%Y-%m') AS MonthAdded, COUNT(id) AS Totalcost FROM audit_log WHERE date_added LIKE '%2017%' AND user_id = '56' AND (action = 'Base Adding') GROUP BY DATE_FORMAT(date_added, '%Y-%m') ASC

A: Here's the details According to your sample data:
Detailed Result:
select  MonthAdded,count(date_substr) as cnt   from
(select '2017-01'as MonthAdded  UNION all
select '2017-02' UNION all
select '2017-03'  UNION all
select '2017-04'  UNION all
select '2017-05' UNION all
select '2017-06'  UNION all
select '2017-07'  UNION all
select '2017-08'  UNION all
select '2017-09'  UNION all
select '2017-10'  UNION all
select '2017-11'  UNION all
select '2017-12') as a

left join

(select id, user_id, action, date_added,SUBSTRING(date_added FROM 1 FOR 7) as date_substr from
(select 75 as id,      56 as user_id,     'Base Adding' action,            '2017-02-29 11:52:35' as date_added UNION all
select  76,      56,      'Base Adding',            '2017-02-29 11:59:28' UNION all
select 77,      61,      'Fuel Adding',            '2017-02-29 12:05:16' UNION all
select 78,      56,      'Update details' ,        '2017-02-29 12:17:08' UNION all
select 79,      57,      'Logged In' ,            '2017-02-29 12:25:41' UNION all
select 80,      56,      'Base Adding',           '2017-03-29 12:40:56' UNION all
select 81,      55,      'Logged In' ,            '2017-02-29 12:51:31' UNION all
select  82,      56,      'Base Adding',            '2017-05-29 12:53:25') as a
where action = 'Base Adding' and user_id = 56) as b

on a.MonthAdded = b.date_substr
group by MonthAdded

Final Query Structure:
select  MonthAdded,count(date_substr) as cnt   from
(select '2017-01'as MonthAdded  UNION all
select '2017-02' UNION all
select '2017-03'  UNION all
select '2017-04'  UNION all
select '2017-05' UNION all
select '2017-06'  UNION all
select '2017-07'  UNION all
select '2017-08'  UNION all
select '2017-09'  UNION all
select '2017-10'  UNION all
select '2017-11'  UNION all
select '2017-12') as a

left join

(select id, user_id, action, date_added,SUBSTRING(date_added FROM 1 FOR 7) as date_substr from
(select * from yourtable) as a
where action = 'Base Adding' and user_id = 56) as b

on a.MonthAdded = b.date_substr
group by MonthAdded

It include until Dec to make sure if you have a data on it.
Result:
2017-01 0
2017-02 2
2017-03 1
2017-04 0
2017-05 1
2017-06 0
2017-07 0
2017-08 0
2017-09 0
2017-10 0
2017-11 0
2017-12 0


text:
Q: subscribe to a url to add event in ical I Want to add my events that is in my server into ical using eventkit. Can I subscribe to a url programatically so that all the event can be sync in ical app automatically.

A: Synchronization is done from your side (Inside objective "c"). You need to fetching all events from server after hitting appropriate URL.
Parse it and save single event with the help of below method:

-(void)addingEvents{

    EKEventStore *eventStore = [[EKEventStore alloc] init];

    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];

    event.title     = <<Event Title>>;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd hh:mma"];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *strDate = [dateFormatter stringFromDate:<<Your event date>>];

    NSDate *startDate = [dateFormatter dateFromString:strDate];

    [dateFormatter release];

    event.startDate = [[NSDate alloc] initWithTimeInterval:0 sinceDate:startDate];
    event.endDate   = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
    NSArray *alertArray = [NSArray arrayWithObject:[EKAlarm alarmWithRelativeOffset:-300]];
    event.alarms = alertArray;

    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
    if (err) {
        NSLog(@"Error occured : %@",[err localizedDescription]);
    }
    [eventStore release];

}


text:
Q: Updating a nested record, rails will send to SQL to update the parent record id to "nil" I have a problem in updating a nested record from its parent record update page (creation works fine).
# app/controllers/users_controller.rb

...

def create
  @user = User.new(user_params)

  respond_to do |format|
    if @user.save
      format.html { redirect_to user_visites_path @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
    else
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

...

def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

...

def user_params
  params.require(:user).permit(:some_attributes, profile_attributes: [:first_name, :last_name, :birthdate, :first_interview, :send_by, :sexe, :tall, :weight, :etc_attributes])
end

# app/model/profile.rb
class Profile < ActiveRecord::Base
  belongs_to :user
end

# app/model/user.rb
class User < ApplicationRecord
  attr_accessor :last_interview

  has_one :profile
  accepts_nested_attributes_for :profile

  has_many :visites
end

When I do send the update request with the params:
{"some_attributes"=>"",
 "profile_attributes"=>
  {"first_name"=>"Jean",
   "last_name"=>"Paul",
   "birthdate(3i)"=>"14",
   "birthdate(2i)"=>"11",
   "birthdate(1i)"=>"2017",
   "first_interview(3i)"=>"12",
   "first_interview(2i)"=>"11",
   "first_interview(1i)"=>"2017",
   "send_by"=>"",
   "tall"=>"",
   "weight"=>"",
   "etc_attributes"=>""}}

I am getting the following error from the logs:
Profile Load (0.4ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? LIMIT 1  [["user_id", 414]]
SQL (2.7ms)  UPDATE "profiles" SET "user_id" = ?, "updated_at" = ? WHERE "profiles"."id" = ?  [["user_id", nil], ["updated_at", "2017-11-28 00:36:37.936914"], ["id", 4]]
SQLite3::ConstraintException: NOT NULL constraint failed: profiles.user_id: UPDATE "profiles" SET "user_id" = ?, "updated_at" = ? WHERE "profiles"."id" = ?

The weird part is that at the second request rails does to SQL it tries to reset "user_id" and more problematic to nil which is causing me the error.
Do you have an idea why and also, how to avoid it?


text:
Q: Regex to validate SMTP Responses I'm writing a regular expression that can interactively validate SMTP responses codes, once the SMTP dialog is completed it should pass the following regex (some parentheses added for better readability):
^(220)(250){3,}(354)(250)(221)$

Or with(out) authentication:
^(220)(250)((334){2}(235))?(250){2,}(354)(250)(221)$

I'm trying to do rewrite the above regexes so that I can interactively check if the dialog is going as expected, otherwise politely send a QUIT command and close the connection saving bandwidth and time, but I'm having a hard time writing an optimal regex. So far I've managed to come up with:
^(220(250(334(235(250(354(250(221)?)?)?){0,})?){0,2})?)?$

Which, besides only matching authenticated connections, has some bugs... For instance, it matches:
220250334235250354250221
220250334334235250354250221

I've also tried the following modification:
^(220(250)?)?((334(235)?){2})?(250(354(250(221)?)?)?){0,}$

This one accepts non-authenticated responses but it fails to match 220250334 and wrongly matches 220250334334235250354250221 (at least 2 250 are needed before the 354 response code).
Can someone help me out with this? Thanks in advance.

An example of what I'm trying to do:
$smtp = fsockopen('mail.example.com', 25);
$result = null;
$commands = array('HELO', 'AUTH LOGIN', 'user', 'pass', 'MAIL FROM', 'RCPT TO', 'RCPT TO', 'DATA', "\r\n.", 'QUIT');

foreach ($commands as $command)
{
    $result .= substr(fgets($smtp), 0, 3);

    if (preg_match('~^(220(250)?)?((334){1,2}(235)?)?(250(354(250(221)?)?)?){0,}$~S', $result) > 0)
    {
        fwrite($smtp, $command . "\r\n");
    }

    else
    {
        fwrite($smtp, "QUIT\r\n");
        fclose($smtp);
        break;
    }
}

Which should act as a replacement for the following procedural code:
$smtp = fsockopen('mail.example.com', 25);
$result = substr(fgets($smtp), 0, 3); // 220

if ($result == '220')
{
    fwrite($smtp, 'HELO' . "\r\n");
    $result = substr(fgets($smtp), 0, 3); // 220

    if ($result == '250')
    {
        fwrite($smtp, 'AUTH LOGIN' . "\r\n");
        $result = substr(fgets($smtp), 0, 3); // 334

        if ($result == '334')
        {
            fwrite($smtp, 'user' . "\r\n");
            $result = substr(fgets($smtp), 0, 3); // 334

            if ($result == '334')
            {
                fwrite($smtp, 'pass' . "\r\n");
                $result = substr(fgets($smtp), 0, 3); // 235

                if ($result == '235')
                {
                    fwrite($smtp, 'MAIL FROM' . "\r\n");
                    $result = substr(fgets($smtp), 0, 3); // 250

                    if ($result == '250')
                    {
                        foreach ($to as $mail)
                        {
                            fwrite($smtp, 'RCPT TO' . "\r\n");
                            $result = substr(fgets($smtp), 0, 3); // 250

                            if ($result != '250')
                            {
                                fwrite($smtp, 'QUIT' . "\r\n");
                                $result = substr(fgets($smtp), 0, 3); // 221
                                fclose($smtp);

                                break;
                            }
                        }

                        if ($result == '250')
                        {
                            fwrite($smtp, 'DATA' . "\r\n");
                            $result = substr(fgets($smtp), 0, 3); // 354

                            if ($result == '354')
                            {
                                fwrite($smtp, "\r\n.\r\n");
                                $result = substr(fgets($smtp), 0, 3); // 250

                                if ($result == '250')
                                {
                                    fwrite($smtp, 'QUIT' . "\r\n");
                                    $result = substr(fgets($smtp), 0, 3); // 221
                                    fclose($smtp);

                                    if ($result == '221')
                                    {
                                        echo 'SUCESS!';
                                    }
                                }

                                else
                                {
                                    fwrite($smtp, 'QUIT' . "\r\n");
                                    $result = substr(fgets($smtp), 0, 3); // 221
                                    fclose($smtp);
                                }
                            }

                            else
                            {
                                fwrite($smtp, 'QUIT' . "\r\n");
                                $result = substr(fgets($smtp), 0, 3); // 221
                                fclose($smtp);
                            }
                        }
                    }

                    else
                    {
                        fwrite($smtp, 'QUIT' . "\r\n");
                        $result = substr(fgets($smtp), 0, 3); // 221
                        fclose($smtp);
                    }
                }

                else
                {
                    fwrite($smtp, 'QUIT' . "\r\n");
                    $result = substr(fgets($smtp), 0, 3); // 221
                    fclose($smtp);
                }
            }

            else
            {
                fwrite($smtp, 'QUIT' . "\r\n");
                $result = substr(fgets($smtp), 0, 3); // 221
                fclose($smtp);
            }
        }

        else
        {
            fwrite($smtp, 'QUIT' . "\r\n");
            $result = substr(fgets($smtp), 0, 3); // 221
            fclose($smtp);
        }
    }

    else
    {
        fwrite($smtp, 'QUIT' . "\r\n");
        $result = substr(fgets($smtp), 0, 3); // 221
        fclose($smtp);
    }
}

else
{
    fwrite($smtp, 'QUIT' . "\r\n");
    $result = substr(fgets($smtp), 0, 3); // 221
    fclose($smtp);
}

A: I presume you're building a string with all the response codes you receive, stripping out the rest of the message?
This is probably not the answer you want, but I can't help but get the feeling that regex is just not the right tool here. Regular expressions are good at parsing text into tokens or extracting interesting sub-strings out of a larger string. But you already have tokens (SMTP response codes) and you're trying to ensure that they arrive in the expected order. I'd just add the response codes to a queue and after every addition check whether the start of the queue matches one of the expected pattern for the state that you're in. If it does, remove that part from the queue and go to the next state. There are only a few states, so I'd just write code specific to those, rather than try to abstract it into some kind of a state machine.
If you do go the Regex way you might want to keep space in the string as separators - it would not only make it easier to match codes, but easier to read the program as well.
Edit: Thanks for posting the code. It's pretty much what I assumed. You're basically trying to create an abstract solution to this problem, so you have the ability to send an a given array of commands and expect back a given pattern of responses. You really don't need to make it abstract - the added complexity is huge and unlikely to pay off in re-use. Just write the code that says: send X, if you receive Y continue, otherwise QUIT. It will be so much easier and more readable.

A: It's amazing how regular expressions become so much easier after a good night of sleep, here it is:
(?>220(?>250(?>(?>334){1,2}(?>235)?)?(?>(?>250){1,}(?>354(?>250(?>221)?)?)?)?)?)?

Which can be simplified to this:
^220(?>250(?>(?>334){1,2}(?>235)?)?(?>(?>250){1,}(?>354(?>250)?)?)?)?$

Since the first response code (220) is not optional and we will always send the last QUIT command.


text:
Q: Strange Behaviour of  i'm using PrimeFaces 5, Glassfish server ver.4 and firefox as browser. I'm developing a web app via Netbeans8.0.1 where in index.xhtml page I need to show a list of tips at each login.
To do this i'm using this code in my index.xhtml page
<f:event type="preRenderView" listener="#{promemoriaController.promemoriaInScadenza()}"/>

This "f:event" is outside the "f:metadata> tag.
I don't know why but the f:event listner is executed twice at every login.
I'm sure that the usage of the promemoriaController.promemoriaInScadenza() is only in the f:event>.
Thank's a lot for your replies

A: Looks like the container of this <f:event>element, is rendered 2 times. 1 from the initial page load, and another one, probably from some ajax action
You could check all the parent elements of this , and see if any of these is called to update from another action. Using the autoupdate="true" attribute can also trigger some unexpected updates and re-renderings

A: Check if your <f:event/> tag is inside <f:metadata> - if so, put it outside.


text:
Q: Cakephp 3.6.14: Controller get post request, reopen view and copy form elements I want when the user submits the form then the contents of this form will be saved in the database but then it will redirect to the same form with the fields same as the previous one so the user can edit some of them and save it again. How I can achieve that?
CODE
add.ctp:
<div class="roles form large-9 medium-8 columns content">
<?= $this->Form->create($role) ?>
<fieldset>
    <legend><?= __('Add Role') ?></legend>
    <?php
        echo $this->Form->control('name');
        echo $this->Form->control('description');
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

RolesController.php (add function)
public function add()
{
    $role = $this->Roles->newEntity();
    if ($this->request->is('post')) {
        $role = $this->Roles->patchEntity($role, $this->request->getData());
        if ($this->Roles->save($role)) {
            $this->Flash->success(__('The role has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The role could not be saved. Please, try again.'));
    }
    $this->set(compact('role'));
}

A: For staying on the same page / form just remove the return $this->redirect(['action' => 'index']) - but I don't think that's what you really want. The user would be dead ended on the "add" page - just adding more entities...
Check out the CakePHP Controller tutorial - it shows how to create the edit method and template. After doing so you have to change the redirect to something like return $this->redirect(['action' => 'edit', $role->get('name')]) (assuming that the name property is appropriate for identifying role entities).


text:
Q: Проблема с версиями node.js При настройке сервера ubuntu 16.04 установил Node.js через nvm. Установил v.8.0.0 при запуске сервера вылетает ошибка, понял что суть в версии Node.js.
Вот что выдает терминал:

aloha@infopanda:~/infopanda.ru$ nodejs -v
v4.2.6

aloha@infopanda:~/infopanda.ru$ node -v
v8.0.0

Как сделать так, чтобы использовался только node (а не nodejs), так как все остальное (nodemon и pm2) используют именно команду node?

A: Возможно nvm (или n) был полезен "раньше". Сейчас есть две основных версии Node - текущая (current) и LTS. Они стабильны и нет никакой причины гибко настраивать версии, кроме как поддержка legacy приложений. Но и тут Docker будет намного удобней. Используйте официальную инструкцию
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

А для запуска разных версий Docker/Node
docker run --rm -it node:carbon ...

Рекомендую не использовать nvm, n и официальные версии из репозиториев Ubuntu. А использовать Docker для разных версий, и LTS версию Node.js как основной пакет. Это очень стабильная связка и в разработке и в production.

A: У вас в системе просто две версии nodejs установлено. Удалите одну.
Посмотрите, где они у вас лежат:
whereis node
whereis nodejs

Я бы рекомендовал удалить оба, а потом переустановить.
Ну или симлинк сделайте.

A: Итак, одно время я действительно пользовался nvm и мне было удобно.
недавно я был вынужден переехать на другую машину и снова полез искать как установить node.js на ubuntu
Описываю 2 самых простых способа:
Для начала установим необходимые пакеты
sudo apt-get install build-essential libssl-dev

*

*Установка node.js с долгосрочной поддержкой, на данный момент это 8.0.0
Все до смешного просто:

sudo apt install nodejs
При необходимости npm ставится так же
sudo apt install npm

*Если Вам нужна какая-то определенная версия

curl -sL https://deb.nodesource.com/setup_8.x -o nodesource_setup.sh
При этом вместо '8' в слове 'setup_8.x' заменяем на ту версию, которая Вам нужна.
Далее выполним только что скачанный скрипт из репозиториев Node
sudo bash nodesource_setup.sh
И собственно устанавливаем node.js с параметром -y
sudo apt install -y nodejs
Вуаля, у вас нужная Вам версия node.js и npm.


text:
Q: How to Use DataSource Loop in SoapU Pro I have used Datasource for uploading Excel sheet which has 4 rows data in SoapUI Pro.
on one time running one row will be used for input data. I want to use all 4 rows data so used datasource loop.
After using data source loop and running , its taking 15 rows(4 rows contains data remaining 11 rows are empty).
How to control it to only 4 rows.

A: Probably the Excel document contains these rows even though they are empty. You can circumvent this problem by ignoring empty rows. The Excel DataSource contains the option "Ignore Empty". Check this option and empty rows will be skipped.


text:
Q: How to fix: Microphone not receiving the voice after installing PyAudio I am getting errors wherever I have written in query and query.replace and the microphone is also not recognizing my voice even after installing PyAudio.
Python version using: Python 3.10.5
OS: Windows 11
IDE used: VS Code
Here is the full code:
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib

print('Initializing The Donna...')

BOSS = 'Sarah'

r = sr.Recognizer()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

#speak func
def speak(text):
    engine.say(text)
    engine.runAndWait()

#greeting acc to current time
def wishMe():

    hour = int(datetime.datetime.now().hour)

    if hour>=0 and hour <12:
        speak('Good Morning' + BOSS)

    elif hour>=12 and hour<16:
        speak('Good Afternoon' + BOSS)

    else:
        speak('Good Evening' + BOSS)

    speak('How may I help you?')

#take command from microphone
def takeCommand():
    with sr.Microphone(device_index=True) as source:
            r.adjust_for_ambient_noise(source, duration=0.2)
            print('Listening...')
            audio = r.listen(source)

    try:

        print('Recogninzing...')
        query = r.recognize_google(audio, Language = 'en-in')
        query = query.lower()
        print(f'user said: {query}\n')

    except Exception  as e:
        print('Say that again please...')
        query = None
    return query

#sending email
def send_email(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('abc2022@gmail.com', 'blahblah')
    server.sendmail('def2022@gmail.com', to, content)
    server.close

def main():
    wishMe()
    query = takeCommand()
    #logic for executing tasks as per the query
    if 'wikipedia' in query:
        speak('Searching wikipedia...')
        query = query.replace('wikipedia', '')
        results = wikipedia.summary(query, sentences = 2)
        speak('According to wikipedia')
        print(results)
        speak(results)

    elif 'open youtube' in query:
        url = 'youtube.com'
        chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
        webbrowser.get(chrome_path).open(url)

    elif 'open google' in query:
        url = 'google.com'
        chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
        webbrowser.get(chrome_path).open(url)

    elif 'open spotify' in query:
        url = 'spotify.com'
        chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
        webbrowser.get(chrome_path).open(url)

    elif 'time' in query:
        strTime = datetime.datetime.now().strftime("%H:%M:%S")
        speak(f'the time is {strTime}')

    elif 'open code' in query:
        codePath = 'C:\\Users\\asus\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe'
        os.startfile(codePath)

    elif 'send a mail' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                speak("whome should i send")
                to = input()
                send_email(to, content)
                speak("Email has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this email")

    elif "who made you" in query or "who created you" in query:
            speak("I have been created by sarahcodebyte.")

    elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("User asked to Locate")
            speak(location)
            webbrowser.open("https://www.google.nl / maps / place/" + location + "")

main()


text:
Q: Need PHP Mailer Form with File Attachment script to send form information with or without attachment I'm having some trouble trying to get my script to send a file attachment with the information collected from the form. I used PHP Mailer Form with File Attachment and modified to fit my specification. So far it will send the form information without the attached image but when I upload an image it will only send the attachment and no other information from the form. I need it to be able to send the form information with or without an attachment. I'm a beginner with php so I'm not sure why its doing this.
Here is my code
<?php

if(isset($_POST['submit'])){

    $sendTo = '<myemail@somesite.com';
    $subject = 'Request';
    $from = $_POST['email_address'];

    // Allowed file types. add file extensions WITHOUT the dot.
    $allowtypes=array("jpg", "png", "gif");

    // Require a file to be attached: false = Do not allow attachments true = allow only 1 file to be attached
    $requirefile="true";

    // Maximum file size for attachments in KB NOT Bytes for simplicity. MAKE SURE your php.ini can handel it,
    // post_max_size, upload_max_filesize, file_uploads, max_execution_time!
    // 2048kb = 2MB,       1024kb = 1MB,     512kb = 1/2MB etc..
    $max_file_size="5120";

    $errors = array(); //Initialize error array

    //Check if the file type uploaded is a valid file type.
    if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) {
            // basename -- Returns filename component of path
            $filename = basename($_FILES['attachment']['name']);
            $ext = substr($filename, strrpos($filename, '.') + 1);
            $filesize=$_FILES['attachment']['size'];
            $max_bytes=$max_file_size*5120;

            //Check if the file type uploaded is a valid file type.
            if (!in_array($ext, $allowtypes)) {
                $errors[]="Invalid extension for your file: ".$filename."";

        // check the size of each file
        } elseif($filesize > $max_bytes) {
                $errors[]= "Your file: ".$filename." is to big. Max file size is ".$max_file_size."kb.";
            }

    } // if !empty FILES

        // send an email
        // Obtain file upload vars
        $fileatt      = $_FILES['attachment']['tmp_name'];
        $fileatt_type = $_FILES['attachment']['type'];
        $fileatt_name = $_FILES['attachment']['name'];

        // Headers
        $headers = 'From: '.$from = $_POST['email_address'];

        // create a boundary string. It must be unique
        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

        // Add the headers for a file attachment
        $headers .= "\nMIME-Version: 1.0\n" .
                  "Content-Type: multipart/mixed;\n" .
                  " boundary=\"{$mime_boundary}\"";

        // Add a multipart boundary above the plain message
        $message ="This is a multi-part message in MIME format.\n\n";
        $message.="--{$mime_boundary}\n";
        $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
        $message.="Content-Transfer-Encoding: 7bit\n\n";
        $message .= "Name: \t\t".$_POST['name']."\n";
        $message .= "Email: \t\t".$_POST['email_address']."\n";
        if($_POST['phone_number'] != ""){
            $message .= "Phone: \t\t".$_POST['phone']."\n";

        $message .= "Date: \t\t".$_POST['full_date']."\n";
        }
        $message .= "\n";
        if($_POST['additional_info'] != ""){
            $message .= "Additional Information: \n".$_POST['additional_info']."\n";
        }
        if (is_uploaded_file($fileatt)) {
        // Read the file to be attached ('rb' = read binary)
        $file = fopen($fileatt,'rb');
        $data = fread($file,filesize($fileatt));
        fclose($file);

        // Base64 encode the file data
        $data = chunk_split(base64_encode($data));

        // Add file attachment to the message
        $message .= "--{$mime_boundary}\n" .
                  "Content-Type: {$fileatt_type};\n" .
                  " name=\"{$fileatt_name}\"\n" .
                  //"Content-Disposition: attachment;\n" .
                  //" filename=\"{$fileatt_name}\"\n" .
                  "Content-Transfer-Encoding: base64\n\n" .
                  $data . "\n\n" .
                  "--{$mime_boundary}--\n";
        }

        // Send the completed message
        mail($sendTo, $subject, $message, $headers);

        header("Location: complete.php");
}

?>

A: Here is what I have done to send a mail with an attachment. Some of the code is mine and some of it has been taken from http://php.net/manual/en/function.mail.php. This code has been tried and tested so, it should work. Also see if sendmail is installed. If on linux ubuntu system try sudo apt-get install sendmail to install it.
File Name: index.php
    <?php
    if( $_POST || $_FILES )
    {
            // email fields: to, from, subject, and so on
            // Here
            $from = "someone@somewhere.com";
            $to = "someone_else@somewhere_else.com";
            $subject = "Mail with Attachment";
            $message = "This is the message body and to it I will append the attachments.";
            $headers = "From: $from";

            // boundary
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

            // headers for attachment
            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

            // multipart boundary
            $message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
            fixFilesArray($_FILES['attachment']);
            foreach ($_FILES['attachment'] as $position => $file)
            {
                    // should output array with indices name, type, tmp_name, error, size
                    $message .= "--{$mime_boundary}\n";
                    $fp     = @fopen($file['tmp_name'],"rb");
                    $data   = @fread($fp,filesize($file['tmp_name']));
                    @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: application/octet-stream; name=\"".$file['name']."\"\n"."Content-Description: ".$file['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$file['name']."\";size=".$file['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }
            $message .= "--{$mime_boundary}--";
            $returnpath = "-f" . $from;
            $ok = @mail($to, $subject, $message, $headers, $returnpath);
            if($ok){ return 1; } else { return 0; }
    }
    //This function will correct file array from $_FILES[[file][position]] to $_FILES[[position][file]] .. Very important

    function fixFilesArray(&$files)
    {
            $names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);

            foreach ($files as $key => $part) {
                    // only deal with valid keys and multiple files
                    $key = (string) $key;
                    if (isset($names[$key]) && is_array($part)) {
                            foreach ($part as $position => $value) {
                                    $files[$position][$key] = $value;
                            }
                            // remove old key reference
                            unset($files[$key]);
                    }
            }
    }
    ?>

            <form method="POST" action="index.php" enctype="multipart/form-data">
                <input type="file" name="attachment[]">

                <input type="submit">
            </form>

By the way I would like to apologize for using sendmail since it is a bit slow. I will try to post a better solution.


text:
Q: How to push downloaded ZIP project from bitbucket to Github? I've downloaded a project that was on BitBucket as a ZIP. I've extracted it and now I want to push that project onto a new repository in GitHub with all its content (including commit history and so on).
How can I achieve this?

A: You can't. By downloading a project in a zip file, you are not downloading the git repository but just his content.

*

*With GitHub "Import repository"

If you want to keep the commit history, you can use the "Import repository" function of GitHub on the top right corner, just next to the profile picture.

Just copy and past your bitbucket project url and GitHub will import it with all the commit history

*With command line

You can do the same with command line
git clone git@bitbucket.org:user/repo.git
cd repo
git remote -v
git remote rm origin # Replace origin with your remote name
git remote add origin https://github.com/user/repo.git # Create a new remote with your GitHub repository
git push -u origin master # Push all code and commit into the new remote


text:
Q: Finding the outer ends of lines in a line feature class I have a polyline feature class and need to turn the ends of the lines into points. However, the lines are made up of segments that are not quite contiguous, with slight gaps between many of the segments. In effect, the lines are dashed, with varying lengths of the gaps and segments. Is there any way, in ArcGIS, to find only the points that are at the ends of the dashed lines, not at the starts and ends of the "dashes"?

A: You can significantly reduce number of potential candidates by applying spatial join of end points to line segments:

Join them to segments:
arcpy.SpatialJoin_analysis("ends", "segments", "in_memory/sj", "JOIN_ONE_TO_MANY",.. , "INTERSECT", **"70 Meters"**)

and find frequency of highlighted field:

Transfer frequency to original table of end points. After 3 iterations with distance in spatial join (gap length?), I was able to achieve this (note count of point in legend):

All of it doable with Basic license. Tip: use results window to make iterations more efficient.


text:
Q: Why is this a description $\log_{10}$ if the intervals between $10, 100, 1000$ are not equal? In one question in regards to the current value of $\log_{10}$ the following was mentioned:

For these purposes, $10$ does have at least one useful feature
beyond being the base of our number system: $\log_{10} 2 = 0.301 ≈
> 0.3$. This is a very common approximation that $3$ dB corresponds to a doubling or halving of the quantity of interest. We could get similar
simplicity by using $\log_{2}$, but $\log_2 10 = 3.321…$ which is not
nearly as convenient for estimation in decimal numbers.

If I understand this correctly 1dB is $\frac{1}{10}= 0.1$ and since $\log_{10} 2 ≈ 0.3$ we consider the noise has been doubled for $3$dB.
To conclude that we must work on a logarithmic scale with base $10$.
But doesn't that imply that the distance between $10$ and $100$ must be equal to the distance between $1$ and $10$? In the case of dB if we move at $\frac{1}{10}$ we have a distance of $10\frac{1}{10}$ from $1$ to $10$ but $1000\frac{1}{10}$ from $10$ to $100$. Doesn't this break the requirement that it is a $\log_{10}$ scale? Or have I misunderstood the point?


text:
Q: Error when trying to parse XML in R I keep getting error while trying to parse xml file in R.
Here is what I am trying to do:
library(XML)
fileUrl <- "http://www.w3schools.com/xml/simple.xml"
doc <- xmlTreeParse(fileUrl, useInternal=TRUE)

I get these error below:
"

Opening and ending tag mismatch: meta line 4 and head
StartTag: invalid element name
Opening and ending tag mismatch: br line 73 and p
Opening and ending tag mismatch: br line 94 and body
Opening and ending tag mismatch: br line 93 and html
Premature end of data in tag br line 92
Premature end of data in tag br line 78
Premature end of data in tag br line 77
...
...
16: Premature end of data in tag br line 64
17: Premature end of data in tag body line 63
18: Premature end of data in tag meta line 3
19: Premature end of data in tag head line 2
20: Premature end of data in tag html line 2

"
I am using R version 3.3.2 on Windows 7. XML lib version is 3.98.1.5.
Would be glad if anybody could help since this supposed to be a simple parsing but I get stuck in here.

A: With package XML it works for me, being the output (with dplyr to have the output in data.frame):
library(XML)
library(dplyr)

fileUrl <- "http://www.w3schools.com/xml/simple.xml"
doc <- xmlTreeParse(fileUrl, useInternal=TRUE) %>%
  xmlToDataFrame()
doc

name price                                                                         description calories
1             Belgian Waffles $5.95                   Two of our famous Belgian Waffles with plenty of real maple syrup      650
2  Strawberry Belgian Waffles $7.95                   Light Belgian waffles covered with strawberries and whipped cream      900
3 Berry-Berry Belgian Waffles $8.95 Light Belgian waffles covered with an assortment of fresh berries and whipped cream      900
4                French Toast $4.50                                 Thick slices made from our homemade sourdough bread      600
5         Homestyle Breakfast $6.95                 Two eggs, bacon or sausage, toast, and our ever-popular hash browns      950

Another option is to try with library xml2:
library(xml2)
library(dplyr)

fileUrl <- "http://www.w3schools.com/xml/simple.xml"

# As a list
doc <-read_xml(fileUrl) %>%
  as_list()


text:
Q: Logging a snapshot of online users for Django website (postgresql backend, nginx webserver) In a Django + postgresql website of mine, I need to publicly show all is online at a point in time (it's a social website). How do I do this? For instance, can there be a way to enumerate all logged in users who hit my nginx webserver in the previous 10 mins? Something like that could work. I'm a beginner and fishing for a viable solution at the moment.

Currently to accomplish this, I store sessions to the database, using an external library to make sessions enumeratable. This allows me to query how many unique users are online at a point in time.
But this scheme creates a lot of needless DB traffic. As a result, logging and pruning logs has become ineffective. Moreover pgFouine shows me that session related DB calls are the biggest performance bottleneck my website currently has.
There's a proposed solution here, but it uses the database.

A: Use django's cache framework to save the result of the db query to memory. That way you don't need to do the expensive database query for every page render.
from django.core.cache import cache

def count_current_users():
    users = cache.get('users')
    if users is None:
       # last count has timed out
       users = do_expensive_db_query()
       cache.set('users', users, timeout=500)
    return users

https://docs.djangoproject.com/en/1.10/topics/cache/#basic-usage
You can also use Template fragment caching and write a custom template tag that only runs the db query if the cache is stale. This will cache the result for 500 seconds.
{% cache 500 logged_in_users %}
    {% expensive_query_db_for_logged_in_users %}
{% endcache %}

If you want your user count to be more real time, you probably have to bypass django's cache framework, and communicate directly with Redis.
Store each logged in user as a key with a set time to live. Getting a list of currently active keys from Redis would be much cheaper than the equivalent query to a sql database. It can also be implemented with just a few lines of python code.

A: If you're using django-user-sessions, the Session model has a last_activity field.
You may be able to do something like:
from user_sessions import Session
from datetime import datetime, timedelta

time_threshold = datetime.now() - timedelta(minutes=10)
qs = Session.objects.filter(last_activity__gt=time_threshold)

Though, the django-user-sessions does not have a database index on that field, which means if you have a very large number of users / sessions, that query may be hard and take a long time. A more complicated answer might involve creating a materialzed view (if you're using postgres) that refreshes via a cron job.

A: Currently, I'm trying a different approach. I've written a middleware where upon each request, the user's user_id is stored in a global sorted set. I do this only if they're authenticated, and I use the redis key-value store to ensure everything is blazingly fast.
The solution isn't live yet. I'm going to report more here and give a full answer once I'm done. I'll also consider other answers given here before marking the correct solution.


text:
Q: Single quotes for strings in SQL Server DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '</X><X>'), '|', ', ')
SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)

SELECT N.value('.', 'varchar(50)') as value
FROM @xml.nodes('X') as T(N);

My output :
1. 'Prudhvi, raj
2. Lalith, Kumar'

Expected output :
1. 'Prudhvi, raj'
2. 'Lalith, Kumar'

A: If you remove all code related to XML and just leave
DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';
select REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '</X><X>'), '|', ', ')

You'll see there are no quotes around . The result is
'Prudhvi, raj</X><X>Lalith, Kumar'

You can fix this by changing the replacement string to ''</X><X>'', with two single quotes before and after the tags :
select REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '''</X><X>'''), '|', ', ')

The result now is :
'Prudhvi, raj'</X><X>'Lalith, Kumar'

This code is very fragile though. It depends whitespace to separate keys, values and pairs. SQL, the language, is very weak when it comes to string parsing and manipulation. This kind of parsing should be done before the data gets stored in the database.

A: You can try the following query,
DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '''</X><X>'''), '|', ', ')
SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)

SELECT N.value('.', 'varchar(50)') as value
FROM @xml.nodes('X') as T(N);

A: Try this
DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE( @rpmProvider , ', ', '|'), ',', '</X><X>'), '|', ', ')

SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)

SELECT ''''+N.value('.', 'varchar(50)')+'''' as value
FROM @xml.nodes('X') as T(N);

A: try like below
 DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '</X><X>'), '|', ', ')
SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)

SELECT case when left( N.value('.', 'varchar(50)'),1)=''''  then '' else
'''' end + N.value('.', 'varchar(50)')  +
case when right( N.value('.', 'varchar(50)'),1)=''''  then '' else
'''' end as value
FROM @xml.nodes('X') as T(N);

 value
'Prudhvi, raj'
'Lalith, Kumar'

demo link


text:
Q: better way of handle clojure exceptions and why my exception is not captured inside go block I'm trying to found a better way of handle exceptions in clojure, I'm using https://github.com/alaisi/postgres.async which thrown an exeption when fail, but I would prefer return false (because I'm using a validator) or even better something like a Either monad (or something more simple like this http://adambard.com/blog/acceptable-error-handling-in-clojure/ )
1) I'm trying to catch the exception and if exist return false, but the code doesnt works (doesnt return false and thrown the exception).
(try
      (dosql [tx (<begin! db)
                 ucount (<execute! tx ["UPDATE groups SET garticlescounter=garticlescounter + 1 WHERE gid=$1"
                                       groupid])
                 uartc (<execute! tx ["UPDATE subtopics SET starticlescount=starticlescount + 1 WHERE stid=$1"
                                      sid])
                 uartins (<insert! tx
                                   {:table "articles"}
                                   {:aurl url :atitle title :asuttopicid sid :acommentcount 0 :alikescount 0 :auid uid})
                 ok? (<commit! tx)]
                ok?)
      (catch Exception _ false))

2)would be possible wrap in a way where if works return ok?  and if doesnt works return false, or maybe [ok? nil] and [nil error] maybe a macro?
----thanks to swinn I did this
;must receive an optional parameter for error response or
; build a [nil ok] response but just know this works for me...
(defmacro async-try-block! [block]
  `(let [chn# (!/chan 1)]
     (!/go
       (let [response# (try
                        ~block
                        (catch Throwable e#))]
         (if (instance? Throwable response#) (!/put! chn# false) (!/put! chn# response#))))
     chn#))

(async-try-block!
    (dosql [tx (<begin! db)
            ucount (<execute! tx ["UPDATE groups SET garticlescounter=garticlescounter + 1 WHERE gid=$1"
                                  groupid])
            uartc (<execute! tx ["UPDATE subtopics SET starticlescount=starticlescount + 1 WHERE stid=$1"
                                 sid])
            uartins (<insert! tx
                              {:table "articles"}
                              {:aurl url :atitle title :asuttopicid sid :acommentcount 0 :alikescount 0 :auid uid})
            ok? (<commit! tx)]
           ok?))

A: I'm not familiar with the postgres.async library, butException is not the root of all Exceptions in the JVM, Throwable is.
Changing your catch to Throwable would be the first change I would suggest, but it seems that (<execute! ...) actually catches the exception for you and returns it, so you need to check the return value using (instance? Throwable)


text:
Q: Refining ui.resizable to provide a reset method I have a use case where I need to reset the size of a textarea to it's initial size. I started from this solution, which resets when set an option, and arrived at this:
$.widget("ui.resizable", $.ui.resizable, {
    options: {
        origWidth: 0,
        origHeight: 0
    },

    _create: function() {
        this._super();
        this.options.origWidth = $(this.element).width();
        this.options.origHeight = $(this.element).height();
    },

    reset: function() {
        this._resize(
            this.options.origWidth,
            this.options.origHeight
        );
    },

    _resize: function(width, height) {
        width != null && $(this.element).width(width);
        height != null && $(this.element).height(height);
        this._proportionallyResize();
    }
});

I'm using it with this setup:
css
#textarea-resizer { width: 200px; }
#textarea { width: 100%; height: 100%; overflow: auto; resize: none; }

html
<div id="textarea-resizer" style="width: 175px">
  <textarea id="textarea"></textarea>
</div>

<input type="button" id="reset" value="Reset" />

js
$('#textarea-resizer').resizable({
    handles: "se",
    alsoResize: '#textarea',
    minHeight: 23,
    minWidth: 175
});

$('#reset').click(function() {
    $('#textarea-resizer').resizable('reset');
});

(The reason for the "alsoResize" is that the ui.resizable do funny things to textarea elements)
The problem is that pressing the "Reset" button changes the #textarea-resizer, but not the #textarea. How can I make this work correctly? Also, should I do something more to make it fit in well with how the Resizable works?


text:
Q: Part of function inside a variable error Sup guys,
So, i'm trying to reduce my code to avoid redundance and i'm stuck on it;
i know yet that you can reduce some code for example:
    var alert=console.warn;alert('sup!');
But on my code i have other context:
i'm putting a part of a function, resumed like it:
    var alert=console.warn**(**;
how can i call the same example above to show the alert?
i'm getting always error
If u get the simple example, i will go harder:
i've this partial code:
for (var i = 0; i < options.length; i++) {
var option = options[i];
var optionText = option.text;
var lowerOptionText = optionText.toLowerCase();
var lowerText = text.toLowerCase();
var regex = new RegExp("^" + text, "i");
var match = optionText.match(regex);
var contains = lowerOptionText.indexOf(lowerText) != -1;
if (match || contains) {

and i want to put it on a variable
After it, i want to call the variable and merge with  this code:
}
searchBox.selectedIndex = 0;
}  //CloseForFunction

Plz help me.
Thanks


text:
Q: Does using Psyco with django make any sense? I know the benefits of Psyco for a Desktop app, but in a Web app where a process ( = a web page or an AJAX call) dies immediately after been fired, isn't it pointless ?

A: You should be using fastcgi or wsgi with django, so the process won't be starting up for each request.
You really need to write your code to be psyco friendly if you want decent gains, and you will not benefit if your bottleneck is the database.

A: First, as gribbler and Ibrahim mentioned, your process won't die unless you are using pure CGI... which you shouldn't be using.
Secondly, the bottleneck in most web apps are database queries, for which Psyco won't help.
If you happen to have a some logic that is computationally intensive it can certainly make sense to use Psyco or Cython.  In fact I read a report somewhere (sorry it's been a while so can't find a link now) by someone who was doing some complex calculations and had great results compiling their entire views.py with Cython.

A: This guy got a performance increase out of it:
http://www.alrond.com/en/2007/jan/25/performance-test-of-6-leading-frameworks/
It's a little bit outdated though.


text:
Q: SVN disappeared from Android Studio - Mac OS After a forced shutdown in MacOS SVN simply disappeared from my Android Studio. I tried unstalling, and installing again from a newly downloaded file, but SVN doesn't seem to want to work with me today.
I have no idea what to do, since, until now, SVN worked right from the box, with no configuration needed at all.
Can anyone give me any pointers?
Thanks,
Manuel

A: After hitting my head on walls for a couple of hours I figured out what was wrong. It seems that, when crashing, Android Studio (i.e. Intellij) disabled the SVN plugin.
Somehow that definition survived a reinstall and even running straing from a newly downloaded file, but to fix it it was just a case of going to Plugin Preferences and enabling the SVN plugin.
/The More you Know/

A: This link was helpful to get me going (OSX 10.1.1, Android Studio 1.3.2, svn via HomeBrew) http://andowebsit.es/blog/noteslog.com/post/how-to-upgrade-subversion-on-osx/


text:
Q: Generic collection MVC Hi All I have trying to use this http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3fundamentals_topic8.aspx, but i have some question
1) my collection under Create t.Albums is always empty however my t.Genre is working
i am not sure how to fix the problem i've included this in my Create.aspx
Inherits="System.Web.Mvc.ViewPage<SomeStore.Controllers.ViewModels.StoreBrowseViewModel>"

----------------StoreBrowseViewModel----------------
public class StoreBrowseViewModel
{
    public StoreBrowseViewModel{}

    public StoreBrowseViewModel(List<Album> _Albums, Genre _Genre)
    {
        this.Genre=_Genre;
        this.Albums = _Albums;
    }
    public Genre Genre { get; set; }
    public List<Album> Albums { get; set; }
}

----------------StoreBrowseController----------------
public ActionResult Create([Bind(Include = "Genre,Albums")]StoreBrowseViewModel t)
{

}

A: Collections are not bound by ModelBinder. What do you need that for?