text:
Q: Angular ng-repeat to PDF or printer CSS presumed alignment issue I am creating some tickets to be printed out using AngularJS. I have try to produce a 1000 tickets and there is an offset of about 5 pixels from first to last ticket. Now as I was fiddeling my code I noticed the output is not the same. I believe it might be how the borders are treated but I'm not sure.
When ng-repeat start the class ticketNo and ticketNoR both are exceeding the bottom border of there relative parent(ng-repeated) by 2 pixels
When I reach 1000 tickets these 2 class are now 2 pixels above the bottom border of there parent element.
The result vary with Chromium and Firefox but there is always an offset. And I can't find where it's from.
This is my code and I realized that the fiddle dont reproduce the issue. I need to get rid of this offset for printing and auto-cutting.
Any idea where it is from?

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

ticket.controller('ticketCtrl', function($scope, $http){
$scope.ticketQty = 1000;
$scope.tickets = [];
$scope.pad = "000000";
$scope.ticketNo = 3000;

for (var i=0; i< $scope.ticketQty; i++){
    var str = "" + $scope.ticketNo;
 var ticketNum = $scope.pad.substring(0, $scope.pad.length -  str.length) + (i+parseInt($scope.ticketNo));
 $scope.tickets[i] = ticketNum  ;

}
    });
.ticket-border{
 position:relative;
 width:800px;
 height:200px;
 border-top:2px solid #4eb610;
    border-bottom:2px solid #4eb610;
    page-break-inside: avoid;
    margin:10px;
}

.tikNo{

  transform-origin: left top 0;
  position:absolute;
  left:50px;
  height:50px;
    width:200px;
    text-align:center;
    word-wrap: break-word;
    font-family: monospace;
    white-space: pre;
    transform: rotate(90deg);
    background-color: #4eb610 !important;
    font-weight: 900;
    font-size: 25px;
    line-height: 60px;
    color:#fff !important;
    -webkit-print-color-adjust: exact !important;
    margin:0px;

    }

.tikNoR{
  transform-origin:right top 0;
  position:absolute;
  right:50px;
  height:50px;
    width:200px;
    text-align:center;
    word-wrap: break-word;
    font-family: monospace;
    white-space: pre;
    transform: rotate(270deg);
    background-color: #4eb610 !important;
    font-weight: 900;
    font-size: 25px;
    line-height: 60px;
    color:#fff !important;
    -webkit-print-color-adjust: exact !important;
    }

.tikNoDot{
  position:absolute;
  top:85px;
  left:35px;
  border-radius:15px;
  height:30px;
  width:30px;
  background-color:#fff !important;
  -webkit-print-color-adjust: exact !important;
  z-index: 1;
}
.tikNoDotR{
  position:absolute;
  top:85px;
  right:35px;
  border-radius:15px;
  height:30px;
  width:30px;
  background-color:#fff !important;
  -webkit-print-color-adjust: exact !important;
  z-index: 1;
}

.ticketLeftSide{
  position:absolute;
  top:0px;
  left:55px;
  width:540px;
  height:198px;
  border-right:2px dashed #4eb610;
  z-index: 2;

}

.ticketRightSide{
  transform-origin: right top 0;
  position:absolute;
  top:10px;
  right:0px;
  width:180px;
  height:160px;
  left:400px;
  z-index: 2;
  line-height: 25px;
  text-align:left;
  word-wrap: break-word;
  font-family: monospace;
  font-size:10px;
  white-space: pre;
  transform: rotate(270deg);

}

body
{
  margin:0px;
}

.price{
 float:right;
  border :2px solid #4eb610;
  border-radius:15px;
  height:75px;
  width:75px;
  margin:10px;
  text-align:center;
  line-height: 75px;
  font-weight: 900;
  font-size: 35px;
   font-family: monospace;
   clear:both;

}

.headline{
  position:absolute;
  top:5px;
  left:5px;
  width:445px;
  height:150px;
  text-align: center;
  font-weight:900;
  font-size: 25px;
}

.datetirage{
  position:absolute;
  top:100px;
  width:445px;
  text-align: center;
    border-top :2px solid #4eb610;
     border-bottom :2px solid #4eb610;
    font-weight:100;
font-size: 15px;
}

.disclaimer{
  position:absolute;
  bottom:0px;
  height:50px;
  width:445px;
  text-align: center;

    font-weight:100;
font-size: 13px;
}
.logoImg{
  height: 60px;
}

.webprint{

  font-size:20px;
  font-weight:400;
}

{{ticket}}

1$

Headline

Date Time

Disclaimer

nom:___________________________
prénom:________________________
Tel:___________________________
Courriel:_____________________@
_______________________________

{{ticket}}

A: The issue is caused by css-border. You can use @media print and play around with the border thickness.
I had similar problem when generating a bar code. The bottom border always overlapped on bar code itself when printing from chrome or Firefox but it always worked in IE, not sure why it just worked in IE. You can also try IE and see if that works for you.


text:
Q: Running a script on all .ai files in a directory I'm a graphic designer and a beginner at coding. So please dumb down for me :)
I have a script that I run through Illustrator. It embeds an image and removes a clipping mask on the file. I need this script to run on multiple .ai files in a folder.
The thing is, I cannot create a batch action (in Illustrator) to run the script. Our IT guy doesn't want to add the script to our Illustrator settings on multiple accounts. Is there a way to add code to my script to do this?
I need it to open all the files, run the script and save. The files can be left open on Illustrator, no need to close.
What code do I need to add to my script?
I am on a Mac not PC.

A: It can be done this way:
function my_script() {

    // copy a full text of your script here

    // or include the jsx file this way:
    # include '~/Desktop/script/my_script.jsx'

}

function main() {

    var folder = Folder.selectDialog('Please, select the folder');
    if (!(folder instanceof Folder)) return;

    var files = folder.getFiles('*.ai');
    if (files.length == 0) {
        alert('Folder doesn\'t content AI files');
        return;
    }

    var i = files.length;
    while (i--) {
        var doc = app.open(files[i]);
        my_script();             // <------- here your script is running
        doc.save();
        doc.close();
    }

    alert(files.length + ' files were processed');
}

main();

A: If you have subfolders with .ai files inside your chosen folder and you need to access them in the script, you may find this JS snippet useful as well:
https://gist.github.com/joonaspaakko/df2f9e31bdb365a6e5df

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finite flat pushforward of a constant sheaf Let $A$ be an abelian group and consider the associated constant sheaf $A$ on a (smooth projective) variety $Y$ (over a field).  Let $f: Y \to X$ be a surjective finite flat morphism.  Is $f_*A$ also a constant sheaf on $X$?

A: Yes the image of a  constant sheaf is a constant sheaf, even  under significantly weaker  hypotheses: it suffices to require that  $Y$ be irreducible and $f$ surjective.
Actually the result is purely topological: given a surjective continuous map $f:Y\to X$ between topological maps, if  $Y$ irreducible then  the direct image of any constant sheaf $\underline A_Y$ on $Y$ is the  constant sheaf $f_*(\underline A_Y)=A_X$ on $X$.
Indeed, given an arbitrary non-empty open subset $V\subset X$ we have $$\Gamma(V,f_*(A_Y))=\Gamma (f^{-1}(V),A_Y)=A$$ the last equality resulting from $f^{-1}(V)$ being connected, like any open subset of an irreducible space .
This proves that  $f_*(   A_Y)=A_X$.
Warning: Beware that the result is false for non surjective $f$.
 For example  if $Y=*$ is a point, the direct image $f_*(A_Y)$ is the sky-scraper sheaf on $X$ with stalk  $A$ at $f(*)\in X$


text:
Q: How to hide a push notification after some time? I have to hide a push notification after 1 minute. What should I do in my service worker to achieve this?

A: You can use the Notification.close() method. You can get the Notification object with ServiceWorkerRegistration.getNotifications.
For example:
self.addEventListener('push', event => {
  event.waitUntil(
    self.registration.showNotification('Title', {
      body: 'Body.',
    })
    .then(() => self.registration.getNotifications())
    .then(notifications => {
      setTimeout(() => notifications.forEach(notification => notification.close()), 60000);
    })
  );
});

A: You have to use Notification.close.
Also, to get the notifications, you have to use ServiceWorkerRegistration.getNotifications(). To identify a specific notification, you can use Notification.tag.
Finally, you must keep a Promise alive inside "waitUntil" to prevent the service-worker to shut down before your timeout triggers:
event.waitUntil(
  self.registration.showNotification('Title', {body: 'Body.', tag: 'my-unique-tag'})
    .then(() => new Promise(resolve => setTimeout(resolve, 60000)) // keep service worker alive
    .then(() => self.registration.getNotifications())
    .then(notifications => {
      const notification = notifications.find(notification => notification.tag === 'my-unique-tag')
      if (notification) {
        notification.close()
      }
    })
  );


text:
Q: convert messages in transit from UUEncode to MIME I have a third-party app that generates emails in UUEncode format with PDF attachments. The PDF attachments are unreadable because iPhones don't understand UUEencode apparently.
I don't see any settings anywhere in Exchange 2010 to make the Exchange server convert it.
Are there any open source SMTP servers that will do this conversion? I'd be willing to send this server's messages through another SMTP server to do the conversion before it's send to Exchange.

A: I found a plug-in for qpsmtpd called tnef2mime. It was originally designed to convert Microsoft's TNEF (winmail.dat) attachments to MIME, but it also converts UUEncoded messages. I couldn't find a canonical source for this plugin, but SME Server keeps the plugin in their distribution and the bug database implies that people are using it recently.
So I added qpsmtpd to a small Ubuntu server I'm using for other purposes, extracted tnef2ime from the RPM, enabled it as a plugin, and I am now sending my problematic SMTP clients through this box first.


text:
Q: jQuery flot graph plot tooltip I have a graph that displays like so:

I'd like the tooltip to display "£1500 sales on 31/07" rather than 4.
My x-axis is generated like so:
xaxis: {
    tickColor: 'transparent',
    tickDecimals: 0,
    ticks: [[1,'27/07'],[2,'28/07'],[3,'29/07'],[4,'30/07'],[5,'31/07'],[6,'01/08'],[7,'02/08']]
},

And the code to generate the tooltip is:
function showTooltip(x, y, contents) {
    jQuery('
' + contents + '
').css({
        top: y - 16,
        left: x + 20
    }).appendTo('body').fadeIn();
}

var previousPoint = null;

jQuery('#graph-lines, #graph-bars').bind('plothover', function (event, pos, item) {
    if (item) {
        if (previousPoint != item.dataIndex) {
            previousPoint = item.dataIndex;
            jQuery('#tooltip').remove();
            var x = item.datapoint[0],
                y = item.datapoint[1];
                showTooltip(item.pageX, item.pageY, '£' + y + ' sales on ' + x);
        }
    } else {
        jQuery('#tooltip').remove();
        previousPoint = null;
    }
});

The important line is:
var x = item.datapoint[0]

How can I get this to read the tick string rather than value?
Thanks

A: I've figured this out, I realised that I need to save the x-axis label within the data points:
var graphData = [{
        // Shop
        data: [ [1, 1300, '27/07'], [2, 1600, '28/07'], [3, 1700, '29/07'], [4, 1500, '30/07'], [5, 1500, '31/07'], [6, 1200, '01/08'], [7, 1000, '02/08'] ],
        color: '#71c73e'
    }, {
        // Net
        data: [ [1, 900, '27/07'], [2, 1100, '28/07'], [3, 1550, '29/07'], [4, 1600, '30/07'], [5, 1800, '31/07'], [6, 1400, '01/08'], [7, 1300, '02/08'] ],
        color: '#77b7c5',
        points: { radius: 4, fillColor: '#77b7c5' }
    }
];

And then replace this:
var x = item.datapoint[0]

With this:
var x = item.series.data[item.dataIndex][2]


text:
Q: Error en regla unique en actualizar Me encuentro testeando la funcionalidad de mi Request de validacion de datos y me encuentro con el siguiente problema.
Cuando quiero actualizar un registro no tengo problema, el problema lo tengo que le quiero asignar el mismo nombre que otro registro, en este caso deberia arrojar el error "el nombre ya se encuentra registrado" pero en vez de devolverme el error directamente el codigo explota.
Adjunto mis codigos a ver si alguien tiene nocion de que puede estar pasando.
Controlador
public function update(SucursalUpdate $request, $id)
{
    $sucursal = Sucursal::find($id);

    $sucursal->name = $request->name;
    $sucursal->estado = $request->estado;

    $sucursal->save();

    return redirect()->route('sucursales.index')->with('info','La sucursal fue actualizada correctamente');
}

Request SucursalUpdate
public function rules()
{
    return [
        'name'      =>  'required',
        Rule::unique('sucursals')->ignore($this->id),
    ];
}

Migracion Tabla Sucursals
public function up()
{
    Schema::create('sucursals', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->string('name')->unique();
        $table->boolean('estado')->defalut(1);

        $table->timestamps();
    });
}

Archivo de rutas
{Route::resource('sucursales', 'Admin\SucursalController');
Route::get('sucursales/changeStatus/{id}', 'Admin\SucursalController@changeStatus')->name('sucursales.changeStatus');}

A: Las reglas se escriben como un solo string separadas por | o separás por comas y encerrás todo entre corchetes (documentación).
Por otro lado, en vez de utilizar $this->id deberías chequear si existe una sucursal, que existirá solo si estás editando una, pero no creando.
public function rules()
{
    $id = $this->route('sucursale')->id ?? null;

    return [
        'name' => ['required', Rule::unique('sucursals')->ignore($id)],
    ];
}

A: El problema era que me encontraba utulizando un controlador de resource por lo que las rutas que generan no siempre son /{id}
Al utilizar el comando

php artisan route:list

Comprobe que la ruta que me generaba para el put era la siguiente

sucursales/{sucursale}

Por lo que cambie mi archivo de reglas por lo siguiente
public function rules()
{
    return [
        'name'      =>  'required|unique:sucursals,name,'.$this->sucursale,
    ];
}

Y quedo andando a la perfección.


text:
Q: 'permission denied' error with random getDownloadURL flutter/firebase I'm writing an app which has user profiles in it. The user is allowed to take a photo or choose from their photo library.
Once the photo is taken, I use this function:
Future<String> uploadFile(File image, String directory, String imageName) async {
    assert(image.existsSync());
    StorageReference storageReference = FirebaseStorage.instance.ref().child('$directory/$imageName');
    StorageUploadTask uploadTask = storageReference.putFile(image);
    await uploadTask.onComplete;
    var dowurl = await storageReference.getDownloadURL();
    return dowurl.toString();
  }

to upload the image to firebase. The image appears in the Firebase storage area fine, and the URL is generated, and added to the user's profile as I've defined in the database.
The rules of firebase are set as follows:
Database
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

Storage
rules_version = '2';
service firebase.storage {
  match /b/myappname.com/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

which I believe should allow access for any user as long as they're authenticated (they are!)
I'm uploading the URLs generated by uploadFile() to the users profile, but about 1/6 of them gives a URL which, when accessed gives the following error:
{
  "error": {
    "code": 403,
    "message": "Permission denied. Could not perform this operation"
  }
}

I'm at a loss as to what is going on here, as the rest of the code works fine, and the 'choice' of file which causes the problem seems completely random.
The URLs generated have different token IDs at the end of each, but I'm not generating them - they're coming from the getDownloadURL() function. I'm keen to stress that the process is the same for each file, but for some reason, randomly, one of the generated URLs doesn't work.
Any help would be much appreciated.


text:
Q: Is numerical approximation the only option when derivative cannot be expressed explicitly as an expression? My problem is the following: Are there any differentiable functions on $\Bbb R$ for which we don't know or can't find an explicit expression for the derivative? So is approximating the derivative numerically the only choice?

A: If you mean that we can't find an explicit expression of the first derivative, then yes, they do exist. Take $f:\Bbb R\to \Bbb R$ as
$$f(x)=\int_0^x \left(\int_0^t e^{\frac{-y^2}{2}}dy\right)dt.$$ Then, it can be proved that
$$f'(x)= \int_0^xe^{\frac{-y^2}{2}}dy.$$ However, this function cannot be expressed in terms of elementary functions. That being said, you can always approximate the derivative numerically. Hope that helps.

A: There's a neat trick involving dual numbers (a number system that has a nonzero infinitesimal element $\epsilon$ such that $\epsilon^2=0$), that lets you numerically calculate derivatives of any function that you can numerically calculate in the first place, to machine precision. This procedure is no less exact than determining an analytical expression for the derivative and computing the value of that expression numerically.

A: For functions on $\Bbb R$: derivability $\iff$ differentiability.
NOTE
That's not the case for functions of several variables for which only one direction is true: differentiability $\implies$ derivability.


text:
Q: Проблема с формулой в PyGame Хочу сделать простейшую функцию прыжка через параболу, но столкнулся с тем, что в pygame позиция может быть только целым числом, а результат функции - дробное, поэтому с каждым прыжком уровень бокса персонажа повышается.
Прыжок:
if player.jumping:
        if jump_height >= -15:
            player.rect.y -= decimal.Decimal((jump_height ** 2) / 2) if jump_height >= 0 else -decimal.Decimal((jump_height ** 2) / 2)
            jump_height -= 1
        else:
            player.jumping = False
            player.rect.y += 8
            jump_height = 15

Весь код:
import pygame
import os
import decimal

# VARIABLES
WIDTH = 1920
HEIGHT = 1080
FPS = 60
player_speed = 15
running = True
jumping = False
jump_height = 15
clock = pygame.time.Clock()

# INITIALIZING
pygame.init()
pygame.mixer.init()
main_window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("TestGame")
sprites = pygame.sprite.Group()

# ASSETS
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')
player_img = pygame.image.load(os.path.join(img_folder, 'player.png'))
player_sneaking_img = pygame.image.load(os.path.join(img_folder, 'sneaking.png'))

# CLASSES
class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = player_img
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT - 100)
        self.sneaking = False
        self.jumping = False

    def move(self, direction):
        if self.rect.left > WIDTH:
            self.rect.right = 0
        elif self.rect.right < 0:
            self.rect.left = WIDTH
        elif direction == 2:
            self.rect.x += player_speed
        elif direction == 3:
            self.sneaking = True
            rect = (self.rect.center[0], self.rect.bottom - (0.75 * self.rect.height) / 2)
            self.image = player_sneaking_img
            self.rect = self.image.get_rect()
            self.rect.center = rect
        elif direction == 4:
            self.rect.x -= player_speed

# FUNCTIONS
def movements_handler():
    global player_speed
    key = pygame.key.get_pressed()
    if (key[pygame.K_w] or key[pygame.K_UP]) and not player.jumping and not player.sneaking:
        player.jumping = True
    if key[pygame.K_d] or key[pygame.K_RIGHT]:
        player.move(2)
    if (key[pygame.K_s] or key[pygame.K_DOWN]):
        if not jumping:
            player_speed /= 2
        player.move(3)
    if key[pygame.K_a] or key[pygame.K_LEFT]:
        player.move(4)

player = Player()
sprites.add(player)

# PROGRAM
while running:
    clock.tick(FPS)

    # EVENT HANDLER

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                player.sneaking = False
                player.image = player_img
                player.rect = player.image.get_rect()
                player_speed = 8

    movements_handler()
    # UPDATE
    if player.jumping:
        if jump_height >= -15:
            player.rect.y -= decimal.Decimal((jump_height ** 2) / 2) if jump_height >= 0 else -decimal.Decimal((jump_height ** 2) / 2)
            jump_height -= 1
        else:
            player.jumping = False
            player.rect.y += 8
            jump_height = 15

    # RENDER
    main_window.fill('white')
    sprites.draw(main_window)
    pygame.display.flip()

# QUIT
pygame.quit()

Получилось немного стабилизировать это с помощью модуля decimal + отнимая каждый раз от высоты 8 пикселей, но мне нужен какой нибудь более универсальный/надежный способ.


text:
Q: CSV con ; Python Tengo un problema con un CSV que esta separado por ; y no por , como siempre acostumbre. Hice mi código hace un tiempo y funciona con CSV separados por ,, y quiero convertirlo (el código) a valores separados por ; o bien sino convertir mi CSV separado por ; a un CSV separado por ,
código:
# coding=utf-8
# encoding=utf8
"""..."""
import sys
from Tkinter import*
import Tkinter as tk
import csv
import pandas as pd
import os

reload(sys)
sys.setdefaultencoding('utf8')

b = "Working.csv"
"""Nueva Ventana."""
ventana = Tk()

"""Dimenciones de la ventana."""
ventana.geometry("1100x900+0+0")

"""Titulo."""
ventana.title("CSV TOOLS")

"""Texto."""
lblUsuario = Label(text="Bienvenidos a CSV Tools", font=("Agency FB", 22)).place(x=10, y=10)

"""Cargar CSV."""
lblUsuario = Label(text="Cargar CSV", font=("Agency FB", 14)).place(x=10, y=100)

"""Campo de texto."""
entradaU = StringVar()
txtUsuario = Entry(ventana, textvariable=entradaU).place(x=10, y=150)

"""Boton."""

def aceptar():
    """."""
    global a
    a = entradaU.get()
    if a == "exit":
        raise SystemExit
    else:
        pass
    try:
        with open(a, 'rb') as f:
            reader = csv.reader(f)
            global lista2
            lista2 = list(reader)
            lstmaterias = Label(ventana, text="Cabeceras:                                  ").place(x=10, y=180)
            lstmaterias = Listbox(ventana, width=100, height=10)
            global lista22
            lista22 = ' '.join(str(e) for e in lista2[0])
            lstmaterias.insert(0, lista22)
            lstmaterias.place(x=10, y=200)
            global entrada2
            entrada2 = StringVar()
            lstmaterias222 = Label(ventana, text="Filtro").place(x=10, y=400)
            global txtusuarijjo
            txtusuarijjo = Entry(ventana, textvariable=entrada2).place(x=10, y=420)
            filtro = Button(ventana, text="   Aceptar   ", command=orden, font=("Agency FB", 10)).place(x=210, y=420)

    except IOError:
        lstmaterias = Label(ventana, text="Error:").place(x=10, y=180)
        lstmaterias = Label(ventana, text="Archivo No Encontrado").place(x=40, y=180)
    with open(a, 'rb') as f:
        reader = csv.reader(f)
        row_count = sum(1 for row in reader)
        row_count = row_count - 1
        row_count_text = Label(ventana, text="Numero de Filas:").place(x=300, y=148)
        row_count_text = Label(ventana, text=row_count).place(x=400, y=148)

aceptar = Button(ventana, text="   Aceptar   ", command=aceptar, font=("Agency FB", 10)).place(x=210, y=148)

def orden():
    """."""
    global a_orden
    a_orden = entrada2.get()
    if a_orden == "exit":
        raise SystemExit
    if len(entrada2.get()) == 0:
        return a_orden
    if a_orden not in lista22:
        a_orden

    else:
        if a_orden in lista22:
            global entrada3
            entrada3 = StringVar()
            lstmaterias = Label(ventana, text="Ascendente:").place(x=350, y=400)
            lstmaterias = Label(ventana, text="(True - Flase)").place(x=350, y=450)
            txtusuario = Entry(ventana, textvariable=entrada3).place(x=350, y=420)
            global f
            f = entrada3.get()
            true_false = Button(ventana, text="   Aceptar   ", command=valores, font=("Agency FB", 10)).place(x=550, y=420)
            global entrada4
            entrada4 = StringVar()
            lstmaterias = Label(ventana, text="Cantidad de datos:").place(x=700, y=400)
            txtusuario = Entry(ventana, textvariable=entrada4).place(x=700, y=420)
            true_false = Button(ventana, text="   Aceptar   ", command=top, font=("Agency FB", 10)).place(x=900, y=420)

def top():
    """."""
    nn = entrada4.get()
    nn = int(nn)
    movies = pd.read_csv(b, nrows=nn)
    movies = movies.to_csv(b, index=False)

def valores():
    """."""
    mayor_menor = "True", "False"
    if len(entrada3.get()) == 0:
        return valores
    else:
        if entrada3.get() not in mayor_menor:
            return valores
        else:
            pass
    movies = pd.read_csv(a, error_bad_lines=False, delimiter=',', encoding="utf-8-sig", low_memory=False)
    movies = movies.sort_values(a_orden, ascending=f)
    movies = movies.to_csv(b, index=False)
    global entrada5
    entrada5 = StringVar()
    lstmaterias = Label(ventana, text="Nombre del Archivo Nuevo:").place(x=10, y=500)
    txtusuario = Entry(ventana, textvariable=entrada5).place(x=10, y=520)
    true_false = Button(ventana, text="   Aceptar   ", command=new_csv, font=("Agency FB", 10)).place(x=210, y=520)

    global entrada6
    entrada6 = StringVar()
    lstmaterias2 = Label(ventana, text="Introduzca las Cabeceras:").place(x=350, y=500)
    txtusuario2 = Entry(ventana, textvariable=entrada6).place(x=350, y=520)
    true_false2 = Button(ventana, text="   Aceptar   ", command=cabex, font=("Agency FB", 10)).place(x=550, y=520)

def new_csv():
    """."""
    global a_valor
    a_valor = entrada5.get()
    if a_valor == "exit":
        raise SystemExit

def cabex():
    """."""
    global a_cabex
    a_cabex = entrada6.get()
    a_cabex = a_cabex.split()
    with open(b, 'r') as csvfile, open(a_valor, "wb") as output:
        reader = csv.DictReader(csvfile)
        writer = csv.DictWriter(output, fieldnames=a_cabex, extrasaction='ignore')
        writer.writeheader()
        for row in reader:
            a = 'fillRate'
            if a in lista2[0]:
                row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
            writer.writerow(row)
    os.remove(b)

    lstmsss = Label(ventana, text="Reporte Creado", font=("Agency FB", 30)).place(x=350, y=600)

ventana.mainloop()

input()


text:
Q: Prevent script running with same arguments twice We are looking into building a logcheck script that will tail a given log file and email when the given arguments are found.  I am having trouble accurately determining if another version of this script is running with at least one of the same arguments against the same file.  Script can take the following:
logcheck -i <filename(s)> <searchCriterion> <optionalEmailAddresses>

I have tried to use ps aux with a series of grep, sed, and cut, but it always ends up being more code than the script itself and seldom works very efficiently.  Is there an efficient way to tell if another version of this script is running with the same filename and search criteria? A few examples of input:
EX1 .\logcheck -i file1,file2,file3 "foo string 0123" email@address.com
EX2 .\logcheck -s file1 Hello,World,Foo
EX3 .\logcheck -i file3 foo email@address1.com,email@address2.com

In this case 3 should not run because 1 is already running with parameters file3 and foo.

A: There are many solutions for your problem, I would recommend creating a lock file, with the following format:
arg1Ex1 PID#(Ex1)
arg2Ex1 PID#(Ex1)
arg3Ex1 PID#(Ex1)
arg4Ex1 PID#(Ex1)
arg1Ex2 PID#(Ex2)
arg2Ex2 PID#(Ex2)
arg3Ex2 PID#(Ex2)
arg4Ex2 PID#(Ex2)

when your script starts:

*

*It will search in the file for all the arguments it has received (awk command or grep)

*If one of the arguments is present in the list, fetch the process PID (awk 'print $2' for example) to check if it is still running (ps) (double check for concurrency and in case of process ended abnormally previously garbage might remain inside the file)

*If the PID is still there, the script will not run

*Else append the arguments to the lock file with the current process PID and run the script.

*At the end, of the execution you remove the lines that contains the arguments that have been used by the script, or remove all lines with its PID.


text:
Q: Global variable messes up my recursive function I've just run into a tricky issue. The following code is supposed to split words into chunks of length numOfChar. The function calls itself, which makes it impossible to have the resulting list (res) inside the function. But if I keep it outside as a global variable, then every subsequent call of the function with different input values leads to a wrong result because res doesn't get cleared.
Can anyone help me out?
Here's the code
(in case you are interested, this is problem 7-23 from PySchools.com):
res = []

def splitWord(word, numOfChar):
    if len(word) > 0:
        res.append(word[:numOfChar])
        splitWord(word[numOfChar:], numOfChar)
    return res

print splitWord('google', 2)
print splitWord('google', 3)
print splitWord('apple', 1)
print splitWord('apple', 4)

A: A pure recursive function should not modify the global state, this counts as a side effect.
Instead of appending-and-recursion, try this:
def splitWord(word, numOfChar):
    if len(word) > 0:
        return [word[:numOfChar]] + splitWord(word[numOfChar:], numOfChar)
    else:
        return []

Here, you chop the word into pieces one piece at a time, on every call while going down, and then rebuild the pieces into a list while going up.
This is a common pattern called tail recursion.
P.S. As @e-satis notes, recursion is not an efficient way to do this in Python. See also @e-satis's answer for a more elaborate example of tail recursion, along with a more Pythonic way to solve the problem using generators.

A: Recursion is completely unnecessary here:
def splitWord(word, numOfChar):
   return [word[i:i+numOfChar] for i in xrange(0, len(word), numOfChar)]

If you insist on a recursive solution, it is a good idea to avoid global variables (they make it really tricky to reason about what's going on). Here is one way to do it:
def splitWord(word, numOfChar):
   if len(word) > 0:
      return [word[:numOfChar]] + splitWord(word[numOfChar:], numOfChar)
   else:
      return []

A: To elaborate on @Helgi answer, here is a more performant recursive implémentation. It updates the list instead of summing two lists (which results in the creation of a new object every time).
This pattern forces you to pass a list object as third parameter.
def split_word(word, num_of_chars, tail):

    if len(word) > 0:
        tail.append(word[:num_of_chars])
        return split_word(word[num_of_chars:], num_of_chars, tail)

    return tail

res = split_word('fdjskqmfjqdsklmfjm', 3, [])

Another advantage of this form, is that it allows tail recursion optimisation. It's useless in Python because it's not a language that performs such optimisation, but if you translate this code into Erlang or Lisp, you will get it for free.
Remember, in Python you are limited by the recursion stack, and there is no way out of it. This is why recursion is not the preferred method.
You would most likely use generators, using yield and itertools (a module to manipulate generators). Here is a very good example of a function that can split any iterable in chunks:
from itertools import chain, islice

def chunk(seq, chunksize, process=iter):
    it = iter(seq)
    while True:
        yield process(chain([it.next()], islice(it, chunksize - 1)))

Now it's a bit complicated if you start learning Python, so I'm not expecting you to fully get it now, but it's good that you can see this and know it exists. You'll come back to it later (we all did, Python iteration tools are overwhelming at first).
The benefits of this approach are:

*

*It can chunk ANY iterable, not just strings, but also lists, dictionaries, tuples, streams, files, sets, queryset, you name it...

*It accepts iterables of any length, and even one with an unknown length (think bytes stream here).

*It eats very few memory, as the best thing with generators is that they generate the values on the fly, one by one, and they don't store the previous results before computing the next.

*It returns chunks of any nature, meaning you can have a chunks of x letters, lists of x items, or even generators spitting out x items (which is the default).

*It returns a generator, and therefor can be use in a flow of other generators. Piping data from one generator to the other, bash style, is a wonderful Python ability.

To get the same result that with your function, you would do:
In [17]: list(chunk('fdjskqmfjqdsklmfjm', 3, ''.join))
Out[17]: ['fdj', 'skq', 'mfj', 'qds', 'klm', 'fjm']


text:
Q: Problems generating source map files with current Gulp setup I have set up a gulpfile.js in my project. It's working pretty nicely mostly, except when it comes to generating source maps, especially for the LESS files it compiles to CSS.
I have put together a gist which contains all the files in my gulp setup. Please note that other than the gulp file.js itself, all the other files are inside a directory called tasks.
The problems I am having are that

*

*I had to disable the autoprefixer in development because the source maps that were being generated were invalid as the autoprefixer modified the original CSS file after the source maps were generated. To compensate, I have added mixins that add the vendor prefixes during development, and I have to disable those for development and enable the autoprefixer for the production environment.

*I am unable to generate a minified CSS file at all if I want source maps. The minification breaks the source maps.

*Although I have LiveReload set up, and the associated browser plugins, I cannot get the CSS to get auto-injected into the page as I am making changes.

If anyone can help me structure my gulp file.js to work more efficiently and more effectively, I would appreciate it.
Again, my gulpfile.js and associated tasks are in this gist.

A:
I had to disable the autoprefixer in development because the source maps that were being generated

The docs at https://www.npmjs.com/package/gulp-autoprefixer describe how to use the autoprefixer with gulp-sourcemaps:
gulp.task('default', function () {
    return gulp.src('src/**/*.css')
        .pipe(sourcemaps.init())
        .pipe(autoprefixer())
        .pipe(concat('all.css'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('dist'));
});

The above create a new source map for all.css. So you should load the sourcemap generated by the less compiler first, see https://github.com/floridoo/gulp-sourcemaps#load-existing-source-maps
The docs of gulp-minify-css do not describe such an usage, but possible you can do:
gulp.task('minify-css', function() {
  gulp.src('./static/css/*.css')
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(minifyCSS({keepBreaks:true}))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('./dist/'))
});

Notice that in most cases you minify only your code for production. Development code, which has source maps should not have to be minified.
Since version 2 of Less you can use plugins for the Less compiler. Also gulp-less allows you to use these plugins (programmatic) see also http://lesscss.org/usage/#plugins-using-a-plugin-in-code
Documentation of gulp-less describes how to use the clean-css and autoprefix plugin at https://github.com/plus3network/gulp-less#plugins. Notice that gulp-minify-css is leveraging clean-css's code too.
Also the usage of gulp-less with gulp-sourcemaps to create sourcemaps has been described at https://github.com/plus3network/gulp-less#source-maps
So you should be able to use:
var LessPluginCleanCSS = require("less-plugin-clean-css"),
    cleancss = new LessPluginCleanCSS({advanced: true});

var LessPluginAutoPrefix = require('less-plugin-autoprefix'),
    autoprefix= new LessPluginAutoPrefix({browsers: ["last 2 versions"]});

gulp.src('./less/**/*.less')
  .pipe(sourcemaps.init())
  .pipe(less({
    plugins: [autoprefix, cleancss]
   }))
  .pipe(sourcemaps.write('./maps'))
  .pipe(gulp.dest('./public/css'));

The above should generate the autoprefixed and minified CSS of your Less source, with CSS sourcemaps written into ./public/css/maps


text:
Q: message queuing patterns We have two pieces of architecture. In essence they form a producer and a consumer. Piece 1 (p1) publishes messages to Piece 2 (p2) which processes the message, this process involves sending the message to a remote node, which must ack the message once it has processed it, this process can take a few seconds at best.
p2 has a finite length in its queue and items are not removed until it receives the ack from the remote node. Due to this p2 can return a QUEUE_FULL response to p1. When p1 receives this response it keeps a queue, whenever a new message is produced it adds it to the end of this queue and then cycles through the queue sending messages to p2 until it once again gets a QUEUE_FULL. The problem here is that once p2's queue is empty/has space it isn't able to notify p1 to produce the messages.
For each instance of producer in p2 there is a corresponding producer in p1, this is important when it comes to the potential solutions below.
One solution could be that p2 could be changed to notify p1 when there is space in its queue, however this solution requires a fair amount of network overhead (http) as it is feasible at any one time many thousands of p2 queues need to notify their corresponding p1 producers.
The other solution could be that p1 could be changed to keep attempting to send the message to p2. The problem with this is that a producer in p1 needs to have a thread that sleeps x before trying to send the next message, clearly there could be a singleton that handles this sleep/retry mechanism however the logic here, as producers and consumers increases to many thousands, gets rather complex;

*

*synchronization on adding, removing, producers

*reading queues, making next read times

*considerations for tight looping when low producer count

*considerations for long waits when high producer count

*.... etc

I'm close to suggesting a MQ tier where p1 publishes to and p2 reads from. However this introduces a new issue where p2 is not able to notify p1 when the remote node goes away, however this could be handled by a http call back from p2 to p1 - the level of overhead here is acceptable as the chance the remote node goes away is low.
Am I missing a design pattern which would remove the need for an MQ (yet another service to worry about, monitor, etc)? Thoughts much appreciated.
Some other details:

*

*each p1 producer instance is request scoped for the most part

*each p2 consumer is a dedicated running thread

A: Mike,
It seems like the process has a significant amount of complexity (with the possibility of introducing more) just to avoid using MQ?  There may be plenty of reasons NOT to use MQ, cost in my experience, but if you have access to it, use it with wild abandon! :)  Its far easier to monitor the new MQ process than it is to write the code to introduce like capabilities.
Ideally, a robust queue would prevent P1 ever really needing to know about P2, or its status.
MQ should also really mitigate the need for P2 to notify P1 that its remote node went down - P1 can continue to happily queue up messages to P2 (depending on message frequency/size/storage limits).  If the remote node is down for a significant amount of time, then hopefully it was a planned event and operators can shutdown P1.  The administrative channel between P2 and P1 sounds like a nice to have?
It also introduces additional complexity - you know your environment, but it can lead to questions like "why am I not getting messages anymore?" - turns out that a service autonomously shutdown another service.  Done right, this is awesome and relieves a support burden for the operators - done wrong, it just adds more support burden.  Nobody likes that guy.
Could you also queue at the data tier, where storage for P2 might not be as much of an issue?
Embrace the queue (MQ, MSMQ, Sql Queue)!
Z

A: Review 3 possibility

*

*What about open yet another MQ for service commands (instead of http invocations);

*consider p2 be multithread, where one thread without waits extracts messages from MQ, and places them to another thread for processing;

*(!) use transactional version of MQ - so p2 could extract messages immediatly and p1 can place it as fast as it can. But if processing fails, queue will be rolled back.


text:
Q: Finding someone willing to train programming in a certain area Is there a way on Stack Overflow or here on meta to find people willing to train a programming language in a certain town or city?
After searching extensively on google and many different websites ive not been able to track down a tutor in Doncaster or nearby to teach me ASP.net and C# on a weekend.
Is it acceptable to post this kind of question on here or Stack Overflow?

A: Not on Stack Overflow itself.
You might want to ask in chat


text:
Q: What size to pick for a (n)varchar column? In a slightly heated discussion on TDWTF a question arose about the size of varchar columns in a DB.
For example, take a field that contains the name of a person (just name, no surname). It's quite easy to see that it will not be very long. Most people have names with less than 10 characters, and few are those above 20. If you would make your column, say, varchar(50), it would definately hold all the names you would ever encounter.
However for most DBMS it makes no difference in size or speed whether you make a varchar(50) or a varchar(255).
So why do people try to make their columns as small as possible? I understand that in some case you might indeed want to place a limit on the length of the string, but mostly that's not so. And a wider margin will only be beneficial if there is a rare case of a person with an extremely long name.

Added: People want references to the statement about "no difference in size or speed". OK. Here they are:

For MSSQL: http://msdn.microsoft.com/en-us/library/ms176089.aspx

The storage size is the actual length of data entered + 2 bytes.

For MySQL: http://dev.mysql.com/doc/refman/5.1/en/storage-requirements.html

L + 1 bytes if column values require 0 – 255 bytes, L + 2 bytes if values may require more than 255 bytes

I cannot find documentation for Oracle and I have not worked with other DBMS. But I have no reason to believe it is any different there.

A: I have heard the query optimizer does take varchar length into consideration, though I can't find a reference.
Defining a varchar length helps communicate intent. The more contraints defined, the more reliable the data.

A: So why do people try to make their columns as small as possible? I don't believe in making them as small as possible, but sizing them appropriately. Some reasons for making (n)varchars smaller rather than larger:
1) With a larger field, all clients that use the database must be able to handle the full size. For example, take a system that holds a United States address with 255 characters per each field: (Similar to TDWTF that you reference, I believe.)

*

*First Name

*Last Name

*Address Line 1

*Address Line 2

*City

*State

*ZIP Code

Now your data entry screens will need to allow and show 255 characters per field. Not hard, but unlikely to look nice with larger fields Printing invoices, you will need line breaking logic to handle the large fields. Depending on tool, not that hard.
But I would not want the problem of formatting the address for an envelope that could have 255 characters for each of those fields or just any one of those fields. Are you going to truncate if the field is too long to fit? Great someone has Address Line 1 of "House Number Streat Number ... blah blah blah ... Appartment number 111." And you'll lop off the important apartment number. Are you going to wrap? How much? What if you just can't fit it in the little box of space on the envelop? Raise an exception and have someone hand letter it?
2) While 10 characters of data held in a varchar(50) versus varchar(255) does not impact size or speed, allowing 255 characters allows for more space to be taken. And if all fields are that large you could hit size limits in SQL Server 2000. (I haven't read up on 2005 & 2008 to see if they can handle rows greater than one page.) And with Oracle you the larger sizes allows row chaining to happen if someone actually uses all the available characters.
3) Indexes have stricter size limits then leaf pages. You may preclude indexes, especially composite indexes, if you create your varchars too big.

On the other hand, I have a long line 1 for my address, and have been frustrated by web sites that don't allow the full thing to be typed.

A: One important distinction is between specifying an arbitrarily large limit [e.g. VARCHAR(2000)], and using a datatype that does not require a limit [e.g. VARCHAR(MAX) or TEXT].
PostgreSQL bases all its fixed-length VARCHARs on its unlimitted TEXT type, and dynamically decides per value how to store the value, including storing it out-of-page. The length specifier in this case really is just a constraint, and its use is actually discouraged. (ref)
Other DBMSs require the user to select if they require "unlimitted", out-of-page, storage, usually with an associated cost in convenience and/or performance.
If there is an advantage in using VARCHAR(<n>) over VARCHAR(MAX) or TEXT, it follows that you must select a value for <n> when designing your tables. Assuming there is some maximum width of a table row, or index entry, the following constraints must apply:

*

*<n> must be less than or equal to <max width>

*if <n> = <max width>, the table/index can have only 1 column

*in general, the table/index can only have <x> columns where (on average) <n> = <max width> / <x>
It is therefore not the case that the value of <n> acts only as a constraint, and the choice of <n> must be part of the design. (Even if there is no hard limit in your DBMS, there may well be performance reasons to keep the width within a certain limit.)
You could use the above rules to assign a maximum value of <n>, based on the expected architecture of your table (taking into account the impact of future changes). However, it makes more sense to define the minimum value of <n>, based on the expected data in each column. Most likely, you will expand to the nearest "round number" - e.g. you will always use either VARCHAR(10), VARCHAR(50), VARCHAR(200), or VARCHAR(1000), whichever is the best fit.

A: I can only speak for Oracle. A VARCHAR2(50) and a VARCHAR2(255) take up exactly the same amount of space and perform identically, if you enter the value 'SMITH'.
However, the reason why it is generally not a good idea to go around declaring all your textual columns as VARCHAR2(4000) is that column length is, effectively, another constraint. And constraints are database implementation of business rules, so they are definitely something that should be defined on the database side of things.
As a for-example. You define a CHECK constraint on a column so that the values it can accept are only 'Y' and 'N'. That saves your application from having to deal with 'y' and 'n' or even '1' and '0'. The check constraint ensures your data conforms to expected standards. Your application code can then make valid assumptions about the nature of the data it has to deal with.
Column length definition is in the same boat. You declare something to be a VARCHAR2(10) because you don't want it accepting an entry of 'ABC123ZYX456' (for whatever reason!)
In Australia, I define STATE columns to be a varchar2(3) because I don't want people typing in 'New South Wales' or 'South Australia'. The column definition pretty much forces them to be entered as 'NSW' and 'SA'. In that sense, a VARCHAR2(3) is almost as much a check constraint as actually specifying a CHECK IN ('NSW','SA','VIC' etc) constraint.
In short, proper column lengths are a way of encoding business rules. They're another form of constraint. They bring all the advantages of constraints (and suffer from many of the same drawbacks). And they ensure, to a small extent, a degree of 'data cleanliness' that "proper" constraints help with, too.
I don't buy the argument, either, that it's best to stick these sorts of things in the client app because it's easier to change there. You have 20,000 people using an app, that's 20,000 updates. You have one database, that's one update. The 'easier to change the client app' argument, if true, would potentially mean the database just gets treated as a giant bit bucket with all the clever logic being handled in client code. It's a big discussion to have, but since all RDBMSes let you define constraints and so on in the database itself, it's pretty clear that there's at least a worthwhile case to be made that such fundamental logic belongs in the backend.

A: Simple answer to this in my opinion is the fact that you cannot use that column as an index key, if you require any indexing you are basically forced to use fulltext... this is with regards to using a varchar(max) column. In any case 'right-sizing' columns makes a lot of sense whenever you [may] want to apply any indexing; updating variable length columns may be a costly maneuver as these are not done in place and can/will cause some amount of fragmentation.
All with regard to MS SQ-Server.

A: I'll answer your question with a question: If there is no difference to the DBMS between a varchar(50) and a varchar(255), why would the DBMS let you make a distinction?  Why wouldn't a DBMS simply say "use varchar for up to xxx characters, and text/clob/etc. for anything over that."  Sure, perhaps Microsoft/Oracle/IBM might keep the length definition for historical reasons, but what about DBMS' like MySQL which has multiple storage backends- why does every one implement definable character column lengths?

A: If you are going to print labels you usually want the string to be no longer than 35 characters. This is why you want some control on the size of the Varchar that you are going to use to accept
the lines that are going to be used to print labels.

A: If you allow the data length to be over 255 and someone links to the data through MS Access the data is not able to be used to join tables (comes in as a memo field).  If the data is exported to excel it will be limited to 255 characters per field.  Compatibility with other programs should be considered when creating data sets.
Data quality control is all about controlling the data entering your environment.  What do you need to store that is over 255 characters? There are times that data needs to be over 255 characters, but they should be far and few between and should be used as supportive supplemental information for a field that can be used for analysis

A: Size do matter, and it CAN affect performance! In mssql the execution planner makes assumptions and this assumption can hurt, when planning a sort of a varchar column, the planner predict average row size to 50% of declared length, + a little for overhead, so if you declare varchar(200) the execution planner estimate row size to around 110 bytes, and if the rows is filled to 80% the execution plan will be forced to use tempdb to sort the rows instead of in memory sort. I have made proof and full example available here: https://kisunu.no/index.php?pid=20130


text:
Q: Роутинг при помощи java web server Jetty Я достаточно долгое время писал весь бэкэнд на Jetty с использованием только сервлетов. (jsp не тогал так как не было необходимости)
Недавно меня попросили добавить некоторые фичи в уже имеющийся проект на php/laravel. Начав разбираться что это за фреймворк (laravel) я наткнулся на очень приятную фичу -- роутинг и контроллеры. И тут у меня появилось желание использовать такой же механизм в своих Jetty серверах.
Коротко: я хочу примерно такое:
//...
Route::get("/", "MainController@index");
Route::get("/{postId}", "MainController@SinglePost");
Route::any("/test", function () {
    return "
test
";
});
//...
Route::get("/events/add", "EventController@showCreateForm"); // при get запросе возвращаем юзеру форму для заполнения
Route::post("/events/add", "EventController@addEvent"); // при post запросе добавляем данные, отправленные юзером

Мне подобный стиль организации запросов на сервере сильно понравился и я решил погуглить подобную надстройку для Jetty. В итоге я получил bladejava и spark, поняв что этих библиотек не одна, я решил написать сюда. Подскажите, какие из подобных библиотек ещё есть и какая из них лучше.


text:
Q: Testing with JMeter:How to simulate load in Jmeter I need to conduct load testing for an application based on the below scenario:
No of stores: 1307
No of users: 1307 x 4 = 5228
Average transactions per day per store: 5 transactions
Total transaction per month for all stores: 1307 x 5 x 30 = 196,050
What will be the virtual users required??and how to simuate it in JMETER .

A: 196050 / 30 (days in month) / 24 (hours in day) / 60 (minutes in hour) = 4.5 requests per minute.
It means 1 request each 13 seconds. I don't think that you even need JMeter to produce such a "load".
If you do - consider using Constant Throughput Timer, it allows to specify target throughput in "requests per minute".
There is more advanced version available via JMeter Plugins project - Throughput Shaping Timer which is more precise, acts on "seconds" level and provides options to set stepping ramp-up and ramp-down load.


text:
Q: select between two dates based on month and year periodic mysql How do I implement the MySQL for selecting data between. Let say I have a variable:
$dateA = '2014-06-25'
$dateB = '2014-08-26'

I make an example MySQL syntax like this:
"select * from table where dateA >= $dateA and dateB <= $dateB"

So I want to make a selection to MySQL using those 2 dates based on the month and year only not including the date itself:
Any ideas about this?
UPDATE
For example all I want to do is like this basically:
"select * from table where dateA >= '2014-06' and dateB <= '2014-08'"

That's basically what I want.

A: You can use a string comparison.
DATE_FORMAT(dateA,'%Y%m') should return dates like: 201406.  You would also need to change the format of your variables or use the same method on them.
where DATE_FORMAT(dateA,'%Y%m') >= DATE_FORMAT($dateA,'%Y%m') and
DATE_FORMAT(dateB,'%Y%m') <= DATE_FORMAT($dateB,'%Y%m')

A: select *
from table
where dateA between date_format( $dateA, '%y-%m-01' ) and last_day( $dateB );

A: select * from table where YEAR(dateA) > YEAR($dateA) and YEAR(dateB) < YEAR($dateB)
    AND MONTH(dateA) > MONTH($dateA) and MONTH(dateB) < MONTH($dateB)

Theres probalby something much more efficient out there, bt this will do too

A: i suggest making the change in php as this enables mysql query cache for wider range of inputs:
$dateA = date("Y-m-01", strtotime('2014-06-25'));
$dateB = date("Y-m-t", strtotime('2014-08-26'));

A: $dateA = '2014-06-25';
$dateB = '2014-08-26';
$dateA_month = '2014-02-01';
$dateB_month = '2014-02-31';
"select * from table where dateA >= $dateA_month and dateB <= $dateB_month";

I wrote the exmaple on purpose with february. This selector works well even is the month in question does not end with 31th. Expecting downvotes from calendar-fans:)

A: Use the following SQL Statement for selecting the data between the two date:-
$dateA = date('Y-m-d', strtotime('2014-06-25'));
$dateB = date('Y-m-d', strtotime('2014-08-26'));

SELECT * FROM table_name WHERE DATE_FORMAT(date_created, '%Y-%m-%d')

BETWEEN $dateA AND $dateB;

A: You can use this
WHERE (someField BETWEEN '2016-01-30 14:15:55' AND '2016-09-29 10:15:55')

A: Try this:
"select * from table where [datetime_column] between " . $dateA . " and " .$dataB


text:
Q: How to replace value in JSON object in Node.js I want to replace the value in existing JSON object in Node.js
Code :
var designationName='Softwar Engineer';
console.log(generateData[0]);

Console Output:
{
email: 'xxxxxx@gmail.com',
designation: 10,
id: 274,
first_name: 'firstname',
mobile: '1234567890',
last_name: 'lastname'
}

In the above console output 'designation' value printed as '10'
Expected Result:
I want to replace "designation: Software Engineer" instead of "designation:10"

A: Considering generateData[0] contains the following json which you fetch from a database
 {
  email: 'xxxxxx@gmail.com',
  designation: 10,
  id: 274,
  first_name: 'firstname',
  mobile: '1234567890',
  last_name: 'lastname'
 };

To replace "designation: Software Engineer" instead of "designation:10"
var designationName = 'Software Engineer';
if(generateData[0]){
 generateData[0]['designation']= designationName;
}
console.log(generateData[0]);

A: var designationName='Softwar Engineer';
if( generateData.length && generateData[0].designation)
{
    generateData[0].designation = designationName;
}
console.log(generateData[0]);


text:
Q: Класс с вложенным классом-массивом с методами управления этим массивом В ListView есть Items и SubItems. Код ниже добавляет к Item'у новый SubItem и получает ссылку на него для выставления свойств:
procedure P;
var
  Item: TListItem;
begin
  Item := ListView.Items.Add();
  Item.SubItems.Add('');
end;

Пытаюсь сделать наподобие, где будет возможность добавлять новые упражнения в массив упражнений через метод класса:
interface

{ Класс для хранения информации об упражнении }
type
TExerciseItem = class
private
  FName, FContent: String;
public
  property ExerciseName: String read FName write FName;
  property ExerciseContent: String read FContent write FContent;
end;

{ Массив упражнений }
type
TArrItemsOfExercises = array of TExerciseItem;

{ Класс для управления массивом упражнений }
type
TExercises = class
private
  FExercises: TArrItemsOfExercises;

  function GetExerciseItem(AIndex: Integer): TExerciseItem;
public
  property Items[AIndex: Integer]: TExerciseItem read GetExerciseItem;

  function Add(const ExerciseName, ExerciseContent: String): TExerciseItem;
end;

implementation

function TExercises.GetExerciseItem;
begin
  Result := FExercises[AIndex];
end;

function TExercises.Add;
var
  Count: Integer;
begin
  Count := Length(FExercises);
  SetLength(FExercises, Count + 1);

  with FExercises[Count] do
  begin
    FName := ExerciseName;
    FContent := ExerciseContent;
  end;

  Result := FExercises[Count];
end;

Теперь описываю класс для хранения информации об уроке и какие упражнения к нему привязаны:
interface

{ Класс для хранения информации об уроке }
type
TLessonItem = class
private
  FName: String;
  FExercises: TExercises;

  function GetSubItem(AIndex: Integer): //Что должно быть здесь?;
public
  property LessonName: String read FName write FName;
  property SubItems[AIndex: Integer]: //И здесь? read GetSubItem;

  constructor Create();
end;

implementation

constructor TLessonItem.Create;
begin
  FExercises := TExercises.Create();
end;

И вот тут возникает вопрос: как использовать уже готовое решение из класса TExercises для управления массивом упражнений, чтобы можно было использовать методы этого класса.
После описания этого класса, я, по аналогии с классом упражнений, пишу дальше:
{ Массив уроков }
type
TArrItemsOfLessons = array of TLessonItem;

{ Класс для управления массивом уроков }
type
TLessons = class
private
  FLessons: TArrItemsOfLessons;

  function GetLessonItem[AIndex: Integer]: TLessonItem;
public
  property Items[AIndex: Integer]: TLessonItem read GetLessonItem;

  function Add(const LessonName: String): TLessonItem;
end;

Как мне доработать классы, чтобы можно было использовать вложенный массив упражнений, по аналогии с примером про ListView?

A: TLessonItem = class
private
  FName: String;
  FExercises: TExercises;

  function GetSubItem(AIndex: Integer): TExerciseItem;
public
  property LessonName: String read FName write FName;
  property SubItems[AIndex: Integer]: TExerciseItem read GetSubItem;

  constructor Create();
end;

function TLessonItem.GetSubItem(AIndex: Integer): TExerciseItem;
begin
  result := FExercises.Items[AIndex];
end;

NB:
TExercises = class
...
  destructor Destroy; override;
end;

destructor TExercises.Destroy;
var
  iter: integer;
begin
  for iter := 0 to Length(FExercises) - 1 do
    FExercises[iter].Free;
  SetLength(FExercises, 0);
  inherited;
end;

function TExercises.Add;
var
  Count: Integer;
begin
  Count := Length(FExercises);
  SetLength(FExercises, Count + 1);

  FExercises[Count] := TExerciseItem.Create; // !!!

  with FExercises[Count] do
  begin
    FName := ExerciseName;
    FContent := ExerciseContent;
  end;

  Result := FExercises[Count];
end;

Позвольте пару слов о выборе имен для элементов кода.
Я бы заменил TExerciseItem на TExercise. И уж точно бы убрал из названий свойств слово "Exercise". Речь и так идет о TExerciseItem, понятно, что свойства Name и Content относятся к "Exercise".


text:
Q: Basic QR code scanner in flutter + qr_code_scanner returning results repeated I am building a QR scanner to help organize a collection. Basic data about the items is encoded into a json string then into a QR code. The generation of such labels programatically was successful. The next phase was to create a simple visor in flutter. The chosen library was qr_code_scanner. My simple app was to be a scanner which when detecting a valid QR code (one containing a json string describing the required structures) would redirect into another screen where data was displayed. The scanner detects the QR codes, the objects are parsed and a widget containing another scaffold is pushed. This is mostly what I want however an issue was detected: when a valid QR was detected the app would push the data display screen multiple times, sometimes as many as 9, thus breaking backward navigation.
The method responsible of handling the event is named "onQRViewCreated" (like in the example).
void onQRViewCreated(QRViewController controller){
    setState(() => this.controller = controller);
    controller.scannedDataStream.listen(
            (qrData) {
            setState(
                    () {
                  barcode = qrData;
                  if (barcode?.format == BarcodeFormat.qrcode) {
                    try {
                      Item item = Item.fromJSon(
                          jsonDecode(barcode?.code ?? "")
                      );
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  ItemDisplay(
                                      key: const Key("item"),
                                      item: item
                                  )
                          )
                      );
                    }
                    on FormatException {
                      Fluttertoast.showToast(msg: "Invalid QR Code!");
                    }
                    on Exception {
                      Fluttertoast.showToast(msg: "Error!");
                    }
                  }
                }
            );
          }
    );
  }

I would like to be able to push the ItemDisplay only once but I don't know how to do it.
Thank you in advance

A: Put await controller.pauseCamera(); before the Navigator.push

A: I would suggest to use mobile_scanner package, which is a newer version from the same author. When creating MobileScanner widget of this package, there is an option allowDuplicates, which you can set to false to avoid this behaviour.


text:
Q: Fast string matching in R I'm attempting to do a word matching in a large data-set. I'm wondering if there is a way of speeding up the slowest operation in my workflow.
What I aim to do is to find the locations of the matches between a dictionary of words and a list of word vectors.
words <- c("cat", "dog", "snake", "cow")
scores <- c(1.5, 0.7, 3.5, 4.6)
dic <- data.frame(words, scores)

wordList <- list(c("jiraffe", "dog"), c("cat", "elephant"), c("snake", "cow"))

The fastest way I have found so far to do this is by doing this:
matches <- function(wordList) {
    subD <- which(dic$words %in% wordList)
}

My desired output is:
matches(wordList):
list(c(2), c(1), c(3, 4))

which I can later use to get the average score per wordList cell by doing
averageScore <- sapply(matches, function(x) {mean(dic[x, "scores"]})

Is there a faster way of doing the string matching than what I am doing in the function:
subD <- which(dic$words %in% wordList)

I have tried the dplyr way, thinking it might be faster, using first "filter" to get a subset of the "dic" and applying "colMeans" on it, but it seems to be twice as slow.
Also, running my matches function in a loop is just as slow as using "lapply" on it.
Am I missing something? Is there a way that is faster than both?

A: Here's one option:
library(data.table)
nn <- lengths(wordList)  ## Or, for < R-3.2.0, `nn <- sapply(wordList, length)`
dt <- data.table(grp=rep(seq_along(nn), times=nn), X = unlist(wordList), key="grp")
dt[,Score:=scores[chmatch(X,words)]]
dt[!is.na(Score), list(avgScore=mean(Score)), by="grp"]
#    grp avgScore
# 1:   1     0.70
# 2:   2     1.50
# 3:   3     4.05


text:
Q: bsxfun vs repmat using different sized matrix inputs to match indices I know there are already a lot of questions regarding how bsxfun is supposed to be faster than repmat, so I hope this question isn't too redundant.
I am using a short code with repmat. The purpose of this code is to identify indices between A and B where the row vectors are the same so I can later remove them, but using repmat takes far too long using Matlab R2016a.
[~,i] = min(abs(dot(A',repmat(B,length(A),1)')./sqrt(sum(A'.^2))./norm(B)-1));

Here A and B are not necessarily the same size, so using repmat doesn't seem to work in general anyway. Currently the size of A and B are 8020x3 and 21615x3. I have found that this method of making the sizes of A and B the same works but I am open to other methods as well.
if isequal(size(A),size(B))==1

else
    a = size(A,1);
    b = size(B,1);

    if a<b
        A = [A;nan(abs(B-A),3)];
    else
        B = [B;nan(abs(B-A),3)];
    end
end

I was looking at the bsxfun documentation and on this Mathworks site https://www.mathworks.com/matlabcentral/answers/297088-speed-up-indexing-repmat-operation and it seems like I should be able to replace repmat(B,length(A),1)' with bsxfun(@times, B, length(A)) but they do not output the same final array, so I must be doing something incorrect.
If possible I would like to modify my code above so that it takes less time to calculate, and also have A and B be different sizes such as given above if possible. If necessary, I can still work with A and B being the same size but they will be both be larger, in this case 571000x3 so the calculations will take longer for this reason as well.
Addition:
In the comments, it was discussed whether intersect would work. Theoretically, it should since A (black) and B are defined as being inside or outside the isosurface (red) within a larger volume T using the function inpolyhedron https://www.mathworks.com/matlabcentral/fileexchange/37856-inpolyhedron-are-points-inside-a-triangulated-volume-#comments. For some reason, the output of inpolyhedron is a set of the points within the isosurface with some scattered points outside as well. When using inpolyhedron to find the values outside the isosurface, these "extra" scattered points are not included in the set B, so intersect finds an empty set when inputting A and B.

A: So it turns out that the creator of inpolyhedron has a "patch" that mostly corrects this issue.
Essentially you need to move the points by a small amount.
Let's say all of my points are in an array called TestPoints.
TestPoints = combvec(x',y',z')';  % x, y, and z are column vectors
NudgedPoints = TestPoints + repmat([1e-10 1e-10 0],length(TestPoints),1);

Create a surface with faces and vertices from the data
[F,V] = isosurface(X,Y,Z,A,-3);   % you can use any value, and X, Y, and Z are positions from a meshgrid
in = inpolyhedron(F,V,NudgedPoints,'FlipNormals',false);
TestPoints_in = TestPoints(in,:);

All credit to this solution goes to Sven the creator of inpolyhedron. You can get in touch with him here.


text:
Q: How to Query this formula and it's possible to add automatically sort fucntion? I'm using this formula below but only show 2 column can I add like 6 - 8 column? and adding more function like sort from A-Z like 0-9 something?
=query(ArrayFormula({{unique(text('RAW'!M:M,"0"))}, {sumif(text('RAW'!M:M,"0"), unique(text('RAW'!M:M,"0")),'RAW'!AV:AV)}}),"Select * where Col2>0")


text:
Q: Does Java support BufferedImage with >8 bit depth? (Deep color) I'm averaging a few hundred images, and rounding errors makes it into grayish muddled mess.  If I could use BufferedImages that had >8 bits per channel, I bet that rounding wouldn't hurt me as much.
Is there a way to use the BufferedImage code on an underlying image that is a high bit depth image?  I mean >16m colors, >24bit, which is I believe called "Deep Color".

A: Yes, it does. :-)
There's no BufferedImage.TYPE_* for deep color though, so you have to create it in a slightly more verbose way than "usual". Also, as the resulting type will be TYPE_CUSTOM it is likely to be significantly slower to paint and display. But if you use it only as a temporary "work" image, this is probably not a major concern.
An example:
private BufferedImage create48BitRGBImage(int width, int height) {
    int precision = 16; // You could in theory use less than the full 16 bits/component (ie. 12 bits/component)
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel colorModel = new ComponentColorModel(colorSpace, new int[] {precision, precision, precision}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
    return new BufferedImage(colorModel, colorModel.createCompatibleWritableRaster(width, height), colorModel.isAlphaPremultiplied(), null);
}

If you want 64 bit ARGB, change the colorModel like this:
new ComponentColorModel(colorSpace, new int[] {precision, precision, precision, precision}, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_USHORT);


text:
Q: Repeat a conditional format rule to several columns I try to apply the following G sheet conditional format rule to several columns without the need to create such conditions manually. Here is the custom formula: =REGEXMATCH(LOWER($C:$C), "release|prod") which has been applied to the range C1:C990 as you can see within the picture

How caw we apply the same conditional format rule to columns D,E,F,G,...O

A: rewrite your custom formula to:
=REGEXMATCH(LOWER(C3), "release|prod")

and apply it to range C3:Z


text:
Q: Why is my usable RAM only half of my Installed RAM? I recently installed another 8GB of RAM, but my computer isn't able to use it. Apparently, it's all "hardware reserved." I don't think that Windows 10 needs 8GB of RAM to run, and I would like to be able to use the memory I installed. Can anyone help?
My MB is the MS-7693 970 Gaming by MSI, and the memory in question is Corsair Vengeance (CMZ8GX3M1A1600C10)

A: Read about mixing computer memory.
Identify your motherboard with powershell. See if your choice of motherboard and cpu supports 16GB of the type of memory you have installed by reading your manual.
Get-WmiObject -Class Win32_BaseBoard | Format-Table Manufacturer, Product, SerialNumber, Version

Identify your memory with powershell:
Get-WmiObject win32_physicalmemory | Format-Table Manufacturer,Banklabel,Configuredclockspeed,Devicelocator,Capacity,Serialnumber -autosize

If you have used a supported amount / type of memory read the following.
Windows 10 Won't Use Full RAM

*

*Modify RAM used on Boot

*BIOS limit Windows from using the full amount of RAM installed

*Windows 10 showed less amount of RAM usable due to a physical defect

A: Windows 10 detected a problem with the 8GB RAM that you recently installed, and is reserving it so that it does not get used.
Your computer may have one of these problems.

*

*The new RAM stick is bad.

*There is a bad memory slot in the motherboard. Try swapping the RAM stick around to another slot.

*The new RAM stick is not compatible with your computer's hardware.

Run the Memory Diagnostic tool in Windows 10 to troubleshoot the problem.

*

*Click the lower-left Start button on the desktop to expand the Start menu, and then select Settings in it.

*Type "Diagnose your computer's memory problem" in the search box and press Enter.

*Follow the on-screen instructions to run it.

If the new RAM is not compatible with the version of Windows 10 that is installed the Memory Diagnostic tool will report it.
If you have a Linux live USB handy, it may show a message about the RAM on the screen when booting the USB to a live session. If you take a photo of this message and search for it online it will help you to troubleshoot the problem. It has been my experience that if a RAM stick is bad the relevant message will appear on an otherwise empty black screen for less than a second right after the manufacturer's splash screen disappears when the computer is booting.

A: After going through hell and every possible solution out there I have another one to add to the list:

*

*Make ABSOLUTELY SURE that your RAM slots are not polluted. I had a tiny amount of dust in one of these slot's which caused this issue.

3 hours of troubleshooting because of this tiny dustcorn -_-
Everything back to normal now


text:
Q: jquery select elements with some attribute with the value I want to select the elements use the value of an attribute, however, the attribute with this value can be anything eg. href, action, id.
so, how can I select those elements?
Update:
In fact, I cannot find any example in this question, but it seems need to post some code to clear the question. So I try.
there is a JSON format data which contains a reference attribute. And I need to find elements which contains this reference. However, the element which be referenced to don't contain the reference attribute, the reference can be a href of an a tag element, also can be an action of a form, mostly, value of reference will appear more than one element in a page.
following code trying to find those elements
if(typeof reference != 'undefined'){
   $('[href="+reference+"]')
   $('[action="+reference+"]')
}

can I use one line to do this?

A: I think what your after is a way to select an element that has any attribute with a particular value.
There's no wild-card way to specify the name of the attribute (as far as I know), but if you can cope with listing out possible attribute names (as you hint with your code) then the way to do it would be like this :
var selecteds = $(
    '[href="' + reference + '"]' +
    ', [action="' + reference + '"]' +
    ', [class="' + reference + '"]' +

);

...and so on


text:
Q: Creating Scheme function that returns a custom map expression Thanks again for your help with my previous scheme questions! I've managed to be able to work through a lot of example questions online with very few hiccups thanks to everybody's help.
Yesterday I created a custom map function that works like the regular map function (or at least I think it does). Today I want to write a function that takes a regular map expression and returns a "my-map" expression.
Here is my definition for my custom map function
(define (mymap proc 1st))

so my new function would look something like this:
(createmymap '(map car '((w x) (y z)))

and return this list (It would return the list, not execute the function)
(mymap car '((w x) (y z)))

I tired to make this as clear as possible but please feel free to ask I know it's a pretty strange question.
Any help is greatly appreciated! Thanks again!


text:
Q: Linking to external page and append its HTML within the original page's wrapper automatically <?php include('header.php'); ?>

    //Here I want to keep appending the information without having to include
    //header and footer files in every external page

<?php include('footer.php'); ?>

Here's where you first land when entering the site:

Välkommen

Befintlig användare?

        Logga in

Ny användare?

        Registrera dig

Now if I click on "registrera dig" (register) I want to grab the contents of the file and append it to the #site-wrapper div above. As it works now it grabs the contents and loads a new page without the header and footer files being included since I don't have them as includes in the file. From my understanding I thought that Jquery Mobile would do this automatically but it doesn't, do I have to manually make an ajax call with Jquery and then append the content to the div or is there a way to make this happen automatically using already built-in Jquery Mobile functions? Haven't been able to find an answer from my searches so hopefully I can get one here.

A: You need AJAX to achieve this.
$( "#site-wrapper" ).load( "folder/page.html", function() {
 // Callback function
});

This snipped would solve your problem. Replace the url with your file!


text:
Q: net::ERR_INSECURE_RESPONSE when loading geojson file I'm looking for some help figuring out why this issue occurs and how to fix it. I'm trying to create an interactive map (replicate this). I have a .geojson file "capecchi.github.io/projects/AirQuality/static_temp.geojson" with all the data, but opening williamcapecchi.com/AirQuality/AQmap_static.html causes the error "net::ERR_INSECURE_RESPONSE" (When using Chrome-- It seems to work fine in IE). I've read other answers related to this error, but being new to development, I'm not sure what is causing this error in my case. After reading this thread I checked the security tab in developer, but instead of finding an explanation of the certificate problem, only saw this:
Any advice would be greatly appreciated!
Bill
*edit: apparently I can't add images to questions yet and so I'll explain: when I check the security tab it simply tells me that "This page is not secure." On the left, I see "Main Origin" as http: //williamcapecchi. com and "Non-Secure Origins" as http:// d3js. org. Clicking on either of these it tells me "Your connection with this origin is not secure."

A: For anyone else struggling with this, my solution was to use http:// addresses instead of https://. Then everything worked fine!


text:
Q: Securing Controller Actions by User in Grails I am using the Grails security plugin on a project.  I am using the annotations on controller actions to restrict access to certain classes of users such as 'ROLE_ADMIN' or  'ROLE_USER'.
(using this as the basis for what I am doing: http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/5%20Configuring%20Request%20Mappings%20to%20Secure%20URLs.html#5.1%20Defining%20Secured%20Annotations)
My question is, how do I restrict an action so a user can only see information about themselves.   For instance, lets say I have a user with id = 1.  If I have an action that shows information about the user at:
mySite/User/Show/1

how do I prevent that same user with id=1 from being able to access
mySite/User/Show/2

?  Is there a simple way to do this?

A: What will be the problenm with the following?:
class SomeController {
    springSecurityService
    // other stuf ...
    def show () {
       User user = User.get(params)
       User logged = User.get(springSecurityService.principal.id)
       if (user.id != logged.id) {
          flash.message = "You can't see the profile of other users"
          redirect action:"list" // You can redirect to other controller/action
          return //Since grails 2 this is needed
       }
       // Logic for display your user
    }
    // other stuf ...
}

A: You can also use Grails controller interceptor if you want to apply same logic to multiple actions
class SomeController {

 def beforeInterceptor = [action: this.&checkUser ]

   def springSecurityService

def checkUser() {
    User user = User.get(params)
       User logged = User.get(springSecurityService.principal.id)
       if (user.id != logged.id) {
   {
       redirect(action: "accessDenied", controller='access' id: params.long("id")) //re-direct accessDenied page
   return false
   }
    return true;
}

}
   Class AccessController{
     def accessDenied= {

        render(view: "accessDenied")

    }
 }

A: what you are asking is part of your business rules. So you are supposed to take care of these scenarios in your code rather than looking out for some plugin or helper code.
What you can do for this is, make sure id of the user accessing the user details is same as id of the user whose details are being questioned.
You can also make this check at object level but that will mean an extra query to database to fetch the user details.
Hope this helps.

A: I have to agree that you are trying to implement a business rule with a security aspect. If a user created some kind of document, you would not use authorization to select what is visible on their profile page, would you?
You have to draw a line on where the authorization aspect reaches and where business rules start.
In my experience, to avoid blurring the lines, i always use authorization roles as types of users associated to a set of functionality. A specific user type can have access to a series of stories, or use cases. These use cases are constrained to specific roles.
If you start asking questions about data visibility (what is hidden on a page, depending on whatever business factor), then you should stay clear of your security framework

A: I would disagree that you need to redefine your business logic vs security logic.  It is a common use case and authorization should cover it.  This is why Grails has filters.  Use an authorization filter to add functionality like this:
class AuthorizationFilters {
    def filters = {
        userCheck(controller: 'user', action: '*') {
            before = {
                // Check current user id is param.id here
            }
        }
    }
}

Thus your security logic is outside your controller.  You could add other controllers if they pass in a user id or even other methods that check if a domain class is owned by the current user here.


text:
Q: AWS Elastic Beanstalk Docker deployment failed Has anyone encountered failed deployment when deploying docker app to aws eb?
Here's a piece of log

time="2016-09-20T09:36:42.802106539Z" level=error msg="Handler for DELETE /v1.23/containers/c7bc72d9ccec returned error: You cannot remove a running container c7bc72d9ccec6557ddca8e90c7c77b350cb0c80be9a90921478adccd70a2b97a. Stop the container before attempting removal or use -f"
  time="2016-09-20T09:36:42.924322201Z" level=error msg="Handler for DELETE /v1.23/images/9daab71ad3c0 returned error: conflict: unable to delete 9daab71ad3c0 (cannot be forced) - image is being used by running container c7bc72d9ccec"
  time="2016-09-20T09:36:42.924865908Z" level=error msg="Handler for DELETE /v1.23/images/dbcc41959b55 returned error: conflict: unable to delete dbcc41959b55 (cannot be forced) - image has dependent child images"

For the first time of the environment deployment, it works well. However, every time I deploy a new version of the app, it fails.
Running on 64bit Amazon Linux 2016.03 v2.1.6 | Docker 1.11.2
My Dockerfile is rather simple:
# Get Node Latest
FROM node:6.5.0

# Create working directory
WORKDIR /app
ADD . /app

# Install depencencies
RUN npm install

# Expost 3000 port
EXPOSE 3000

# Start app
CMD ["node", "server.js"]

A: It turns out that npm install might take too long to run, cuz once I put node_modules into the zip and remove npm install from Dockerfile, it takes 3-5 minutes for deploying now.


text:
Q: Should I forget dynamic memory allocation and pointers and always pass by v? I have noticed that most C++ experts always advice it's better to pass by value, due to RVO. This allows me not worry too much about pointer manipulation and is easier to write code as well. No complaints there. This makes me wonder whether it is the correct approach to not use dynamic memory allocation (on the heap) at all and always pass parameters and return results by value?
This means instead of coming up with signatures like this:
Character* getCharacter(Sprite *sprite, Action* action)

I should more or less stick to signatures like:
Character getCharacter(Sprite sprite, Action action)

Is my understanding correct? or did I juth think i thaw a putthy cath?

A: They each have there pro's and con's. remember that using words like "always" is an absolute. Only the Dark Side deals in absolutes.
So let's look at each way and when we would use them.

*

*Pass by value is good when the object being passed is smaller (since a local copy gets made). It is also good if you want to be sure to not accidentally change the original data. Its shortcoming is it makes a local copy and that can be bad if it is really big.

*Pass by reference only passes a memory address. Therefore, large objects can be passed for a relatively low footprint. Also, with a reference, you can modify the original (this is both good and bad). This enables you to "return" more than one variable (so to speak). So obviously, the big con here is that you can mistakenly change the original data.

*Constant pass by reference is generally accepted to be a very strong candidate for doing things. It has the pros of both pass by reference and value. Low footprint since it is a reference AND you can't change the original. There aren't many cons accept for the fact that your use of the variable in the method needs to change a little. Remember, its a const and therefore cannot be modified in the function.

Remember, there is no magic-bullet. Nothing is always better. Determine what you need and select the right tool for the job.
EDIT: also, has been said. Passing is not the same as dynamic allocation. dynamic allocation only happens with the "new" keyword. My suggestion would be to avoid the "new" keyword for now until you have a better understanding of arguments and pointers.

A: Whether or not you allocate an object on the heap typically is driven by one of the following concerns:

*

*If the new object needs to outlive the function that creates it, the object must be allocated on the heap.

*If the object is very large, and does not fit on the stack, then you must allocate it on the heap.

Beyond that, the choice of pass by value or pass by reference is determined by the semantics. If you want to operate on a copy, pass by value. If you want to operate on the actual object, pass by reference.

A: Your statement is simply utterly untrue. There is some light advice to pass by value instead of the mainstream const-ref in the special case where the function will copy the argument to a local variable anyway.
And for passing by-nonconst-pointer, pass by value was never an alternative. The first implies an optional out or inout param and the second and input param.
And mentioned dynamic allocation in question title just fits no way with the content.
Your understanding in definitely not correct.


text:
Q: How do I read from JSON File in Java? I've read some other questions about this, but they did not seem to help me.
As the title says, I want to know how to read from .json files using Java.
Eg. I want my program to read a boolean value. (That is what I want it to.)
I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed.
What I've found so far (That did not work):
    String str = "Name";
    JSONObject obj = new JSONObject();
    String n = (String) obj.get("Name");
    if (!n.equals("true")) {

    } else
    if (n.equals("true")) {
        ButtonsShow = true;
    } else if (n.equals("false")) {
        ButtonsShow = false;
    }

Click to view the .Json file

A: you try it:
  import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample {
     public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("c:\\test.json"));

        JSONObject jsonObject = (JSONObject) obj;

        String name = (String) jsonObject.get("name");
        System.out.println(name);

        long age = (Long) jsonObject.get("age");
        System.out.println(age);

        // loop array
        JSONArray msg = (JSONArray) jsonObject.get("messages");
        Iterator<String> iterator = msg.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

     }

}


text:
Q: I cannot deploy Alexa skill(built using jovo) on Heroku So I am following this tutorial to deploy my Alexa skill on Heroku.
How to Deploy your Alexa Skill and Google Action to Heroku
I reached the stage where I have to type this script in my windows cmd:
# Add Heroku App Remote
$ heroku git:remote -a

But, I keep getting this error:

Any idea what might be causing this issue?
Thanks guys :D

A: There's a bug in their tutorial. They created an app called jovo-sample-app on Heroku so the command would be:
heroku git:remote -a jovo-sample-app

Obviously if you're following the tutorial yourself the app name will be different.

A: Try heroku git: remote -a [heroku-app-name] from Heroku docs


text:
Q: Filling the area between three points (java.awt.Point) with Graphics (java.awt.Graphics) I have three points in my code and I would like to fill the area between them, or in other words draw and fill a triangle between 3 points.
I thought about simply drawing lines with a for loop (from x1 to x2) but I don't think that will be efficient, is there any other way to do this that is more efficient?

A: I would draw a Polygon with three Points:
Graphics.fillPolygon(int[], int[], int)

A: You can use a buffered image and paint pixels one at a time.  BufferedImage is MUCH faster than using the paintcomponent of a gui object.  Use the WriteableRaster in a BufferedImage, then loop through the pixels one at a time, marking the ones that fall within your triangle.
Your algorithm looks something like:
equation for line 1
equation for line 2
equation for line 3
then for each point as you loop through writeableraster:
    check if x and y are each between the three lines

Alternatively, you could try this example which is more of a paint approach.


text:
Q: any sort of getElement(s)By---- function for getting a class by name, returns undefined function getElsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("div"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    }

function getSong() {
    console.log("getSong ran");
    var songN = getElsByClass("info")[0], nmSong = getCookie();
    console.log(songN);
    songN = songN.getElementsByTagName("a");
    songN = songN[0].innerText + " - " + songN[1].innerText;
    if (nmSong != songN) {
        setCookie(songN);
    } else {
        setCookie(songN);
    }
    sendSong(songN);
    return songN;
}
setInterval(getSong(), 10000);

I've tried songN = document.getElemenetsByClassName("info"), and every combination I could find, and it will only run for maybe 30 seconds before it closes, I need it to run for hours, unattended...
I can run
var songN = getElsByClass("info")[0];
console.log(songN); //is actually defined when ran in Javascript Console in Chrome..
songN = songN.getElementsByTagName("a");
songN = songN[0].innerText + " - " + songN[1].innerText;

in Javascript console, and it returns exactly, what I'm trying to do, but if it runs as a userscript or after it's been injected into the web page, I get Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined, and I've tried to define it many different ways I found through searching google, and stackoverflow, I've ran the script on window.load, in the <head>, and tried to make it run in <body>.
getElsByClass() is my last attempt at it, it's not actually apart of my script, just a bit I tried from another script, tried shortening the name so it couldn't possibly conflict, but still nothing.
=== Update ===
Here is some more of the code..
function getCookie() {
    console.log("getCookie ran");
    var sname = "songname=", ca = document.cookie.split(';'), i = 0, c, t;
    for (i; i < ca.length; i++) {
        c = ca[i].trim();
        if (c.indexOf(sname) == 0) {
            t = c.substring(sname.length, c.length);
            console.log(t);
            return t;
        }
    }
    return "";
}

function setCookie(cvalue) {
    console.log("setCookie ran");
    var d = new Date();
    d.setTime(d.getTime() + 210000);//set it to expire in 3 minutes and 30 seconds from current time (this is average song time.)
    document.cookie = "songname=" + cvalue + "; expires=" + d.toGMTString();
}


text:
Q: Thickbox --> IE8 --> Google Map Problem we are using the solution from mapmaker.donkeymagic.co.uk to create a google map that is then being embeded into a webpage.
An example of it working is here
http://www.fairlieyachtclub.com/erracms/pages/contact.aspx?articleid=15&zoneid=16
Now.... in ie6/ie7/ie8 compatibility mode/firefox3+
The map works correctly when the image is clicked
The map is loaded into the thickbox application and works as we expect
However... in ie8 the map does not load
Can somebody assist in troubleshooting this issue?

A: Bonjour,
Même problème d'affichage sous IE8, une GoogleMap ouverte dans Thickbox ne s'affichait pas complètement, le lien suivant m'a permi de résoudre cela rapidement :
Bug avec Google Map et Thickbox 3


text:
Q: How to refer to an object by its name? Is there a possible way to refer an object through it's name in Vb.Net?
The case is, I have menu items created in my designer with names such as MenuA, MenuB and MenuC.
On the database, I created a table consisting the list of all available menus in string format : MenuA, MenuB all the way to MenuZ.
Also I created a dynamic table consisting the user permission, what menu is accessible by a certain user.
So when I started the app, it will get the name of menu assigned to the logged user, and start to turn the Visible property to TRUE.
If it was a Control, I would just loop through it by Parent.Controls.Find(FoundMenu, True).
My problem is most of it is not a control, it is an Item added to the Control, or even another SubItem added to the Item.
So how can I found an object in my UI only by it's name?
SearchQuery = "SELECT menu_name FROM tbl_menulist menu, tbl_user user WHERE menu.id_menu = user.id_menu"
QueryReader = ExecuteQueryReader(SearchQuery)

QueryReader.Read()

//What I'm looking for is something like Controls.Find method to look for an object by name
//Seems silly, but what I'm looking for is to create something like below
//QueryReader(0).ToString = Menu Name

Dim FoundMenu As Object = FindMenuByName(QueryReader(0).ToString)
FoundMenu.Visible = True

Anyone can help me with this, I would really appreciate any suggestions.
Thank you :)

A: If this is a WinForm application, you can find the matching menu item by using a recursive method, such as:
Private Function findMenuItem(ByVal name As String, ByVal menuStrip As MenuStrip) As ToolStripMenuItem
    Return findMenuItem(name, menuStrip.Items)
End Function

Private Function findMenuItem(ByVal name As String, ByVal menuItems As IEnumerable(Of ToolStripItem)) As ToolStripMenuItem
    Dim foundItem As ToolStripMenuItem = Nothing
    For Each i As ToolStripMenuItem In menuItems.OfType(Of ToolStripMenuItem)()
        If i.Name = name Then
            foundItem = i
            Exit For
        Else
            foundItem = findMenuItem(name, i.DropDownItems)
            If foundItem IsNot Nothing Then
                Exit For
            End If
        End If
    Next
    Return foundItem
End Function

Then, you can use it like this (where MenuStrip1 is the name of your top level menu strip):
Dim menuItem As ToolStripMenuItem = findMenuItem(QueryReader(0).ToString, MenuStrip1)


text:
Q: Add Gradle cache to Sonatype Nexus Is there an option available to add the Gradle dependency cache to Sonatype Nexus repository so that i can use that cached dependencies for my project later.

A: The easiest way will be writing a Gradle script, that will exact all the artifacts from Gradle cache using Gradle Artifact Query API and save them in a Maven layout. Then you can import them to Nexus or Artifactory.


text:
Q: What changes to the code do I need to do when publishing on Amazon app store? I have an app on GooglePlay and would like to publish on Amazon app store.
is there anything I need to change in my code?
Most likely, the licence check from Google library has to be removed. Right?
is there anything else?
Many thanks!

A: Dont think I need to answer this , but my app just completed a successful review today.And I did not make any changes in my app. I believe if you are using Billng,Advertisements, Maps and any feature that has an implementation by Amazon must be changed.