text:
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

using F = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using K = Microsoft.CodeAnalysis.CSharp.SyntaxKind;

namespace Cometary.Tests
{
    /// <summary>
    ///   <see cref="Component"/> that adds With*() members to a class.
    /// </summary>
    public sealed class Immutable : Component
    {
        /// <inheritdoc />
        public override ClassDeclarationSyntax Apply(ClassDeclarationSyntax node, INamedTypeSymbol symbol, CancellationToken cancellationToken)
        {
            var parameters = ImmutableArray.CreateBuilder<ParameterSyntax>();
            var arguments  = ImmutableArray.CreateBuilder<ArgumentSyntax>();
            var ctorStmts  = ImmutableArray.CreateBuilder<StatementSyntax>();

            // Generate all parameters and statements
            var members = symbol.GetMembers();

            for (int i = 0; i < members.Length; i++)
            {
                IPropertySymbol member = members[i] as IPropertySymbol;

                if (member == null || !member.IsReadOnly || !member.CanBeReferencedByName)
                    continue;

                // Read-only prop, we good
                string propName = member.Name;
                string paramName = $"{char.ToLower(propName[0]).ToString()}{propName.Substring(1)}";
                TypeSyntax paramType = ((PropertyDeclarationSyntax)member.DeclaringSyntaxReferences[0]
                    .GetSyntax(cancellationToken)).Type;

                MemberAccessExpressionSyntax propAccess = F.MemberAccessExpression(
                    K.SimpleMemberAccessExpression,
                    F.ThisExpression(),
                    F.IdentifierName(propName)
                );

                // Make parameter & argument
                parameters.Add(F.Parameter(F.Identifier(paramName)).WithType(paramType));
                arguments.Add(F.Argument(propAccess));

                // Make ctor stmt
                ctorStmts.Add(F.ExpressionStatement(
                    F.AssignmentExpression(K.SimpleAssignmentExpression,
                        propAccess,
                        F.IdentifierName(paramName)
                    )
                ));
            }

            // The ctor is full, make all the 'with' methods
            TypeSyntax returnType = F.IdentifierName(symbol.Name);
            MemberDeclarationSyntax[] additionalMethods = new MemberDeclarationSyntax[parameters.Count + 1];

            arguments.Capacity = arguments.Count;
            ImmutableArray<ArgumentSyntax> args = arguments.MoveToImmutable();

            for (int i = 0; i < parameters.Count; i++)
            {
                ParameterSyntax parameter = parameters[i];
                string parameterName = parameter.Identifier.Text;

                ArgumentSyntax name = F.Argument(F.IdentifierName(parameterName));
                SeparatedSyntaxList<ArgumentSyntax> allArguments = F.SeparatedList(args.Replace(args[i], name));

                StatementSyntax returnStmt = F.ReturnStatement(
                    F.ObjectCreationExpression(returnType).WithArgumentList(F.ArgumentList(allArguments))
                );

                additionalMethods[i] = F.MethodDeclaration(returnType, $"With{char.ToUpper(parameterName[0]).ToString()}{parameterName.Substring(1)}")
                    .AddModifiers(F.Token(K.PublicKeyword), F.Token(K.NewKeyword))
                    .AddParameterListParameters(parameter)
                    .AddBodyStatements(returnStmt);
            }

            // Add the private ctor
            additionalMethods[parameters.Count] = F.ConstructorDeclaration(symbol.Name)
                .AddModifiers(F.Token(K.PrivateKeyword))
                .AddParameterListParameters(parameters.ToArray())
                .AddBodyStatements(ctorStmts.ToArray());

            return node.AddMembers(additionalMethods);
        }
    }
}


text:
SET SERVEROUTPUT ON

SPOOL C:/ORACLEXE/SCRIPTS/SELECTS.TXT

COLUMN ALL_PERSONS FORMAT a15;
COLUMN HIGH_PAID_PERSONS FORMAT a15;
COLUMN PERSONS_OLDER30 FORMAT a15;

SELECT Name AS ALL_PERSONS, SUM(Amount) AS INCOME
FROM TABLE_1 T1 JOIN TABLE_2 T2
ON T1.MemberId = T2.MemberId
GROUP BY Name, T1.MemberId;

SELECT Name AS HIGH_PAID_PERSONS, SUM(Amount) AS INCOME
FROM TABLE_1, TABLE_2
WHERE TABLE_1.MemberId = TABLE_2.MemberId
GROUP BY Name, TABLE_1.MemberId
HAVING SUM(Amount) > 500;

SELECT Name AS PERSONS_OLDER30, SUM(Amount) AS INCOME
FROM TABLE_1, TABLE_2
WHERE TABLE_1.MemberId = TABLE_2.MemberId AND
	  BirthDate < ADD_MONTHS(CURRENT_DATE, -30 * 12)
GROUP BY  Name, TABLE_1.MemberId;

SPOOL OFF;

redpajama_set_name: RedPajamaGithub


text:
/************************************************************
*
* @File: thread.c
* @Goal:
* @Author: Roger Fernandez (st20723)
* @Date: October 30th, 2013
*
*************************************************************/

// Own libraries
#include "libs.h"
#include "adts.h"

/*************************************************************
*
* @Name: write_socket
* @Goal: Send a message to client
* @Arg: In: client_socket
            frame_info = frame
       Out: None
* @Ret: Nothing
*
**************************************************************/

void write_socket (int client_socket, char destination[7], char type, char message[100])
{
    struct frame frame_info;
    // Create message frame
    bzero (frame_info.origin, 7);
    strcpy (frame_info.origin, "server");
    bzero (frame_info.destination, 7);
    strcpy (frame_info.destination, destination);
    frame_info.type = type;
    bzero (frame_info.data, 100);
    strcpy(frame_info.data, message);
    //Send frame
    write (client_socket, &frame_info, MAX_FRAME);
}

/*************************************************************
*
* @Name: parse_data_one_arg
* @Goal: Parse frame's data
* @Arg: In: frame_info = frame
            room_name = room's name
       Out: room_name = room's name
* @Ret: Nothing
*
**************************************************************/

void parse_data_one_arg (struct frame frame_info, char **room_name)
{
    int j = 0;
    size_t i = 0;
    char cursor, tmp[2048], *data;
    bzero(tmp, 2048);
    for (i = 0; i < strlen(frame_info.data) + 1; i++)
    {
        cursor = (frame_info.data)[i];
        if (cursor == '\0')
        {
            data = strdup (tmp);
            (*room_name) = data;
            j = 0;
        }
        else
        {
            tmp[j++] = cursor;
        }
    }
}

/*************************************************************
*
* @Name: parse_data_two_args
* @Goal: Parse frame's data
* @Arg: In: frame_info = frame
            room_name = room's name
            capacity = room's capacity
       Out: name = room's name
            capacity = room's capacity
* @Ret: Nothing
*
**************************************************************/

void parse_data_two_args (struct frame frame_info, char **room_name, int *capacity)
{
    int j = 0, count = 0;
    size_t i = 0;
    char cursor, tmp[2048], *data;
    bzero(tmp, 2048);
    for (i = 0; i < strlen(frame_info.data) + 1; i++)
    {
        cursor = (frame_info.data)[i];
        if (cursor == ':' || cursor == '\0')
        {
            data = strdup (tmp);
            switch (count)
            {
                case 0: // name
                {
                    (*room_name) = data;
                }
                break;
                case 1: // capacity
                {
                    if (capacity != 0)
                    {
                        (*capacity) = atoi (data);
                    }
                }
                break;
            }
            j = 0;
            count++;
        }
        else
        {
            tmp[j++] = cursor;
        }
    }
}

/*************************************************************
*
* @Name: delete_room
* @Goal: Responds to delete room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void delete_room (int client_socket, struct frame frame_info, struct room **rooms)
{
    char *room_name, str[100];
    bzero (str, 100);
    // Get frame data '<name>:<capacity>'
    parse_data_one_arg(frame_info, &room_name);
    // Search if user is the room's admin
    if (!linkedlist_delete_room(rooms, frame_info.origin, room_name))
    {
        sprintf (str, "Not enough privileges to delte room %s\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'D', str);
    }
    else
    {
        sprintf (str, "Successfully deleted room %s\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'D', str);
    }
}

/*************************************************************
*
* @Name: exit_room
* @Goal: Responds to exit room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void exit_room (int client_socket, struct frame frame_info, struct room **rooms, struct node *list)
{
    char *room_name, str[100];
    bzero (str, 100);
    // Get frame data '<name>'
    parse_data_one_arg (frame_info, &room_name);
    if (linkedlist_search_userexist (*rooms, frame_info.origin, room_name))
    {
        sprintf (str, "Room %s doesn't exist\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'X', str);
    }
    else if (!linkedlist_exit_room (rooms, frame_info.origin, room_name, list))
    {
        sprintf (str, "Not inside room %s\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'X', str);
    }
    else
    {
        sprintf (str, "Successfully disconnected from room %s\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'X', str);
    }
}

/*************************************************************
*
* @Name: talk_room
* @Goal: Responds to talk room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void talk_room (int client_socket, struct frame frame_info, int id_queue, struct room *rooms)
{
    char *room_name, str[100];
    bzero (str, 100);
    // Get frame data '<name>:<capacity>'
    parse_data_two_args (frame_info, &room_name, 0);
    // Search if room exists
    struct q_message message;
    message.id = 1;
    bzero (message.origin, 7);
    strcpy (message.origin, frame_info.origin);
    bzero (message.destination, 7);
    strcpy (message.destination, frame_info.destination);
    message.type = frame_info.type;
    bzero (message.data, 100);
    strcpy (message.data, frame_info.data);
    if (msgsnd (id_queue, (struct msgbuff*) &message, sizeof (message) - sizeof (long), IPC_NOWAIT) != 0)
    {
        perror ("msgsnd");
    }
}

/*************************************************************
*
* @Name: enter_room
* @Goal: Responds to enter room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void enter_room (int client_socket, struct frame frame_info, struct room **rooms, struct node *list)
{
    char *room_name, str[100];
    bzero (str, 100);
    // Get frame data '<name>'
    parse_data_one_arg (frame_info, &room_name);
    if (linkedlist_search_userexist (*rooms, frame_info.origin, room_name))
    {
        sprintf (str, "Already inside room %s\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'S', str);
    }
    else if (!linkedlist_enter_room (rooms, frame_info.origin, room_name, list))
    {
        write_socket (client_socket, frame_info.origin, 'N', "Room is full or doesn't exist\n\n");
    }
    else
    {
        sprintf (str, "Successfully connected to room %s\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'S', str);
    }
}

/*************************************************************
*
* @Name: modify_room
* @Goal: Responds to modify room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void modify_room (int client_socket, struct frame frame_info, struct room **rooms)
{
    char *room_name, str[100];
    int capacity;
    bzero (str, 100);
    // Get frame data '<name>:<capacity>'
    parse_data_two_args (frame_info, &room_name, &capacity);
    // Search if user is the room's admin
    if (!linkedlist_modify_room (rooms, frame_info.origin, room_name, capacity))
    {
        sprintf (str, "Not enough privileges to modify room %s capacity\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'M', str);
    }
    else
    {
        sprintf (str, "Successfully modified room %s capacity\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'M', str);
    }
}

/*************************************************************
*
* @Name: create_room
* @Goal: Responds to create room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void create_room (int client_socket, struct frame frame_info, struct room **rooms, struct node *list)
{
    char *room_name, str[100];
    int capacity = 0, room_id = 0, user_id = 0;
    bzero (str, 100);
    // Get frame data '<name>:<capacity>'
    parse_data_two_args (frame_info, &room_name, &capacity);
    // Search for existing room
    if (!linkedlist_search_room(*rooms, room_name))
    {
        // Create a room id based on id on the room
        room_id = linkedlist_search_roomid (*rooms);
        // Get user id from users linkedlist
        user_id = linkedlist_search_userid (list, frame_info.origin);
        // Add a new room to the room's linkedlist
        if (capacity > 0)
        {
            append_room (rooms, frame_info.origin, room_name, capacity, room_id, user_id);
            sprintf (str, "Successfully created room %s\n\n", room_name);
            write_socket (client_socket, frame_info.origin, 'Z', str);
        }
        else
        {
            sprintf (str, "Room %s cannot be created\n\n", room_name);
            write_socket (client_socket, frame_info.origin, 'Z', str);
        }
    }
    else
    {
        sprintf (str, "Room %s already exists\n\n", room_name);
        write_socket (client_socket, frame_info.origin, 'Z', str);
    }
}

/*************************************************************
*
* @Name: show_rooms
* @Goal: Responds to show room request
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void show_rooms (int client_socket, struct frame frame_info, struct room *head)
{
    char str[100];
    int count = 0;
    struct room *curr = head->next;
    bzero (str, 100);
    write_socket (client_socket, frame_info.origin, 'S', "The following rooms are available:\n");
    while (curr != NULL)
    {
        sprintf (str, "[%s]-[%d/%d]\n\n", curr->name, users_linkedlist_length (curr->users), curr->capacity);
        write_socket (client_socket, frame_info.origin, 'S', str);
        curr = curr->next;
        count++;
    }
    if (count == 0)
    {
        write_socket (client_socket, frame_info.origin, 'S', "There is no currently rooms available\n\n");
    }
}

/*************************************************************
*
* @Name: socket_error
* @Goal: Creates a dedicated server
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void socket_error (int s, const char *msg)
{
    char str[2048];
    sprintf (str, "%s: %s\n\n", msg, strerror (s));
    write(1, str, strlen(str));
    exit (EXIT_FAILURE);
}

/*************************************************************
*
* @Name: message_reader
* @Goal: reads a message from specific mailbox
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void *message_reader (void *arg)
{
    int out = 0;
    struct thread thread_info;
    struct q_message message;
    struct frame frame_info;
    thread_info = *(struct thread*)(arg);
    while (!out)
    {
        if (msgrcv (thread_info.id_queue, (struct msgbuff*) &message, sizeof (message) - sizeof (long), thread_info.id_user + 1, 0) > 0)
        {
            // Create message frame
            bzero (frame_info.origin, 7);
            strcpy (frame_info.origin, "server");
            bzero (frame_info.destination, 7);
            strcpy (frame_info.destination, "client");
            frame_info.type = 'T';
            bzero (frame_info.data, 100);
            strcpy(frame_info.data, message.data);
            //Send frame
            write (thread_info.client_socket, &frame_info, MAX_FRAME);
        }
        else
        {
            out = 1;
        }
    }
    return (void *) 0;
}

/*************************************************************
*
* @Name: dedicated_server
* @Goal: Creates a dedicated server
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void *queue_reader (void *arg)
{
    int i = 0, j = 0, k = 0, out = 0, start = 1, *ids = NULL;
    struct thread thread_info;
    struct q_message message;
    char room[100], data[100], str[100];
    thread_info = *(struct thread*)(arg);
    bzero (room, 100);
    while (!out)
    {
        if (msgrcv (thread_info.id_queue, (struct msgbuff *) &message, sizeof (message) - sizeof (long), 1, 0) > 0)
        {
            // Initialize message backup
            bzero (data, 100);
            // Copy message to backup
            strcpy (data, message.data);
            i = 0;
            // Get the room from message data
            while (message.data[i] != ':' && start)
            {
                room[i] = message.data[i];
                i++;
            }
            linkedlist_get_room_usersid (thread_info.rooms, room, &ids);
            if (ids != NULL)
            {
                for (i = 1; i <= ids[0]; i++)
                {
                    if (ids[i] != linkedlist_search_userid (thread_info.users, message.origin))
                    {
                        message.id = ids[i] + 1;
                        if (start)
                        {
                            // Initalize message
                            bzero (message.data, 100);
                            // Copy initial message
                            bzero (str, 100);
                            sprintf (str, "[%s] %s: ", room, message.origin);
                            strcpy (message.data, str);
                            // Send message's first part
                            if (msgsnd (thread_info.id_queue, (struct msgbuff *) &message, sizeof (message) - sizeof (long), IPC_NOWAIT) != 0)
                            {
                                out = 1;
                            }
                            // Initialize message
                            bzero (message.data, 100);
                            // Copy message backup
                            for (k = strlen(room) + 1, j = 0; k < 100; k++, j++)
                            {
                                message.data[j] = data[k];
                            }
                        }
                        // Send message's second part
                        if (msgsnd (thread_info.id_queue, (struct msgbuff *) &message, sizeof (message) - sizeof (long), IPC_NOWAIT) != 0)
                        {
                            out = 1;
                        }
                    }
                }
            }
            free (ids);
            start = 0;
            for (i = 0; i < 100; i++)
            {
                if (message.data[i] == '\n')
                {
                    start = 1;
                    i = 100;
                    bzero (room, 100);
                }
            }
        }
        else
        {
            out = 1;
        }
    }
    return (void *) 0;
}

/*************************************************************
*
* @Name: socket_reader
* @Goal: reads from the socket
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void *socket_reader (void *arg)
{
    int n = 0, out = 0;
    struct thread thread_info;
    struct frame frame_info;
    thread_info = *(struct thread*)(arg);
    while (!out)
    {
        n = 0;
        bzero (&frame_info, MAX_FRAME);
        bzero (frame_info.origin, 7);
        n += read (thread_info.client_socket, frame_info.origin, 7);
        bzero (frame_info.destination, 7);
        n += read (thread_info.client_socket, frame_info.destination, 7);
        n += read (thread_info.client_socket, &frame_info.type, 1);
        bzero (frame_info.data, 100);
        n += read (thread_info.client_socket, frame_info.data, 100);
        if (n != MAX_FRAME)
        {
            out = 1;
            write (1, "Client disconnected thread\n", strlen ("Client disconnected thread\n"));
            linkedlist_disconnect_user (&thread_info.users, thread_info.id_user);
            close (thread_info.client_socket);
        }
        else
        {
            switch (frame_info.type)
            {
                case 'S':
                    show_rooms (thread_info.client_socket, frame_info, thread_info.rooms);
                break;
                case 'Z':
                    create_room (thread_info.client_socket, frame_info, &thread_info.rooms, thread_info.users);
                break;
                case 'M':
                    modify_room (thread_info.client_socket, frame_info, &thread_info.rooms);
                break;
                case 'N':
                    enter_room (thread_info.client_socket, frame_info, &thread_info.rooms, thread_info.users);
                break;
                case 'T':
                    talk_room (thread_info.client_socket, frame_info, thread_info.id_queue, thread_info.rooms);
                break;
                case 'X':
                    exit_room (thread_info.client_socket, frame_info, &thread_info.rooms, thread_info.users);
                break;
                case 'D':
                    delete_room (thread_info.client_socket, frame_info, &thread_info.rooms);
                break;
            }
        }
    }
    return (void *) 0;
}

/*************************************************************
*
* @Name: dedicated_server
* @Goal: Creates a dedicated server
* @Arg: In: None
       Out: None
* @Ret: Nothing
*
**************************************************************/

void *dedicated_server (void *arg)
{
    int s = 0;
    struct thread thread_info;
    pthread_t t1,t2;
    thread_info = *(struct thread*)(arg);
    // Message reader
    s = pthread_create (&t1, NULL, message_reader, (void *) &thread_info);
    if (s != 0)
    {
        socket_error (s, "pthread_create");
    }
    // Socket reader
    s = pthread_create (&t2, NULL, socket_reader, (void *) &thread_info);
    if (s != 0)
    {
        socket_error (s, "pthread_create");
    }
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return (void *) 0;
}


text:
import React, { Component } from 'react';
import cx from './NavigationLeft.scss';

export default class NavigationLeft extends Component {
  render() {
    return (

Player

Wallet

DAL

ICO

Trading

Market

    );
  }
}


text: A model to simulate work of a road network


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <meta name="generator" content="Wowchemy 5.1.0 for Hugo" />

  <meta name="description" content="Harmonic Drives (HD) are commonly used in robotics because of zero-backlash and compactness. This makes them ideal for several mechatronic applications. Despite their wide use, there is no compelling literature on their performance, and to date it is not clear how they fare in a complete actuation setup. In this work we evaluate the joint structure we currently install on the iCub humanoid robot comprising an HD speed reducer showing that their efficiency is not optimal." />

    <link rel="alternate" hreflang="en" href="https://miggia.github.io/publication/parmiggiani-14-performance/" />

  <link rel="alternate" hreflang="it" href="https://miggia.github.io/it/publication/parmiggiani-14-performance/" />

    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />

    <meta name="theme-color" content="#1565c0" />

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.9.0/css/academicons.min.css" integrity="sha512-W4yqoT1+8NLkinBLBZko+dFB2ZbHsYLDdr50VElllRcNt2Q4/GSs6u71UHKxB7S6JEMCp5Ve4xjh3eGQl/HRvg==" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha256-FMvZuGapsJLjouA6k7Eo2lusoAX9i0ShlWFG6qt7SLc=" crossorigin="anonymous">

          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/github.min.css" crossorigin="anonymous" title="hl-light" media="print" onload="this.media='all'">
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" media="print" onload="this.media='all'" disabled>

      <link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&family=Roboto+Mono&family=Roboto:wght@400;700&display=swap">
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&family=Roboto+Mono&family=Roboto:wght@400;700&display=swap" media="print" onload="this.media='all'">

  <link rel="stylesheet" href="/css/wowchemy.ddb2a9c79d7760a321f1b5392a04566a.css" />

    <link rel="manifest" href="/it/index.webmanifest" />

  <link rel="icon" type="image/png" href="/media/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_32x32_fill_lanczos_center_2.png" />
  <link rel="apple-touch-icon" type="image/png" href="/media/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_180x180_fill_lanczos_center_2.png" />

  <link rel="canonical" href="https://miggia.github.io/it/publication/parmiggiani-14-performance/" />

  <meta property="twitter:card" content="summary" />

  <meta property="og:site_name" content="Alberto Parmiggiani" />
  <meta property="og:url" content="https://miggia.github.io/it/publication/parmiggiani-14-performance/" />
  <meta property="og:title" content="On the performance of actuators with harmonic drive speed reducers | Alberto Parmiggiani" />
  <meta property="og:description" content="Harmonic Drives (HD) are commonly used in robotics because of zero-backlash and compactness. This makes them ideal for several mechatronic applications. Despite their wide use, there is no compelling literature on their performance, and to date it is not clear how they fare in a complete actuation setup. In this work we evaluate the joint structure we currently install on the iCub humanoid robot comprising an HD speed reducer showing that their efficiency is not optimal." /><meta property="og:image" content="https://miggia.github.io/media/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_2.png" />
    <meta property="twitter:image" content="https://miggia.github.io/media/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_2.png" /><meta property="og:locale" content="it" />

      <meta
        property="article:published_time"
        content="2021-05-26T14:11:13+00:00"
      />

    <meta property="article:modified_time" content="2014-01-01T00:00:00+00:00">

  <title>On the performance of actuators with harmonic drive speed reducers | Alberto Parmiggiani</title>

Cerca

        <input name="q" id="search-query" placeholder="Cerca..." autocapitalize="off"
        autocomplete="off" autocorrect="off" spellcheck="false" type="search" class="form-control"
        aria-label="Cerca...">

      Alberto Parmiggiani

    <button type="button" class="navbar-toggler" data-toggle="collapse"
            data-target="#navbar-content" aria-controls="navbar-content" aria-expanded="false" aria-label="Attiva la navigazione">

    </button>

      Alberto Parmiggiani

          Home

          Progetti

          Talks

          Pubblicazioni

          Contatti

            Light

            Dark

            Automatic

          Italiano

            Italiano

            English

On the performance of actuators with harmonic drive speed reducers

      Alberto Parmiggiani,
      Marco Randazzo,
      Giorgio Metta

    January 2014

  Citazione

    Progetti

Abstract

Harmonic Drives (HD) are commonly used in robotics because of zero-backlash and compactness. This makes them ideal for several mechatronic applications. Despite their wide use, there is no compelling literature on their performance, and to date it is not clear how they fare in a complete actuation setup. In this work we evaluate the joint structure we currently install on the iCub humanoid robot comprising an HD speed reducer showing that their efficiency is not optimal.

Tipo

              Conference paper

Publicazione

Int. Conf. on New Actuators (ACTUATOR)

      Published with Wowchemy — the free, open source website builder that empowers creators.

Citazione

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

           Copia

           Download


text:
using loopy::LServer;
using loopy::ThreadShared;
using loopy::DefaultController;

int
main() {

  // do your initialization for the shared thread object here
  std::string str = "Example app";
  auto sharedObj = ThreadShared::getInstance();
  sharedObj.name = str;

  // now do your initialization for the thread server
  LServer& server = LServer::getInstance("127.0.0.1", 8000, 2);

  // default example. Request with /hello
  server.get("/hello", &DefaultController::Hello);

  // complex example. Request with /complex/hello?id=4&username=baz
  server.get("/complex/hello", &DefaultController::ComplexHello);

  // small example, but is also a section for complex hello
  server.get("/section/hello", &DefaultController::SubComplexHello);

  // a dedicated section for complex hello
  server.intern("/section/hello2", &DefaultController::SubComplexHello2);

  // default handler when there is no response to be found
  server.setHandlerFor404(&DefaultController::FileNotFound);

  // run the server!
  server.run();
  return 0;
}


text:
function TwitterLib(onAuthenticated, onHitsUpdated, microbloggingService, baseUrl, baseOauthUrl, baseSigningUrl, baseOauthSigningUrl, baseSearchUrl, oauthTokenData) {
  this.remainingHitsCount = 150;
  this.nextHitsReset = 0;
  this.onAuthenticated = onAuthenticated;
  this.onHitsUpdated = onHitsUpdated;
  this.hourlyLimit = 150;
  this.microbloggingService = microbloggingService;
  this.ignoreRequests = false;
  this.lastAccessLevel = null;
  var _this = this;
  this.oauthLib = new TwitterOAuth(microbloggingService, oauthTokenData, function() {
    _this.updateHourlyHitsLimit.call(_this);
    if(!_this.username()) {
      _this.verifyCredentials(function() {
        _this.onAuthenticated();
      });
    } else {
      _this.onAuthenticated();
    }
  });

  if(!baseUrl.match(/\/$/)) {
    baseUrl = baseUrl + '/';
  }
  TwitterLib.URLS = {
    BASE: baseUrl,
    BASE_OAUTH: baseOauthUrl,
    BASE_SIGNING: baseSigningUrl,
    BASE_OAUTH_SIGNING: baseOauthSigningUrl,
    BASE_SEARCH: baseSearchUrl
  };
}
TwitterLib.prototype = {
  username: function() {
    return this.oauthLib.screen_name;
  },
  authenticated: function() {
    return this.oauthLib.authenticated;
  },
  tokenRequested: function() {
    return this.oauthLib.tokenRequested;
  },
  authenticating: function() {
    return this.oauthLib.authenticating;
  },
  startAuthentication: function() {
    if(!this.oauthLib.authenticating) {
      this.oauthLib.getRequestToken();
    }
  },
  generateOauthHeader: function(signedData, includeRealm) {
    var authorization = 'OAuth ';
    if(includeRealm) {
      authorization += 'realm="http://api.twitter.com/", ';
    }
    authorization += 'oauth_consumer_key="' + signedData.oauth_consumer_key + '", ' +
    'oauth_signature_method="HMAC-SHA1", ' +
    'oauth_token="' + signedData.oauth_token + '", ' +
    'oauth_timestamp="' + signedData.oauth_timestamp + '", ' +
    'oauth_nonce="' + encodeURIComponent(signedData.oauth_nonce) + '", ' +
    'oauth_version="1.0", ' +
    'oauth_signature="' + encodeURIComponent(signedData.oauth_signature) + '"';

    return authorization;
  },
  signOauthEcho: function(xhr, url) {
    var signedData = this.oauthLib.prepareSignedParams(url, {}, 'GET');

    xhr.setRequestHeader('X-Auth-Service-Provider', url);
    xhr.setRequestHeader('X-Verify-Credentials-Authorization', this.generateOauthHeader(signedData, true));
  },
  signOauth: function(xhr, url, params, method) {
    var signedData = this.oauthLib.prepareSignedParams(url, params, method);

    xhr.setRequestHeader('Authorization', this.generateOauthHeader(signedData));
  },
  ajaxRequest: function(url, callback, context, requestParams, httpMethod, useSearchAPI, overriddenTimeout) {
    if(!httpMethod) {
      httpMethod = "GET";
    }
    if(!requestParams) {
      requestParams = {};
    }
    var requestUrl;
    if(useSearchAPI) {
      requestUrl = TwitterLib.URLS.BASE_SEARCH + ".json";
    } else {
      requestUrl = TwitterLib.URLS.BASE + url + ".json";
    }
    var _this = this;
    var beforeSendCallback = function(request, settings) {
      if(!useSearchAPI) {
        var signingUrl = TwitterLib.URLS.BASE_SIGNING + url + ".json";
        _this.signOauth(request, signingUrl, requestParams, httpMethod);
      }
    };
    var errorCallback = function (request, status, error) {
      if(_this.ignoreRequests) {
        return;
      }
      console.warn("Failed Request", requestUrl + '?' + $.param(requestParams), request, status, error);
      var fmtError;
      if(status == 'timeout') {
        fmtError = "(timeout)";
      } else {
        try {
          if(request && request.readyState == 4) {
            if(request.status == 401) {
              if(_this.oauthLib.adjustTimestamp(request, 'Date')) {
                console.log('Unauthorized, trying again using adjusted timestamp based on server time.');
                _this.ajaxRequest(url, callback, context, requestParams, httpMethod, useSearchAPI, overriddenTimeout);
                return;
              } else {
                _this.ignoreRequests = true;
                TweetManager.instance.signoutAndReauthenticate();
              }
            } else if(request.status == 403 && url.match('direct_messages')) {
              if(_this.lastAccessLevel) {
                if(_this.lastAccessLevel.match('directmessages')) {
                  // The permission level is correct so that's some bizarre glitch
                  TweetManager.instance.disableDMS();
                } else {
                  _this.ignoreRequests = true;
                  TweetManager.instance.signoutAndReauthenticate();
                }
              }
            }
          }
        } catch(e) {
          /* Ignoring */
        }
      }
      if(!fmtError) {
        try {
          if(!request.responseText) {
            throw 'no response';
          }
          if(_this.microbloggingService == 'identica') {
            var txt = request.responseText;
            fmtError = '"' + txt.replace(/<.*>(.*)<.*>/, '$1') + '"';
          } else {
            var rspObj = JSON.parse(request.responseText);
            fmtError = '"' + rspObj.error + '"(' + request.statusText + ')';
          }
        } catch(e) {
          fmtError = '"' + error + '"(' + status + ')';
        }
      }
      callback(false, null, fmtError, context, request);
    };
    var successCallback = function(data, status, request) {
      if(_this.ignoreRequests) {
        return;
      }
      if(request.status === 0) {
        // Empty responses are a pain...
        errorCallback(request, 'error', 'empty response');
        return;
      }
      if(!data) {
        data = [];
      } else if(useSearchAPI) {
        if(data) {
          data = data.results;
        }
        if(!data) {
          data = [];
        }
      }
      _this.normalizeTweets(data);
      callback(true, data, status, context, request);
    };
    $.ajax({
      type: httpMethod,
      url: requestUrl,
      data: requestParams,
      dataType: "json",
      timeout: overriddenTimeout,
      success: successCallback,
      error: errorCallback,
      beforeSend: beforeSendCallback,
      complete: function(request) {
        if(!request) return;
        try {
          var remaining = request.getResponseHeader("X-RateLimit-Remaining");
          if(remaining) {
            _this.remainingHitsCount = remaining;
            _this.nextHitsReset = request.getResponseHeader("X-RateLimit-Reset");
            _this.hourlyLimit = request.getResponseHeader("X-RateLimit-Limit");
            var accessLevel = request.getResponseHeader('X-Access-Level');
            if(accessLevel) {
              _this.lastAccessLevel = accessLevel;
            }

            _this.onHitsUpdated(_this.remainingHitsCount, _this.nextHitsReset, _this.hourlyLimit);
          }
        } catch(e) { /* ignoring */ }
      }
    });
  },

  normalizeTweets: function(tweetsOrTweet) {
    if(tweetsOrTweet.hasOwnProperty('id_str')) {
      tweetsOrTweet = [tweetsOrTweet];
    }
    for(var i = 0, len = tweetsOrTweet.length; i < len; ++i) {
      var ti = tweetsOrTweet[i];

      // Damn Snowflake... Damn 53 bits precision limit...
      if(ti.id_str) {
        ti.id = ti.id_str;
      }
      if(ti.in_reply_to_status_id_str) {
        ti.in_reply_to_status_id = ti.in_reply_to_status_id_str;
      }
      if(ti.in_reply_to_user_id_str) {
        ti.in_reply_to_user_id = ti.in_reply_to_user_id_str;
      }
      if(ti.current_user_retweet_id_str) {
        ti.current_user_retweet_id = ti.current_user_retweet_id_str;
      }
      if(ti.retweeted_status) {
        ti.retweeted_status.id = ti.retweeted_status.id_str;
      }
      if(ti.current_user_retweet) {
        ti.current_user_retweet.id = ti.current_user_retweet.id_str;
      }

      if(!ti.user) {
        // DMs
        ti.user = ti.sender;
      }
      if(!ti.user) {
        // Search result
        ti.user = {
          name: ti.from_user,
          screen_name: ti.from_user,
          profile_image_url: ti.profile_image_url
        };
      }
    }
  },

  verifyCredentials: function(callback) {
    var _this = this;
    this.ajaxRequest("account/verify_credentials", function(success, data) {
      if(success) {
        _this.oauthLib.screen_name = data.screen_name;
      }
      if(callback) {
        callback(success, data);
      }
    });
  },

  remainingHitsInfo: function() {
    return [this.remainingHitsCount, this.nextHitsReset, this.hourlyLimit];
  },

  updateHourlyHitsLimit: function() {
    var _this = this;
    this.ajaxRequest("account/rate_limit_status", function(success, data, status, context, xhr) {
      if(success) {
        _this.hourlyLimit = data.hourly_limit;
      }
      if(xhr) {
        var accessLevel = xhr.getResponseHeader('X-Access-Level');
        if(accessLevel && !accessLevel.match('directmessages')) {
          // For some reason twitter is not authenticating with the correct access
          // level. In this cases we'll disable DMS
          TweetManager.instance.disableDMS();
        }
      }
    });
  },

  showTweet: function(callback, id) {
    this.ajaxRequest('statuses/show/' + id, callback, null, null, "GET", false);
  },

  tweet: function(callback, msg, replyId) {
    var params = { status: msg };
    if(replyId) {
      params.in_reply_to_status_id = replyId;
    }
    this.ajaxRequest('statuses/update', callback, null, params, "POST", false, 30000);
  },

  retweet: function(callback, id) {
    this.ajaxRequest('statuses/retweet/' + id, callback, null, null, "POST");
  },

  destroy: function(callback, id) {
    this.ajaxRequest('statuses/destroy/' + id, callback, null, null, "POST");
  },

  destroyDM: function(callback, id) {
    this.ajaxRequest('direct_messages/destroy/' + id, callback, null, null, "POST");
  },

  favorite: function(callback, id) {
    this.ajaxRequest('favorites/create/' + id, callback, null, null, "POST");
  },

  unFavorite: function(callback, id) {
    this.ajaxRequest('favorites/destroy/' + id, callback, null, null, "POST");
  },

  lists: function(callback) {
    this.ajaxRequest(this.username() + '/lists', callback, null, null, "GET");
  },

  subs: function(callback) {
    this.ajaxRequest(this.username() + '/lists/subscriptions', callback, null, null, "GET");
  },

  timeline: function(timeline_path, callback, context, params) {
    params = params || {};
    params.include_entities = 'true';
    params.include_my_retweet = 'true';
    this.ajaxRequest(timeline_path, callback, context, params);
  },

  searchTimeline: function(callback, context, params) {
    params.result_type = 'recent';
    params.include_my_retweet = 'true';
    this.ajaxRequest('', callback, context, params, "GET", true);
  },

  blockedUsers: function(callback) {
    this.ajaxRequest('blocks/blocking', callback, null, null, "GET");
  },

  friendsIds: function(callback) {
    var params = {
      cursor: -1
    };
    this.ajaxRequest('friends/ids/' + this.username(), callback, null, params, "GET");
  },

  trendingTopics: function(callback, param) {
    var request = 'trends';
    if (param != undefined) {
      request += '/' + param;
    } else {
      request += '/1'; //1 - worldwide
    }
    this.ajaxRequest(request, callback, null, null, "GET");
  },

  lookupUsers: function(callback, usersIdList) {
    var params = {
      user_id: usersIdList.join(',')
    };
    this.ajaxRequest('users/lookup', callback, null, params, "GET");
  },

  usersTimeline: function(callback, params) {
    params.include_rts = 'true';
    params.include_my_retweet = 'true';
    this.ajaxRequest('statuses/user_timeline', callback, {}, params);
  },

  follow: function(callback, username) {
    var params = {
      screen_name: username,
      follow: false
    };
    this.ajaxRequest('friendships/create', callback, null, params, "POST");
  },

  unfollow: function(callback, username) {
    var params = {
      screen_name: username
    };
    this.ajaxRequest('friendships/destroy', callback, null, params, "POST");
  },

  block: function(callback, username) {
    var params = {
      screen_name: username
    };
    this.ajaxRequest('blocks/create', callback, null, params, "POST");
  },

  report: function(callback, username) {
    var params = {
      screen_name: username
    };
    this.ajaxRequest('report_spam', callback, null, params, "POST");
  }
};

var globalOAuthInstance;
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if(!globalOAuthInstance)
    return;
  if(request.identica_request_token) {
    if(!globalOAuthInstance.authenticated && globalOAuthInstance.tokenRequested) {
      if(globalOAuthInstance.oauth_token == request.identica_request_token) {
        globalOAuthInstance.authenticating = true;
        globalOAuthInstance.getAccessToken.call(globalOAuthInstance, '', function() {
          chrome.tabs.remove(sender.tab.id);
        });
      }
    }
  }
  if(request.check_pin_needed) {
    if(!globalOAuthInstance.authenticated && globalOAuthInstance.tokenRequested) {
      sendResponse({});
    }
    return;
  }
  var pin = request.cr_oauth_pin;
  if(pin) {
    globalOAuthInstance.authenticating = true;
    globalOAuthInstance.getAccessToken.call(globalOAuthInstance, pin, sendResponse);
  }
});

function TwitterOAuth(microbloggingService, oauthTokenData, onAuthenticated) {
  this.user_id = null;
  this.screen_name = null;
  this.authenticated = false;
  this.onAuthenticated = onAuthenticated;
  this.responseCallback = null;
  this.authenticating = false;
  this.tokenRequested = false;
  this.timeAdjusted = false;
  this.oauthTokenData = oauthTokenData;
  this.microbloggingService = microbloggingService;

  if(microbloggingService == 'twitter') {
    this.consumerSecret = SecretKeys.twitter.consumerSecret;
    this.consumerKey    = SecretKeys.twitter.consumerKey;
  } else if(microbloggingService == 'identica') {
    this.consumerSecret = SecretKeys.identica.consumerSecret;
    this.consumerKey    = SecretKeys.identica.consumerKey;
  }

  globalOAuthInstance = this;

  var _this = this;
  var cachedToken = this.oauthTokenData.val();
  if(cachedToken) {
    this.authenticating = true;
    this.tokenRequested = true;
    setTimeout(function() {
      _this.accessTokenCallback.call(_this, cachedToken);
    }, 0);
  }
}
TwitterOAuth.prototype = {
  getAccessToken: function(pin, callback) {
    this.responseCallback = callback;
    this.makeRequest.call(this, 'access_token',
      { oauth_verifier: pin }, this.accessTokenCallback);
  },
  prepareSignedParams: function(url, params, httpMethod) {
    var accessor = {
      consumerSecret: this.consumerSecret,
      tokenSecret: this.oauth_token_secret
    };
    if(!httpMethod)
      httpMethod = 'POST';
    var message = {
      action: url,
      method: httpMethod,
      parameters: [
        ['oauth_consumer_key', this.consumerKey],
        ['oauth_signature_method', 'HMAC-SHA1']
      ]
    };
    if(this.oauth_token) {
      OAuth.setParameter(message, 'oauth_token', this.oauth_token);
    }
    for(var p in params) {
      OAuth.setParameter(message, p, params[p]);
    }
    OAuth.completeRequest(message, accessor);
    return OAuth.getParameterMap(message.parameters);
  },
  adjustTimestamp: function(request) {
    var serverHeaderFields = ['Last-Modified', 'Date'];
    var serverTimestamp;
    for(var i = 0, len = serverHeaderFields.length; i < len; ++i) {
      var headerField = serverHeaderFields[i];
      var fieldValue = request.getResponseHeader(headerField);
      if(!fieldValue) {
        continue;
      }
      serverTimestamp = Date.parse(fieldValue);
      if(serverTimestamp && !isNaN(serverTimestamp)) {
        break;
      }
    }
    if(serverTimestamp) {
      var beforeAdj = OAuth.timeCorrectionMsec;
      OAuth.timeCorrectionMsec = serverTimestamp - (new Date()).getTime();
      if(Math.abs(beforeAdj - OAuth.timeCorrectionMsec) > 5000) {
        console.log("Server timestamp: " + serverTimestamp + " Correction (ms): " + OAuth.timeCorrectionMsec);
        return true;
      }
    }
    return false;
  },
  makeRequest: function(url, params, callback) {
    var signingUrl = TwitterLib.URLS.BASE_OAUTH_SIGNING + url;
    var signedParams = this.prepareSignedParams(signingUrl, params);
    var requestUrl = TwitterLib.URLS.BASE_OAUTH + url;
    var _this = this;
    $.ajax({
      type: 'POST',
      url: requestUrl,
      data: signedParams,
      success: function(data, status, xhr) {
        callback.call(_this, data, status, xhr);
      },
      error: function (request, status, error) {
        var fmtError = '';
        try {
          if(_this.adjustTimestamp(request)) {
            console.log('First OAuth token request failed: ' + status + '. Trying again using adjusted timestamp.');
            callback.call(_this, null, null, true);
            return;
          }
          fmtError = '"' + request.responseText + '"(' + request.statusText + ')';
        } catch(e) {
          fmtError = '"' + error + '"(' + status + ')';
        }
        callback.call(_this, null, fmtError);
      }
    });
  },
  accessTokenCallback: function(data, status, xhr) {
    this.authenticating = false;
    var success = true;
    if(!data) {
      success = false;
      this.error = status;
      console.log('accessTokenCallback error: ' + status);
    } else {
      var paramMap = OAuth.getParameterMap(data);
      this.oauthTokenData.save(data);
      this.oauth_token = paramMap['oauth_token'];
      this.oauth_token_secret = paramMap['oauth_token_secret'];
      this.user_id = paramMap['user_id'];
      this.screen_name = paramMap['screen_name'];
      this.authenticated = true;
      if(this.onAuthenticated) {
        this.onAuthenticated();
      }
    }
    if(this.responseCallback) {
      try {
        this.responseCallback(success);
      } catch(e) { /* ignoring */ }
    }
  },
  requestTokenCallback: function(data, status, tryAgain) {
    var _this = this;
    var alertRequestError = function(errorMsg) {
      _this.error = errorMsg;
      console.log('requestTokenCallback error: ' + errorMsg);
      alert("Ouch... Something bad happened to Chrome Bird while calling Twitter's API. Request token response: " + errorMsg +
            "\n\nThis problem is probably due to incorrect date and time settings in your operating system. Please, review your settings and try again.");
    };
    if(!data) {
      if(tryAgain) {
        this.getRequestToken();
        return;
      }
      alertRequestError(status);
      return;
    }

    var paramMap = OAuth.getParameterMap(data);
    this.oauth_token = paramMap['oauth_token'];
    this.oauth_token_secret = paramMap['oauth_token_secret'];

    if(!this.oauth_token || !this.oauth_token_secret) {
      alertRequestError("Invalid oauth_token: " + data);
      return;
    }

    chrome.tabs.create({
      "url": TwitterLib.URLS.BASE_OAUTH + 'authorize?oauth_token=' + this.oauth_token,
      "selected": true
    });
    this.tokenRequested = true;
  },
  getRequestToken: function() {
    this.oauth_token_secret = '';
    this.oauth_token = null;
    this.makeRequest('request_token', {}, this.requestTokenCallback);
  }
};


text:
<?php
namespace gossamer\core\datasources;

use gossamer\libraries\service\ColumnMappings;
use Monolog\Logger;
use gossamer\core\datasources\AdapterInterface;

class DBConnection implements AdapterInterface
{
    // change these values. Yes, this should be a config file outside of web root
    // preferably in an environment variable if this were a dedicated server.

    protected $host = 'this-should-be-in-credentials.yml';

    protected $user = 'this-should-be-in-credentials.yml';

    protected $pass = 'this-should-be-in-credentials.yml';

    protected $db ='this-should-be-in-credentials.yml';

    private $lastQuery='';

    protected $logger = null;

    var $stack;

    private $rows;

    private $conn = null;

    private $rowCount = 0;

    public function __construct($host=null, $user=null, $pass=null, $db=null) {
        if(!is_null($host)) {
            $this->user = $user;
            $this->pass = $pass;
            $this->db = $db;
            $this->host = $host;
        }

    }

    public function getRowCount() {
        return $this->rowCount;
    }

    public function setLogger(Logger $logger) {
        $this->logger = $logger;
    }

    function getAllRowsAsArray(){
        if(isset($this->stack))
            return $this->stack;

        $this->stack=array();
        while ($ra=mysqli_fetch_array($this->rows)) {
             array_push($this->stack,$ra);
        }

        unset($this->rows);

        return $this->stack;
    }

    public function setCustomer(SQLInterface $customer) {
        if(!($customer instanceof SQLInterface)) {
            throw new InterfaceNotImplementedException();
        }

        $this->user = $customer->dbUsername;
        $this->pass = $customer->dbPassword;
        $this->db = $customer->dbName;
        $this->host = $customer->dbHost;

    }

    public function beginTransaction(){
        $this->getConnection();
        mysqli_query($this->conn, "BEGIN" );
    }

    public function commitTransaction(){
       $this->getConnection();
        mysqli_query($this->conn, "COMMIT");
    }

    public function rollbackTransaction(){
        $this->getConnection();
        mysqli_query($this->conn, "BEGIN");
    }

    public function getConnection(){
        if(is_null($this->conn)) {
            $this->conn = mysqli_connect($this->host, $this->user, $this->pass, $this->db);

            if (!$this->conn) {
                die('Could not connect: ' . mysql_error());
            }
        }
        mysqli_query($this->conn, 'SET NAMES "utf8"');

        return $this->conn;
    }

    public function query($query, $fetch = true){

        $this->lastQuery = $query;

        //mysql_select_db($this->db);

        $results = mysqli_query($this->getConnection(), utf8_decode($query));

        if (!$results) {
          //  die('Invalid query: ' . mysqli_error());
        }
        if(strtolower(substr($query,0,6)) == 'delete' ) {
            return 0;
        }elseif(strtolower(substr($query,0,6)) == 'insert') {
            error_log('id is '.mysqli_insert_id($this->conn));
            return mysqli_insert_id($this->conn);
        }elseif(strtolower(substr($query,0,6) =='update')) {
            return;
        } else {
            $this->rowCount = mysqli_query($this->getConnection(), 'SELECT FOUND_ROWS()');
        }

        //mysql_close($conn);
        if($fetch && $results){

            $stack=array();
            while ($ra=mysqli_fetch_array($results, MYSQL_ASSOC)) {
                 array_push($stack,$ra);
            }

            unset($results);

            return $stack;
        } elseif($fetch && !$results) {
            return;
        }

        $insertId = mysqli_insert_id();

        return $insertId;
    }

    public function getTableColumnMappings(AbstractEntity $entity){
        if(!$entity instanceof AbstractEntity){
            throw new \RuntimeException('DBConnection::getTableColumnMappings - entity my be instance of AbstractEntity');
        }
       // $columns = $this->query('SHOW COLUMNS FROM ' . $tableName);

        $mappings = new ColumnMappings($this);
        $columns = $mappings->getTableColumnList($entity->getTableName());
        return $columns;
    }

    public function getLastQuery(){
        return $this->lastQuery;
    }

}


text:
using System.Linq;
using BluffinMuffin.Protocol;
using BluffinMuffin.Protocol.Lobby;
using BluffinMuffin.Protocol.Lobby.RegisteredMode;
using BluffinMuffin.Protocol.Lobby.QuickMode;
using BluffinMuffin.Server.Protocol.Test.Mocking;
using BluffinMuffin.Protocol.Tests.DataTypes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BluffinMuffin.Server.Protocol.Test
{
    [TestClass]
    public class LobbyCommandVsResponse
    {
        private void CheckIfResponseIs<T>(AbstractCommand c) where T : AbstractCommand
        {
            var server = new ServerMock();
            server.Send(c);
            server.LobbyCommands.CompleteAdding();
            var received = server.ServerSendedCommands.GetConsumingEnumerable().First();
            Assert.AreEqual(typeof(T), received.Command.GetType());
        }
        [TestMethod]
        public void AuthenticateUserCommand()
        {
            CheckIfResponseIs<AuthenticateUserResponse>(LobbyCommandMock.AuthenticateUserCommand());
        }
        [TestMethod]
        public void CheckDisplayExistCommand()
        {
            CheckIfResponseIs<CheckDisplayExistResponse>(LobbyCommandMock.CheckDisplayExistCommand());
        }
        [TestMethod]
        public void CheckUserExistCommand()
        {
            CheckIfResponseIs<CheckUserExistResponse>(LobbyCommandMock.CheckUserExistCommand());
        }
        [TestMethod]
        public void CreateTableCommand()
        {
            CheckIfResponseIs<CreateTableResponse>(LobbyCommandMock.CreateTableCommand());
        }
        [TestMethod]
        public void CreateUserCommand()
        {
            CheckIfResponseIs<CreateUserResponse>(LobbyCommandMock.CreateUserCommand());
        }
        [TestMethod]
        public void GetUserCommand()
        {
            CheckIfResponseIs<GetUserResponse>(LobbyCommandMock.GetUserCommand());
        }
        [TestMethod]
        public void IdentifyCommand()
        {
            CheckIfResponseIs<IdentifyResponse>(LobbyCommandMock.IdentifyCommand());
        }
        [TestMethod]
        public void JoinTableCommand()
        {
            CheckIfResponseIs<JoinTableResponse>(LobbyCommandMock.JoinTableCommand());
        }
        [TestMethod]
        public void ListTableCommand()
        {
            CheckIfResponseIs<ListTableResponse>(LobbyCommandMock.ListTableCommand());
        }
        [TestMethod]
        public void CheckCompatibilityCommand()
        {
            CheckIfResponseIs<CheckCompatibilityResponse>(LobbyCommandMock.CheckCompatibilityCommand());
        }
    }
}


text:
<?php

namespace Code16\Sharp\View\Utils\Content;

abstract class Fragment
{
    public string $type;
}


text:
$(function () {
    var QRCode = function (searchtype) {
        if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
            if (searchtype == 1) {
                window.location.href = "exhibitorWebToSearchView";
            } else if (searchtype == 2) {
                window.location.href = "activityWebToSearchView";
            }
        }
        else if (browser.versions.android) {
            window.search_obj.onClickSearch();
        }
    }

    var iphone = $('.iphone-btn');
    iphone.click(function () {
        if (browser.versions.weixin) {
            $('.leadPage').show();
        }else{
            if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
                this.href = "https://itunes.apple.com/cn/app/kai-juan-ri-li/id1057442967?mt=8";
            }
            else if (browser.versions.android) {
                this.href = "javascript:"
            } else {
                this.href = "https://itunes.apple.com/cn/app/kai-juan-ri-li/id1057442967?mt=8"
            }
        }
    });
    $('.leadPage').click(function () {
        $(this).hide();
    });
    var btn = $('.android');
    btn.click(function () {
        if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
            this.href = "javascript:";
        }
        else if (browser.versions.android ) {
            this.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.openbook.mars"
        } else {
            this.href = "http://android.myapp.com/myapp/detail.htm?apkName=com.openbook.mars"
        }
    });
});


text:
#include "flowmap.h"

// private function declarations
static int _flowmap_search(flowmap *m, uint64_t hashtag, flowmap_node *n,
                    uint32_t time, bool get_next, flowmap_entry **entry,
                    bool *is_overflow, uint32_t **prev);
static uint32_t _flowmap_overflow_alloc(flowmap *m);
static void _flowmap_overflow_free(flowmap *m, flowmap_overflow_node *n);
static void _flowmap_overflow_lock(flowmap *m);
static void _flowmap_overflow_unlock(flowmap *m);
static size_t _next_power2(size_t i);

// public function definitions

flowmap* flowmap_new(uint32_t capacity) {
  flowmap *m;
  uint64_t array_len;
  uint32_t i;

  if (!capacity)
    return NULL;

  array_len = _next_power2(capacity /
              (FLOWMAP_FILL_RATIO * FLOWMAP_ENTRIES_PER_NODE));
  if (array_len == 0)
    return NULL;

  if (array_len > UINT32_MAX)
    return NULL;

  if (array_len < FLOWMAP_MIN_LEN)
    array_len = FLOWMAP_MIN_LEN;

  m = malloc(sizeof(*m));
  if (!m)
    return NULL;

  m->array = aligned_alloc(LEVEL1_DCACHE_LINESIZE,
                            sizeof(flowmap_node) * array_len);
  if (!m->array) {
    free(m);
    return NULL;
  }

  m->n_overflow = capacity * FLOWMAP_OVERFLOW_RATIO;
  if (m->n_overflow < 1)
    m->n_overflow = 1;

  m->overflow = calloc(m->n_overflow, sizeof(flowmap_overflow_node));
  if (!m->overflow) {
    free(m->array);
    free(m);
    return NULL;
  }

  m->capacity = capacity;
  m->array_mask = array_len - 1;
  m->elem_count = ATOMIC_VAR_INIT(0);
  m->seed = 0;
  m->hash = stafford_mix64;
  m->overflow_list_head = 0;
  m->overflow_count = 0;
  m->overflow_idx = 0;
  atomic_flag_clear(&m->overflow_lock);

  // initialize array
  memset(m->array, 0, sizeof(flowmap_node) * array_len);
  for (i=0; i < array_len; i++) {
    m->array[i].next = ATOMIC_VAR_INIT(FLOWMAP_NODE_NEXT_INITIALIZER);
  }

  // initialize overflow free list
  for (i=0; i < m->n_overflow; i++) {
    m->overflow[i].next = i+1;
  }
  m->overflow[m->n_overflow-1].next = FLOWMAP_NODE_NEXT_INITIALIZER;

  return m;
}

void flowmap_delete(flowmap *m) {
  assert(m);

  free(m->array);
  free(m->overflow);
  free(m);
}

//  1: key/value inserted
// -1: key already exists, value is unchanged
// -2: no memory to insert key/value
int flowmap_insert(flowmap *m, uint64_t key, uint8_t tag, uint8_t value,
                    uint32_t expiration, uint32_t time) {
  assert(m);
  assert(expiration);

  uint64_t hash, hashtag;
  flowmap_node *n;
  flowmap_entry *entry;
  bool is_overflow;
  uint32_t *prev;
  int rv;

  hash = m->hash(key, m->seed);
  n = &m->array[hash & m->array_mask];
  hashtag = (hash & FLOWMAP_HASH_MASK) + (tag << FLOWMAP_TAG_SHIFT);
  entry = NULL;
  prev = NULL;

  // acquire lock before accessing the chain
  msb_spinlock32_lock(&n->next);

  switch (_flowmap_search(m, hashtag, n, time, true, &entry, &is_overflow,
                          &prev)) {
    case -1:  // not found, but available
      entry->entry = hashtag + value;
      entry->expiration = expiration;
      rv = 1;
      break;
    case 1:   // key found
      rv = -1;
      break;
    case -2:  // not found, but no room
      rv = -2;
      break;
    default:  // shouldn't get here
      rv = -2;
      assert(0);
  }

  // release the locks
  if (is_overflow)
    _flowmap_overflow_unlock(m);
  msb_spinlock32_unlock(&n->next);

  return rv;
}

/*! get the value of an associated key and tag from the map
  \param[in] m the map
  \param[in] key the key whose value should be retrieved
  \param[in] tag the tag whose value should be retrieved
  \param[out] value the associated value, if found
  \param[in] expiration update the entry's expiration on success
  \param[in] time the current time
  \returns
  1:success
  -1:key not found or expired
*/
int flowmap_get(flowmap *m, uint64_t key, uint8_t tag, uint8_t *value,
                uint32_t expiration, uint32_t time) {
  assert(m);

  uint64_t hash, hashtag;
  flowmap_node *n;
  flowmap_entry *entry;
  bool is_overflow;
  uint32_t *prev;
  int rv;

  hash = m->hash(key, m->seed);
  n = &m->array[hash & m->array_mask];
  hashtag = (hash & FLOWMAP_HASH_MASK) + (tag << FLOWMAP_TAG_SHIFT);
  entry = NULL;
  prev = NULL;

  // acquire lock before accessing the chain
  msb_spinlock32_lock(&n->next);

  switch (_flowmap_search(m, hashtag, n, time, false, &entry, &is_overflow,
                          &prev)) {
    case 1:   // found
      rv = 1;
      *value = entry->entry & FLOWMAP_VALUE_MASK;
      entry->expiration = expiration;
      break;
    case -3:  // not found
      rv = -1;
      break;
    default:  // shouldn't get here
      rv = -1;
      assert(0);
  }

  // release the locks
  if (is_overflow)
    _flowmap_overflow_unlock(m);
  msb_spinlock32_unlock(&n->next);

  return rv;
}

/*! set the value of an associated key and tag from the map
  \param[in] m the map
  \param[in] key the key whose value should be set
  \param[in] tag the tag whose value should be set
  \param[out] value the value to set, if found
  \param[in] expiration update the entry's expiration on success
  \param[in] time the current time
  \returns
  1:success
  -1:key not found or expired
*/
int flowmap_set(flowmap *m, uint64_t key, uint8_t tag, uint8_t value,
                uint32_t expiration, uint32_t time) {
  assert(m);

  uint64_t hash, hashtag;
  flowmap_node *n;
  flowmap_entry *entry;
  bool is_overflow;
  uint32_t *prev;
  int rv;

  hash = m->hash(key, m->seed);
  n = &m->array[hash & m->array_mask];
  hashtag = (hash & FLOWMAP_HASH_MASK) + (tag << FLOWMAP_TAG_SHIFT);
  entry = NULL;
  prev = NULL;

  // acquire lock before accessing the chain
  msb_spinlock32_lock(&n->next);

  switch (_flowmap_search(m, hashtag, n, time, false, &entry, &is_overflow,
                          &prev)) {
    case 1:   // found
      entry->entry = hashtag + value;
      entry->expiration = expiration;
      rv = 1;
      break;
    case -3:  // not found
      rv = -1;
      break;
    default:  // shouldn't get here
      rv = -1;
      assert(0);
  }

  // release the locks
  if (is_overflow)
    _flowmap_overflow_unlock(m);
  msb_spinlock32_unlock(&n->next);

  return rv;
}

/*! remove a key from the map
  \param[in] m the map
  \param[in] key the key to remove
  \param[in] tag the tag to remove
  \param[in] time the current time
  \returns
  2:key not found or expired
  1:success
*/
int flowmap_remove(flowmap *m, uint64_t key, uint8_t tag, uint32_t time) {
  assert(m);

  uint64_t hash, hashtag;
  flowmap_node *n;
  flowmap_entry *entry;
  flowmap_overflow_node *o;
  bool is_overflow;
  uint32_t *prev;
  int rv;

  hash = m->hash(key, m->seed);
  n = &m->array[hash & m->array_mask];
  hashtag = (hash & FLOWMAP_HASH_MASK) + (tag << FLOWMAP_TAG_SHIFT);
  entry = NULL;
  prev = NULL;

  // acquire lock before accessing the chain
  msb_spinlock32_lock(&n->next);

  switch (_flowmap_search(m, hashtag, n, time, false, &entry, &is_overflow,
                          &prev)) {
    case 1:
      rv = 1;
      if (IN_ARRAY(entry, m->array, m->array_mask + 1)) {
        entry->entry = 0;
        entry->expiration = 0;
      } else {  // overflow entry
        o = CONTAINER_OF(entry, struct flowmap_overflow_node, entry);
        if (prev == NULL) {
          msb_spinlock32_setval(&n->next, o->next);
        } else {
          *prev = o->next;
        }
        _flowmap_overflow_free(m, o);
      }
      break;
    case -3:  // not found
      rv = 2;
      break;
    default:  // shouldn't get here
      rv = 2;
      assert(0);
  }

  // release the locks
  if (is_overflow)
    _flowmap_overflow_unlock(m);
  msb_spinlock32_unlock(&n->next);

  return rv;
}

/*! attempt to get the value of an associated key and tag from the map
    if the key and tag exist, otherwise insert a new entry into the map
  \param[in] m the map
  \param[in] key the key whose value should be retrieved
  \param[in] tag the tag whose value should be retrieved
  \param[in, out] value if the key/tag exist, value = the associated value, otherwise this is the value to use for inserting the new entry
  \param[in] expiration set the entry's expiration on success
  \param[in] time the current time
  \returns
  2:insert success
  1:get success
  -1:no memory to insert key/value
*/
int flowmap_get_or_insert(flowmap *m, uint64_t key, uint8_t tag, uint8_t *value,
                          uint32_t expiration, uint32_t time) {
  assert(m);
  assert(value);
  assert(expiration);

  uint64_t hash, hashtag;
  flowmap_node *n;
  flowmap_entry *entry;
  bool is_overflow;
  uint32_t *prev;
  int rv;

  hash = m->hash(key, m->seed);
  n = &m->array[hash & m->array_mask];
  hashtag = (hash & FLOWMAP_HASH_MASK) + (tag << FLOWMAP_TAG_SHIFT);
  entry = NULL;
  prev = NULL;

  // acquire lock before accessing the chain
  msb_spinlock32_lock(&n->next);

  switch (_flowmap_search(m, hashtag, n, time, true, &entry, &is_overflow,
                          &prev)) {
    case 1:   // key found
      *value = entry->entry & FLOWMAP_VALUE_MASK;
      entry->expiration = expiration;
      rv = 1;
      break;
    case -1:  // not found, but available
      entry->entry = hashtag + *value;
      entry->expiration = expiration;
      rv = 2;
      break;
    case -2:  // not found, but no room
      rv = -1;
      break;
    default:  // shouldn't get here
      rv = -1;
      assert(0);
  }

  // release the locks
  if (is_overflow)
    _flowmap_overflow_unlock(m);
  msb_spinlock32_unlock(&n->next);

  return rv;
}

/*! attempt to set the value of an associated key and tag in the map
    if the key and tag exist, otherwise insert a new entry into the map
  \param[in] m the map
  \param[in] key the key whose value should be set
  \param[in] tag the tag whose value should be set
  \param[in] value the value to set/insert
  \param[in] expiration set the entry's expiration on success
  \param[in] time the current time
  \returns
  2:insert success
  1:set success
  -1:no memory to insert key/value
*/
int flowmap_set_or_insert(flowmap *m, uint64_t key, uint8_t tag, uint8_t value,
                          uint32_t expiration, uint32_t time) {
  assert(m);
  assert(value);
  assert(expiration);

  uint64_t hash, hashtag;
  flowmap_node *n;
  flowmap_entry *entry;
  bool is_overflow;
  uint32_t *prev;
  int rv;

  hash = m->hash(key, m->seed);
  n = &m->array[hash & m->array_mask];
  hashtag = (hash & FLOWMAP_HASH_MASK) + (tag << FLOWMAP_TAG_SHIFT);
  entry = NULL;
  prev = NULL;

  // acquire lock before accessing the chain
  msb_spinlock32_lock(&n->next);

  switch (_flowmap_search(m, hashtag, n, time, true, &entry, &is_overflow,
                          &prev)) {
    case 1:   // key found
      entry->entry = hashtag + value;
      entry->expiration = expiration;
      rv = 1;
      break;
    case -1:  // not found, but available
      entry->entry = hashtag + value;
      entry->expiration = expiration;
      rv = 2;
      break;
    case -2:  // not found, but no room
      rv = -1;
      break;
    default:  // shouldn't get here
      rv = -1;
      assert(0);
  }

  // release the locks
  if (is_overflow)
    _flowmap_overflow_unlock(m);
  msb_spinlock32_unlock(&n->next);

  return rv;
}

// private function definitions

//  1 = found, *entry points to the entry
// -1 = not found, if get_next, *entry points to available entry
// -2 = not found, if get_next, no room to insert, *entry is unmodified
// -3 = not found, !get_next
// *prev is only valid if !get_next
int _flowmap_search(flowmap *m, uint64_t hashtag, flowmap_node *n,
                    uint32_t time, bool get_next, flowmap_entry **entry,
                    bool *is_overflow, uint32_t **prev) {
  assert(m);

  flowmap_entry *e, *available = NULL;
  flowmap_overflow_node *o;
  uint32_t i, next;

  *prev = NULL;
  *is_overflow = false;

  // search the node
  for (i=0; i < FLOWMAP_ENTRIES_PER_NODE; i++) {
    e = &n->entries[i];
    // skip over expired entries
    if (e->expiration < time) {
      if (!available)
        available = e;
      continue;
    }

    // check for matching entries
    if (hashtag == (e->entry & FLOWMAP_HASHTAG_MASK)) {
      *entry = e;
      return 1;
    }
  }

  // continue searching in the overflow area, if any
  next = msb_spinlock32_getval(&n->next);
  if (next != FLOWMAP_NODE_NEXT_INITIALIZER) {
    *is_overflow = true;
    _flowmap_overflow_lock(m);
  }

  while (next != FLOWMAP_NODE_NEXT_INITIALIZER) {
    o = &m->overflow[next];
    e = &o->entry;

    // check expired entries
    if (e->expiration < time) {
      // free unnecessary entries
      if (available || !get_next) {
        // modify metadata to remove this entry from the chain
        if (*prev) {
          next = **prev;
          **prev = o->next;
        } else {  // in flowmap_node
          next = msb_spinlock32_getval(&n->next);
          msb_spinlock32_setval(&n->next, o->next);
        }
        // actually remove the entry
        _flowmap_overflow_free(m, o);
      } else {    // we can use this entry
        available = e;
        *is_overflow = true;
        *prev = &m->overflow[next].next;
        next = **prev;
      }
      continue;
    } // expired

    // check for matching entries
    if (hashtag == (e->entry & FLOWMAP_HASHTAG_MASK)) {
      *entry = e;
      *is_overflow = true;
      return 1;
    }

    *prev = &m->overflow[next].next;
    next = **prev;
  } // for overflow

  if (get_next) {
    if (available) {
      *entry = available;
    } else {    // allocate a new entry
      next = _flowmap_overflow_alloc(m);
      if (next == FLOWMAP_NODE_NEXT_INITIALIZER)
        return -2;

      // fixup prev to point to the new entry
      if (*prev) {
        **prev = next;
      } else {  // in flowmap_node
        msb_spinlock32_setval(&n->next, next);
      }

      *entry = &m->overflow[next].entry;
      *is_overflow = true;
    } // !available
    return -1;
  } // if (get_next)

  // end of the line...
  return -3;
}

// look for the next free entry for insertion
// returns the index of the entry, or FLOWMAP_NODE_NEXT_INITIALIZER if no room
// must be called with the overflow_lock held
uint32_t _flowmap_overflow_alloc(flowmap *m) {
  assert(m);

  uint32_t rv = m->overflow_list_head;

  if (rv != FLOWMAP_NODE_NEXT_INITIALIZER) {
    m->overflow_list_head = m->overflow[m->overflow_list_head].next;
    m->overflow[rv].next = FLOWMAP_NODE_NEXT_INITIALIZER;
    m->overflow_count++;
  }

  return rv;
}

// make a flowmap_overflow_node available for reuse
// must be called with the overflow_lock held
void _flowmap_overflow_free(flowmap *m, flowmap_overflow_node *n) {
  assert(m);
  assert(n);

  n->entry.entry = 0;
  n->entry.expiration = 0;
  n->next = m->overflow_list_head;
  m->overflow_count--;
  m->overflow_list_head = ((char*)n - (char*)m->overflow) / sizeof(*n);
}

void _flowmap_overflow_lock(flowmap *m) {
  while (atomic_flag_test_and_set_explicit(&m->overflow_lock,
                                            memory_order_acquire))
    MSB_SPINLOCK_PAUSE();
}

void _flowmap_overflow_unlock(flowmap *m) {
  atomic_flag_clear_explicit(&m->overflow_lock, memory_order_release);
}

/*! Round up to the next power of 2

  \param[in] i the int to round, 0 <= i <= SIZE_MAX/2 +1
  \returns the next highest power of 2
  \returns i if is already a power of 2
  \returns 0 when i > SIZE_MAX/2 +1
*/
size_t _next_power2(size_t i) {
  uint64_t j;

  if (i == 0)
    return 1;

  i--;
  for (j = 1; j < CHAR_BIT*sizeof(size_t)-1; j*=2)
    i |= i >> j;
  i++;

  return i;
}


text:
place: "Weinheim"
title: "Kostenlose senseBox Fortbildungen für Lehrkräfte an weiterführenden Schulen"
description: "Die Hopp Foundation for computer literacy & informatics bietet sechs unterschiedliche, kostenlose senseBox Fortbildungen zu den Themen Physical Computing, IoT, Luftqualitätsmessung, Smart Cities, Citizen Science und Digital Farming an. Anmeldung weiter Informationen https://snsbx.de/hopp-foundation"
link: "https://www.hopp-foundation.de/workshops/lehrer-workshops/weiterfuehrende-schulen/informatik/"
starting-date: 2020-03-10
ending-date: 2020-03-14
---


text:
package apollo.deploy_options;

import apollo.maven.MavenDeployOption;
import com.google.inject.Inject;
import com.google.inject.name.Named;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

public class SourcesDeployOption implements MavenDeployOption {

    private final String sourcesOption;

    @Inject
    public SourcesDeployOption(@Named("sourcesOption")String sourcesOption) {
        this.sourcesOption = sourcesOption;
    }

    @Override
    public Optional<String> getCommandOption(Path pathToPom) {
        Optional<String> sourcesOptional = Optional.empty();

        if (Files.exists(getSourcesPath(pathToPom))){
            sourcesOptional = Optional.of(sourcesOption + getSourcesPath(pathToPom).toString());
        }

        return sourcesOptional;
    }

    private Path getSourcesPath(Path pathToPom){
        int last = pathToPom.toString().lastIndexOf(".");
        return Paths.get(pathToPom.toString().substring(0, last) + "-sources.jar");
    }

}


text:
function hello (name) {
  return `Hello, ${name || 'Anonymous'}!`;
}

export default hello;


text:
package com.netflix.simianarmy.basic;

import java.util.Properties;

import com.netflix.simianarmy.MonkeyConfiguration;

/**
 * The Class BasicConfiguration.
 */
public class BasicConfiguration implements MonkeyConfiguration {

    /** The properties. */
    private Properties props;

    /**
     * Instantiates a new basic configuration.
     * @param props
     *            the properties
     */
    public BasicConfiguration(Properties props) {
        this.props = props;
    }

    /** {@inheritDoc} */
    @Override
    public boolean getBool(String property) {
        return getBoolOrElse(property, false);
    }

    /** {@inheritDoc} */
    @Override
    public boolean getBoolOrElse(String property, boolean dflt) {
        String val = props.getProperty(property);
        return val == null ? dflt : Boolean.parseBoolean(val);
    }

    /** {@inheritDoc} */
    @Override
    public double getNumOrElse(String property, double dflt) {
        String val = props.getProperty(property);
        return val == null ? dflt : Double.parseDouble(val);
    }

    /** {@inheritDoc} */
    @Override
    public String getStr(String property) {
        return getStrOrElse(property, null);
    }

    /** {@inheritDoc} */
    @Override
    public String getStrOrElse(String property, String dflt) {
        String val = props.getProperty(property);
        return val == null ? dflt : val;
    }

    /** {@inheritDoc} */
    @Override
    public void reload() {
        // BasicConfiguration is based on static properties, so reload is a no-op
    }

    @Override
    public void reload(String groupName) {
        // BasicConfiguration is based on static properties, so reload is a no-op
    }
}


text:
package connmgr

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"github.com/libp2p/go-libp2p-core/connmgr"
	"github.com/libp2p/go-libp2p-core/peer"

	"github.com/benbjohnson/clock"
)

// DefaultResolution is the default resolution of the decay tracker.
var DefaultResolution = 1 * time.Minute

// bumpCmd represents a bump command.
type bumpCmd struct {
	peer  peer.ID
	tag   *decayingTag
	delta int
}

// removeCmd represents a tag removal command.
type removeCmd struct {
	peer peer.ID
	tag  *decayingTag
}

// decayer tracks and manages all decaying tags and their values.
type decayer struct {
	cfg   *DecayerCfg
	mgr   *BasicConnMgr
	clock clock.Clock // for testing.

	tagsMu    sync.Mutex
	knownTags map[string]*decayingTag

	// lastTick stores the last time the decayer ticked. Guarded by atomic.
	lastTick atomic.Value

	// bumpTagCh queues bump commands to be processed by the loop.
	bumpTagCh   chan bumpCmd
	removeTagCh chan removeCmd
	closeTagCh  chan *decayingTag

	// closure thingies.
	closeCh chan struct{}
	doneCh  chan struct{}
	err     error
}

var _ connmgr.Decayer = (*decayer)(nil)

// DecayerCfg is the configuration object for the Decayer.
type DecayerCfg struct {
	Resolution time.Duration
	Clock      clock.Clock
}

// WithDefaults writes the default values on this DecayerConfig instance,
// and returns itself for chainability.
//
//  cfg := (&DecayerCfg{}).WithDefaults()
//  cfg.Resolution = 30 * time.Second
//  t := NewDecayer(cfg, cm)
func (cfg *DecayerCfg) WithDefaults() *DecayerCfg {
	cfg.Resolution = DefaultResolution
	return cfg
}

// NewDecayer creates a new decaying tag registry.
func NewDecayer(cfg *DecayerCfg, mgr *BasicConnMgr) (*decayer, error) {
	// use real time if the Clock in the config is nil.
	if cfg.Clock == nil {
		cfg.Clock = clock.New()
	}

	d := &decayer{
		cfg:         cfg,
		mgr:         mgr,
		clock:       cfg.Clock,
		knownTags:   make(map[string]*decayingTag),
		bumpTagCh:   make(chan bumpCmd, 128),
		removeTagCh: make(chan removeCmd, 128),
		closeTagCh:  make(chan *decayingTag, 128),
		closeCh:     make(chan struct{}),
		doneCh:      make(chan struct{}),
	}

	d.lastTick.Store(d.clock.Now())

	// kick things off.
	go d.process()

	return d, nil
}

func (d *decayer) RegisterDecayingTag(name string, interval time.Duration, decayFn connmgr.DecayFn, bumpFn connmgr.BumpFn) (connmgr.DecayingTag, error) {
	d.tagsMu.Lock()
	defer d.tagsMu.Unlock()

	if _, ok := d.knownTags[name]; ok {
		return nil, fmt.Errorf("decaying tag with name %s already exists", name)
	}

	if interval < d.cfg.Resolution {
		log.Warnf("decay interval for %s (%s) was lower than tracker's resolution (%s); overridden to resolution",
			name, interval, d.cfg.Resolution)
		interval = d.cfg.Resolution
	}

	if interval%d.cfg.Resolution != 0 {
		log.Warnf("decay interval for tag %s (%s) is not a multiple of tracker's resolution (%s); "+
			"some precision may be lost", name, interval, d.cfg.Resolution)
	}

	lastTick := d.lastTick.Load().(time.Time)
	tag := &decayingTag{
		trkr:     d,
		name:     name,
		interval: interval,
		nextTick: lastTick.Add(interval),
		decayFn:  decayFn,
		bumpFn:   bumpFn,
	}

	d.knownTags[name] = tag
	return tag, nil
}

// Close closes the Decayer. It is idempotent.
func (d *decayer) Close() error {
	select {
	case <-d.doneCh:
		return d.err
	default:
	}

	close(d.closeCh)
	<-d.doneCh
	return d.err
}

// process is the heart of the tracker. It performs the following duties:
//
//  1. Manages decay.
//  2. Applies score bumps.
//  3. Yields when closed.
func (d *decayer) process() {
	defer close(d.doneCh)

	ticker := d.clock.Ticker(d.cfg.Resolution)
	defer ticker.Stop()

	var (
		bmp   bumpCmd
		now   time.Time
		visit = make(map[*decayingTag]struct{})
	)

	for {
		select {
		case now = <-ticker.C:
			d.lastTick.Store(now)

			d.tagsMu.Lock()
			for _, tag := range d.knownTags {
				if tag.nextTick.After(now) {
					// skip the tag.
					continue
				}
				// Mark the tag to be updated in this round.
				visit[tag] = struct{}{}
			}
			d.tagsMu.Unlock()

			// Visit each peer, and decay tags that need to be decayed.
			for _, s := range d.mgr.segments {
				s.Lock()

				// Entered a segment that contains peers. Process each peer.
				for _, p := range s.peers {
					for tag, v := range p.decaying {
						if _, ok := visit[tag]; !ok {
							// skip this tag.
							continue
						}

						// ~ this value needs to be visited. ~
						var delta int
						if after, rm := tag.decayFn(*v); rm {
							// delete the value and move on to the next tag.
							delta -= v.Value
							delete(p.decaying, tag)
						} else {
							// accumulate the delta, and apply the changes.
							delta += after - v.Value
							v.Value, v.LastVisit = after, now
						}
						p.value += delta
					}
				}

				s.Unlock()
			}

			// Reset each tag's next visit round, and clear the visited set.
			for tag := range visit {
				tag.nextTick = tag.nextTick.Add(tag.interval)
				delete(visit, tag)
			}

		case bmp = <-d.bumpTagCh:
			var (
				now       = d.clock.Now()
				peer, tag = bmp.peer, bmp.tag
			)

			s := d.mgr.segments.get(peer)
			s.Lock()

			p := s.tagInfoFor(peer)
			v, ok := p.decaying[tag]
			if !ok {
				v = &connmgr.DecayingValue{
					Tag:       tag,
					Peer:      peer,
					LastVisit: now,
					Added:     now,
					Value:     0,
				}
				p.decaying[tag] = v
			}

			prev := v.Value
			v.Value, v.LastVisit = v.Tag.(*decayingTag).bumpFn(*v, bmp.delta), now
			p.value += v.Value - prev

			s.Unlock()

		case rm := <-d.removeTagCh:
			s := d.mgr.segments.get(rm.peer)
			s.Lock()

			p := s.tagInfoFor(rm.peer)
			v, ok := p.decaying[rm.tag]
			if !ok {
				s.Unlock()
				continue
			}
			p.value -= v.Value
			delete(p.decaying, rm.tag)
			s.Unlock()

		case t := <-d.closeTagCh:
			// Stop tracking the tag.
			d.tagsMu.Lock()
			delete(d.knownTags, t.name)
			d.tagsMu.Unlock()

			// Remove the tag from all peers that had it in the connmgr.
			for _, s := range d.mgr.segments {
				// visit all segments, and attempt to remove the tag from all the peers it stores.
				s.Lock()
				for _, p := range s.peers {
					if dt, ok := p.decaying[t]; ok {
						// decrease the value of the tagInfo, and delete the tag.
						p.value -= dt.Value
						delete(p.decaying, t)
					}
				}
				s.Unlock()
			}

		case <-d.closeCh:
			return
		}
	}
}

// decayingTag represents a decaying tag, with an associated decay interval, a
// decay function, and a bump function.
type decayingTag struct {
	trkr     *decayer
	name     string
	interval time.Duration
	nextTick time.Time
	decayFn  connmgr.DecayFn
	bumpFn   connmgr.BumpFn

	// closed marks this tag as closed, so that if it's bumped after being
	// closed, we can return an error. 0 = false; 1 = true; guarded by atomic.
	closed int32
}

var _ connmgr.DecayingTag = (*decayingTag)(nil)

func (t *decayingTag) Name() string {
	return t.name
}

func (t *decayingTag) Interval() time.Duration {
	return t.interval
}

// Bump bumps a tag for this peer.
func (t *decayingTag) Bump(p peer.ID, delta int) error {
	if atomic.LoadInt32(&t.closed) == 1 {
		return fmt.Errorf("decaying tag %s had been closed; no further bumps are accepted", t.name)
	}

	bmp := bumpCmd{peer: p, tag: t, delta: delta}

	select {
	case t.trkr.bumpTagCh <- bmp:
		return nil
	default:
		return fmt.Errorf(
			"unable to bump decaying tag for peer %s, tag %s, delta %d; queue full (len=%d)",
			p.Pretty(), t.name, delta, len(t.trkr.bumpTagCh))
	}
}

func (t *decayingTag) Remove(p peer.ID) error {
	if atomic.LoadInt32(&t.closed) == 1 {
		return fmt.Errorf("decaying tag %s had been closed; no further removals are accepted", t.name)
	}

	rm := removeCmd{peer: p, tag: t}

	select {
	case t.trkr.removeTagCh <- rm:
		return nil
	default:
		return fmt.Errorf(
			"unable to remove decaying tag for peer %s, tag %s; queue full (len=%d)",
			p.Pretty(), t.name, len(t.trkr.removeTagCh))
	}
}

func (t *decayingTag) Close() error {
	if !atomic.CompareAndSwapInt32(&t.closed, 0, 1) {
		log.Warnf("duplicate decaying tag closure: %s; skipping", t.name)
		return nil
	}

	select {
	case t.trkr.closeTagCh <- t:
		return nil
	default:
		return fmt.Errorf("unable to close decaying tag %s; queue full (len=%d)", t.name, len(t.trkr.closeTagCh))
	}
}


text:
// -*- c-basic-offset: 2; related-file-name: "insert.h" -*-
/*
 * @(#)$Id$
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
 * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.
 * Or
 * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
 * Berkeley, CA,  94707. Attention: P2 Group.
 *
 */

#include "commitBuf.h"
#include "commonTable.h"
#include "val_str.h"
#include "plumber.h"
#include "scheduler.h"

DEFINE_ELEMENT_INITS(CommitBuf, "CommitBuf");

CommitBuf::CommitBuf(string name)
  : Element(name, 1, 1),
    _action(new CommitBuf::Action(boost::bind(&CommitBuf::flush, this, _1))) { }

CommitBuf::CommitBuf(TuplePtr args)
  : Element(Val_Str::cast((*args)[2]),1,1),
    _action(new CommitBuf::Action(boost::bind(&CommitBuf::flush, this, _1))) { }

void CommitBuf::flush(TupleMSet *buffer)
{
  ELEM_WORDY("CommitBuf Flushing "
             << buffer->size()
             << " Tuples");
  for (TupleMSet::iterator it = buffer->begin();
       it!= buffer->end();it++){
    if (!output(0)->push(*it, 0) == 1) {
      throw Element::Exception("COMMIT BUFFER: down stream element can't handle all tuples!");
    }
  }
}

int
CommitBuf::initialize()
{
  Plumber::scheduler()->action(_action);
  return 0;
}

int
CommitBuf::push(int port, TuplePtr t, b_cbv cb)
{
  _action->addTuple(t);
  return 1;
}

/**********************************
* CommitBuf::Action
*/

CommitBuf::Action::Action(CommitBuf::FlushCB cb)
  : _flush(cb) {}

void
CommitBuf::Action::commit()
{
  _flush(&_buffer);
  _buffer.clear();

}

void
CommitBuf::Action::abort()
{
  _buffer.clear();
}


text:
import { Component } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import OutputPort from '../output-port';
import SubsetPort from './subset-port';
import { SubsetPackage } from '@/data/package';

@Component
export default class SubsetOutputPort extends mixins(OutputPort, SubsetPort) {
  protected isSelection = false;
  protected reverseOutputDirection = false;

  /** Clears package items but retains the dataset. */
  public clearPackageItems() {
    this.package.clearItems();
    this.isUpdated = true;
  }

  /** Clears package items and the dataset. */
  public clear() {
    this.package.clearDataset();
    this.clearPackageItems();
  }

  /**
   * Updates the subset package. Avoid setting isUpdated to true when neither the dataset nor the subset changes.
   */
  public updatePackage(pkg: SubsetPackage) {
    const prevPkg = this.package;
    this.package = pkg;
    if (!prevPkg.isSamePackage(pkg)) {
      this.isUpdated = true;
    }
  }

  protected tooltip(): string {
    return `${this.package.numItems()} items`;
  }

  protected get iconClasses(): string {
    if (this.isSelection) {
      return 'far fa-square';
    }
    return this.maxConnections === 1 ? 'fas fa-circle' :
      (!this.reverseOutputDirection ? 'fas fa-caret-right' : 'fas fa-caret-left');
  }
}


text:
namespace Microsoft.Azure.Search
{
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// DocumentsOperations operations.
    /// </summary>
    public partial interface IDocumentsOperations
    {
        /// <summary>
        /// Queries the number of documents in the Azure Search index.
        /// </summary>
        /// <param name='searchRequestOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        Task<AzureOperationResponse<long>> CountWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
import { ProxyNativeModule } from 'expo-modules-core';

import { Notification, NotificationContentInput } from './Notifications.types';

export interface NotificationPresenterModule extends ProxyNativeModule {
  getPresentedNotificationsAsync?: () => Promise<Notification[]>;
  presentNotificationAsync?: (
    identifier: string,
    content: NotificationContentInput
  ) => Promise<string>;
  dismissNotificationAsync?: (identifier: string) => Promise<void>;
  dismissAllNotificationsAsync?: () => Promise<void>;
}


text:
Quaggan
======

Extremely basic URL Shortener

Requirements
------------

* Ruby 2.1.0 or newer
* Rails 4.0.2 or newer
* PostgreSQL 9.1 or newer
* Git

Database
--------

* PostgreSQL with ActiveRecord

Development
-----------

* Template Engine: ERB
* Front-end Framework: Twitter Bootstrap (Sass)
* Form Builder: Bootstrap Form
* Authentication: Devise
* Authorization: CanCan

Installation
------------

Installation guide, set up PostgreSQL, then the project.

#### PostgreSQL

* Create a user and the databases
```
createuser quaggan -d -s
createdb -Oquaggan -Eutf8 quaggan_development (only needed for development)
createdb -Oquaggan -Eutf8 quaggan_production (only needed for production)
createdb -Oquaggan -Eutf8 quaggan_test (only needed for development)
```

#### Project

###### Development
* Pick a folder you'd like to use and clone the git repository in there
```
cd <where-you-want-the-project>
git clone git@github.com:nohm/quaggan.git
cd quaggan
```
* Install dependencies
```
bundle install
```
* Fill in the config file `config/application.yml`
```
<your-text-editor> config/application.yml
```
* Create database tables and base data and initialize routes
```
rake db:migrate
rake db:seed
rake routes
```
* Start the server and work on it!
```
sh script/server
```

###### Production
* You can use the development guide if you want, but to deploy your own version use this
* First follow the development version for your local environment, then in that folder;
* Configure `config/deploy.rb`
```
<your-text-editor> config/deploy.rb
```
* Prepare your server using `mina`
```
mina setup
```
* Copy over or edit  `config/application.yml` and `config/database.yml`
```
scp config/application.yml <user>@<server>:<deploy-location>/shared/config/
scp config/database.yml <user>@<server>:<deploy-location>/shared/config/
OR
<your-text-editor> <deploy-location>/shared/config/application.yml
<your-text-editor> <deploy-location>/shared/config/database.yml
```
* Deploy to your server using `mina`
```
mina deploy
```
* If you use `Passenger Phusion` the application will be running now
* If you don't you'll have to edit `config/deploy.rb` to start the server, or use your own solution

Contributing
------------

If you make improvements to this application, please share with others.

* Fork the project on GitHub.
* Make your feature addition or bug fix.
* Commit with Git.
* Send the author a pull request.

License
-------

MIT


text:
const Koa = require('koa')
const fs = require('fs')

const app = new Koa()
const port = 3004

const write = (path, data) => {
	return new Promise((resolve, reject) => {
		fs.writeFile(path, data, err => {
			if (err) reject(err)
			else resolve(data)
		})
	})
}

const parsePost = ctx => {
	return new Promise((resolve, reject) => {
		try {
			let postData = ''
			ctx.req.addListener('data', data => {
				postData += data
			})

			ctx.req.addListener('end', () => {
				console.log(postData)
				resolve(parseQueryString(postData))
			})
		} catch (err) {
			reject(err)
		}
	})
}

// 解析 post 数据 foo=bar&baz=qux&1234567=1234567
const parseQueryString = queryString => {
	// 仅处理最简单情况
	let query = {}
	let queryList = queryString.split('&')
	queryList.map(item => {
	  itemArray = item.split('=')
		query[itemArray[0]] = decodeUitemArray[1]
	})
	console.log(queryList)
	return query
}
app.use(async ctx => {
	let url = ctx.url

	let reqQuery = ctx.query
	let reqQueryString = ctx.querystring
	//console.log('req object ...')
	//let ctxReq = ''
	//for (let prop in ctx.req) {
		//ctxReq = ctxReq.concat('\n', prop)
		//console.log(ctxReq)
	//}
	//let req = '\n'.concat(...ctxReq)
	//await write('ctx.req.txt', req)
	// console.log('Process ID is: ', process.pid)
	if (url == '/' && ctx.method == 'GET')
		ctx.body = {
			url,
			reqQuery,
			reqQueryString
		}
	else {
		let postData = await parsePost(ctx)
		ctx.body = postData
	}
})

app.listen(port)

console.log(`running on http://localhost:${port}`)


text:
@interface SLApplicationBundle : NSObject

@property (nonatomic, readonly) NSString *path;
@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) NSString *displayName;
@property (nonatomic, readonly) NSString *version;
@property (nonatomic, readonly) NSString *identifier;
@property (nonatomic, readonly) NSString *size;
@property (nonatomic, readonly) NSImage *icon;
@property (nonatomic, readonly, getter = isSystemApplication) BOOL systemApplication;

- (instancetype)initWithApplicationDirectoryPath:(NSString *)path;

@end


text:
<?php

namespace CoreTest\Form\Element;

use PHPUnit\Framework\TestCase;

use Core\Form\Element\ToggleButton;

/**
 *
 * @backupGlobals disabled
 * @covers \Core\Form\Element\ToggleButton
 */
class ToggleButtonTest extends TestCase
{

    /**
     * @var ToggleButton
     */
    protected $target;

    protected function setUp(): void
    {
        $this->target = new ToggleButton();
    }

    public function testConstructor()
    {
        $this->assertInstanceOf('Core\Form\Element\ToggleButton', $this->target);
        $this->assertInstanceOf('Laminas\Form\Element', $this->target);
        $this->assertAttributeSame('toggleButton', 'viewHelper', $this->target);
    }

    public function testSetGetViewHelper()
    {
        $expected = "my/view/helper";
        $this->target->setViewHelper($expected);
        $this->assertEquals($expected, $this->target->getViewHelper());
    }
}


text:
#region License

// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System;
using System.Runtime.Serialization;

namespace FluentMigrator.Exceptions
{
    [Serializable]
    public class ProcessorFactoryNotFoundException : FluentMigratorException
    {
        public ProcessorFactoryNotFoundException()
        {
        }

        public ProcessorFactoryNotFoundException(string message) : base(message)
        {
        }

        public ProcessorFactoryNotFoundException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        public ProcessorFactoryNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
import baseConfig from "./rollup.base.config.js";
import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import globals from "rollup-plugin-node-globals";
import json from "rollup-plugin-json";

const filepath = process.env.filepath;
const filename = filepath.replace(/.+\//, "");
const basename = filename.replace(/\..+/, "");

export default Object.assign(baseConfig, {
  entry: "dist/" + filepath,
  dest: "website/static/lib/" + filename,
  format: "iife",
  plugins: [json(), resolve({ preferBuiltins: true }), commonjs(), globals()],
  useStrict: false,
  moduleName: basename.replace(/.+-/, ""),
  external: ["assert", "fs", "module"]
});


text:
var fs = require('fs');
var parse = require('..');

var large = fs.readFileSync('examples/page.xml', 'utf8');
var small = fs.readFileSync('examples/developerforce.xml', 'utf8');

suite('parse', function(){
  bench('small', function(){
    parse(small)
  })

  bench('large', function(){
    parse(large)
  })
})


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragonChange : MonoBehaviour {
    [SerializeField]
    GameObject lightning;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}