text:
Q: SWT ScrolledComposite is displaying content incorrectly after resizing I would like to have a ScrolledComposite that has multiple composites within it.
If the window is resized, the ScrolledComposite isn't resizing correctly. If I shrink the width down it will cut the bottom of the content off and not allow the user to scroll down enough. If I then increase the width to much larger it will always keep the scroll bar and will allow the user to scroll too far down.
I've tried updating the minimum height of the ScrolledComposite like the answer in this question but it hasn't helped. I've tried following multiple tutorials and looking at examples but I can't see what is causing this.
Example
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

public class Example {

    public static void main(String[] args) {

    final Display display = new Display();
    final Shell shell = new Shell(display);

    shell.setText("Scrolled Composite Example");

    // Create a scrolled composite with content
    shell.setLayout(new GridLayout(1, true));
    shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    final Composite scrollParent = new Composite(shell, SWT.NONE);
    scrollParent.setLayout(new FillLayout());
    scrollParent.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).span(1, 1).create());

    final ScrolledComposite scrollComposite = new ScrolledComposite(scrollParent, SWT.V_SCROLL);

    final Composite scrollContent = new Composite(scrollComposite, SWT.NONE);
    scrollContent.setLayout(new GridLayout(1, true));

    scrollComposite.setContent(scrollContent);
    scrollComposite.setExpandHorizontal(true);
    scrollComposite.setExpandVertical(true);

    // Add a composite to the scroll content (A label with lots of text)
    final Composite cell = new Composite(scrollContent, SWT.BORDER);
    cell.setLayout(new GridLayout(4, false));
    cell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    final Label l = new Label(cell, SWT.WRAP);

    l.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    l.setText(StringUtils.repeat('1', 10000));

    // Listen for width changes to update the minimum height
    scrollContent.addListener(SWT.Resize, new Listener() {
        int width = -1;

        @Override
        public void handleEvent(final Event e) {
        int newWidth = scrollContent.getSize().x;
        if (newWidth != width) {
            scrollComposite.setMinHeight(scrollContent.computeSize(newWidth, SWT.DEFAULT).y);
            width = newWidth;
        }
        }
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
    }
}

What is causing this?

A: I managed to fix this by adding a listener for size changes of the ScrolledComposite.
If the ScrolledComposite is resized I get the client area width and calculate the minimum size required for the content.
scrolledComposite.addListener(SWT.Resize, event -> {
    final int width = scrolledComposite.getClientArea().width;
    scrolledComposite.setMinSize(content.computeSize(width, SWT.DEFAULT));
});


text:
Q: Unable to redirect website on HTTPS in Django after using SSL_REDIRECT = True I have created a website with an admin page and REST APIs, I am using the centOS server to deploy the website. I have this code in my settings.py file:
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'djangosecure.middleware.SecuritsyMiddleware'
]
CORS_ALLOW_ALL_ORIGINS=True
CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:4200',
                          'http://localhost:4200',
                         'http://*']

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

If I remove the SSL_Redirect lines from code then the server runs properly but it runs on HTTP.
I want my website to run on HTTPS, That is why I am using these settings.
Due to these settings, my website doesn't run at all and the browser gives a response as the site took too long to respond.
When I see logs, all the endpoints are giving 301 as a response code. I am not able to get that why this happening. I have gone through all the Django SSL Documentation but I did not find any solution.
LOGS:
2021-09-25 16:24:18,091 autoreload 598 INFO Watching for file changes with StatReloader
2021-09-25 16:24:19,585 server 110 INFO HTTP/2 support enabled
2021-09-25 16:24:19,585 server 121 INFO Configuring endpoint tcp:port=8001:interface=0.0.0.0
2021-09-25 16:24:19,588 server 155 INFO Listening on TCP address 0.0.0.0:8001
2021-09-25 16:24:24,520 http_protocol 160 DEBUG HTTP b'GET' request for ['157.38.102.103', 63772]
2021-09-25 16:24:24,523 http_protocol 256 DEBUG HTTP 301 response started for ['157.38.102.103', 63772]
2021-09-25 16:24:24,523 http_protocol 223 DEBUG HTTP close for ['157.38.102.103', 63772]
2021-09-25 16:24:24,523 http_protocol 269 DEBUG HTTP response complete for ['157.38.102.103', 63772]
2021-09-25 16:24:24,523 runserver 153 INFO [32mHTTP GET /admin/ 301 [0.00, 157.38.102.103:63772][0m

It will be very helpful if someone can provide a solution to this problem.
Thanx in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hosting Static sites via EC2 ELB and Cloudfront Looking to host multiple static web sites by pointing DNS to an Elastic Load Balancer and serving the content via Cloudfront.
Is this a plausible approach? Are there any gotchas we should look out for. How should we configure DNS for each site?
Appreciate any thoughts on this
Dom

A: Each ELB will have it's own public DNS.  You will need a CNAME for your domains to map them to the ELB so that your users can get to your ELB like this: www.mysite.com.
CloudFront will push an S3 bucket to Amazon's edge network - putting that content closer to it's requesting user.  Your domain names shouldn't point directly to this content, however your site (on your EC2 instance) will consist of HTML files that reference your CloudFront distribution.
Now you'll have one or more servers processing requests and CloudFront serving the content.  Very plausible.
Best of luck.
Chad

A: You can point your ELB or EC2 instance to cloudfront and this will push your dynamic content closer to your users.
http://aws.amazon.com/about-aws/whats-new/2012/05/13/amazon-cloudfront-now-supports-dynamic-content/

A: If the content is static it makes more sense to think in terms of CloudFront pointing at S3.
For Amazon S3 buckets configured to host static websites, you also have the option of creating an 'Alias' record that maps to your S3 website bucket. Alias records have two advantages: first, unlike CNAMEs, you can create an Alias record for your zone apex (e.g. example.com, instead of www.example.com), and second, queries to Alias records are free of charge.


text:
Q: ¿Por qué me sale undefined en una vista de blade.php en laravel? Estoy intentando hacer la vinculación de un 3er. formulario que en este caso es la de vehículos, para ello genero el controlador VehiculoController.php con la siguiente información:

<? php

namespace App\ Http\ Controllers;

use Illuminate\ Http\ Request;
use App\ Vehiculo;

class VehiculoController extends Controller {
  public
  function create() {

    $titulo = "Formulario de Vehículo";

    return view('vehiculo.create', [
      'titulo' => $titulo
    ]);
  }

  public
  function save(Request $request) {

    $vehiculo = Vehiculo::all();

    $validate = $this - > validate($request, [
      'propietario_id' => 'integer|required',
      'conductor_id' => 'integer|required',
      'placa' => 'required|string|max:25|unique:vehiculos,placa',
      'color' => 'required|string|max:25',
      'marca' => 'required|string|max:40',
      'tipo_vehiculo' => 'required|string|max:30'
    ]);

    $propietario_id = $request - > input('propietario_id');
    $conductor_id = $request - > input('conductor_id');
    $placa = $request - > input('placa');
    $color = $request - > input('color');
    $marca = $request - > input('marca');
    $tipo_vehiculo = $request - > input('tipo_vehiculo');

    $vehiculo = new Vehiculo();

    $vehiculo - > propietario_id = $propietario_id;
    $vehiculo - > conductor_id = $conductor_id;
    $vehiculo - > placa = $placa;
    $vehiculo - > color = $color;
    $vehiculo - > marca = $marca;
    $vehiculo - > tipo_vehiculo = $tipo_vehiculo;

    $vehiculo - > save();

    return redirect() - > route('home') -
      > with(['message' => 'Los datos guardados correctamente!!']);

  }

}

Una vez hecho esto tengo también el modelo que contiene la siguiente información, vehiculo.php:

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Vehiculo extends Model
{
    protected $table = 'vehiculos';

    // Relación Many to One
    public function propietario(){
        return $this->belongsTo('App\Propietario', 'propietario_id');
    }

    // Relación Many to One
    public function conductor(){
        return $this->belongsTo('App\Conductor', 'conductor_id');
    }
}
?>

Y acontinuación, en la vista tengo el archivo create.blade.php con la siguiente información:

@use vehiculo; @extends('layouts.app') @section('content')

      @include ('includes.message')

{{ $titulo }}

          <form method="POST" action="{{ route('vehiculo.save') }}">
            @csrf {{--ACÁ ESTÁ EL ERROR POR EL QUE NO ME PERMITE CONTINUAR LO QUE ESTÁ EN value="..." --}}
            <input type="hidden" name="propietario_id" value="{{'@'.$vehiculos->propietario->id }}" /> {{--
            <input type="hidden" name="conductor_id" value="{{ $vehiculo->conductor_id }}" />--}}

              Placa

                <input id="cedula" type="text" class="form-control @error('cedula') is-invalid @enderror" name="cedula" required autocomplete="cedula" autofocus /> @error('cedula')

                                        {{ $message }}
                                     @enderror

              Color

                <input id="color" type="text" class="form-control @error('color') is-invalid @enderror" name="color" required autocomplete="color" /> @error('color')

                                        {{ $message }}
                                     @enderror

              Marca

                <input id="marca" type="text" class="form-control @error('marca') is-invalid @enderror" name="marca" required autocomplete="marca" /> @error('marca')

                                        {{ $message }}
                                     @enderror

              Tipo de Vehículo

                <input id="tipo_vehiculo" type="text" class="form-control @error('tipo_vehiculo') is-invalid @enderror" name="tipo_vehiculo" required autocomplete="tipo_vehiculo" /> @error('tipo_vehiculo')

                                        {{ $message }}
                                     @enderror

                <button type="submit" class="btn btn-primary">
                                    Registro
                                </button>

          </form>

@endsection

Estas son las rutas que le di en el archivo web.php del proyecto
// VEHÍCULO
Route::get('info-vehiculo', 'VehiculoController@create')->name('vehiculo.create');
Route::post('/vehiculo/save', 'VehiculoController@save')->name('vehiculo.save');

El siguiente reporte es lo que me genera como resultado


text:
Q: Two same span elements but have different width I create two span elements and add them to DOM with visibility = hidden.
After adding both span element to DOM, I get width and height of both elements.
Surprisingly, both width and height are different.
text, font-size, font-family all are same in both span.
What could be the reason for difference in size?
var sp1 = goog.dom.createDom('span', null);
sp1.innerText = text;
sp1.style.fontSize = "60px";
sp1.style.fontFamily = family;
sp1.style.visibility = "hidden";
goog.dom.appendChild(document.body, sp1);

var sp2 = goog.dom.createDom('span', null);
sp2.innerText = text;
sp2.style.fontSize = "60px";
sp2.style.fontFamily = family;
sp2.style.visibility = "hidden";
goog.dom.appendChild(document.body, sp2);

var sz1 = goog.style.getSize(sp1);
var sz2 = goog.style.getSize(sp2);

assert(sz1 == sz2)

HTML of page

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <link type="text/css" rel="stylesheet" href="ff.css">

        <title>Web Fonts</title>

1. Quick Brown Fox Jumps over the Lazy Dog

2. Quick Brown Fox Jumps over the Lazy Dog

3. Quick Brown Fox Jumps over the Lazy Dog

4. Quick Brown Fox Jumps over the Lazy Dog

test

        3. Quick Brown Fox Jumps over the Lazy Dog
        3. Quick Brown Fox Jumps over the Lazy Dog

The span in questions are the two span at end of html document.
Size of 1st = (1217, 67)
Size of second = (1267, 136)

A: If they are next to differently sized elements (such as being next to a div rather than on their own separate line) they would be different sizes as they are inline elements and not block level elements.

A: Thanks for the HTML.
Consider this: the font-size you have set for those spans is quite big, and when the window is not wide enough the text inside the spans starts to wrap.
Spans have display:inline; by default and when wrapped the two text will appear as one BUT with different wrapping, because the second continues immediately after the first and its text is most probably broken on a different place.
If you set display:block; for those spans there should be no difference.


text:
Q: How to slow read output from UrlFetchApp/ waiting function till get respond from url (Google Apps Script) var api_url = 'dns.google/resolve?name=site.com';
var response = UrlFetchApp.fetch(api_url);
var responseText = response.getContentText();
return {text : responseText};

When I have ran this, output will get this
{"Status": 0,"TC": false,"RD": true,"RA": true,"AD": false,"CD": false,"Question":[ {"name": "site.com.","type": 1}],"Answer":[ {"name": "site.com.","type": 1,"TTL": 299,"data": "204.74.99.100"}],"Comment": "Response from 204.13.250.39."}

I need this output, by parsing.
[ {"name": "site.com."
   "type": 1
   "TTL": 299
   "data": "204.74.99.100"
} ]

But in actual case its note getting output.even though running this through bash scripts will get responses,
$]curl -s https://dns.google/resolve?name=site.com

{"Status": 0,"TC": false,"RD": true,"RA": true,"AD": false,"CD": false,"Question":[ {"name": "site.com.","type": 1}],"Answer":[ {"name": "site.com.","type": 1,"TTL": 188,"data": "204.74.99.100"}]}

What can be done here, can someone suggest I have less knowledge in Javasript and Parsing data with JSON

A: function getDatta() {
  const json = '{"Status": 0,"TC": false,"RD": true,"RA": true,"AD": false,"CD": false,"Question":[ {"name": "site.com.","type": 1}],"Answer":[ {"name": "site.com.","type": 1,"TTL": 299,"data": "204.74.99.100"}],"Comment": "Response from 204.13.250.39."}';
  const obj = JSON.parse(json);
  Logger.log(JSON.stringify(obj.Answer));
}

Execution log
5:07:41 PM  Notice  Execution started
5:07:41 PM  Info    [{"name":"site.com.","type":1,"TTL":299,"data":"204.74.99.100"}]
5:07:42 PM  Notice  Execution completed


text:
Q: Epiceditor paired with MathJax Is there anyway to load a script (such as MathJax) into the EpicEditor preview iFrame? I want my previews to be correct Markdown and then have the javascript run to preview the MathJax content.
Thanks!

A: It seems that you ought to inject MathJax script manually into previewer iframe. Something like this:
var editor = new EpicEditor(opts).load();

previewer = editor.getElement('previewer');
var mathjax = previewer.createElement('script');
mathjax.type = 'text/javascript';
mathjax.src = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
previewer.body.appendChild(mathjax);

var config = previewer.createElement('script');
config.type = 'text/x-mathjax-config';
config.text = "MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$']], displayMath: [['$$','$$']], processEscapes: true}});";
previewer.body.appendChild(config);

And then you can render equations on preview event:
editor.on('preview', function() {
    editor.getElement('previewerIframe').contentWindow.eval(
        'MathJax.Hub.Queue(["Typeset",MathJax.Hub]);');
});

That also works in fullscreen live edit mode.


text:
Q: How to parse outlook email using spring I have a use case where i need to read the content of the mail in outlook inbox and convert it into xml and send it to diffrent system.Is there any library which can help me in parsing the content.

A: Outlook is the client for the email server.(May be exchange server).
You actually need to connect to the server to read the email.
If you know the server, you can find a API for it.
Checkout this URL if you are trying to access the exchange server:
http://archive.msdn.microsoft.com/ewsjavaapi


text:
Q: PlayFramework and MongoDB Auto-Reconfiguration Error I am having an issue with auto-reconfiguration using Play2 and MongoDB.  Any help would be much appreciated.  I have emailed the error log, compiled application and application.conf to support@cloudfoundry.com..
Thanks!

A: just to bring this thread up to date;
Please see the comments on the filed ticket at https://cloudfoundry.atlassian.net/browse/CF-141

We only implemented Play auto-reconfig for Postgres and MySQL. We
  would like to do auto-config for the additional services like Mongo,
  but need to find a common pattern for usage in a Play app (one
  possibility is common property names in application.conf). In the
  meantime, you can externalize connection props to application.conf and
  use the CF-provided props that get resolved on app start:
  mongodb.host=${?cloud.services.mongodb.connection.hostname}
  mongodb.port=${?cloud.services.mongodb.connection.port}
  mongodb.db=${?cloud.services.mongodb.connection.db}
  mongodb.username=${?cloud.services.mongodb.connection.username}
  mongodb.password=${?cloud.services.mongodb.connection.password}


text:
Q: How to use readmore.js with foundation 6 Doesnt seem to work. Is there a fix? It seems readmore is expecting sections and artcles; however, foundation uses divs i.e. row and columns. How to fix?

A: You can use any HTML5 tag with Foundation's grid. The default grid uses Flexbox, no floats and the styles are class based, not tag based.
Example:


text:
Q: Why does Ubuntu not lock ATA-Password protected disc on reboot? I am on a Acer Timeline X 4830TG Laptop. Currently using Ubuntu 13.04.
I do use 2 HDDs instead of the DVD-ROM drive.
I can set ATA passwords within bios for both drives (which I have done).
If I cold-start the machine I am forced by Bios to enter the HDD Passwords (at least I must unlock the one which is marked as bootable).
Than GRUB starts and I can boot into Ubuntu.
If I did not unlock the second Harddisk I will get many log lines about /dev/sdb not be accessible.
(see kernel.log here: http://paste.ubuntu.com/6179903/ )
[also not this second HardDrive is not mounted via fstab nor are there any requird partitions for ubuntu, it is instead a NTFS Volume which I manually mount if I need to acess this data-grave]
But anyway: the main problem and question is:
why the heck does Ubuntu not lock the 1.HDD if i reboot it
 ./.
why does it only lock the 2.Harddrive if it was unlocked before reboot?
The Result is this: I reboot Ubuntu, 2. HDD gets locked, first stays unlocked, Bios WON't ask for HDD Password (of the second, locked HDD) so I end up with above linked errors on bootup and also am unable to acess the second HDD from within Ubuntu, cause it is locked.
My expected behaviour would be either: both drives get locked during reboot, or
NONE of them gets locked, so the state AFTER reboot will be like it was before.
Thanks for answers in  advance.

A: Your expectation is incorrect; it isn't the job of the OS to do this.  Instead the drive locks itself when you power off.
You may be able to manually unlock the drive in Ubuntu using the hdparm --security-unlock command, assuming the bios doesn't freeze the security settings, in which case it takes a power cycle to unfreeze it.


text:
Q: Regex match 2 letters and up to 10 digits afterwards I have the following regex which is matching the first 2 letters RR and then 4 numbers after.
RR[0-9]{4}

How can I change it to detect the first 2 letters RR and then up to 10 digits afterwards?
I know I can do...
^[0-9]*$

To match all numbers but how can I limit this and add it to the first regex?

A: You can use RR\d{0,10}. This matches RR, followed by 0 to 10 digits, i.e. up to 10 digits.


text:
Q: Jquery Datatables - Seleccionar datos a través de una api pública estoy intentando montar una tabla dinámica con Jquery Datatables usando los datos públicos de una api, para ello tengo este código en el layout de blade
Aquí cargo los cdn de jquery y datables

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">

En el formulario  tengo el siguiente código
@extends('layout')

@section('content')

            User Id
            Id
            Title
            Completed

            User Id
            Id
            Title
            Completed

@endsection

El error que me da es este, y hace que no me cargue los datos de la tabla.
 Uncaught TypeError: Cannot read property 'length' of undefined

A: Para que te funcione debes dejar el código tal que así:

Ya que te faltaba en el apartado "ajax" añadir dataSrc


text:
Q: How to make the code workable for more than one file file object in following scenario? I've a form containing four file controls. They may get increase and decrease in number depending on user's choice. But at least one of them will remain on a form.
I want to display the image thumbnail of the image selected by user for upload for each of these file controls.
I'm able to display the thumbnail image for one file control but not able to make it workable for more than one file control on a form.
The HTML form code is as below :
<form action="add.php" role="form" method="post" enctype="multipart/form-data">

  <input type="file" name="product_image[1]" id="product_image_1">

  <input type="file" name="product_image[2]" id="product_image_2">

  <input type="file" name="product_image[3]" id="product_image_3">

  <input type="file" name="product_image[4]" id="product_image_4">
  .
  .
  .
  .
  .
  and could be so on
</form>

The jquery code which worked for me for only one file control is as follows:
HTML code is :
<form id="form1" runat="server">
  <input type='file' id="imgInp" />

</form>

jQuery code :
$(document).ready(function() {
  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        $('#blah').attr('src', e.target.result);
      }

      reader.readAsDataURL(input.files[0]);
    }
  }

  $("#imgInp").change(function() {
    readURL(this);
  });
});

js Fiddle link is : http://jsfiddle.net/LvsYc/
The above code worked really very fine for me when there is only one such file field.
But not able to make the same thing workable for a form when there could be more than one such file controls are present.
Can someone please help me in this regard?
Thanks for spending some of your valuable time in understanding my issue. Waiting for your precious replies.
If you want any information regarding my question please do let me know.

A: Probably my answer to this question will help:
$.fn.checkFileType = function (options) {
var defaults = {
    allowedExtensions: [],
    preview: "",
    success: function () {},
    error: function () {}
};
options = $.extend(defaults, options);
$previews = $(options.preview);
return this.each(function (i) {

    $(this).on('change', function () {
        var value = $(this).val(),
            file = value.toLowerCase(),
            extension = file.substring(file.lastIndexOf('.') + 1),
            $preview = $previews.eq(i);

        if ($.inArray(extension, options.allowedExtensions) == -1) {
            options.error();
            $(this).focus();
        } else {
            if (this.files && this.files[0] && $preview) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $preview.show().attr('src', e.target.result);
                    options.success();
                };

                reader.readAsDataURL(this.files[0]);
            } else {
                options.error();
            }

        }

    });

  });
};

You can use the above function as follows:
$('.fileUpload').checkFileType({ // where fileUpload is the common class given for file upload elements
  allowedExtensions: ['jpg', 'jpeg',"gif"], // allowed extensions
  preview: ".preview", // where .preview is the common class given for file upload elements
  success: function () {
    alert('success')
  },
  error: function () {
    alert('Error');
  }
});

The image will be set as the src of element at the index of your <input> among the set of elements matched by the jQuery selector specified in preview option.
Demo


text:
Q: Twitter Bootstrap glyphicons font's not found when using assetic in prod on Symfony2 I've read a lot of posts about this  but couldn't get this to work for my project.
So basiclly I have a Symfony2 project which includes twitter bootstrap (v3). Every thing works fine in dev mode but when I try it in prod mode i got errors saying that the twitter bootstrap fonts couldn't be found:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/Symfony/css/fonts/glyphicons-halflings-regular.woff
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/Symfony/css/fonts/glyphicons-halflings-regular.ttf
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/Symfony/css/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular

Which is normal cause I dont have a css/ folder in Symfony/
Here is how the project is structured:
app/
src/
vendor/
web/
   css/
      compiled/
   fonts/
   js/

twig file:
{% block stylesheets %}
    {% stylesheets output="css/compiled/main.css" filter='cssrewrite'
        'css/bootstrap.min.css'
        'css/general.css'
        'css/navigation.css'
    %}
        <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

I used:
php app/console assetic:dump --env=prod

I've checked in the bootstrap.min.css (in web/css/compiled) files (prod and dev) and they both have the same path for the fonts. Something like (../../../fonts/fontName.ext).
If we look at the path it shouldn't work neither in dev nor in prod mode as the path puts the fonts/ file outside the web directory. Yet, it works in dev mode.
Any idea on how to resolve this ?
I would be greatful.

A: If you use the "cssrewrite" filter, it rewrites the path to the font-files (to their original source) as Maxoo already said.
You can add the assetic path for the font-files in the following way (so they are copied to the css/fonts/ folder and the css-files will find them by using the orginal ../fonts/ path)
I've used the following solution:
config.yml:
assetic:
    debug:          %kernel.debug%
    use_controller: false
    assets:
        bootstrap_fonts_woff:
            inputs:
                - 'original/path/to/bootstrap/fonts/glyphicons-halflings-regular.woff'
            output: fonts/glyphicons-halflings-regular.woff
        bootstrap_fonts_ttf:
            inputs:
                - 'original/path/to/bootstrap/fonts/glyphicons-halflings-regular.ttf'
            output: fonts/glyphicons-halflings-regular.ttf
        bootstrap_fonts_svg:
            inputs:
                - 'original/path/to/bootstrap/fonts/glyphicons-halflings-regular.svg'
            output: fonts/glyphicons-halflings-regular.svg
        bootstrap_fonts_eot:
            inputs:
                - 'original/path/to/bootstrap/fonts/glyphicons-halflings-regular.eot'
            output: fonts/glyphicons-halflings-regular.eot

Then call
php app/console assetic:dump --env=prod

which should export the files to the fonts-directory inside your web-folder.
Hope this helps!

A: You don't have to search them under Symfony/ path, infact Symfony2 webfolder is web/ so url is "relative" to web/ folder.
BTW, you have to use the following command
php app/console assets:install

If you like to have symlinks you could also add --symlink parameter to your command
So what's the difference between assets:install and assetics:dump ?
assets:install will symlink or copy the desired resources to "public web folder"
assetic:dump will only combine all js into one

A: Proper Solution:

*

*Install Nodejs, setup symfony2 config file, it will compile cssrewrite filter of your choice into CSS automatically. This will resolve these errors.

*my config.yml and config_dev.yml looks like this just an assetic section - Be very careful with the path syntax or else you will get this error "An error occurred while running: ... Error: Cannot find module 'less'" Any many people ran into these 3 errors messages google this string to find out "An error occurred while running: Error: Cannot find module 'less'"
assetic:
debug: '%kernel.debug%'
use_controller:
       enabled: '%kernel.debug%'
       profiler: true
filters:
    cssrewrite: ~
    ###is for linux path i am on windows for dev and linux for prod
    less:
        ###node: /usr/bin/nodejs
        ###node_paths: [/usr/lib/nodejs]
        node: "C:\\Program Files (x86)\\nodejs\\node.exe"
        node_paths: ["C:\\Users\\John\\AppData\\Roaming\\npm\\node_modules"]
        apply_to: "\.less$"

*

*do not forget installing "npm install -g less"

*In my specific case: when doing "php app/console assetic:dump" I get this same error. This is because my Windows dev web server is setup like this: the web root is "C:\xampp\htdocs\" and the project is like this "C:\xampp\htdocs\phantom\" and the assetic:dump puts glyphicons-halflings-regular.ttf, glyphicons-halflings-regular.woff, and glyphicons-halflings-regular.woff2 in "C:\xampp\htdocs\phantom\web\fonts" HOWEVER, when page is loaded it looks in "http://localhost/" as you can see this is the issue with my development setup. So i copy folder fonts "C:\xampp\htdocs\phantom\web\fonts" to web root "C:\xampp\htdocs\" That solves the problem.

*This will not happen in production environment where your server web root is "C:\xampp\htdocs\phantom\web\". I tested on a production server without need to manually copy the fonts folder to webroot.

*In addition, when running  the same command in your project directory "php app/console assetic:dump" you will get error like "FileError: '../bootstrap/less/bootstrap.less' wasn't found. Tried - ../bootstrap/less/bootstrap.less,C:\xampp\htdocs\phantom\vendor\mopa\bootstrap-bundle\Mopa\Bundle\BootstrapBundle\Resources\public\bootstrap" By the same token bootstrap was installed by "php app/console assets:install" in "C:\xampp\htdocs\phantom\web\bootstrap" which is not correct webroot directory so again to resolve this same temporary issue in development i will just copy directory "C:\xampp\htdocs\phantom\web\bootstrap" to "C:\xampp\htdocs\bootstrap" that solves problem. Run your command again it will compile to css nicely and cleanly.

A: May be you should try to keep the Bootstrap folder structure unchanged (downloading it with bower for example). By the way the cssrewrite filter will parse your css files to reflect the location of the fonts.


text:
Q: Changing the color of an item in the listbox to Red Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For i = 0 To 5
            Actions.Items.Add("Added Action" & i) ' Actions is list box
        Next

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        For i = 0 To 5
            Errors.Items.Add("Added Error" & i) 'Errors is list box
            If i = 5 Then
                'change the font color to red
            End If
        Next
    End Sub
End class

Here one of the item colour of my error list box colour has to be changed and other item colours should be black which is the default. I don't want to use drawitem event handler since it is affecting the performance. Is there any other way to directly change the colour of one of the items of list box. Maybe Xml?

A: ListView sounds like a good alternative. However, if you must use a ListBox, then you must use the ListBox.DrawItem Event to color individual lines. In this case, you will need to draw each item manually with code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' this must be set to be make the DrawItem event fire
    Errors.DrawMode = DrawMode.OwnerDrawFixed
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For i = 0 To 5
        Actions.Items.Add("Added Action" & i) ' Actions is list box
    Next
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    For i = 0 To 5
        Errors.Items.Add("Added Error" & i) 'Errors is list box
        ' don't worry about coloring here, the logic is in the DrawItem event handler
    Next
End Sub

Private Sub Errors_DrawItem(sender As Object, e As DrawItemEventArgs) Handles Errors.DrawItem
    Dim g = e.Graphics
    Dim c = If(e.Index Mod 6 = 5, Color.Red, Color.White)
    e.DrawBackground()
    g.FillRectangle(New SolidBrush(c), e.Bounds)
    e.DrawFocusRectangle()
    g.DrawString(
        DirectCast(sender, ListBox).Items(e.Index).ToString(),
        e.Font,
        New SolidBrush(e.ForeColor),
        New Point(e.Bounds.X, e.Bounds.Y))
End Sub

According to your example, every sixth item is colored red (0 to 5, item 5). Repeatedly clicking Button2 will cause 6 items to be added every time, and your logic always colored item 5. For this reason, I test the condition Index Mod 6 = 5. Your example may have been simplified, but this is all the information I have. I hope you can make it work!
I thought this sounded familiar... see my answer.


text:
Q: error in grid search optimization -ValueError: Could not interpret optimizer identifier:  i tried to optimize my DL model using the grid search algorithm
it runs and when it complete it arise the following error - note that i used both tensorflow and keras - cause i didn't understand the reason of the error.
i try to import just each of them , but i doesnt work also
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import InputLayer
 import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
 from keras.layers import Dropout
from tensorflow.keras import regularizers
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import concatenate
from tensorflow.keras.models import Model
from numpy import argmax
from sklearn.model_selection import GridSearchCV, KFold
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras import optimizers
from keras.optimizers import Adam
from keras.models import Sequential
from keras.layers import Dense,Dropout
#Grid  search optimization
def create_model(learn_rate, dropout_rate):
    # Create model
    model = keras.Sequential()
    model.add(layers.Dense(260, input_dim=265, activation='relu'))
    model.add(layers.Dense(240, activation='relu',kernel_regularizer=regularizers.l2(0.01)))
    model.add(layers.Dense(128, activation='relu'))
    model.add(layers.Dropout(0.1))
    model.add(layers.Dense(56, activation='relu'))
    model.add(layers.Dense(16, activation='relu'))
    model.add(layers.Dropout(0.1))
    model.add( layers.Dense(1, activation='sigmoid', name='class'))
    # Compile the model
    adam = Adam(lr=learn_rate)
    model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
    return model

# Create the model
model = KerasClassifier(build_fn=create_model, verbose=1)

learn_rate = [0.001, 0.02, 0.2]
dropout_rate = [0.0, 0.2, 0.4]
batch_size = [10, 20, 30]
epochs = [1, 5, 10]

seed = 42

# Make a dictionary of the grid search parameters
param_grid = dict(learn_rate=learn_rate, dropout_rate=dropout_rate, batch_size=batch_size, epochs=epochs )

# Build and fit the GridSearchCV
grid = GridSearchCV(estimator=model, param_grid=param_grid,
                    cv=KFold(random_state=seed), verbose=10)

grid_results = grid.fit(X_train, Y_train)

when i run grid.fit
it runs then show the following error
ValueError: Could not interpret optimizer identifier: <keras.optimizers.Adam object at 0x0000027A2BE4BAC8>

any help will be appreciated


text:
Q: Haskell - defining commutative functions: How to consider actual arguments by combination, not permutation I want to define a function that considers it's equally-typed arguments without considering their order. For example:
weirdCommutative :: Int -> Int -> Int
weirdCommutative 0 1 = 999
weirdCommutative x y = x + y

I would like this function to actually be commutative.
One option is adding the pattern:
weirdCommutative 1 0 = 999

or even better:
weirdCommutative 1 0 = weirdCommutative 0 1

Now lets look at the general case: There could be more than two arguments and/or two values that need to be considered without order - So considering all possible cases becomes tricky.
Does anyone know of a clean, natural way to define commutative functions in Haskell?
I want to emphasize that the solution I am looking for is general and cannot assume anything about the type (nor its deconstruction type-set) except that values can be compared using == (meaning that the type is in the Eq typeclass but not necessarily in the Ord typeclass).

A: There is actually a package that provides a monad and some scaffolding for defining and using commutative functions. Also see this blog post.

A: In a case like Int, you can simply order the arguments and feed them to a (local) partial function that only accepts the arguments in that canonically ordered form:
weirdCommutative x y
  | x > y      = f y x
  | otherwise  = f x y
 where f 0 1 = 999
       f x' y' = x' + y'

Now, obviously most types aren't in the Ord class – but if you're deconstructing the arguments by pattern-matching, chances are you can define at least some partial ordering. It doesn't really need to be >.


text:
Q: Simple menu tabs using jQuery I am trying to create simple tabs menu using jQuery. Which should show and hide a div according to the navigation icon click.
JSfiddle: check my code on fiddle
HTML

All Contacts

Facebook

Google

Yahoo

Hotmail

Manually Added

ALLLL

FACEEEE

goooo

YAAAA

HOTTTT

MANNNNNN

SCRIPT
$('.nav li a').click(function(){
    var name = $(this).parent('li').attr('class');
    alert(name)
    $('.friendInfo .nav li a').parent('li').removeClass('selected');
    $(this).parent('li').addClass('selected');
    $('.friendInfo .frndList ul').css('display','none');
    $('.friendInfo .frndList ul#"+name+"').css('display','block');
})

A: Try this
$('a', '.nav').click(function(){
   var name = $(this).parent('li').attr('class').replace(/selected/gi, '');
   $('.selected', '.nav').removeClass('selected');
   $(this).parent().addClass('selected');
   $('ul', '.frndList').hide();
   $('#' + name).show();
})

Fiddle here

A: Try this:
  $('.nav li a').click(function (e) {
     e.preventDefault();
     var name = $(this).parent('li').attr('class');
     $('.selected').removeClass('selected'); // removes the selected class
     $(this).addClass('selected'); // adds the selected class to current clicked elem
     $('#'+name).show().siblings('ul').hide(); // shows the target and hides other
  });

Fiddle

A: DEMO
Script
$('.frndList ul').first().show();
$('.nav li a').click(function(){

        var name = $(this).parent('li').attr('class');
            alert(name)
        $('.nav li a').parent('li').removeClass('selected');
        $(this).parent('li').addClass('selected');
        $('.frndList ul').css('display','none');
        $('.frndList ul#'+name).css('display','block');
        })

CSS
.frndList ul{display:none;}

HTML

All Contacts

Facebook

Google

Yahoo

Hotmail

Manually Added

 ALLLL

 FACEEEE

goooo

 YAAAA

 HOTTTT

 MANNNNNN


text:
Q: What to do if reference is a variable in Pine Script V4? When reading a previous candle's conditions we use [x]...
But how do you call on a previous condition with an unknown [x] location.
Sorry I'm new to scripting.
For example, I want my script to detect whether the current condition is greater than the previous one. Not a specific number of bars back, just "previously" or "most recently".
I don't want to print a "LONG" signal if the previous signal was "LONG"... But I don't know how many bars back the previous "LONG" signal was because that is a variable distance.
printlong = shortsignal[most recently?] lol

A: You can generally use valuewhen() to obtain values you can use for comparison. For example :
long_val0 = valuewhen(long_signal, val, 0) // the most recent value of val when long_signal occurred.
long_val1 = valuewhen(long_signal, val, 1) // the second most recent value of val

short_val0 = valuewhen(short_signal, val, 0)
short_val1 = valuewhen(short_signal, val, 1)

long_index0 = valuewhen(long_signal, bar_index, 0)
long_index1 = valuewhen(long_signal, bar_index, 1)

short_index0 = valuewhen(short_signal, bar_index, 0)
short_index1 = valuewhen(short_signal, bar_index, 1)

Then you can use some logic test to determine most recent signal and their values. So for example if you just want to negate reentering a long if the previous signal was also a long.
This will return true if the previous signal was a short_signal and the current bar is a long_signal. We don't use long_index0 here as it would return the bar_index of the current bar as it is the most recent long_signal
if long_signal and long_index1 < short_index0
    // enter a new long

If you wanted to do something conditional, say only enter a consecutive long if a variable is higher than it was at the time of the last long_signal
if long_signal
    if long_index1 > short_index0 // If true, this would tell us if the last prior signal was long ( two consecutive long signals, current bar and previous signal)
        if long_val0 > long_val1 // current val is higher than the last
            // Do something like : still enter another long, otherwise if val is lower don't enter a long
    else // in the case that short_index0 > long_index1 (the prior signal was short)
        // Enter new long


text:
Q: Build Tree from List of "Contains" relationships I have a list of areas (A,B,C...) , each with a list of the towns (1, 2, 3, 4) they contain.
Note, these are NOT direct parents, the same town shows up in any area that contains it.
A: 1 2 3 4 5 6 7 8 9
B: 2 3 4 5
C: 4 5
D: 2 3
E: 5 6 7

In my case, they always form a unique hierarchical relationship where an area can contain another area, along with the towns that are not in any of the child areas.
A: B E   1 8 9
B: C D
C:       4 5
D:       2 3
E:       5 6 7

If we assume that the hierarchy is unique, can someone give me a pointer to an algorithm in any general purpose language (or pseudo-code) (I'm using C#) to derive the hierarchy?
I've developed something that I think works, but I'd prefer something that's more mathematically certain than "this seems to work".
I'm perfectly happy to have it break if there is no unique hierarchy.
Many thanks

A: My solution, which I think is correct, but is not efficient, is
(1) Determine the immediate parent area for each town:
For each town, find the area with the smallest number of towns that contains that town.
(2) Determine the immediate parent for each area:
For each area, find the area with the smallest number of towns that fully contains that area (not including itself, of course) [completely contain = all towns in area A are also in area B]
Again: this seems to work assuming that if a area X contains a town that area Y contains, then area X contains all the towns that area Y contains, or vice-versa.
In my case, I test this (again massively inefficiently, but I've got small (< 1,000 towns) data sets) by modifying step 1.  For each town, I find all areas that contain that town and sort them by number of towns in the area.  I then check that each area is a complete contained by the next area in the list.
If anyone has a known correct answer (or one more efficiently, I'd be grateful for your contribution.)


text:
Q: Rails 3 find_or_create_by I'm following http://railscasts.com/episodes/102-auto-complete-association
Everything seems fine. I'm trying to create an invoice and also a client on the fly. It does work. Everything cool.
client belongs_to account
invoice belongs_to account
invoice belongs_to client
Buuut, both models (Client and Invoice) have a mandatory attribute: account_id.
When I'm trying to create a new client on the fly I get an error :client_id: - can't be blank
The reason I'm getting this error it's because a Client can't be created because it's requiring an account_id in the Client model. If I remove this line validates :account_id, :presence => true in Client model the invoice is added but Client has no account_id.
I do have this in clients_controller.rb in the create action to set a default value @client.account_id = current_user.account_id
invoice.rb
validates :account_id, :presence => true
validates :client_id, :presence => true

def client_name
  client.name if client
end

def client_name=(name)
  self.client = Client.find_or_create_by_name(name) unless name.blank?
end

A: check these write-ups on the ActiveRecord Query Interface for Rails 3.x :
http://guides.rubyonrails.org/active_record_querying.html   (see section "15 Dynamic Finders")
http://m.onkey.org/active-record-query-interface
You'll need to create the account first, then the client, then the invoice - otherwise your validations will fail.
It's best to create the client and invoice through their parents, e.g.:
a = Account.find( current_user.account_id )

c = a.clients.create(:name => "new client")
a.save   # better "save" than sorry ;-)

c.invoices.create(:invoice_date => Time.now)
c.save

I'd recommend playing around with this in your development database using rails console,
so you get a feel for it.


text:
Q: Makecmds.sty and fontspec Error \usepackge{fontspec}

\usepackge[Script=Devanagari]{Kokila.ttf}
\begin{document}
   यह देवनागरी लिपि है.
\end{document}

This gives error of fontspec requires XeTex Or LauTex. However I have already installed fontspec package. One more problem what I getting in multilinguage font using Pollyglossia. Here it asking for makecmds.sty missing. This is also installed.


text:
Q: Simple Angular SPA in ASP .NET 5 - getting blank page on startup I'm attempting to set up a very simple Angular single-page-application in ASP .NET 5.  I've begun with an empty project - the only angular dependency at the moment is ngRoute.
The problem:

When I run the project, I get a blank page in my browser - with no errors in the developer console.

EDIT
I removed the [] from the angular.module('app', []).controller as suggested but now an error is thrown:

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
  Error: [$injector:unpr] Unknown provider: a

I'm using npm, bower, and grunt - but I don't think they have anything to do with the problem.
Here's what the project structure looks like:

Here's the index.html:
<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8" />
    <title></title>
    <!-- angular -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular-route.js"></script>
    <!-- app -->
    <script src="app.js"></script>
</head>
<body ng-cloak>
    <div ng-view>
    </div>
</body>
</html>

Here's the app.js:
(function () {
    'use strict';

    var app = angular.module('app', ['ngRoute']);

    app.config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'Views/home.html',
                controller: 'home'
            })
            .otherwise({
                redirectTo: '/'
            });
    });
})();

Here's the home.js:
(function () {
    'use strict';
    angular.module('app').controller('home', function controller($scope) {
        $scope.title = 'Home';
    });
})();

Here's the home.html:
<div ng-controller="home">
    {{ title }}
</div>

Why do I get a blank page and not the text "Home" rendered on screen?
The app.js under wwwroot contains all of the contents of the Scripts folder - with the app.js contents written first.  Here's the gruntfile.js:
module.exports = function (grunt) {
    // Load grunt plugins from npm.
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-contrib-watch");

    // Configure plugins.
    grunt.initConfig({
        // Combine and minify all of the javascript files from the Scripts folder into the wwwroot
        // folder, making sure the app.js is placed at the beginning.
        uglify: {
            my_target: {
                files: { "wwwroot/app.js": ["Scripts/App/app.js", "Scripts/**/*.js"] }
            }
        },

        // Re-run the uglify task when any of the files in the Scripts folder change.
        watch: {
            scripts: {
                files: ["Scripts/**/*.js"],
                tasks: ["uglify"]
            }
        }
    });

    // Define tasks.
    grunt.registerTask("default", ["uglify", "watch"]);
};

I can see that the angular.js, angular-route.js, and app.js have loaded correctly in the browser.  Here's the contents of the "uglified" app.js:
!function(){"use strict";var a=angular.module("app",["ngRoute"]);a.config(function(a){a.when("/",{templateUrl:"Views/home.html",controller:"home"}).otherwise({redirectTo:"/"})})}(),function(){"use strict";angular.module("app",[]).controller("home",function(a){a.title="Home"})}();

A: Claies is right when it comes to app initialization, but there is another thing.
You problem is much more complicated than you think. You are using uglifyjs, which changes names of variables in controller arguments. You need to use ngannotate in gruntfile.js or switch to longer controller definition.
This is brief explanation:
uglify wants to make your JS files lighter and changes it from this:
myApp.controller('GreetingController', function($scope, service) {
  $scope.greeting = 'Hola!';
  service.fnc();
});

To this:
myApp.controller('GreetingController', function(a,b) {
  a.greeting = 'Hola!';
  b.fnc();
});

This causes problems for angular because it does not know what a is.
If you want to solve it without changing your controllers, you can use ngannotate task. Alternative way is changing controller's definition:
myApp.controller('GreetingController', ['$scope', 'service', function($scope, service) {
  $scope.greeting = 'Hola!';
  service.fnc();
}]);

Uglify will transform that to:
myApp.controller('GreetingController', ['$scope', 'service', function(a, b) {
  a.greeting = 'Hola!';
  b.fnc();
}]);

NOTE: Please have in mind that using ngannotate is probably better way, beacause you will not face same problems with 3rd party services etc.

A: Your home.js has a subtle bug.  You are re-declaring your app module, which is removing all the route configuration.
angular.module('app', []).controller... is the setter syntax for a module. Instead, you should use angular.module('app').controller getter syntax, to avoid re-declaring the module.


text:
Q: Setting page zoom to user preference I would like the users of my web app to be able to set the level of zoom they want for each page in my app, store that zoom level as a cookie (for each page), and zoom the page to the desired level the next time the user displays that page.
I have been able to do this with a popup window that has arrows on it, allowing the user to specify the amount of zoom and X and Y offset.  But, this is tedius for the user.  What I really want is to allow the user of a phone/tablet to specify the zoom they want simply with a pinch and/or spread action available on phones and tablets.
My problem is that I can't reliably detect the amount of zoom created by the user action of pinching and/or spreading.  I tried using
var zoom = window.outerWidth / window.innerWidth;
This works in Chrome, but doesn't change in Firefox when the user changes the zoom level.
Does anyone know how to reliable detect the zoom level after a pinching and/or spreading action performed by the user across all modern browsers?
Thanks,
Gary


text:
Q: xades4j.utils.XadesProfileResolutionException: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException SoapUI On a latest SoapUI version 5.6.0 I have a problem with signing documents.
log : xades4j.utils.XadesProfileResolutionException: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
java jdk 14.0.2
libraries: xades4j-1.5.1,xmlsec-2.0.9
Anyone can help?

A: The latest version of xades4j includes the proper JAXB dependencies.
Info on alternatives with earlier versions here: https://github.com/luisgoncalves/xades4j/issues/212


text:
Q: Selecting the value of an entire dictionary I'm making a simple quiz game and I'm having some trouble with calculating the results. The problem is really simple, I need to find out how to say if clicked1 has a value more than the whole dictionary it is in then do this function. Here is the code for the dictionary and the function I'm trying to make. Also, if someone could explain why possibilities.value doesn't work for my problem that would be much appreciated.
var possibilities = {
    'clicked1': 0,
    'clicked2': 0,
    'clicked3': 0,
    'clicked4': 0,
};

function results(){
    if (possibilities['clicked1'] > possibilities){
        console.log("it worked");
    }
};

A: Just iterate through Object.values with every:

var possibilities = {
    'clicked1': 0,
    'clicked2': 0,
    'clicked3': 0,
    'clicked4': 0,
};

if (Object.values(possibilities).every(val => possibilities.clicked1 >= val || val == possibilities.clicked1)) {
  console.log("It works!");
}

A: You can use every(). You can also check if the max value of the object values by using Math.max() and Rest Parameters

var ps = {
    'clicked1': 4,
    'clicked2': 1,
    'clicked3': 2,
    'clicked4': 3,
};
if(Object.keys(ps).every(key => ps[key] <= ps.clicked1)){
  console.log("worked")
}
//Second Method:
//Object.values(ps) will return '[4,1,2,3]' And then using ... all values
//are passed to function Math.max() single argument. and it will return the max value out of those and then compare that value with you desired value
if(Math.max(...Object.values(ps)) === ps.clicked1){
    console.log("Worked");
}

A: Here is an approach that is quite similar to what you had in your attempt.
Basically loop over the keys and values in the dictionary, ignoring the value for the key, 'clicked1':

let possibilities = {
  'clicked1': 0,
  'clicked2': 0,
  'clicked3': 0,
  'clicked4': 0,
};

function result() {
  for (let key in possibilities) {
    if (key !== 'clicked1' &&  possibilities[key] >= possibilities['clicked1']) {
      return "it did not work";
    }
  }
  return "it worked";
}

console.log(possibilities);
console.log("result() =", result());
possibilities['clicked1'] = 1;
console.log(possibilities);
console.log("result() =", result());

A: Another alternative is to check if you found some element greater than possibilities["clicked1"]. If you found one, you will know possibilities["clicked1"] is not the max value, otherwise it will be the max value among all others. For approach this we can use Object.values() to get an array of values from your object, and then we use Array.some() to do the mentioned verification:

var possibilities1 = {'clicked1': 6, 'clicked2': 3, 'clicked3': 4, 'clicked4': 5};
var possibilities2 = {'clicked1': 3, 'clicked2': 3, 'clicked3': 4, 'clicked4': 5};

function results(ps)
{
    let found = Object.values(ps).some(x => x > ps['clicked1']);
    found ? console.log("not worked") : console.log("worked");
};

results(possibilities1);
results(possibilities2);


text:
Q: Как центрировать
* относительно границ
*? Как можно центрировать  элементы списка
 относительно границ списка
?

ul {
  border: dashed blue 2px;
  list-style-position: inside;
  text-align: center;
}
li {
  border: dashed green 2px;
}

Text

Text

Text

A: @Rumata Может так?

ul {
  border: dashed blue 2px;
  list-style-position: none;
  margin: 0;
  padding: 0;
}
li {
  border: dashed green 2px;
  margin: 0;
  padding: 0;
  text-align: center;
}

Text

Text

Text


text:
Q: Bash: cant' read out strings with spaces after looping through array of strings I am using a loop to read the contents of an array, which contains all of the directories and files in the directory hierarchy called 'music' (contents are strings from the previous output of 'find' command). The idea is to separate the full directory path of each array element in "directory_contents" into substrings according to genre, artist, and title. Since my music directory is sorted first by genre, then by artist, then by title, I am grabbing each relevant item using awk where the delimiter "/" shows up. For example, if the directory looks like this after using find "./Electronic/Squarepusher/My Red Hot Car.aif", I will separate "Electronic", "Squarepusher", and "My Red Hot Car", then store them each in separate arrays for genre, artist, and title. Later I will sort these data, then pipe the sorted output into another utility to print all the directory contents in a nice looking table (haven't done this yet). For now, I am just trying to view the results of the string separation with echo statements, and for the most part it seems to work. However, I can't seem to extract substrings which contain spaces, which isn't good:
-->./Hip-Hop/OutKast/title1.aif<--
Genre:
Hip-Hop
Artist:
OutKast
Title:
title1

-->./Hip-Hop/OutKast/title2.aif<--
Genre:
Hip-Hop
Artist:
OutKast
Title:
title2

-->./Hip-Hop/OutKast/title3.aif<--
Genre:
Hip-Hop
Artist:
OutKast
Title:
title3

-->./Jazz/John<--
Genre:
Jazz
Artist:
John
Title:

-->Coltrane/title1.aif<--
Genre:
title1.aif
Artist:

Title:

As you can see, when the loop reads in the string "John Coltrane", it is treating the space as a delimiter, and treating everything after "John" as a different filename. I tried looking for a solution in the bash manual under the section "Arrays" as well as other posts here, but couldn't find a solution that worked for my specific problem (sorry). If anyone has ideas, they would be greatly appreciated. The problematic code appears below, in the for loop (I didn't post the whole script because it is pretty lengthy, but let me if it is needed):
#more before this...

#declare variables
declare -a genre_list
declare -a title_list
declare -a artist_list
declare -a directory_contents

#populate directory with contents
cd $directory
directory_contents=$(find .  -mindepth 1 -type f)
cd ..

for music_file in ${directory_contents[*]}; do
    if [[ $DEBUG = "true" ]] ; then
        echo "-->$music_file<--"
    fi

    echo "Genre:"
    echo $music_file | awk -F"/" '{print $2}'
    echo "Artist:"
    echo $music_file | awk -F"/" '{print $3}'
    echo "Title:"
    echo $music_file | awk -F"/" '{print $4}' | awk -F"." '{print $1}'
    echo ""
done

A: Why don't you simply do it in single line:
cd $directory && \
find .  -mindepth 3 -maxdepth 3 -type f | \
awk -F'/' '{split($4,A,".aif"); printf "Genre: %s\nArtist: %s\nTitle: %s\n\n",$2,$3,A[1];}'

Update: (removed the .aif from the Title part)

A: If you can, you should use Perl for this task:
#! /usr/bin/perl

foreach my $fname (<*/*/*>) {
  next unless -f $fname;
  next unless $fname =~ m"^([^/]+)/([^/]+)/([^/.]+)\.\w+$";
  my ($genre, $artist, $title) = ($1, $2, $3);
  printf("Genre: %s\nArtist: %s\nTitle: %s\n\n", $genre, $artist, $title);
}

It is faster and simpler than the shell, and it is immune against whitespace in file names.

A: MUSICDIR="/some/path"
cd "$MUSICDIR"

find  . -type f -print | (IFS=/;while read dot genre artist title
do
    echo =$genre= =$artist= =$title=
done)

A: You might try setting the delimiter that bash uses. Perhaps to a newline character?
IFS=\n


text:
Q: Rails server and cron jobs are crashes on server I use Ruby - 2.1.2 and rails- 4.
On server rails server crashes sometimes with no error in log files.
I need to restart server again.
Also cron jobs also getting crash.
In my application, I need to upload very big file (Almost 80 mb).
Please help not getting why server getting crash.


text:
Q: Solving integral $\int{\frac{dx}{x^2+ax+4}}$ with assumptions
Solve the following integral for the given cases:
$$\int{\frac{dx}{x^2+ax+4}},\space\rm{if}\space|a|\lt4$$
$$\int{\frac{dx}{x^2+ax+4}},\space\rm{if}\space|a|\ge4$$

I'm trying to solve this problem, but I didn't quite understand how those assumptions are supposed to change the final result.
My first attempt was to solve it ignoring the assumptions, so I got this:
$$\frac{2\arctan(\frac{a+2x}{\sqrt{16-a^2}})}{\sqrt{16-a^2}}$$
By looking at it, I can tell that the assumption $|a|\ge4$ would imply in a division by zero and square roots from negative values, but that's all I can see here.
It seems that the assumptions should be used during the integral resolution to lead to different results, but I'm not getting how.
Another information that may be relevant is that $x^2+ax+4$ becomes irreducible when $|a|\lt4$

A: Note
$$I=\int{\frac{dx}{x^2+ax+4}}= \int{\frac{dx}{(x+\frac a2)^2+\frac{16-{a^2}}4}}
$$
For $|a|\lt4$, we have $\frac{16-{a^2}}4\gt 0$ and
$$I = \frac2{\sqrt{16-{a^2}}}\tan^{-1}\frac{2x+a}{ {\sqrt{16-{a^2}}}}+C
$$
For $|a|\gt 4$, we have $\frac{16-{a^2}}4\lt 0$ and
$$I = \frac1{\sqrt{{a^2}-16}}
\ \ln \left|\frac{1-\frac{2x+a}{\sqrt{a^2-16}}}{1+\frac{2x+a}{\sqrt{a^2-16}} {}}\right| +C
$$
For $|a|=4$, we have
$$I = \int\frac{dx }{(x\pm 2)^2}= -\frac1{x\pm 2}+C
$$

A: This change in behavior is explained by the real or complex nature of the roots of the denominator. By a linear transform, the two cases can be reduced to the forms
$$\int\frac{dx}{x^2\pm1}$$ and you can't get rid of the sign, because of these roots.
The antiderivatives are respectively
$$\arctan(x)$$ and $$\text{artanh}(x).$$
Notice the relation via imaginary numbers,
$$\arctan(ix)=i\text{ artanh}(x).$$


text:
Q: Android / Getting with application name of any status bar notification In NotificationListenerService class, there are onNotificationPosted(StatusBarNotification sbn) and onNotificationRemoved(StatusBarNotification sbn) functions.
Consider the onNotificationPosted(StatusBarNotification sbn) function.
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
        String pack = sbn.getPackageName();
        String ticker = new String();
        if(sbn.getNotification().tickerText != null) {
            ticker = sbn.getNotification().tickerText.toString();
        }
        Bundle extras = sbn.getNotification().extras;

        String title = extras.getString("android.title");
        String text = extras.getCharSequence("android.text").toString();
        int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
        Bitmap id = sbn.getNotification().largeIcon;
}

So, with this function, I am able to get title, text, app icon and package name of any new notifications whatever that come in the mobile device from my own Android application, of course. I want to get the app name of the notification (for example, if the package name is com.kpbird.nlsexample, the app name is NLService, so the app name can be significantly different enough from the portion of package name to the right of the rightmost dot in the package name). How can I be able to do that process of extracting the app name from the posted status bar notification of the mobile device for the new notifications as they come in, forever?
for(String key : extras.keySet())
        {
            Log.i("Key", key);
        }

2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.title
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.subText
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.showChronometer
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.icon
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.text
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.progress
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.progressMax
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.appInfo
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.showWhen
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.largeIcon
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.infoText
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.originatingUserId
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.progressIndeterminate
2018-12-07 11:49:56.543 26392-26392/android.notificationlistener I/Key: android.remoteInputHistory

It appears that there is no key available in Bundle extras for getting the app name. There also seems to be no variable declared in StatusBarNotification sbn class available for getting the app name. However, it seems that it is possible to get the timestamp that is essentially the time at which any notification had been posted into the status bar of the mobile device from the StatusBarNotification sbn class for the new notifications as they come in.
StatusBarNotifications.java

private final String pkg;
private final int id;
private final String tag;
private final String key;
private String groupKey;
private String overrideGroupKey;
private final int uid;
private final String opPkg;
private final int initialPid;
private final Notification notification;
private final UserHandle user;
private final long postTime;


text:
Q: Create and write to new csv file during 'for' loop The code below is intended to create a csv file called 'file-0.csv' and start writing lines by iterating through the for loop until it reaches 100 lines. When the limit is reached, it should stop writing to 'file-0.csv', create 'file-1.csv', and continuing the for loop where it left off, start writing to 'file-1.csv' until it reaches 100 lines, and so on until the for loop is complete.
The actual behavior of the code below (complete, and executable) is that it creates the new files as expected (4 total), but it continues to write all lines to 'file-0'....
##### Python 3.5 #####

import csv

rowCounter     = 0
fileCounter    = 0
List_A         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_B         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_C         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

def new_file():
    global fileCounter
    fileCounter += 1
    with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile:
        rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile:
    rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

    for word1 in List_A:
        for word2 in List_B:
            for word3 in List_C:
                sentence = word1 + word2 + word3
                rowWriter.writerow ([sentence])

                rowCounter += 1

                if rowCounter == 100:
                    new_file()
                    rowCounter = 0
                else:
                    continue

Same code as above, but heavily commented:
##### Python 3.5 #####

######################
####### Setup ########
######################

### Use the CSV library
import csv

### Initialize counters
rowCounter     = 0
fileCounter    = 0

### Create three lists of 'words'
List_A         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_B         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_C         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

### Function/subroutine that creates new CSV file with incremented filename
def new_file():
    ### Make the variable 'fileCounter' usable by the function
    global fileCounter
    ### Add 1 to 'fileCounter'
    fileCounter += 1
    ### Create new CSV file using the value of 'fileCounter' as part of the name
    with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile:
        rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

######################
#### Main Program ####
######################

### Create initial CSV file using the value of 'fileCounter' as part of the name
with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile:
    ### Create writer object and define how it should behave
    rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

    ### Create & Write lines ###
    ### Nested 'for' loops to iterate through all combinations of words
    for word1 in List_A:
        for word2 in List_B:
            for word3 in List_C:
                ### Build our 'sentence' from the current iteration
                sentence = word1 + word2 + word3
                ### Write 'sentence' to file
                rowWriter.writerow ([sentence])

                ### Increment row counter
                rowCounter += 1

                ### Check if value of rowCounter is 100 and if so, execute
                ### 'new_file' and reset rowCounter to 0. If not, continue.
                if rowCounter == 100:
                    new_file()
                    rowCounter = 0
                else:
                    continue

I suspect the problem is 'rowWriter' not getting updated or passed back to the main loop properly, but I can't seem to figure out how to do it (and anyway, I'm not even sure if that's it).
I've tried to document and make the code "generic" so others can get some use out of any answers. Any help is greatly appreciated.

A: Leaving the with block closes with file. Therefore, the new_file function just opens and immediately closes a file.
You could do somthing like the following:
import csv

rowCounter     = 0
fileCounter    = 0
List_A         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_B         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_C         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

# create file handle
csvfile = open('file-' + str(fileCounter) + '.csv', 'w')

rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

for word1 in List_A:
    for word2 in List_B:
        for word3 in List_C:
            sentence = word1 + word2 + word3
            rowWriter.writerow ([sentence])

            rowCounter += 1

            if rowCounter == 100:
                # close current filehandle
                csvfile.close()
                fileCounter += 1
                # open new file
                csvfile =  open('file-' + str(fileCounter) + '.csv', 'w')
                rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
                rowCounter = 0

# close file
csvfile.close()

or with defining a function:
import csv

rowCounter     = 0
fileCounter    = 0
List_A         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_B         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_C         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

def new_writer( csvfile, counter ):
     if csvfile:
         csvfile.close()

     # open new file
     csvfile =  open('file-' + str(counter) + '.csv', 'w')
     rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

     counter += 1

     return rowWriter,csvfile,counter

rowWriter, csvFile, fileCounter = new_writer( None, fileCounter )

for word1 in List_A:
    for word2 in List_B:
        for word3 in List_C:
            sentence = word1 + word2 + word3
            rowWriter.writerow ([sentence])

            rowCounter += 1

            if rowCounter == 100:
                # close current file and open a new one
                rowWriter, csvfile, counter =  new_writer( csvfile, fileCounter )
                rowCounter = 0

# close file
csvFile.close()

A: Thanks @desiato!
I accepted your answer, but ended up using lines 23-29 of your code and ended up with this (it works great!):
import csv

rowCounter     = 0
fileCounter    = 0
List_A         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_B         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
List_C         = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile:
    rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)

    for word1 in List_A:
        for word2 in List_B:
            for word3 in List_C:
                sentence = word1 + word2 + word3
                rowWriter.writerow ([sentence])

                rowCounter += 1

                if rowCounter == 100:
                    csvfile.close()
                    fileCounter += 1
                    csvfile =  open('file-' + str(fileCounter) + '.csv', 'w')
                    rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
                    rowCounter = 0
                else:
                    continue


text:
Q: Requiring hierarchy of directives and using parent in child scope I'd like to be able to have something similar to this:

And then in someDirective:
link: function(scope, el, attrs) {
  console.log(scope.property); // "value"

How is this achievable? I'm having trouble with 1) requiring the parent directive and 2) accessing it's scope. Here's what I tried (directive/property names are fake):
app.directive('property', function() {
  transclude: true,
  template: '<ng-transclude></ng-transclude>',
  controller: function(){},
  scope: {
    property: '='
  }
});

app.directive('someDirective', function() {
  require: '^property'
  transclude: true,
  replace: true,
  scope: {
    someDirective: '='
  }
  templateUrl: 'my_template.html',
  controller: function($scope) {
    console.log($scope.property);
  }
});

I don't fully understand how this works. Can anyone please clarify the exact usage?
The problem I'm trying to solve is how to avoid repetitive defining of a binded property across children directives. They're all supposed to point to the same object in the controller scope, so I'd like to avoid setting on each use of the child directive, and instead only define them once on the parent. Is this possible? Thanks in advance :)

A: Have you tried with $scope.$parent.property?
Requiring directives is good if you want to share some functionalities across directives. A directive has a controller with useful functions that you want to use for your child directives (let's say B directive).


text:
Q: Help with averaging specific columns awk I need to process some data for my dissertation and I need to do it though Linux as I have > 2 million points. I've currently gotten my selected data it in a file that looks something like this using awk:
2003.1 -142 42.0000 -6.8990
2003.2 -142 42.0000 -4.7063
...
2003.12 -142 42.0000 -2.1986
2004.1 -139 42.0000 0.6408
2004.2 -139 42.0000 3.7293
2004.3 -137 50.0000 6.9090
2004.4 -136 50.0000 10.0193

Columns are: decimal year, longitude, latitude, value respectively. I want to average each point value that has the same lat and long in the same year (so disregarding the decimal place on the year).
e.g so the output will look like:
2003   1   1   30.000
2003   1   2   20.000
...
2003   180 90  40.000
2004   1   1   30.000
2004   1   2   20.000
...
2004   180 90  40.000
...
...
...
2015   180 90 -100.000

An average for each point per year.
I've currently been using awk so if anyone can show me how do to it using that it will be much appreciated, Thanks!

A: Something like
#!/usr/bin/gawk
BEGIN {OFS = "\t"}
{
    key = int($1) OFS $2 OFS $3
    sum[key] += $4
    count[key]++
}
END {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    for (key in sum)
        print key, sum[key]/count[key]
}


text:
Q: How to do Parent-Child Relationship in F# I am trying to rewrite a C# application I wrote long time ago into F#, but I am having some troubles, because this is my first attempt in writing something meaningful in F#
in my C# software, I have the following class "Buildings" which is the parent class that I need to usein the rest of the application:
public class Buildings()
{
    Buildings()
    {
        Spectre = new Spectres(this);
    }
    public double Height;
}

and another class called "Spectres", which is only used through Buildings:
public class Spectres(Buildings prntBuilding)
{
    Spectres()
    {
        _prntBuilding = prntBuilding;
    }

    private Buildings _prntBuilding;
    public double doSomethingToheight()
    {
       return _prntBuilding.Height * 2.0;
    }
}

my question is: how can I do this in F#, are there alternatives for this Parent-Child relationship in F#?
Edit: I found a solution
type Buildings() as self =
   member this.Hn = 1.0 with get, set
   member val Spectre = new Spectres(self) with get, set

and Spectres(prntBuinding : Buildings) =
   let DoSomethingToHeight = prntBuilding.Hn * 2.0

A: Presumably your issue is caused by the ordering of declarations in F# affecting visibility of the second type. (Order matters in F#.)
You can solve this without much hoopla with mutually recursive types, as in:
type Buildings() =

    member val Height = 0.0 with get, set

and Spectres(prntBuilding : Buildings) =

    member __.DoSomething () = prntBuilding.Height * 2.0

The and indicates that they know about each other.
The documentation for mutually recursive types is here: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/classes#mutually-recursive-types

A: The best approach is to rethink your design.
Why does the Spectres class need to know about its parent? In the sample code you've shown us, the Spectres class only needs to know its parent in order to get one input parameter (the height) for the doSomethingToheight method. Well, why not just pass the height directly to that method?
let doSomethingToHeight height = height * 2.0

As an added bonus, this version of the doSomethingToHeight function is a pure function: it has no side effects, and its result is entirely determined by its input parameters. Pure functions have many advantages: they're much easier to test, and they're also much easier to reuse in other parts of your code. You'll be surprised how valuable that is: once you start rewriting your methods to be pure functions instead, you'll eventually discover all kinds of ways that they can be reused elsewhere.
And incidentally, now the Spectres class in your example code looks like this in C# (I'll keep the examples in C# to show that this design approach isn't limited to F#, and because you're more familiar with reading C# code at this point):
public class Spectres()
{
    Spectres(Buildings prntBuilding)
    {
        _prntBuilding = prntBuilding;
    }

    private Buildings _prntBuilding;
    public double doSomethingToheight(double height)
    {
       return height * 2.0;
    }
}

Now there's no particular reason for Spectres to need to keep the reference to the parent building around. (At least in this example code; in your original code, you might have other uses for it. But I'm working just with what you've shown us so far). So let's get rid of that unnecessary constructor parameter and private field:
public class Spectres()
{
    Spectres()
    {
    }

    public double doSomethingToheight(double height)
    {
       return height * 2.0;
    }
}

And now, this is a class that has just a single function in it and does no other work than supporting that single function. Have you ever read Steve Yegge's brilliant article, "Execution in the Kingdom of the Nouns"? Classes that do nothing but carry around a single function should be replaced with that function. In C# that's a bit tricky because all functions must live in a class somewhere, but you can get the closest to a standalone function by making it a static method in some utility class where you keep all of your standalone functions:
public static class StandaloneFunctions
{
    public static double doSomethingToHeight(double height)
    {
        return height * 2.0;
    }
}

Of course, in F# those seven lines can be reduced down to the simple one-line definition I showed you at the beginning of this answer:
let doSomethingToHeight height = height * 2.0

No need to declare a static class for that function to live in; the F# compiler will take care of that for you behind the scenes. All you have to do is think about your data, and how your data will be transformed.
At this point, you're probably saying, "Yes, but my Building class has other interactions with Spectre that you don't know about, and your solution won't work because of those interactions." Well, if you use a similar approach to those interactions (turn them into pure functions), I bet you'll discover that it does work, and furthermore, is much simpler to understand in the long run. And if you're not sure how to do that transformation, ask another question about the part you're unsure of; there are several F# experts around who will probably be happy to help you with it.


text:
Q: Why does this filter work on a List but not on an IQueryable? I need to create an extension method that will filter collection List<TSource> according to a list of validation rules List<<IRule>, bool>.
But I get an error VisitSubQueryExpression method is not implemented and I don't see/can not find what is the problem cause.
This is my extension method:
public static List<TSource> ValidItems<TSource>(this IQueryable<TSource> source,
                                  List<IValidationRule<TSource>> validationRules)
{
     return source.Where(testableItem =>
            validationRules.All(rule => rule.RulePassed(testableItem))).ToList();
}

IRule interface:
public interface IValidationRule<T> //with implementation class ValidationRule<T>
{
    Func<T, bool> RulePassed { get; set; }
    //... +other code
}

Sample of extension method call
//initialization of List<SampleType> listToValidate = ...
var validItems = listToValidate.ValidItems(
                  new List<IValidationRule<SampleType>() {
                       new ValidationType<SampleType> {
                       RulePassed = (s) => string.IsNullOrWhiteSpace(SampleType.Name),
                       //...initalize other ValidationType parameters
                       }
                   });

this sample should filter listToValidate list and remove all SampleType instances, with Name property that is Null or Whitespace
What is wrong with my extension method? What does this "VisitSubQueryExpression method is not implemented" error mean?
if I change it to be an extension method for List<TSource> not IQueryable<TSource> - it works! Why?
replacing this IQueryable<TSource> with this List<TSource>, it works, why? Where method should work on IQueryable<T> (inherits from IEnumerable<T>), shouldn't it?
public static List<TSource> ValidItems<TSource>(this List<TSource> source,
                                  List<IValidationRule<TSource>> validationRules)
{
     return source.Where(testableItem =>
            validationRules.All(rule => rule.RulePassed(testableItem))).ToList();
}

A: Your rule.RulePassed cannot be translated by your IQueryable provider.
public static List<TSource> ValidItems<TSource>(this IQueryable<TSource> source,
                              List<IValidationRule<TSource>> validationRules)
{
    var result = new List<TSource>();
    foreach (var testableItem in source)
    {
        if (validationRules.All(rule => rule.RulePassed(testableItem))
        {
            result.Add(testableItem);
        }
    }
    return result;
}

A: IQueryable<T> implements IEnumerable<T> but not vice versa. And List<T> doesn't implement IQueryable<T>.
This is the list of interfaces exposed by List:

Since both IQueryable and IList inherit from IEnumerable<T> you could use that and call .AsQueryable on it to convert both cases.

A: List<T> does not implement IQueryable<T>, so you can't call an extension method on it defined on IQueryable<T>.


text:
Q: How to create a table using tableviewer which has 2 coloumns and 10 rows in jface How to create a table using TableViewer which has 2 columns and 10 rows.I am trying to create a table using the above link http://www.vogella.com/tutorials/EclipseJFaceTable/article.html
i am not able to develop it .So please help me to do as i am new to jface
I have created the columns of the table but i am not able to add the data into it using content provider and label so please help me to do.The code to create the column header is as follows
TableColumnLayout layout = new TableColumnLayout();
composite.setLayout(layout);

//Instantiate TableViewer
TableViewer tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);

TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn empty = tableViewerColumn.getColumn();

layout.setColumnData(empty, new ColumnPixelData(100, true, true));
empty.setText("");

TableViewerColumn tableViewerColumn_Time = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn time = tableViewerColumn_Time.getColumn();
//Specify width using weights
layout.setColumnData(time, new ColumnWeightData(2, ColumnWeightData.MINIMUM_WIDTH, true));
time.setText("Time");

TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn message = tableViewerColumn_2.getColumn();
//Specify width using weights
layout.setColumnData(message, new ColumnWeightData(4, ColumnWeightData.MINIMUM_WIDTH, true));
message.setText("Message");

A: You need a class containing the data for the rows, something like:
class MyRowData
{
  String getTime()
  {
     ... your code
  }

  String getMessage()
  {
     .... your code
  }
}

Add column label providers to your columns which get the data from your class:
tableViewerColumn_Time.setLabelProvider(new ColumnLabelProvider() {
  @Override
  public String getText(Object element) {
    return ((MyRowData)element).getTime();
  }
});

tableViewerColumn_2.setLabelProvider(new ColumnLabelProvider() {
  @Override
  public String getText(Object element) {
    return ((MyRowData)element).getMessage();
  }
});

Use a standard array / list content provider:
tableViewer.setContentProvider(ArrayContentProvider.getInstance());

Create a list containing your rows:
List<MyRowData> rows = new ArrayList<>();

rows.add(new MyRowData(.....
....

Tell the table viewer to use the list:
tableViewer.setInput(rows);

This setInput call must be done last.


text:
Q: Непонятно условие цикла  --  while(1) Друзья, подскажите, в скобках условия цикла while -- единица. Это алгоритм "двоичный поиск". Алгоритм работает, но эта единица в условии цикла непонятна:
         while(1)
         {...........}

A: Общая форма цикла while имеет следующий вид:
while(условие) оператор; //(оператор это тело цикла)

Условие может быть любым допустимым выражение в языке. Функция проверяет на Истину или Ложь условие.
Если ИСТИНА то цикл продолжается (все что в теле цикла) - любое значение кроме 0.
Если ЛОЖЬ то цикл прекращается - 0.
В данном случае while(1), while(5), while(-15) истина - цикл продолжается бесконечно или пока в теле цикла не будет break, exit(), return или goto.
А while(0) уже ложь и цикл останавливается не начавшись.

A: Ничего необычно - это просто значит исполнять этот цикл вечно. Классический способ.
Конечно, где то должен быть break или return что бы этот цикл остановить. Иначе он будет исполнятся очень долго:)
A: Это цикл без условия. Он будет исполняться, пока ты не его не прервёшь при помощи операторов break, return, goto, вызова exit, ExitProcess или исключения. Также цикл без условия можно создать при помощи конструкции for(;;) {...}.
A: Это значит, что цикл бесконечный. Прервать его итерацию можно через break или return (ну или через throw).


text:
Q: Each loop setting a value to nil I'm working with a one to many relationship in which a Workout has many Workout_drills and the Workout_drills table also belongs to a Drills table that acts a reference table.
At the creation of a Workout, 5 Workout_drills are created which contain a randomly created Drill_id (pulling from the table of drills) and the same Workout ID for all Workout_drill records.
Here is the Workouts Controller:
  def show
    @workout = current_user.workouts.find(params[:id])
    @workout_drills = @workout.workout_drills
  end

Here is the view:
<% @workout_drills.each do |w| %>

      <%= link_to w.drill.name, drill_path(w) %>
      <%= w.drill.description %>
      <%= w.drill.pointers %>
      <% if w.drill.video.present? %>
      <%= link_to "Video", w.drill, class: 'btn-xs btn-success' %>
      <% else %>
      Not Yet
      <% end %>

    <% end %>

  <%= link_to 'Begin Workout', workout_drill_path, class: 'btn btn-success' %>

For some reason, the workout_drills populate correctly when called but when I try and call the w in my terminal, the drill_id becomes nil.
I feel like this is a simple problem but I am at a loss for how to find what is happening. Any advice would be extremely helpful.


text:
Q: Tumblr API Avatar *Complete PHP noob here. I'm trying to write simple php that returns a tumblr avatar. Tumblr has an address you can navigate to, to retreve the blog avatar. For example navigating to:
http://api.tumblr.com/v2/blog/david.tumblr.com/avatar/512
leads to this:
http://27.media.tumblr.com/avatar_a963092d964b_512.png
I simply want the .png address as a variable. Here's what I got but it just spits out a big page of strange text.
<?php
$avatar = file_get_contents("{the link above, I can only have two hyperlinks in a post}");
echo $avatar;
?>

I assume the file_get_contents is not what I want to use but I don't know what to use.

A: You can use the official PHP Tumblr Client and just provide your consumer key.
// Authenticate via API Key
$client = new Tumblr\API\Client('yourkeyhere');

// Make the request
$client->getBlogAvatar('yourblog.tumblr.com', 16); //You can choose different size here on the second parameter

then this will return the URL of the image.
You can refer to this for more of the Tumblr API Avatar Endpoint and others
https://api.tumblr.com/console/calls/blog/avatar

A: Have you tried:
<?php
$avatar = "http://27.media.tumblr.com/avatar_a963092d964b_512.png";
echo $avatar;
?>


text:
Q: How to use phantomjs to download the html code of an xmlFile with an xslFile? I want to get the html code of a xml file with a xslFile.But when I use phantomjs to get the code ,I find it is the xml code but not the html code.An Interesting thing is that When I  view the elements in the FireFox Webbrowser ,it is the html code I see.But I get the xml code with phantomjs.
code in fireFox webbrowser
but it is xml code in the cmdLine with phantomjs.Look here:
code I get in the cmdLine with phantomjs
Here coms the question,how can I get the html code of an xml with an xsl File?
Thanks!


text:
Q: I want to print the "\" character in python but I get "\\" I have a python list of strings with 000_S_0000 formatting. Since I want this list to be displayed in a LaTeX document, I want to save it first in a .txt file using a different formatting for each of its strings, specifically this one: 000\_S\_0000.
However, when I wrote the modified list in the .txt file, each string was formated as 000\\_S\\_0000 instead.
How could I solve that? Why isn't it working?
Thanks in advance!
This is my code:
def posa_barres_latex(ll_PTIDs):
    for i in range(len(ll_PTIDs)):
        snou = ''
        for caracter in ll_PTIDs[i]:
            if caracter == "_":
                snou = snou + "\_"
            else:
                snou = snou + caracter
        ll_PTIDs[i] = snou
    with open("sortida_exclosos_criteri_c.txt","w") as f:
        f.write(str(ll_PTIDs))

posa_barres_latex(['002_S_2043', '018_S_2138', '013_S_2324', '129_S_4073', '002_S_4237', '019_S_4285', '130_S_4468', '136_S_4517', '013_S_4791', '031_S_4194','002_S_4219', '002_S_4251', '136_S_4408', '130_S_4605', '130_S_4925', '013_S_4985'])

P.S. I am using python 3.

A: To print a single '\' using the print command just use:
print('\\')
The first '\' escapes the second one.

A: Your Python version matters in this case.
But '\' is the escape character, it's used to encode other characters, for example '\n' is a newline.
You can escape '\' as \\ and it'll just print '\'.
If you're using strings with a lot of them, it might be easier to use raw strings - just put an r in front of them. Example:
print(r"000\_S\_000")
Will print it exactly as you type it.


text:
Q: debuging bug in scope when drag arrow breakpoint -> Start debug mode
-> Reach if(calculate) line
-> Drag arrow to next line {
-> Reach string sValue = "ABC123";
-> Threw an exception Object reference not set to an instance of an object.
But if i set calculate = true and don't drag arrow and just continue with F10 there is no exception at all. You can see in code, 5 cases when throw exception and when not throw exception. When i define sValue before if block, there is no exception.
Can you explain why throw exception in this situation ?
Steps
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        public static List<SaleLineItem> SaleItems = new List<SaleLineItem>();

        static void Main(string[] args)
        {
            SaleItems.Add(new SaleLineItem { ItemId = "ABC123", NetAmount = 2 });
            SaleItems.Add(new SaleLineItem { ItemId = "ABC123", NetAmount = 3 });

            try
            {
                bool calculate = false;
                // string sValue = "ABC123";

                if (calculate)
                {
                    string sValue = "ABC123";
                    decimal total = 0;

                    #region Exception
                    total = SaleItems.Where(t => t.ItemId != sValue).Count();
                    // total = SaleItems.Where(t => t.ItemId != sValue).Sum(t => t.NetAmountWithTax);
                    // var newSaleItems = SaleItems.FirstOrDefault(t => t.ItemId != sValue);
                    #endregion

                    #region No Exception
                    // string newValue = sValue;
                    // var newSaleItems = SaleItems.FirstOrDefault();
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    [Serializable]
    public class SaleLineItem
    {
        public string ItemId { get; set; }
        public decimal NetAmount { get; set; }
    }
}

A: I might have found a reason why that happens.
First of all I beoke down your code to see what it needs to get that Exception and ended up like this:
List<string> SaleItems = new List<string>();
var test = false;

if(test)
{
    var sValue = "ABC123";

    SaleItems.Count(t => t != sValue);
}

This produces the exact same error, as you described.
So my guess was this could be a problem with the compiler that optimized something, so I took a look at the Intermediate Language (IL) produced by this code. Here's the part that I think is interesting: (Note: The lines starting with // are just comments for visualisation to which part of the code the comments belong)
//000013:
//000014:           if(test)
  IL_0009:  ldloc.1
  IL_000a:  stloc.2
//000015:           {
//000016:               var sValue = "ABC123";
//000017:
//000018:               SaleItems.Count(t => t != sValue);
//000019:           }
//000020:       }
//000021:   }
//000022: }
  IL_000b:  ldloc.2
  IL_000c:  brfalse.s  IL_0034
  IL_000e:  newobj     instance void TestConsoleApplciation_delete_.Program/'<>c__DisplayClass0_0'::.ctor()
  IL_0013:  stloc.3
//000015:           {
  IL_0014:  nop
//000016:               var sValue = "ABC123";
  IL_0015:  ldloc.3
  IL_0016:  ldstr      "ABC123"

The breakpoint is set at the if(test) in Line 14, which is in IL the line that starts with IL_0009:.
Now, if you drag the debugger to the next line (Line 15), it will internally jump to the line IL_0014: and continue from there, so the lines between are skipped.
The problem there is now that the next command that is executed is ldloc.3 at line IL_0015: (ignoring the nop command, which does nothing) and this command tries to load the variable that is stored at line IL_0013: but that command was not executed, so it throws the NullReferenceException because there is nothing to load.
Note: I do not now if this is the real reason why the Exception is thrown but I think it is a pretty reasonable guess.


text:
Q: QGIS 3.6 picture in ui form (Qt5 Designer) I'm facing trouble with display a picture in a ui form based on a field (path).
With the autogenerate form it works but when I try with a personalized form I cannot see the picture.
I tried with a Qlabel and QWebView in Qt Designer and in QGIS layer property I put the field as Attachment but without success.
I know that I can make a little python script to achieve this but I would like to store the ui in a db.
Does anyone have an idea ?

A: It seems possible by tricking QGIS and Qt Creator.
This is how I proceeded.
In QtCreator, you create a new QTextBrowser widget. As usual, you give it the name of the QGIS source field. You need to right click on the new widget and select "Promote In…" and enable both options "QtWebView/QtWebKit" and "QgsExternalResourceWidget" if they are not.

In QGIS now, you select your custom form.
The source field has to be set as a Text source. You have to enable HTML rendering as well.

The data has to be input as HTML inside the field.
So you can create for example a field in which you will store the path of your picture and then create a calculation field rendering HTML as follow:
'<img src="' || "Photo" || '">'

That's all what you have to do.
That will let you create more beautiful forms than the ones in QGIS.
It's even more simple than before.

A: you can use tips tool  in qgis and write with html code for insert any file and even open file out of qgis