text:
Q: how to filter dataframe using a function? i would like to use the following function to filter a dataframa
def isInRadius(position):
    latCheck = False
    lonCheck = False
    if position.lat < 0:
        latCheck = position.lat <= upperLat and position.lat >= lowerLat
    else:
        latCheck = position.lat >= upperLat and position.lat <= lowerLat

    if not latCheck:
        return False

    if position.lon < 0:
        lonCheck = position.lon <= righterLon and position.lon >= lefterLon
    else:
        lonCheck = position.lon >= righterLon and position.lat <= lefterLon

    return latCheck and lonCheck

The dataframe has more columns than 'lat' and 'lon' but i would like to filter it by those 2 according to the logic implemented on the function above.
I have try dataFrame.filter(lambda x: isInRadius(x)) and dataFrame.filter(isInRadius) and dataFrame.filter(lambda x: isInRadius(x.iLoc[0])) and other approaches but none worked, resulting in the error "TypeError: 'function' object is not iterable"
How should i do it?
On C# i would do
var filtered = myCollection.Where(x => isInRadius(x));

A: Just use the .apply functionality of pandas dataframes
df[df.apply(isInRadius, 1)]

A: No need to use an apply
import pandas as pd

df2 =pd.DataFrame({'lookup_id':['a','a','c','c','c'],'val':[1,1,1,1,1]})
print(df2)

  lookup_id  val
0         a    1
1         a    1
2         c    1
3         c    1
4         c    1

# Replace this with whatever your function actually does
def val_is_a(r):
    return r['lookup_id'] =='a'

df2.loc[lambda df : val_is_a(df)]

    lookup_id   val
0   a           1
1   a           1


text:
Q: How to know the sort type when querying the list of files in a folder using Directory.GetFiles? I'm querying a folder using Directory.GetFiles() to get all *txt files and I'd like to get the first file in the list.  (I already know how to implement this)
However, I'd like the list to be sorted by having the newest date modified from the top so I'll get the most newest file first.
Any idea how?

A: You can use OrderBy with the CreationTime property.
DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos("*.txt");
var orderedFiles = files.OrderBy(f => f.CreationTime);

For example, this code is getting all files In C, and sorting list by Creation time.
Here you can read more about that.

A: var output = allFiles.OrderBy(item=> new FileInfo(item).CreationTime);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deny Access to directories from unauthorized users I am not being paid for this and I would like to know the quickest way to do the following. A former client has a page which only members can access. This page links to a number of galleries which he only wants members to access. The galleries are not protected by any kind of authentication.
What I assume is the quickest way to do this is to create a .htaccess file which only allow people to view the site when the come from a certain referrer. Would this work?
My current thinking is that I could use a php script to deploy a .htaccess file into each of the gallery directories. (There are around a 100 at the moment.)
I found this link which might be what I am after but to be honest I really don't get it. Is my thinking sound?

A: If you are willing to go down the PHP road why not consider recommending an existing gallery application like Gallery2 or Coppermine, or building some basic authentication with cookies to manage access?

A: Yes, using a .htaccess file is a good idea, but making exceptions for all of the IP addresses and/or URLs that his members could possibly come from is going to be a pain.
Just tell him to have them use a password, and setup the .htaccess file in conjunction with a .htpasswd file.
.htaccess How-To on Apache.org
.htpasswd on Apache.org

A:
What I assume is the quickest way to do this is to create a .htaccess
  file which only allow people to view the site when the come from a
  certain referrer. Would this work?

Not always, no. Not all browsers submit the HTTP Referer field, and some firewalls even remove it. Your biggest issue will be that, if you add it, you'll get sporadic complaints and that'll be hard to investigate unless you have logs to hand that include the referring page.

This page links to a number of galleries which he only wants members
  to access.

However you verify if a user is a member, is how you protect your gallery.


text:
Q: How to do a calculation on a ng2-smart-table (angular) I need to calculate (Maximumtemperature+Minimumtemperature/2) when adding a new row in the table, the result should appear in the average temperature field with the possibility of manual alteration as well.
 temperaturaMaxima: {
    title: 'Temperatura Máxima',
    type: 'number',
  },
  temperaturaMinima: {
    title: 'Temperatura Mínima',
    type: 'number',
  },
  temperaturaMedia: {
    title: 'Temperatura Média',
    type: 'number',
    valuePrepareFunction: (value, row) => {
      tMaxima = row.temperaturaMaxima;
      tMinima = row.temperaturaMinima;
      return (value = tMaxima + tMinima / 2);
    },
  },

A: Type should be changed to a numeric type, not a string
return (value = tMaxima + tMinima / 2);

This should be changed to
return (value = (tMaxima + tMinima) / 2);

Because tMaxima + tMinima should run first

A: I'm trying the following solution:
import { Observable } from 'rxjs';
import { Component, OnInit } from '@angular/core';
import { Clima } from 'src/app/model/Clima';
import { ClimaService } from 'src/app/service/clima.service';
import { ActivatedRoute, Router } from '@angular/router';
import {
  SmartTableDatepickerComponent,
  SmartTableDatepickerRenderComponent,
} from 'src/app/smart-table-datepicker/smart-table-datepicker.component';
import { CustomComponent } from './custom.component';
import { LocalDataSource, ViewCell } from 'ng2-smart-table';

@Component({
  selector: 'app-clima',
  templateUrl: './clima.component.html',
  styleUrls: ['./clima.component.css'],
})
export class ClimaComponent implements OnInit {
  climas: Observable<Clima[]>;
  clima = new Clima();

  idFazenda: Number = +JSON.parse(localStorage.getItem('idFazenda'));

  settings = {
    add: {
      addButtonContent: '',
      createButtonContent: '',
      cancelButtonContent: '',
      confirmCreate: true,
    },
    edit: {
      editButtonContent: '',
      saveButtonContent: '',
      cancelButtonContent: '',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '',
      confirmDelete: true,
    },
    columns: {
      dataClima: {
        title: 'Data Clima',
        type: 'custom',
        renderComponent: SmartTableDatepickerRenderComponent,
        width: '250px',
        filter: false,
        sortDirection: 'desc',
        editor: {
          type: 'custom',
          component: SmartTableDatepickerComponent,
        },
      },
      temperaturaMaxima: {
        title: 'Temperatura Máxima',
        type: 'number',
      },
      temperaturaMinima: {
        title: 'Temperatura Mínima',
        type: 'number',
      },
      temperaturaMedia: {
        title: 'Temperatura Média',
        type: 'number',
        editor: {
          type: 'custom',
          component: CustomComponent,
          onComponentInitFunction: (instance: any) => {
            instance.save.subscribe(row => {
              //this.source.refresh();
            });
          },
        },
      },

      umidadeRelativa: {
        title: 'Umidade Relativa',
        type: 'number',
      },
      velocidadeVento: {
        title: 'Velecidade do Vento',
        type: 'number',
      },
      precipitacao: {
        title: 'Precipitação Total',
        type: 'number',
      },
      radiacaoMedia: {
        title: 'Radiação',
        type: 'number',
      },
    },
  };

  constructor(
    private climaService: ClimaService,
    private router: Router,
    private routeActive: ActivatedRoute
  ) {}

  ngOnInit(): void {
    let idFazenda: Number = +JSON.parse(localStorage.getItem('idFazenda'));
    this.climaService.getClimaListByFazenda(idFazenda).subscribe(data => {
      //this.source.load(data);
      this.climas = data;
      //this.total = data.totalElements;
    });
  }

  novo() {
    this.clima = new Clima();
  }

  excluirClima(event) {
    if (window.confirm('Tem certeza de que deseja excluir?')) {
      this.climaService.deletarClima(event.data.idClima).subscribe(data => {
        // console.log("Retorno do método delete : " + data);
        //this.culturas.splice(index, 1);/*Remover da tela*/
        // this.usuarioService.getStudentList().subscribe(data => {
        //   this.students = data;
        // });
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  salvarClima(event) {
    console.log('Edit Event In Console');
    console.log(event);
    if (
      this.clima.idClima != null &&
      this.clima.idClima.toString().trim() != null
    ) {
      /* Atualizando ou Editando*/

      console.log(this.clima);
      this.climaService.updateClima(this.clima).subscribe(data => {
        this.novo();
        this.router.navigate(['climaList']);
        console.info('Clima Atualizado: ' + data);
      });
    } else {
      event.newData.idFazenda = this.idFazenda;
      console.log('Create Event In Console');
      console.log(event);
      this.climaService.salvarClima(event.newData).subscribe(data => {
        /*Salvando um novo Clima */
        this.novo();
        console.info('Gravou Clima: ' + data);
      });
      event.confirm.resolve(event.newData);
    }
  }

  onEditConfirm(event) {
    console.log('Edit Event In Console');
    console.log(event);
    this.climaService.updateClima(event.newData).subscribe(data => {
      this.novo();
      console.info('Clima Atualizado: ' + data);
    });
    event.confirm.resolve(event.newData);
  }
}

My custom component:
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'custom-component',
  template: `
    <input
      [(ngModel)]="rowData.temperaturaMedia"
      (ngModelChange)="onModelChange()"
    />
  	`,
})
export class CustomComponent {
  rowData: any;

  @Output() save: EventEmitter<any> = new EventEmitter();

  onModelChange() {
    var tMaxima: number = this.rowData.temperaturaMaxima;
    var tMinima: number = this.rowData.temperaturaMinima;
    this.rowData.temperaturaMedia = (tMaxima + tMinima) / 2;
    this.save.emit(this.rowData);

    console.log(this.rowData.temperaturaMedia);
  }
}

The image below shows that the custom component is loading, but I am not able to calculate the fields.
enter image description here


text:
Q: Background Threads in Windows Phone So far during my experience in Windows Phone 7 application development I notices there are different ways to runs an action in an asynchronous thread.

*

*System.Threading.Thread

*System.ComponentModel.BackgroundWorker

*System.Threading.ThreadPool.QueueUserWorkItem()

I couldn't see any tangible difference between these methods (other than that the first two are more traceable).
Is there any thing you guys consider before using any of these methods? Which one would you prefer and why?

A: The question is kinda answered but the answers are a little short on detail (IMO).
Lets take each in turn.
System.Threading.Thread
All the threads (in the CLR anyway) are ultimately represented by this class.  However you probably included this to query when we might want to create an instance ourselves.
The answer is rarely.  Ordinarily the day-to-day workhorse for dispatching background tasks is the Threadpool.  However there are some circumstances where we would want to create our own thread.  Typically such a thread would live for most of the app runtime.  It would spend most of its life in blocked on some wait handle.  Occasionally we signal this handle and it comes alive to do something important but then it goes back to sleep.  We don't use a Threadpool work item for this because we do not countenance the idea that it may queue up behind a large set of outstanding tasks some of which may themselves (perhaps inadverently) be blocked on some other wait.
System.ComponentModel.BackgroundWorker
This is friendly class wrapper around the a ThreadPool work item.   This class only to the UI oriented developer who occasionally needs to use a background thread.  Its events being dispatched on the UI thread makes it easy to consume.
System.Threading.ThreadPool.QueueUserWorkItem
This the day-to-day workhorse when you have some work you want doing on a background thread.  This eliminates the expense of allocating and deallocating individual threads to perform some task.  It limits the number of thread instances to prevent too much of the available resources being gobbled up by too many operations try to run in parallel.
The QueueUserWorkItem is my prefered option for invoking background operations.

A: It arguably depends on what you are trying to do, you have listed 3 very different threading models.

*

*Basic threading

*Designed for applications with a seperate UI thread.

*Managed thread pool

Have you read MSDN etc...
http://www.albahari.com/threadin
Http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

A: You don't state "what for", but

*

*Basic Thread - quite expensive, not for small jobs

*Backgroundworker - mostly for UI + Progressbar work

*ThreadPool - for small independent jobs

I think the TPL is not supported in SL, which is a pity.

A: The background worker tends to be better to use when your UI needs to be update as your thread progresses because it handles invoking the call back functions (such as the OnProgress callback) on the UI thread rather than the background thread. The other two don't do this work. It is up to you to do it.


text:
Q: Django - Displaying model data based on primary key I have a model of multiple images and I want to display each of them in their own separate Owl carousel when an image is clicked by using the primary key as a reference. I have everything set up but for some reason my images are not being loaded into the carousel. I have no bad responses so If anyone can help me I'd be grateful.
EDIT here are my models.py:
from django.db import models

# model for displaying images on homepage
class Portrait(models.Model):
    name = models.CharField(max_length= 100)
    painting = models.ImageField(upload_to= 'paintings')
    long_description = models.TextField()
    price = models.IntegerField()
    short_description = models.TextField()
    painting_left = models.ImageField(upload_to= 'carousel_paintings')
    painting_right = models.ImageField(upload_to= 'carousel_paintings')
    painting_top = models.ImageField(upload_to= 'carousel_paintings')
    painting_bottom = models.ImageField(upload_to= 'carousel_paintings')
    painting_back = models.ImageField(upload_to= 'carousel_paintings')

    def __str__(self):
        return self.name

# model for carousel
class Carousel(models.Model):
    painting_front = models.ImageField(upload_to= 'carousel')
    painting_left = models.ImageField(upload_to= 'carousel')
    painting_right = models.ImageField(upload_to= 'carousel')
    painting_top = models.ImageField(upload_to= 'carousel')
    painting_bottom = models.ImageField(upload_to= 'carousel')
    painting_back = models.ImageField(upload_to= 'carousel')

    def __str__(self):

        return self.name

urls.py:
urlpatterns = [
    # homepage
    path('', views.index, name='index'),

    # get the primary key when an image is clicked
    path('<int:pk>', views.index, name='index_with_pk'),

    # use that primary key to fetch that image's data
    path('carousel/', views.carouselData, name="carousel_data")

]

ajax call in index.html when image is clicked:
$.ajax({
   type: "GET",
   url: '{% url "carousel_data"%}',
   data: { "prime_key": prime_key },
   success: function(data) {
      console.clear();
      console.log("Image object primary key: " + prime_key);
      $(".owl-carousel").owlCarousel({
           items:1,
           loop:true,
           nav:true,
           dots: false,
           autoplay: false,
           autoplayTimeout: 5000,
           smartSpeed: 500,
           autoplayHoverPause: false,
           margin: 20,
           touchDrag: true,
           mouseDrag: false,
           navText : ["",""]
      });
   },
   error: function(data){
      console.log('something went wrong');
   }
})

views.py:
def carouselData(request):

    if request.method == "GET":
        # get the primary key from ajax
        my_key = request.GET.get('prime_key')
        carouselObjects = Portrait.objects.filter(pk=my_key).values(
        'painting_left',
        'painting_right',
        'painting_top',
        'painting_bottom',
        'painting_back'
        )[0]

        carouselContext = {
        'carouselObjects': carouselObjects
        }

        # return the data
        return render(request, "carousel.html", carouselContext)

carousel.html is not fetching these image objects:
{% block carousel_content %}

{% endblock %}

A: My only guess would be to make sure you have these settings in your settings:
MEDIA_ROOT =  os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

And your urls should be:
from django.conf.urls.static import static

urlpatterns = [
    # homepage
    path('', views.index, name='index'),

    # get the primary key when an image is clicked
    path('<int:pk>', views.index, name='index_with_pk'),

    # use that primary key to fetch that image's data
    path('carousel/', views.carouselData, name="carousel_data")

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


text:
Q: How can I use the value inside my Text() widget in flutter? I'm working on a type of counter in flutter which increases with a button and decreases with another button, but the deal is that I don't know how to use the final value from the counter, and save/grab it with a floating action button.

This is my Text() widget
Container(
              margin: EdgeInsets.zero,
              padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: _counter != 0
                      ? widget.counterTextBackgroundColor
                      : Colors.grey[350]),
              child: Text(
                '$_counter',
                style: TextStyle(
                  fontSize: widget.counterTextSize,
                  color: widget.counterTextColor,
                ),
              ),
            ),

I tried with the TextField() widget but it looks bad, it looks too big and one of the problems with it is that if the counter is 0 my decrease IconButton doesn't show, so it extends more, and I did try with FormTextField too, the same thing.
Counter Extends with TextField()

A: I assume from your question that on pressing the button, you want to increase or decrease the value of your text, without using a textbox. All you have to do is increment the counter inside the SetState() method as follows-
floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
              //Enter the code you want to change here
              _counter=_counter+1;
            });
        },)

Now, outside of this code, you can use _counter variable anytime to get the value.

A: There are six Text widget, and for this you need to use six counter variables. We can use List<int> in this case.
Apply your decoration.
class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<int> _counters = List.filled(6, 0);

  List<String> titles = List.generate(6, (index) => "item $index");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        ...List.generate(
          titles.length,
          (index) => _item(
            index: index,
          ),
        )
      ],
    ));
  }

  Widget _item({
    Color background = Colors.red,
    required int index,
  }) =>
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
              color: background, borderRadius: BorderRadius.circular(12)
              //....
              ),
          child: Row(
            children: [
              Text(titles[index]),
              Spacer(), // provide space
              IconButton(
                onPressed: () {
                  setState(() {
                    _counters[index]--;
                    if (_counters[index] <= 0) _counters[index] = 0;
                  });
                },
                icon: Icon(Icons.minimize),
              ),

              SizedBox(width: 12),
              Text(_counters[index].toString()), SizedBox(width: 12),
              IconButton(
                onPressed: () {
                  setState(() {
                    _counters[index]++;
                  });
                },
                icon: Icon(Icons.add),
              ),
            ],
          ),
        ),
      );
}

A: It is possible to use TextEditingController in your case, or create custom controller.
Hope the full code bellow help you and others (without exception management):
import 'package:flutter/material.dart';

class FormControllerScreen extends StatefulWidget {
  const FormControllerScreen({Key? key}) : super(key: key);

  @override
  State<FormControllerScreen> createState() => _FormControllerScreenState();
}

class _FormControllerScreenState extends State<FormControllerScreen> {
  TextEditingController ctrlOne = TextEditingController();
  TextEditingController ctrlTwo = TextEditingController();
  TextEditingController ctrlThree = TextEditingController();

  @override
  void initState() {
    ctrlOne.text = '0';
    ctrlTwo.text = '0';
    ctrlThree.text = '50';
    super.initState();
  }

  getStyleButtonStyle() {
    return ElevatedButton.styleFrom(
      padding: EdgeInsets.zero,
      minimumSize: const Size(20, 20),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          buildFormElement("controller one", 0, 5, 1, ctrlOne),
          buildFormElement("controller two", -5, 5, 1, ctrlTwo),
          buildFormElement("controller three", 50, 100, 10, ctrlThree),
          TextButton(onPressed: onSave, child: const Text("SAVE")),
        ],
      ),
    );
  }

  void onSave() {
    print("controller one:   " + ctrlOne.text);
    print("controller two:   " + ctrlTwo.text);
    print("controller three: " + ctrlThree.text);
  }

  Widget buildFormElement(String label, int min, int max, int step, TextEditingController controller) {
    return Row(
      children: [
        Text(label),
        ElevatedButton(
          style: getStyleButtonStyle(),
          onPressed: () {
            onRemove(min, step, controller);
          },
          child: const Icon(Icons.remove),
        ),
        Text(controller.text),
        ElevatedButton(
          style: getStyleButtonStyle(),
          onPressed: () {
            onAdd(max, step, controller);
          },
          child: const Icon(Icons.remove),
        ),
      ],
    );
  }

  onRemove(int min, int step, TextEditingController controller) {
    int x = int.parse(controller.text);
    if (x > min) {
      setState(() {
        controller.text = (x - step).toString();
      });
    }
  }

  onAdd(int max, int step, TextEditingController controller) {
    int x = int.parse(controller.text);
    if (x < max) {
      setState(() {
        controller.text = (x + step).toString();
      });
    }
  }
}


text:
Q: Does ORMLite support dynamic Type of C#? I am looking into ORMLite from ServiceStack and what I am trying to do here is that call a stored procedure which in turn return many many rows which definitely would not be bound to any domain object but also may or may not have a dto object to map with. I was wondering if I can bind it to a  type. However, it sounds like ORMLite does not support dynamic type binding at  this time. Does ORMLite support  at this point?

A: By design OrmLite does not support marshalling to dynamic types, and expects resultsets to mapped to Typed POCO's.
Although it does have specialized API's to access Dynamic Result Sets using C# 7 Tuples:
var query = db.From<Employee>()
    .Join<Department>()
    .OrderBy(e => e.Id)
    .Select<Employee, Department>(
        (e, d) => new { e.Id, e.LastName, d.Name });

var results = db.Select<(int id, string lastName, string deptName)>(query);

var row = results[i];
$"row: ${row.id}, ${row.lastName}, ${row.deptName}".Print();

Or List<object>:
db.Select<List<object>>(db.From<Poco>()
  .Select("COUNT(*), MIN(Id), MAX(Id)"))[0].PrintDump();

/* Output */
[
    10,
    1,
    10
]

Or using Dictionary<string,object>, e.g:
db.Select<Dictionary<string,object>>(db.From<Poco>()
  .Select("COUNT(*) Total, MIN(Id) MinId, MAX(Id) MaxId"))[0].PrintDump();

/* Output */
{
    Total: 10,
    MinId: 1,
    MaxId: 10
}

As well as being able to map into loose-typed .NET collections:
Dictionary<int, string> trackIdNamesMap = db.Dictionary<int, string>(
    "select Id, Name from Track")

Dictionary<int, List<string>> albumTrackNames = db.Lookup<int, string>(
    "select AlbumId, Name from Track")

List<string> trackNames = db.Column<string>("select Name from Track")

HashSet<string> uniqueTrackNames = db.ColumnDistinct<string>("select Name from Track")

Using Dapper's Query
OrmLite does have an embedded version of Dapper which does support dynamic results:
using ServiceStack.OrmLite.Dapper;

using (var db = new SqlConnection(@"Data Source=... etc."))
{
    db.Open();

    var p = new DynamicParameters();
    p.Add("@params", "Id=21");

    IEnumerable<dynamic> dynamicResults = db.Query(sql:"GetPivotData", param: p,
        commandType:CommandType.StoredProcedure);
}


text:
Q: ¿Cómo deshabilitar una lista de checkbox e inputs extraidos de una BD con JavaScript? En mi BD tengo dos tablas llamadas 'producto' y 'material', estoy haciendo un CRUD para los productos y en la vista 'create' extraigo la lista de materiales registrados en la BD con la finalidad de seleccionar la cantidad de materiales que se usaron en la elaboración de un producto.
A continuación se muestra una tabla la cual contiene una lista de checkbox con los materiales, y un input de tipo number el cual registrará la cantidad de material utilizado:

    @foreach($material as $mat)

<input type="checkbox" id="boxMat" name="mat[]" value="{{$mat['id']}}">{{$mat['nombre']}}

        <input class="input-group-text" id="unidadM" type="number" name="unidadM[]" min="0" >

       {{$mat['unidad']}}

    @endforeach

y el siguiente código en JavaScript
for (var i = 0; i < document.getElementsByName("unidadM[]").length; i++) {

  document.getElementByName('mat[]')[i].onchange = function() {
    document.getElementByName('unidadM[]')[i].disabled = !this.checked;
  }

}

Lo que quiero es que al momento de cargar la vista 'create' los input que se encuentran al lado de lista de checkbox estén deshabilitados, y se habiliten sólo si se selecciona el checkbox correspondiente.

A: Te recomiendo que cuando crees los inputs dentro de un bucle le asignes un incremental a el id por ejemplo id="boxMat1", id="boxMat2", etc., Ya que el id debe de ser único, mencionado esto te explico el código, obtenemos las etiquetas de los checkbox (eso ya lo tienes claro), así mismo las recorremos con un for, después por medio del id le agregamos un .addEventListener de tipo change, obtenemos el id del checbox seleccionado y le hacemos un split() para obtener sólo el número (aunque puedes agregar atributos data-* para no ocuparlo), guardamos en una variable idNum  la posición [1] que sería el número que requerimos, después validamos si el check esta checked habilitamos el input tipo number -> document.getElementById(num${idNum}).disabled = false;  y si no esta checado lo des-habilitamos. Espero sea lo que requieres, cualquier duda hazla saber.

var check = document.getElementsByName('mat[]');

for(var i = 0; i < check.length; i++){
    let checks = check[i].id;

   document.getElementById(checks).addEventListener('change',function(){

    let idCheck = this.id.split('check');

      let idNum = idCheck[1];

      console.log(idNum);

      if(this.checked){
        document.getElementById(`num${idNum}`).disabled = false;

      }else{

        document.getElementById(`num${idNum}`).disabled = true;

      }

    })
}

<input type="checkbox" id="check1" name="mat[]" value="1">
<input type="checkbox" id="check2" name="mat[]" value="2">

<input type="number" id="num1" name="unidadM[]" disabled>
<input type="number" id="num2" name="unidadM[]" disabled>


text:
Q: How to calculate Chern number of a band numerically? I have a tight-binding Hamiltonian with an aperiodic potential which shows non-trivial topological properties. I wanted to calculate the Chern number of it's bands. How can I do it numerically?

A: I hope this is not too late to do some good.  You have many options to compute a Chern number numerically.  There are several real-space formulas and a formula based on scattering theory.  Let me discuss some of the real-space formulas.
The first is called, in physics anyway, the Bott index.  This will work if the following hold:  you are on a regular lattice; the Hamiltonian involves hopping terms only to nearest and next-nearest neighbors; the ratio of the norm of the Hamiltoninan to the gap size is about 10 or smaller.
To compute the Bott index, take a lattice model of about 15-by-15 and impose periodic boundary conditions.  Now take the (diagonal) position observables, scale them so the width and length is $2\pi$, and form exponentials $U_0=\mathrm{exp}(iX)$  and $V_0=\mathrm{exp}(iY)$.  Do a full eigensolve of the Hamiltoninan and find the projector $P$ corresponding to all energy below a certain gap.  Now form invertible matrices $U= PU_0P + (I-P)$ and $V= PU_0P + (I-P)$.
Compute all eigenvalues of $VU{V^\dagger}{U^\dagger}$, take the log of all of these, now sum them up.  The real part of this complex number will be the Chern number (or minus the Chern number).
Be sure to repeat this with a larger system size, to get some evidence you are avoiding the effects of small system size.  As to why, and when, the Bott index equals the Chern number, you can look here:  "On the equivalence of the Bott index and the Chern number on a torus, and the quantization of the Hall conductivity with a real space Kubo formula" by
Toniolo, Arxiv:1708.05912.
A recent decription of the Bott invariant is here:  "Topological Photonic Quasicrystals: Fractal Topological Spectrum and Protected Transport" by Bandres, Rechtsman, and Segev, Phys. Rev. X, 6(2), 011016, 2016.  Sample code implementing this in Matlab is here:   http://digitalrepository.unm.edu/math-statsdata/5/
This invariant will fail you if you have a small gap between bands.  If the gap is about 1/100 of the norm of the Hamiltonian, you will need system size like 100-by-100, and so the dense matrix methods above are too slow and memory intensive.  If you are going beyod the classical band insulator, say working on a quasicyrstal, then periodic boundary conditions will be difficult to define so as to preserve the gaps.  The mathematical version Bott index is twenty years old and not suited to large matrix calculations.
A more modern approach is to use a local index.  For example, there is an index due to Kitaev that was computed as a local index here:  "Amorphous topological insulators constructed from random point sets" by Mitchell, Nash, Hexner, Turner & Irvine, Nature Physics (2018)
doi:10.1038/s41567-017-0024-5.
My take on a local index, which works with sparse matrix calculations and so on rather large systems, is detailed here:  "K-theory and pseudospectra for topological insulators", Annals of Physics Volume 356, 383-416, 2015.  Sample code is also here:  http://digitalrepository.unm.edu/math-statsdata/5/
There are issues in how to rescale the position observables with combining these into a single matrix.  These are just now getting resolved in joint work with Scultz-Baldes available on the Arxiv.
I suggest you try the Bott index unless you have an exotic situation.  Best of luck.


text:
Q: Doubts in running an Rcpp example I'm trying to reproduce the examples of "Seamless R and C++ Integration with Rcpp" book, but some codes are not running. Specifically, it is on chapter 5, Section 5.2.3 and the code follows above:
#ifndef _mypackage_RCPP_HELLO_WORLD_H
#define _mypackage_RCPP_HELLO_WORLD_H

    #include <Rcpp.h>
    /*
       * note : RcppExport is an alias to 'extern "C"' defined by Rcpp.
       *
       * It gives C calling convention to the rcpp_hello_world
       * function so that it can be called from .Call in R.
       * Otherwise, the C++ compiler mangles the
       * name of the functioand .Call can't find it.
       * It is only useful to use RcppExport when the function
       * is intended to be called by .Call. See the thread
       * http://thread.gmane.org/gmane.comp.lang.r.rcpp/649/focus=672
       * on Rcpp-devel for a misuse of RcppExport 19
    */

    RcppExport SEXP rcpp_hello_world();

    #endif

and the next is
#include "rcpp_hello_world.h"

SEXP rcpp_hello_world() {
    using namespace Rcpp;

    CharacterVector x = CharacterVector::create( "foo", "bar" )  ;
    NumericVector y   = NumericVector::create( 0.0, 1.0 ) ;
    List z            = List::create( x, y ) ;

    return z ;
}

The error showed by R is
Error in .Call("rcpp_hello_world", PACKAGE = "mypackage") :
  "rcpp_hello_world" not available for .Call() for package "mypackage"

Have anyone faced a problem like this?
Thanks in advance!

When I try to tip
R CMD check mypackage_1.0.tar.gz

I got an error like this
* using log directory '/Users/Marcos/Downloads/mypackage.Rcheck'
* using R version 3.0.2 (2013-09-25)
* using platform: x86_64-apple-darwin10.8.0 (64-bit)
* using session charset: UTF-8
* checking for file 'mypackage/DESCRIPTION' ... OK
* checking extension type ... Package
* this is package 'mypackage' version '1.0'
* checking package namespace information ... OK
* checking package dependencies ... OK
* checking if this is a source package ... OK
* checking if there is a namespace ... OK
* checking for executable files ... OK
* checking for hidden files and directories ... OK
* checking for portable file names ... OK
* checking for sufficient/correct file permissions ... OK
* checking whether package 'mypackage' can be installed ... ERROR
    Installation failed.
See '/Users/Marcos/Downloads/mypackage.Rcheck/00install.out' for details.

In the file 00install.out, the first error is
* installing *source* package 'mypackage' ...
** libs
llvm-g++-4.2 -arch x86_64 -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I"/Library/Frameworks/R.framework/Versions/3.0/Resources/library/Rcpp/include"   -fPIC  -mtune=core2 -g -O2  -c RcppExports.cpp -o RcppExports.o
In file included from /Library/Frameworks/R.framework/Versions/3.0/Resources/library/Rcpp/include/RcppCommon.h:28,
                 from /Library/Frameworks/R.framework/Versions/3.0/Resources/library/Rcpp/include/Rcpp.h:27,
                 from RcppExports.cpp:4:
/Library/Frameworks/R.framework/Versions/3.0/Resources/library/Rcpp/include/Rcpp/platform/compiler.h:93:17: error: cmath: No such file or directory

And then, I just got error messages.

A: This example (and chapter) discusses how to build (and load) an entire package, here called mypackage.
Did you actually create, compile and load mypackage?
This works, as we do this each and every time the unit tests run.
Edit:  Here is a full log for you
R> library(Rcpp)
R> Rcpp.package.skeleton("mypackage")   ## page 66, Section 5.2.1
Creating directories ...
Creating DESCRIPTION ...
Creating NAMESPACE ...
Creating Read-and-delete-me ...
Saving functions and data ...
Making help files ...
Done.
Further steps are described in './mypackage/Read-and-delete-me'.

Adding Rcpp settings
 >> added Depends: Rcpp
 >> added LinkingTo: Rcpp
 >> added useDynLib directive to NAMESPACE
 >> added Makevars file with Rcpp settings
 >> added Makevars.win file with Rcpp settings
 >> added example src file using Rcpp attributes
 >> compiled Rcpp attributes
 >> added Rd file for rcpp_hello_world
R>

We can now build the tarball:
R> system("R CMD build mypackage")
* checking for file 'mypackage/DESCRIPTION' ... OK
* preparing 'mypackage':
* checking DESCRIPTION meta-information ... OK
* cleaning src
* checking for LF line-endings in source and make files
* checking for empty or unneeded directories
* building 'mypackage_1.0.tar.gz'

R>

then we can install it:  (and I am doing that on a Windows machine for a change)
R> system("R CMD INSTALL mypackage_1.0.tar.gz")
* installing to library 'c:/opt/R-library'
* installing *source* package 'mypackage' ...
** libs

*** arch - i386
g++ -m32 -I"c:/opt/R-CURR~1/include" -DNDEBUG    -I"c:/opt/R-library/Rcpp/include" -I"d:/RCompile/CRANpkg/extralibs64/local/include"     -O2 -Wall  -mtune=core2 -c RcppExports.cpp -o RcppExports.o
g++ -m32 -I"c:/opt/R-CURR~1/include" -DNDEBUG    -I"c:/opt/R-library/Rcpp/include" -I"d:/RCompile/CRANpkg/extralibs64/local/include"     -O2 -Wall  -mtune=core2 -c rcpp_hello_world.cpp -o rcpp_hello_world.o
g++ -m32 -shared -s -static-libgcc -o mypackage.dll tmp.def RcppExports.o rcpp_hello_world.o c:/opt/R-library/Rcpp/lib/i386/libRcpp.a -Ld:/RCompile/CRANpkg/extralibs64/local/lib/i386 -Ld:/RCompile/CRANpkg/extralibs64/local/lib -Lc:/opt/R-CURR~1/bin/i386 -lR
installing to c:/opt/R-library/mypackage/libs/i386

*** arch - x64
g++ -m64 -I"c:/opt/R-CURR~1/include" -DNDEBUG    -I"c:/opt/R-library/Rcpp/include" -I"d:/RCompile/CRANpkg/extralibs64/local/include"     -O2 -Wall  -mtune=core2 -c RcppExports.cpp -o RcppExports.o
g++ -m64 -I"c:/opt/R-CURR~1/include" -DNDEBUG    -I"c:/opt/R-library/Rcpp/include" -I"d:/RCompile/CRANpkg/extralibs64/local/include"     -O2 -Wall  -mtune=core2 -c rcpp_hello_world.cpp -o rcpp_hello_world.o
g++ -m64 -shared -s -static-libgcc -o mypackage.dll tmp.def RcppExports.o rcpp_hello_world.o c:/opt/R-library/Rcpp/lib/x64/libRcpp.a -Ld:/RCompile/CRANpkg/extralibs64/local/lib/x64 -Ld:/RCompile/CRANpkg/extralibs64/local/lib -Lc:/opt/R-CURR~1/bin/x64 -lR
installing to c:/opt/R-library/mypackage/libs/x64
** R
** preparing package for lazy loading
** help
Warning: C:/Users/deddelbuettel/AppData/Local/Temp/RtmpaiaZVk/R.INSTALL65481db46d2b/mypackage/man/mypackage-package.Rd:30: All text must be in a section
*** installing help indices
** building package indices
** testing if installed package can be loaded
*** arch - i386
*** arch - x64
* DONE (mypackage)
R>

after which we can load and run it:
R> library(mypackage)
R> rcpp_hello_world()
[[1]]
[1] "foo" "bar"

[[2]]
[1] 0 1

R>

and finally remove it as it has no real use case besides demonstrating these mechanics:
R> remove.packages("mypackage")
Removing package from 'c:/opt/R-library'
(as 'lib' is unspecified)
R>

A: Go to the terminal:
R CMD build mypackage
R CMD check mypackage_1.0.tar.gz
R CMD install mypackage

and in R:
library(mypackage)
rcpp_hello_world()
[[1]]
[1] "foo" "bar"

[[2]]
[1] 0 1

Now, I don't understand where to use the code written in "Listing 5.4", Do I need to write it or this is created automatically?


text:
Q: Conversion of String to Date - Unparseable date: "03/26/2012" I'm experimenting on a Java Program that makes use of Jasper Reports. What started out as a (supposedly) simple "arrange the dates in descending order" task for the Report became more complex when I found out that the 'dates' were in String format, and thus, were being sorted, albeit in a wrong manner. Example:

*

*03/26/12

*03/26/12

*08/11/12

*08/26/12

*10/26/11

I can only guess that the 10/26/11 is placed on the bottom simply because of the 10 in front.
I've looked into the Jasper Report using iReport 3.0.0, and I've found the following:

*

*The date in question (named: DTEEFFEC), under Fields, is set to String.

*The textField is also set to String.

This doesn't produce any errors, it only makes it difficult, if not impossible, to arrange the 'dates' in descending order.
So I've done the following:

*

*Left DTEEFFEC as is (String).

*Changed the textField from Java.Lang.String to Java.Util.Date

*Added the following to the New Field Expression:
new SimpleDateFormat("MM-dd-yyyy").parse($F{DTEEFFEC}.toString())
I found out that bit of code after some research on my problem. A lot of the responses were along the lines of "it worked", but not so for me.
Caused by: java.text.ParseException: Unparseable date: "03/26/2012"

That is what the Java program returns. I've tried tinkering with both the field and the textField (alternating between either String or Date values), but it gives me other errors entirely.
Can I have some help on this?
Thanks.
Other information: I'm using iReports 3.0.0 to modify the JRXML file, and Eclipse for the Java Program. If the Referenced Libraries under Eclipse is to be believed, I'm using JasperReports 3.5.2. The entire thing runs on Windows 7.

A: Look at your code:
new SimpleDateFormat("MM-dd-yyyy").parse(...)

That's clearly expecting something of the form "MM-dd-yyyy" such as "03-26-2012".
Now look at your actual data: "03/26/2012". (Apparently, even though your earlier samples were two-digit years...)
That's got slashes, not dashes. So you need to change your pattern appropriately:
new SimpleDateFormat("MM/dd/yyyy").parse(...)

A: Change the new SimpleDateFormat("MM-dd-yyyy") into new SimpleDateFormat("mm/dd/yyyy")
so the parser can correctly parse your date input


text:
Q: Retrieving and inserting multiple entries in MySQL/PHP I'm trying to create a form that retrieves data from a database and then allows me to add data to one column for multiple entries.
Every entry has an ID, a lot of other fields, and a category. I am trying to add these categories for every ID in the database using one form.
I came up with the solution below, but (of course)this only inserts the LAST entry in the form, because the variable ID is changed with every new row.
The form I have now shows me what I want to see, but it does not save it the way I need it to.
The question is, (how) can I make a form that has all entries in the database with a dropdown menu next to it,
lets me select the right category from the dropdown, and save it to the database?
The form:
  $result = mysqli_query($con,"SELECT * FROM aw");

while($row = mysqli_fetch_array($result))
{
echo '
<input type="hidden" name="ID" value="'.$row[ID].'."> '.$row[ID].'	';
echo '

<select name="cat" onchange="this.form.submit()">
<option value="C1">category1</option>
<option value="C2"">category2</option>
</select>

';
}

?>

<input type="submit" title="SAVE" >

</form>

The insert.php
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$_POST[ID]','$_POST[cat]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }

mysqli_close($con);
?>

I changed my code according to Tom's answer and I now have the following:
This does print the values like they should be, but it still saves only the last entry into the database. I'm sure I must be missing something here..
$name = $_POST['ID'];
$category = $_POST['cat'];

foreach( $name as $key => $n ) {
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$n','$category[$key]')";

  print "The id is ".$n.", category is ".$category[$key]."
";

}

A: The problem is your using the name elements regardless of how many rows..
So name="ID" & name="cat" needs to change on each row or have an array type
you could use something like name="ID[]" as this would append/ create an array to $_POST['ID']... but you still would want to change your SQL query to handle each of these.
EDIT
If i understand, you want to be able to identify a row from the table so you can use that in the database?? One way todo this is when creating the table.. Give the TR a id/name attribute that is the row id from the database.
Then can simply know by checking that if your using the select menu from row #4, you check the id/name attribute of the current row and you have your database id.

  John
  1111
  ....

  Bill
  2222
  ....

  Roger
  3333
  ....

With something like the above, Say i had a button in on of the columns... When i click on that button.. all i have todo is find the parent TR and get its id value.... Then explode it by "_" and get the last piece to have the id..
So your PHP would generate the id easily... Also, using a form would not be the best case here.. Using multiple forms within a table is... wasteful... sort of ..
I would suggest more so, having a button that simple calls a js function which will then post/ajax/jquery what you need from that row.
--- Trying to understand exactly what you need??

A: First of all, use PDO::Mysql, the SQL functions you are using are a bit deprecated and do not focus much on security. At the moment your code is vulnerable to SQL injections and your output is sensitive to XSS attacks (always sanitize output).
I was wrong, MySQL is deprecated but MySQLi is not! I do prefer using PDO::Mysql because of the range of databases it supports (MySQLi only supports a MySQL database, PDO::Mysql supports many more)
Now to your original question, you can create a sort of array. By making name="ID" to name="ID[]" and name="cat" to name="cat[]".
Now you can do
$name = $_POST['ID'];
$category = $_POST['cat'];

foreach( $name as $key => $n ) {
  print "The id is ".$n.", category is ".$category[$key];
}


text:
Q: Can't Connect to (or start?) Google Cloud Compute Instance I attempted to restart my Windows instance (using the Start menu), but haven't been able to connect to it. After a few hours of waiting, I also tried using the Reboot button in the Google Developers Console. That didn't work either. I can't RDP into it, or even ping it. However, when I look at the instance in the GDC, it's been steady at 27% CPU usage for the duration. Anyone know what's going on or how to fix it?

A: You can run this gcutil command to reset the instance: gcutil --project=[project-id] resetinstance [instance-name]
If this has no effect, a suggestion would be to delete the instance without deleting the boot disk and then create a new instance with that disk. This will ensure that you get a fresh instance without losing any of your previous data.


text:
Q: How to select the five greatest number mysql How to select the first five high number from my table
for example: bid_table > 10 customers enter bid, and the query need to give only the five high bid from this 10 customers
thanks
Yaniv

A: SELECT bid FROM bid_table
ORDER BY bid DESC
LIMIT 5;

The limit clause gives you just five results. The order by and desc parts give the results from highest to lowest.

A: SELECT * FROM bid_table ORDER BY bid DESC LIMIT 5;


text:
Q: Wy can't I cast a statically cast Lambda as a TIMEPROC Function pointer in a settimer? I coded this multiple times.
But it doesn't even seem to work in a simple console hello word application.
Is hWND the one to blame, lambda, or the casting of the lambda?
void sleeper()
{
    Sleep(10000);
}
int main()
{
    SetTimer
    (GetConsoleWindow(), 1, 1000, [](HWND, UINT, UINT_PTR, DWORD)
        {
        printf("Hello World!");
        }
    );
    sleeper();
    return 0;
}

It doesn't give me warnings.

A: You cannot cast a lamba to a TIMEPROC* or any other type of function pointers that use a different calling convention than the default (one can not specify the calling convention of a lambda).  Lambdas are callable objects.  This type is similar to a class, with a member function.
Aside from that, you MUST use the correct declaration for yout TIMERPROC hook.  It is:
// definition from the MS website.  It is incomplete (typical from MS)
// ref: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-timerproc
void Timerproc(
  HWND unnamedParam1,
  UINT unnamedParam2,
  UINT_PTR unnamedParam3,
  DWORD unnamedParam4
)

// the actual definition from winuser.h.
typedef VOID (CALLBACK* TIMERPROC)(HWND, UINT, UINT_PTR, DWORD):

// note the use of CALLBACK, which expands to __stdcall.  That's the very important
// detail missing from the actual documentation.

You can declare your timeproc as a free-standing function, or as a static member function of a class, Unfortunately the onluy parameter you can pass to the callback is a HWND, this means that if you want to pass any extra parameter to your callback, you have to use static (aka global) variables.
Example 1.
void CALLBACK myTimerProc(HWND, UINT, UINT_PTR, DWORD)
{
   printf("Hello World!");
}

int main()
{
    // NOTE nIDEvent, the timer ID has to be unique for the window and NON-ZERO,
    // See MS documentation here: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-settimer
    SetTimer(GetConsoleWindow(), 1, 1000, myTimerProc);
    sleeper();
    return 0;
}

Example2, if you want to define locally:
int main()
{
    struct local // or any other
    {
        static void CALLBACK timerProc(HWND, UINT, UINT_PTR, DWORD)
        {
            printf("Hello World!");
        }
    }

    SetTimer(GetConsoleWindow(), 1, 1000, local::timerProc);
    sleeper();
    return 0;
}

EDIT:  For reference, the actual parameters for the TIMERPROC callback.
Source: http://www.icodeguru.com/VC%26MFC/MFCReference/html/_mfc_cwnd.3a3a.settimer.htm
void CALLBACK EXPORT TimerProc(
   HWND hWnd,      // handle of CWnd that called SetTimer
   UINT nMsg,      // WM_TIMER
   UINT nIDEvent   // timer identification
   DWORD dwTime    // system time
);


text:
Q: Как вывести значение data-атрибута в поле input формы в модальном окне magnific-popup? На html-странице несколько карточек товара с кнопками "Заказать":

Название товара

Заказать

...

и одна форма отправки заказа, которая открывается в модальном окне magnific-popup:

    <form id="feedback">

<input type="hidden" id="product" name="Product" value="">

<input type="text" id="name" name="Имя" placeholder="Имя *" required>

<input type="tel" id="phone" name="Телефон" placeholder="Телефон *" required>

<button id="send" class="button">Отправить</button>

    </form>

За работу модального окна отвечает код:
$(function () {
    $('.popup-modal').magnificPopup();
});

Какой код и где именно дописать, чтобы в value скрытого input формы выводилось название товара?
<input type="hidden" id="product" name="Product" value="Название товара">

Это html, переменных нет.
Заранее благодарен

A: $(function () {
    $('.product').magnificPopup({});
    $('.product').bind('click', function() {
        var dataproduct = $(this).data('product');
        $('input#product').val(dataproduct);
    });
});


text:
Q: .NET Standard F# library does not store non-English characters properly I create a .NET Standard F# library with F# 4.3.4 (I also tested with 4.5) with the following code:
namespace ClassLibrary2

module Say =
    let a = "国".Length.ToString()
    let b = sprintf "%A" ("国".ToCharArray() |> Array.map int)
    let c = "国"

When referencing that library from another project (.net core or .net framework):
Console.WriteLine(Say.a); // F# .net standard
Console.WriteLine(Say.b);
Console.WriteLine(Say.c == "国");

I get the following output:
2
[|65533; 65533|]
False

The equivalent C# .NET Standard library:
using System;
using System.Linq;

namespace ClassLibrary1
{
    public static class Class1
    {
        public static string a = "国".Length.ToString();
        public static string b = String.Join(", ", "国".ToCharArray().Select(i => ((int)i).ToString()));
        public static string c = "国";
    }
}

gives the expected output:
1
22269
True

Here's a repo showing the issue: https://github.com/liboz/Kanji-Bug.
This looks likely to be a bug, but I was wondering what would be a reasonable workaround for this problem?  Specifically, I want to be able to be able to check equality for strings with something like Say.c = "国" where I might be using non-English characters while using a .NET Standard library.

A: So, the issue appears to be that the first file that the dotnet cli generates in an F# library does not use Unicode for its encoding. So, when creating a .NET Standard F# library that file for me was generated with Shift-JIS encoding, likely due to region settings on my own computer. Therefore, the solution to my issue was to simply save the default Library1.fs file with UTF-8 encoding manually so that it would have the same encoding as all the other files.


text:
Q: AngularJS / Forcing resolve property to run at anytime As most of angular developers know, Resolve property allows to protect access to certain pages.
Here a brief example of snippet code:
.config(['$routeProvider', 'securityAuthorizationProvider',
                function ($routeProvider, securityAuthorizationProvider) {
                      $routeProvider.when('/test', {
                          templateUrl: '/myCorrespondingView.tpl.html',
                          controller: 'MyCorrespondingCtrl',
                          resolve: securityAuthorizationProvider.requireAuthenticatedUser
                      });
                }])

Let's suppose a page containing a link called "Click here to access to protected page" (making a $location.path("/test") under the hood).
Expectations are: when I click on it, make resolve as being rejected and...do not redirect to any other pages than the caller's page.
This causes to...nothing (the simple fact that user can't reach page is enough) but the URL changed to the targeted protected page.
=> myApp.com/test
(why Angular doesn't make this replacement only in case of a successful promise result ?? :(, but this is another question that I've just asked: AngularJS / Changing the URL only when corresponding template's resolve property is solved ).
Then...click again...
It seems that the resolve remains not processed again at all.
Then...click on other link on the application (without full redirect of course), whichever you want in order to change the URL, and reclick on the protected link => Resolve would be well processed again.
Is there an Angular mechanism that checks for the current page URL and the wanted page URL, and avoids to reprocess resolve task if both are the same?
I really want to force the resolve process even if the URL already corresponds to the targeted page one.
**UPDATED ********
From this post: https://stackoverflow.com/a/12429133/985949

Angular watches for a location change (whether it's accomplished
  through typing in the location bar, clicking a link or setting the
  location through $location.path()). When it senses this change, it
  $broadcasts an event, "$locationChangeSuccess," and begins the routing
  process.

It sounds that the check I supposed above is indeed done by $location.path method...
Would be great if one can force the evaluation.

A: Angular routes respond to changes in the URL, not to clicks. If the location does not change in the browser angular will not pick it up at all.
It seems what you should do is create a service that listens to "$locationChangeSuccess" and keeps track of the last successful route. Then have another listener on $routeChangeError that resets the location to the last succesful route on a failure. This would prevent you from staying in an inconsistent state where the location does not match your current active route.
Once you do that, clicking on the link again would cause the browser to attempt to change the location again, thus triggering your resolves again.

A: I found this post confirming the solution of @dtabuenc just above.
Here's mine:
angular.module('services.locationChanger', [])
    .service('locationChanger', ['$location', '$route', '$rootScope', function ($location, $route, $rootScope) {

        this.skipReload = function () {
            var lastRoute = $route.current;
            $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
            });
            return this;
        };

        this.withoutRefresh = function (url, doesReplace) {
            if(doesReplace){
                $location.path(url).replace();
            }
            else {
                $location.path(url || '/');
            }
        };
    }]);

and any caller within the resolve process part would be:
locationChanger.skipReload().withoutRefresh("/", true);

Works like a charm.


text:
Q: Issue with DB2 DELETE COMMAND I have a SQL table with column A & B
and I have a requirement to delete data from a corresponding DB2 table whose column values are not same as the above mentioned sql table.. I have implemented something like below to achieve this functionality.
RSSQL.Open "select * from sql_table"

ConnDB2 "DELETE from db2_table where not exists(select 1 from
  db2_table d where d.A='" & rssql.fields(0) & "' and d.B = '"&
  rssql.fields(1) &"')

but this delete command is not able to delete any values in the db2 table. Please help.
SQL TABLE:
COLUMN A   COLUMN B
12          23
34          56

DB2 TABLE:
COLUMN A  COLUMN B
1             2
12           23
3             4
34           56

So, My delete command should delete first and third row. Post delete, the db2 table should look like below:
DB2 TABLE:
COLUMN A    COLUMN B
12            23
34            56

A: I think this is the delete that you want:
delete from db2_table dt
    where not exists (select 1
                      from sql_table st
                      where st.columna = dt.columna and st.columnb = dt.columnb
                     );

I'm not sure why you are executing two queries.


text:
Q: Jquery menu not hiding on mouse leave I have the following menu (which is just an icon that needs to display a drop down menu. I can get the menu to show and hide with toggle, but when I do that, as soon as I try to move to the displayed links it closes, if I trigger it on hover with with add class, I cant get the menu to go away. Does anyone have a way to smoothly show and hide this menu on mouse over and click?

        (

 @Ajax.ActionLink("Icon Legend", "font_legend", null, new AjaxOptions {           UpdateTargetId = "placeholder_extra1", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }, new { @class = "" })

Sign Out

Support

A: Use it:

A: Try somesing like this:

           $(document).ready(function () {
$("span#show_global_menu").hover(function () {
     $("ul#dropdown").slideDown("slow");
},function(){
      $("ul#dropdown").slideUp("slow");
});

      });
 </script>


text:
Q: coded ui params method doesn't work I am attempting to automate entering in values on a html page using Microsoft's coded UI.  When I use the normal method (i.e. the hardcoded values gotten through the action recording) everything works fine but if I use the params method and pass it an explicit value it doesn't work at all; worse yet, the test does not fail at this point, it just seems to skip over that step.
I'm hoping someone can give me an idea of what I'm missing (if anything) when I set up the data driven aspect of the test or if there's something else I can try out.  Thanks
erik
Here is the Data Connection string from the test itself
        [DeploymentItem("PFChecks\Data\Company.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\Company.xml", "Iteration", DataAccessMethod.Sequential), TestMethod]
and the line of code trying to use the params method to set the value on the field.
            usEnterSSN.methodUserSyncEnterSSNParams.UISsnoEditText = "012831444";
There is only one object in this method to be used, the UISsnoEditText object.  The object name is correct in the UI Map and matches what it is named on the web page itself.  The params method fails to work if I explicity set the value (as above) or if I use TestContext.DataRow method.
Any ideas would be welcome and let me know if I can provide any further information to help answer this question.
Thanks
erik

A: There are 2 things I can think of.

*

*Are you moving the code to the UIMap.cs file before editing and then working from there?
if not you should do that.

*Try removing Certain Search Properties and Filter Properties from the UIMap.uitest file.
If this didn't help I'll need more info, perhaps even a Screen Cap.

A: Three things occur.
(1) Is the assignment above in the correct place?  The uimap...xxxParams.yyyEdit = ...; should be before the call of the method that uses it.
(2) You can use the Visual Studio debugger to set breakpoints and to step through a Coded UI test. (You need to right-click in the codeduitest.cs file and select Debug tests.
(3) From the comment clarifying the question. You need to have both the assignment and the call. So the general form is uimap...xxxParams.yyyEdit = ...; uimap...xxx();. The method call reads values from the ...Params, the default value there is the value entered when recording the test. The assignment overwrites the default value of the ...Params item.
There are some good discussion of data driven testing linked from http://blogs.msdn.com/b/mathew_aniyan/archive/2010/02/11/content-index-for-coded-ui-test.aspx , as well as many other items about Coded UI tests.


text:
Q: i need to let a user to add a role from a frontend form i need to let a registered user who already has role or 2 roles the ability to add himself a role via frontend form.
i tried to look for it and didn't find anything related that can help me.
any ideas?
thanks.

A: I think each user can only have one role.
However this is how its possible to change role, if for some reason that I dont know the user can have more than one role, remove the remove role line. you can check the available roles here.
$current_user = wp_get_current_user();
// Remove role
$current_user->remove_role( 'subscriber' );
// Add role
$current_user->add_role( 'editor' );


text:
Q: Create a php file within the module In magento I have started to set up an admin module and am not using layout XML but rather just the indexController to load my phtml.
 public function indexAction()
 {
   $this->loadLayout();
   $this->_addContent($this->getLayout()->createBlock('adminhtml/template')->setTemplate('module/page1.phtml'));
   // ...

From that phtml file I need to query another php file but I don't understand how I can add another file and what the path would be to page2.phtml ? So I just need a home for this other php file. It can really be anywhere on the server.
For example from my index I am loading a script that runs Ajax on another php file.  How can I add that somewhere inside the module and what would the url be to it.  This whole controller business has me pretty confused.  I am tired and hoping to wake up to a bounty of stack overflow wisdom. My apologies if this question is not very clear.  I will edit tomorrow after some coffee if need be.

A: In Magento, URLs are not paths to phtml files (which are just templates), they are paths to controllers and actions. A URL is comprised of the "frontname" (a reference to the module), then the controller, then the action. The partial code you've shown is the index action (the default action) for your controller. The target of your Ajax call will be another action probably in the same controller. That action can then use the technique you've used above to load the appropriate template phtml file (page2.phtml).


text:
Q: large sparse matrix, svd I want to calculate SVD , but I didn't find good java library for this. Now, I have data store in hashmap, because matrix didn't fit into memory due to the fact that sizes are about 400 000 X 10 000 and most of them are 0. I tried MTJ, JBLAS, Jama and others but most of them don't support sparse matrices or are too slow. I need this calculation to be done in max 2-3 minutes. Can somebody recommend me something ?
I read also about irbla in R, but it is possible to send my data from java to R, make calculations and send it back to my java program ?

A: I faced a similar problem while trying to apply Non-negative Matrix Factorization (NNMF) and Probabilistic Latent Semantic Analysis to large sparse term-document matrices. I tried Jblas1 and Jama2 but I finally used Matlab. And because I was writting the whole app in Java I ended up calling Matlab with Java through the Matlab Runtime Compiler (MRC).
What to do:
Matlab has a feature called Matlab Builder JA. Use this tool to produce a .jar file which has your matlab code and can then be called by your java program. This .jar needs the MRC to work.
1Jblas was much faster than Jama but I had problems and couldn't make it run with jdk for 64bits.
2 Jama used doube[][] and this caused problems with memory.Maybe the above have changed because I am reffering back to July 2012 and don't have clear image about now.


text:
Q: Firebase with SAML authorization callback URL Trying to get dot some Is and cross some Ts on getting SAML to function correctly with Firebase. I've followed Google's workflow on how to add SAML to a project (https://cloud.google.com/identity-platform/docs/how-to-enable-application-for-saml) but am hitting a wall with the authorization callback URL. When clicking the login to go to the SAML, it takes you to the provider's URL to sign in. But after logging in, you just get redirected back to the firebase site (*.firebaseapp.com/__/auth/handler), not the actual site. I've got the site URL set up as an authorized Domain in Firebase/Cloud Identity Platform. I'm not using Firebase hosting for the project, but I thought that as long as the URL is in the Authorized Domain, I didn't need to set up a redirect.
*3:26pm 2/26 - I think part of it might also be how I entered the SP Entity ID. I had used the same as the Entity ID that was with the SSO URL


text:
Q: SELECT only a certain set of rows at a time I need to select data from one table and insert it into another table. Currently the SQL looks something like this:
   INSERT INTO A (x, y, z)
   SELECT x, y, z
   FROM B b
   WHERE ...

However, the SELECT is huge, resulting in over 2 millions rows and we think it is taking up too much memory. Informix, the db in this case, runs out of virtual memory when the query is run.
How would I go about selecting and inserting a set of rows (say 2000)? Given that I don't think there are any row ids etc.

A: You can do SELECT FIRST n * from Table.  Where n is the amount of rows you want, say 2000.  Also, in the WHERE clause do an embedded select that checks the table you are inserting in to for rows already existing.  So that the next time the statement is ran, it will not include already inserted data.

A: I assume that you have some script that this is executed from? You can just loop and limit as long as you order the values returned from the nested select. Here is some pseudo code.
total = SELECT COUNT(x) FROM B WHERE ...
while (total > 0)
  INSERT INTO A (x, y, z) SELECT x, y, z FROM B b WHERE ... ORDER BY x LIMIT 2000
  total = total - 2000
end

A: I'm almost certain that IDS only lets you use the FIRST clause where the data is returned to the client1, and that is something you want to avoid if at all possible.
You say you get an out of memory error (rather than, say, a long transaction aborted error)?  Have you looked at the configuration of your server to ensure it has a reasonable amount of memory?
It depends in part on how big your data set is, and what the constraints are - why you are doing the load across tables.  But I would normally aim to determine a way of partitioning the data into loadable subsets and run those sequentially in a loop.  For example, if the sequence numbers are between 1 and 10,000,000, I might run the loop ten times, with condition on the sequence number for AND seqnum >= 0 AND seqnum < 1000000' and thenAND seqnum >= 1000000 AND seqnum < 2000000', etc.  Preferably in a language with the ability to substitute the range via variables.
This is a bit nuisancy, and you want to err on the conservative side in terms of range size (more smaller partitions rather than fewer bigger ones - to reduce the risk of running out of memory).

1 Over-simplifying slightly. A stored procedure would have to count as 'the client', for example, and the communication cost in a stored procedure is (a lot) less than the cost of going to the genuine client.


text:
Q: "...probably knew the answer judging by..." Is this grammatically correct? Example:

"What do you think about my house?" Tommy asked, who probably knew the
  answer judging by my open mouth.

...who probably knew the answer judging by... has only one Google result. So I wonder whether it's grammatical.

A: Here's a simple example of a non-defining relative clause similar to OP's construction...

My sister, who lives in France, is coming to stay with me next week.
   'who lives in France' is not essential, which means that I only have one sister and she does not need to be defined by the relative clause

In OP's case, there's only one Tommy - the extra information contained in the who clause simply tells us more about him, not which Tommy he is. In such constructions, the actual noun being referenced (Tommy, in this case) must immediately precede who...

"What do you think about my house?" asked Tommy, who probably knew the answer judging by my open mouth.

Other than the erroneous transposition of those two words, syntactically OP's text is perfectly normal English. It could be punctuated differently - for example, with a dash instead of a comma, or by placing the relative clause in brackets. But these are just stylistic choices.

Having said that, although grammatically the example is fine after that minor change, it's semantically problematic once we stop to ask Who is actually doing this "judging"?. I'm afraid there's no obvious way to fix that - sometimes valid syntax lets you say things that are effectively nonsense.

A: This is not correct. 'Judging by ...'  functions here as a comment phrase. In your sentence it means something like 'if one were to judge by my (open) mouth', which is not possible. . Thus we could say "Tommy knew how I felt, judging by the expression on his face". One possibility for what you want to say is "What do you think about my house?" Tommy asked, who probably knew the answer when he saw my jaw drop.

A: In this context, he is "judging" your answer from your body language.
Or more simplistically, he is guessing your answer from your body language, before you answer verbally.
You walk into his very nice house and your mouth drops open in astonishment. He sees this and knows you're impressed, he has already worked this out from your body language (your open mouth) but he asks you anyway, presumably because he's enjoying your reaction and wants you to praise his house.

A: On the surface it would seem grammatical and idiomatic to most native speakers. But when they looked more closely at that sentence, they would realize that it is not quite idiomatic. I suspect some may disagree with me on this.
"...judging by my open mouth" is the problemmatic phrase. It is not used as one would typically use it.
Here are some examples of proper uses:
Judging by your wet shoes, I assume you've been walking through puddles.
I assume you've been picking raspberries, judging by all those scratches on your hands and forearms.
To judge from the look on his face, he had just seen a ghost.
Here is an example of a non-idiomatic use:
"Have you been walking through puddles?" Tommy asked, who probably knew the answer judging by my wet shoes.
Why is that not idiomatic?  The adverbial phrase  "judging by {something}", when used idiomatically, refers to a judgment that is being made by the speaker of the sentence.
So what that sentence about Tommy actually says is this:
Judging by my wet shoes, I believe Tommy already knew the answer to his question, "Have you been walking through puddles?"
That is, the adverbial phrase modifies "I believe". It is a condition of that belief.
Here is that sentence corrected:
Judging from the way he had stared at my shoes, Tommy already knew the answer to his question, "Have you been walking through puddles?"

A:
"What do you think about my house?" Tommy asked, who probably knew the
  answer judging by my open mouth.

The word "probably" plus the first person perspective (use of the word my) is causing a problem.  By using these devices, you are speaking from a biased first person viewpoint - someone who is evaluating the probability that Tommy already knew the answer.  Together, it seems to imply that the biased speaker is "judging by my open mouth", which is contradictory, though I'm sure an English speaker could figure out due to the contradiction that you in fact meant that Tommy is doing the judging.
If you want to keep the the biased first person perspective, I suggest trying to make who's doing what more clear:

"What do you think about my house?"  Tommy asked, who probably knew
  the answer since my mouth was hanging open.


text:
Q: Why control padding with line-height? I was browsing this page over at meyerweb:
http://meyerweb.com/eric/css/edge/menus/demo.html
and I noticed something curious about the way the padding in the header is created:
h1 {margin: 0; padding: 1em 0.25em 0; font: bold 2.5em Arial, sans-serif; line-height: 0.8em; border-bottom: 1px solid silver; text-align: right; color: #557; letter-spacing: 2px;}

Now if you remove the line-height directive, it adds a little bit of padding to the top.  So the line-height is functioning essentially to remove a bit of padding from the top of the h1.  My question is: why not leave out line-height and change the padding-top from 1em to .9em?
I realize there are many ways to skin a cat in CSS, but I figured if an expert like meyer does it this way there is probably some reason for the choice.
Thanks,
Jonah

A: The reason for using a line height smaller than 1em is not actually not related to the spacing on top, but rather the space between the bottom border and the bottom of the line. Perhaps an example would illustrate this better: http://www.jsfiddle.net/yijiang/tptbe/

As you can see, with the default 1em the line sits slightly above the bottom of the letters 'p' and 'g', but with 0.8em the letters are raised just below the letters 'a' and 'b', a position that is more aesthetically pleasing

A: To make gap between bottom edge of h1 to the line become smaller.

A: Like Jeff said, it's not to remove the upper padding, it's to make the text overlap the border below it slightly - changing the margin or padding on it, in either direction would not cause the same effect.


text:
Q: Most robust CSS-only button solution? What's the best, most robust CSS-button definition?
Ideally, I'd like gradients, rounded images, and graceful degradation down to IE8. It would also be great if the buttons didn't use any images, and the buttons scaled horizontally to fit their content.
What's the best solution to this?

A: Use the tools at http://css-tricks.com/examples/ButtonMaker

A: It is possible to use gradients, box-shadow, border-radius, rgba colour et cetera in older versions of Internet Explorer, using CSS3 PIE. Look at their demo with all these CSS3 properties.
Now, combine CSS3 PIE with the button maker mentioned in the comments and you're done!

A: Huge fan of JQuery UI buttons.  Demo is here
Yes, they do use some images...but the images are also common to the many other features of JQuery UI, which offers your page some amazing features (and more coming all the time)  It does gracefully degrade, and you can extend it to round in IE via another JQuery plugin.  My favorite part is ThemeRoller, which allows you to build a page using themeroller capable plugins, then style or change at will, even with a tool that floats over the site.  You could easily include a way for your user to switch the entire theme of the site with a button click.  Plus, there's an editor to easily make your own themes if you don't like what's there.
As for gradients, you have fade up, fade down, curved fade, patterns, and then "build your own" options with variations of those and more plus color overlays and opacities.
Setting up a button is as easy as: <button class="ui-state-default ui-corner-all" type="submit">Button</button>

A: There is no way to do what you're asking with CSS only, as gradients and corners were only added as of CSS3 and even now they are still not fully supported.
The best way to achieve gradients now is to use an actual image, you can then be assured that most if not all browsers will support it (if you're using a .png image, IE6 may have an issue with it but there are CSS hacks to get around it).
Rounded corners can be added to the site in two different ways:

*

*The first is via images and you would place these at the corners of the element giving the rounded appearance. What I've said before about .png images still applies here.

*The second method is to use JavaScript. Most frameworks will have plugins designed with Web 2.0 features in mind. I recommend jQuery as it's easy to implement.

Out of the above two methods the first one is preferred if you want to make absolutely sure that the users can see curves, however if you aren't too concerned about them having JavaScript disabled I would definitely use jQuery as it's 100 times easier to use.


text:
Q: Measuring "concentration" in an expansion Suppose we have a vector $v \in \mathbb{R}^{n}$ which we expand in some orthonormal basis $\{g_{m}\}$ of $\mathbb{R}^{n}$:
\begin{align*}
v = \sum_{m=1}^{n} a_{m}g_{m}
\end{align*}
I want to measure how "concentrated" $v$ is in the basis $\{g_{m}\}$. To wit, I would like some measurement that is maximized when $a_{m} = 0$ for all but one $m$, and minimized when all the $a_{m}$ have the same magnitude. Is there a nice way to measure this "concentration" (preferably easily computed), and is there standard terminology for it?

A: The Gini coefficient is an excellent way to measurement sparsity. Here, we use the following definition of Gini coefficient:
\begin{align*}
G(v) := \frac{1}{n-1}\left[ \frac{2}{\left\| v\right\|_{1} } \sum_{i=0}^{n-1} (i+1)|v_i^{(s)}|  - n - 1  \right]
\end{align*}
where $v_{i}^{(s)}$ is the $i$th coefficient of the vector $v$ sorted by increasing  magnitude. Note that this definition differs from (say) Wikipedia's definition, which only applies it to wealth inequality, where each element is real and non-negative.
We have some nice properties of $G$:

*

*If $v_{j} \mapsto e^{i\theta_j}v_{j}$, we feel intuitively that the sparsity is unchanged, and indeed $G(v)$ is invariant under these phase changes.

*If $0 \ne \lambda \in \mathbb{C}$, it is easy to see that $G(\lambda v) = G(v)$ (changing units doesn't change sparsity).

*If $v_{j} = 0$ for all but one $j$, then $G(v) = 1$, which is the maxima of $G$. If all coefficients are of equal magnitude, then $G(v) = 0$, which is the minima of $G$.

*If $\Pi$ is a permutation of the elements of $v$, the $G(\Pi v) = G(v)$. (Permutations don't affect sparsity.) The particular way that the Gini coefficient achieves this is via sorting, which is not ideal due to it requiring $\mathcal{O}(n\log n)$ operations, but the invariance is indeed manifest.

*The property of the Gini coefficient not shared by the Hoyer measure (a normalized ratio of $\ell_1$ and $\ell_2$ norms) is its invariance under concatenation: $G(v\oplus v) = G(v)$. How much weight should be given to this property is unclear, especially given the sorting requirement.


text:
Q: [Babel]: Unknown option: foreign.Children I'm getting that error when I build using this script:
webpack --colors --progress --watch --config --jsx-loader webpack.config.js

Here's my package.json file:
{
  "dependencies": {
    "autoprefixer": "^6.0.3",
    "node-libs-browser": "^0.5.3",
    "object-assign": "4.0.1",
    "underscore": "1.8.3",
    "react": "0.14.7",
    "react-dom": "0.14.7",
    "react-router": "2.0.0",
    "history": "^1.17.0",
    "superagent": "^1.8.0",
    "react-addons-css-transition-group": "0.14.7",
    "react-bootstrap": "0.28.2",
    "react-select": "^1.0.0-beta9",
    "moment": "2.11.2",
    "truncate": "2.0.0",
    "superagent-promise-plugin": "2.1.0",
    "rrule": "2.1.0"
  },
  "devDependencies": {
    "babel-core": "^6.13.2",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.13.2",
    "babel-preset-stage-0": "^6.5.0",
    "babel-runtime": "^6.11.6",
    "css-loader": "^0.23.1",
    "eslint": "^3.2.2",
    "eslint-config-defaults": "^9.0.0",
    "eslint-loader": "^1.5.0",
    "eslint-plugin-react": "^6.0.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "html-webpack-plugin": "^2.22.0",
    "isparta-instrumenter-loader": "^1.0.1",
    "jsx-loader": "0.13.2",
    "less": "^2.3.1",
    "less-loader": "^2.2.3",
    "livereload": "^0.5.0",
    "null-loader": "^0.1.1",
    "postcss-loader": "^0.9.1",
    "raw-loader": "^0.5.1",
    "style-loader": "^0.13.1",
    "webpack": "^1.12.13",
    "webpack-livereload-plugin": "0.4.0"
  },
  "babel": {
    "presets": [
      "stage-0",
      "es2015",
      "react"
    ]
  }
}

And my webpack.config.js
var webpack = require('webpack');
var path = require('path');
var LiveReloadPlugin = require('webpack-livereload-plugin')

module.exports = {
    output: {
        path: __dirname,
        filename: "bundle.js",
    },
    resolve: {
        extensions: ['', '.js', '.jsx'],
        root: [
          path.resolve('./../../../../../../Javascripts/modules')
        ],
        moduleDirectories:
        [
          './../../../../../../Javascripts/modules'
        ]
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" },
            {
                test: /\.less$/,
                loader: "style!css!less"
            },
            { test: /\.html$/, loader: 'raw', exclude: [/node_modules/, path.resolve('./../../../../../../Javascripts/modules')] },
            {
                test: /(\.jsx|\.js)$/,
                loader: 'babel',
                exclude: [/(node_modules|bower_components)/]
            },
            {
                test: /(\.jsx|\.js)$/,
                loader: "eslint-loader",
                exclude: [/node_modules/, path.resolve('./../../../../../../Javascripts/modules')]
            }
        ]
    },
    eslint: {
        configFile: './src/js/.eslintrc'
    },
    entry: "./src/index.js",
    plugins: [
        new LiveReloadPlugin()
    ]
};

Any idea how to resolve that error? Based on my Google searches, it's a package versioning issue, but that's all I've been able to figure out.

A: You might be missing the react babel presets npm package.
Try this:
npm i --save-dev babel-preset-react

A: I ended up rolling back to Babel 5, and this issue went away. Not a great answer for those who might find this later on, but it works fine for my app.


text:
Q: Using .Dispose in a thread safe way In a previous question I was given an awesome solution to a memory leak issue I was experiencing. There is one problem though- the solution involves disposing of unnecessary data in an event handler that appears to be being called before its last iteration has finished. Every time a new frame is pulled from my webcam, it calls this event handler.
    private void Handle_New_Frame(object sender, NewFrameEventArgs eventArgs)
    {
        //textBox1.Text = "Frame #: " + counter;
        //counter++;

        //bitmap = (Bitmap)eventArgs.Frame.Clone();
        if (bitmap != null)
            bitmap.Dispose();
        bitmap = new Bitmap(eventArgs.Frame);

        //bitmap = AForge.Imaging.Image.Clone(eventArgs.Frame);

        if (videoPictureBox1.Image != null)
            videoPictureBox1.Dispose(); //THE CRASH HAPPENS HERE.
        videoPictureBox1.Image = bitmap;
    }

The error is: Cross-thread operation not valid: Control 'videoPictureBox1' accessed from a thread other than the thread it was created on.
My problem is that I am not at all familiar with C# threading, and not in a comfortable place with threading in general. I have found similar questions on StackOverflow but none that I was able to pull enough information relating to my own issue to put me on the right track (or maybe I looked right at the answer and missed it!)
I found two MSDN answers in the links below, but I'm still having a bit of a difficult time grasping what solution would be the most suitable for my issue.
http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k%28EHInvalidOperation.WinForms.IllegalCrossThreadCall%29;k%28TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5%29;k%28DevLang-csharp%29&rd=true
http://msdn.microsoft.com/en-us/library/8843a9ch.aspx
I apologize for asking two questions in such short succession, and also for them being on the same topic. I'm just afraid without a nudge in the proper direction, I might flail around like a fish out of water on google for a while, looking at the wrong places.
So my question: What method do you think would be best suited to avoid this error? If you happen to know of documentation, sample code or a tutorial that would help me figure this out, that too would be awesome.
Thanks!

A: You should not be disposing your videopicturebox if you are still using it.  You should only dispose resources that are not needed anymore.
Your code should be something like this
private void Handle_New_Frame(object sender, NewFrameEventArgs eventArgs)
{
    var newBitmap = new Bitmap(eventArgs.Frame);
    //This assumes the picture box descends from Control
    if(videoPictureBox1.InvokeRequired)
    {
        Action action = () => videoPictureBox1.Image = newBitmap;
        //Invoke to make the action happen on the GUI thread
        videoPictureBox1.Invoke(action);
    }
    else
        videoPictureBox1.Image = newBitmap;
    //Dispose the old bitmap now that it is not assigned to the picturebox anymore
    if (bitmap != null)
        bitmap.Dispose();
    bitmap = newBitmap;
}

You could also split the logic out into another method and then Invoke that method or not depending on if the Invoke is required.


text:
Q: python: change datatype that includes .0 I am working with a dataframe, that unfortunately imports the column "ID" in the following format: 7.350943+e
I thought I fixed the issue with this code:
pd.set_option('display.float_format', lambda x: '%3.f' % x)

However, this only fixes the display, in the back-end it remains in this scientific format.
When I try to create a new column based on column ID and column source, I get the following:
df['Primary_key']=df['ID'].apply(str)+'_'+df['Source']

Name       ID        Source      Primary_key
John    782857635    email       782857635.0_email

What format do I need to change the datatype to in order to get rid of the .0?
df['ID'].values
array([782929635.0, 783063368.0, 782960457.0, ..., 783257941.0,
       783535550.0, nan], dtype=object)

I tried replacing it, in the Primary key, but it didn't work (there was no change to the dataframe)
df['Primary_key']= df['Primary_key'].str.strip().replace(".0_","_")

A: I think you should try something like:
df['ID'] = df['ID'].apply(str).strip().replace(".0","")

A: int() is what you seem to be looking for.
[int(i) for i in whateverList]


text:
Q: Only show specific sheet in the embed Google Spread Can I embed a specific sheet not the whole spreadsheet in html webpage?
<iframe height="500" src="https://docs.google.com/spreadsheets/d/<key>/edit?usp=sharing" width="100%">

A: Some useful info from documentation will help:

To publish a file:

*

*Open a document, spreadsheet, presentation, or drawing.

*Click the File menu.

*Select Publish to the Web.

*While the entire file will be published, some file types have more    publishing options: Spreadsheet: Choose to publish the entire
  spreadsheet or individual sheets. You can also choose a publishing
  format (web page, .csv, .tsv, .pdf, .xlsx, .ods).

*Click Publish.

*Copy the URL and send it to anyone you'd like to see the file. Or,
  embed it into your website.

If you choose Embed in step 4,

you'll get this code:


text:
Q: 50 amp hour and 100 amp hour lifepo4 batteries in series I have four 12 V, 50 amp hour lifepo4 batteries running in series, so 48 V. I need to increase the capacity of the battery bank. Can I get four 100 12 V amp hour batteries and create 4 sets of 150 amp hour battery banks by running a 50 amp hour and 100 amp hour in parallel. Then running those 4 banks in series to get 48? Will I have any issues in the long run? If so should I just buy 8 more 50 amp hour batteries instead?
Batteries are only 4 months old, very lightly used.

A: Your circuit is pretty much legitimate, as long as connecting 12V LiFePO4 in series is legitimate in the first place.
For most 12V LiFePO4 batteries the manual explicitly states that series connection is not allowed. It is not that it will not work, it will need a pretty unusual type of battery management system and will be of lower reliability anyway.
Of course, the batteries should be of the same chemistry, connected as symmetrically as possible and should be as similar as possible, ideally the same brand and model.

A: Imagine two capacitors in series initially charged with a load.
Which cap decays faster? The smaller one.
Which cap charges up past full voltage faster? The smaller one
BMS units are intended to shunt current on discharge with current on the stronger battery so it appears as weak as the weakest cell in order to prevent the weakest cell from getting damaged from undervoltage damage. Then during charging shunt the weakest cell to bypass current from exceeding the CV max while the stronger batteries catch up.
Normally 6cell batteries are matched <0.1% when new and the CV phase allows the current to decline while the stronger cells try to catch-up in series.
What happens without a BMS with external mismatched packs is the weaker packs accelerate faster in aging in a runaway condition from under and over charge, so you never want battery packs mismatched for Ah or ESR for longest life cycles.
This also means choosing to use less CV and cutout voltage reduces capacity but total life cycles increase dramatically. (E.g. 10x for 50% capacity utilization re Battery university, your mileage may vary)
It also means unless you have dozens of cells , when a string or module has 1 dead cell and the others are near end of life, it's just a short matter of time before the next cell is dead and then the next etc. so batteries are like Caps and must be balanced as they perform as well as the weakest link.
To prove the point here, I modelled your 50Ah batteries to show how each battery gradually changes with respect to the others. It uses a comparator to decide when to charge 10A and discharge 10A with a simple battery model initialized to 12.0V then counts each cycle displayed on LEDs in binary. The voltage is sampled every second and the run time shows after about 50 cycles the capacity difference from Vmax has shifted by a spread of about 0.5V out of 14V. Eventually when one pack exceeds absolute max or min, degradation accelerates. this proves the point that a master BMS is needed to track all packs and need to be charged separately to same voltage after 50 cycles.
Here is the simulation.


text:
Q: Confused by the different type of verbs I am trying to brush up on my grammar but I am confused on when to use the correct tense of the verb.
How/when should I use the correct tense?
a) I write the letter.
b) I am writing the letter.
c) I wrote the letter.
d) I was writing the letter.
e) I have wrote the letter.
f) I have been writing the letter.

A: In e) it should be "have written" and not "have wrote".
The rules:
The Present Simple Tense: (the indefinite present tense)

*

*for something general, that is always true
The earth turns round the sun.

*for habitual, repeated actions
Tom smokes. I get up at seven every day.

*for future actions:
A.   if they are a part of a fixed plan, especially in connection with journeys (arrive, begin, leave, ...)
When does the train for London leave?
B.  in adverbial clauses of time and condition (IF, WHEN)
When Tom comes, I'll be sleeping.

*NOTE: sometimes Present Simple is also used for the real present = NOW
a.  with verbs that cannot be used in –ing form (=state verbs)
I (can) see George in the street.
b.  in demonstrations for the audience
I break the eggs into the cup, I mix them well, …

The Present Continuous Tense: (the progressive present tense)

*

*for the real present
We are learning the present continuous tense now.

*for an action that is repeated over a limited period of time but is not habitual
I usually go to work by car but this week I am walking because my car is    broken.

*if an activity annoys the speaker, especially with always and its synonyms
John is always talking during my lessons.

*for the arranged or planned actions for near future
I am playing tennis with Tom tomorrow.

*instead of going-to-future with COME and GO

*I'm going to go to Paris this summer.
 I'm going to Paris this summer.

The Past Simple Tense: (the indefinite past tense)
A. TEMPORAL FUNCTION
- for actions that happened at a definite point or period of past time, no connection with present
I had breakfast at 8 o'clock this morning.  They lived in London during the war / for four years.
- to express actions that happened one after another
    She woke up at 7, washed, had breakfast and went to school.
- to ask about the time of a past action
    When did you get married?
-   when speaking of actions of dead people
Sheakespeare wrote Hamlet.
B. MODAL FUNCTION
In conditional clauses Type 2 and following expressions such as I WISH, IF ONLY, IT'S TIME… In this function it always something contrary to the fact and NOT past!
    I wish I had more time.
    I would go to the USA if I had enough money.
The Past Continuous Tense: (the progressive past tense)

*

*for an action that was in progress at a definite past moment OR between two points in past (between…and – also Past Simple is possible here!)
Yesterday at 7 o'clock I was having breakfast. (a bit earlier, a bit later) Compare: Yesterday at 7 o'clock I had breakfast.
From seven to seven thirty I was walking to the factory.

*for an action that was going on at a definite past moment and was interrupted by another past action
I was just bathing the baby when the telephone rang.

*for two continuous past actions that were happening simultaneously
Last night I was reading and Betty was playing the piano.

The present perfect simple tense:

*

*for unfinished past, actions that started in the past and continue up to the present
I have lived in Ljubljana since1995.

*for expressing experience
Mary has already been in America, but I haven't.

*for present results of past events
Tony has broken his leg that's why he can't play tennis.

The Present Perfect Continuous Tense

*

*for activities that began in the past and may still be going on
I have been learning English for 6 years.

*for activities that began in the past, have just ended and have present consequences
I am tired because I have been running


text:
Q: What is a monad-transformer as distinct from a monad? The question says it all, really. I know a (Scala) Monad looks like this:
trait Monad[M[_]] {
  def pure[A](a : A) : M[A]
  def bind[A, B](ma : M[A], f : A => M[B]) : M[B]
}

What does a Monad Transformer look like? And what are they used for?

EDIT. Consider the following REPL session: if a monad transformer somehow decorates a monad with reader capabilities (or vice versa)
Let's say I just want to use replicateM from Scalaz;
scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._

scala> some(4).replicateM[List](2)
res20: Option[List[Int]] = Some(List(4, 4))

Now let's say, rather than having an Option[Int], I need to read an Int value from a File:
scala> val f = (_ : java.io.File) => some(1)
f: (java.io.File) => Option[Int] = <function1>

So, I can treat this reader, as if it was a Monad?
scala> ReaderT(f).replicateM[List](2)
<console>:16: error: value replicateM is not a member of scalaz.ReaderT[Option,java.io.File,Int]
       ReaderT(f).replicateM[List](2)
                  ^

Err, no.
Apologies if this all seems stupid, I'm just trying to understand what lovely goodness my wrapping the File => Option[Int] in a ReaderT can actually buy me.

A: Monad Transformers are used for combining / extending monads (add capabilities of one monad to another). E.g., ReaderT (Reader Transformer) enriches given monad M with Reader capabilities (transforms given monad into Reader retaining original features of M).
At the same time, Monad Transformers are normal monads that have bind, return, and other operations.
You can find examples of monad transformers in Scalaz - e.g., for Reader and State monads.

A: Monad transformers are type functions that when applied to a monad type, generate a new monad, that combines the behavior of both components.
E.g. in the xmonad window manager, the computations run inside:
newtype X a = X (ReaderT XConf (StateT XState IO) a)

that is, a Reader composed with a State and an IO monad.

*

*Reader gives access to read-only memory

*State provides a form of read-write state

*IO allows arbitrary external effects

Note that monad transforms are thus higher-rank types. They take a monadic type of kind (* -> *), and yield a new type of that kind.
As always, the Haskell wiki has some useful content:

*

*Monad transformers

*Monad transformers step by step: a tutorial.

Where it all began:

*

*Functional Programming with Overloading and Higher-Order Polymorphism

A: I don't think Reader is for reading values from a file. Pretty sure it's for reading values of configuration. I think of it as an alternative to global variables, statics, or dynamic/thread-local variables (called "special variables" in Common Lisp or sometimes fluide variables in Scheme with it's "fluid-let"). So, use Reader/ReaderT rather than access a global or dynamic variable and rather than pass parameters into each of your methods that may require access to some configuration option. This can be useful when some very deep piece of code suddenly requires access to a new configuration option. You can pass the option down from your main() function, sneakily access a global or use Reader/ReaderT.