text:
"""convertcal.py: Converts several ICS files and exports a Javascript array suitable for fullcalendar.io."""

__author__      = "Ricardo Band <xen@c-base.org>, Uwe Kamper <uk@c-base.org>, cketti <cketti@c-base.org>"
__copyright__   = "Copyright 2016-2017, Berlin, Germany"

import urllib.request
from copy import copy
from dateutil.rrule import rrulestr, rruleset
from datetime import datetime, timedelta, date
import pytz
import json
import os
import re
import sys
import traceback

from icalendar import Calendar

DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

# Parameter dict used for timedeltas, e.g. timedelta(**INTO_PAST)
# From now, what is the oldest date that we want to list?
INTO_PAST = {
    'days': 365
}

berlin = pytz.timezone('Europe/Amsterdam')

# Parameter dict used for timedeltas, e.g. timedelta(**INTO_FUTURE)
# From now, what is the furthest we want to expand recurring events into the future.
INTO_FUTURE = {
    'days': 365
}

newcal = Calendar()
newcal.add('prodid', '-//' + 'c-base' + '//' + 'c-base.org' + '//')
newcal.add('version', '2.0')
newcal.add('x-wr-calname', 'c-base events')

def do_one_ics(ics, default_location):
    events = []
    global newcal
    cal = Calendar.from_ical(ics)
    oldest_non_recurring = datetime.utcnow().replace(tzinfo=pytz.utc) - timedelta(**INTO_PAST)

    all_events = []
    for ev_id, event in enumerate(cal.walk('vevent')):
        newcal.add_component(event)
        d = event.get('dtstart').dt
        de = get_end_date(event, d)
        title = clean_up_title(event.get('summary'))
        if d.year == 2019 and d.month == 5:
            print(repr(d))
            print("---->", title, event.get("rrule"))
        if not de:
            print("Skipping event: %s" % title)
            continue

        uid = event.get('uid', '')
        location = event.get('location', default_location)
        description = event.get('description', '')
        is_all_day = False
        if not isinstance(d, datetime):
            d = datetime(d.year, d.month, d.day, tzinfo=pytz.utc)
            is_all_day = True

        # If the event is a recurring event
        if event.get('rrule'):
            event_template = {
                "id": ev_id,
                "title": title,
                "description": description,
                "location": location,
                "allDay": is_all_day,
                "uid": uid,
            }

            events = get_events_from_rrule(event, event_template, d, de)
            all_events.extend(events)
            continue

        # Ignore regular events that are older than one year.
        if d < oldest_non_recurring:
            # print("Skipping non-recurring event %s because it is too old (%s)" %(event.get('summary'), d.isoformat()))
            continue

        # This is just a regular event, just use it as is
        current = {
            "id": ev_id,
            "title": title,
            "start": d.isoformat(),
            "description": description,
            "location": location,
            "uid": uid
        }
        if is_all_day == True:
            current["allDay"] = True
            current["end"] = de.isoformat()
        else:
            current["allDay"] = False
            current["end"] = de.isoformat()
        all_events.append(current)
    return all_events

def clean_up_title(title):
    if title == None:
        return "Kein Titel"
    return re.sub(r"\n", " ", title)

def get_events_from_rrule(ical_event, event_template, start_date, end_date):
    events = []

    ical_rrule = ical_event.get('rrule')
    ical_rrule_str = ical_rrule.to_ical().decode('utf-8')
    rrule = rrulestr(ical_rrule_str, ignoretz=True, dtstart=start_date.replace(tzinfo=None))
    ruleset = rruleset()
    ruleset.rrule(rrule)

    exdates = get_exdates(ical_event)
    for exdate in exdates:
        for exdate_date in exdate.dts:
            datetime_or_date = exdate_date.dt
            if isinstance(datetime_or_date, datetime):
                exclusion_datetime = datetime_or_date.replace(tzinfo=None)
            elif isinstance(datetime_or_date, date):
                exclusion_datetime = datetime(
                    year=datetime_or_date.year,
                    month=datetime_or_date.month,
                    day=datetime_or_date.day)
            else:
                continue

            ruleset.exdate(exclusion_datetime)

    after = datetime.utcnow() - timedelta(**INTO_PAST)
    before = datetime.utcnow() + timedelta(**INTO_FUTURE)
    rrule_instances = list(ruleset.between(after, before))
    for num, rrule_instance in enumerate(rrule_instances, start = 1):
        event = copy(event_template)
        event['uid'] = "{}-{}".format(event_template['uid'], num)
        event['start'] = berlin.localize(rrule_instance).isoformat()

        if not event["allDay"]:
            instance_end_date = datetime(rrule_instance.year, rrule_instance.month, rrule_instance.day,
                                         end_date.hour, end_date.minute, end_date.second)
            event["end"] = berlin.localize(instance_end_date).isoformat()
        print(repr(event))
        events.append(event)

    return events

def get_exdates(ical_event):
    exdate_ical = ical_event.get('exdate')
    if not exdate_ical:
        exdates = []
    elif isinstance(exdate_ical, list):
        exdates = exdate_ical
    else:
        exdates = [exdate_ical]

    return exdates

def get_end_date(event, start_date):
    dtend = event.get('dtend')
    if dtend:
        end_date = dtend.dt
    else:
        duration = event.get('duration')
        if not duration:
            return None
        end_date = start_date + duration.dt

    return end_date

export_name = os.path.join(os.path.dirname(__file__), 'html', 'exported', 'events.js')
export_json_name = os.path.join(os.path.dirname(__file__), 'html', 'exported', 'events.json')
merged_name = os.path.join(os.path.dirname(__file__), 'html', 'exported', 'c-base-events.ics')
error_name = os.path.join(os.path.dirname(__file__), 'html', 'exported', 'errors.js')
online_name = os.path.join(os.path.dirname(__file__), 'html', 'exported', 'online.js')

try:
    events_ics = urllib.request.urlopen('https://c.c-base.org/calendar/events.ics').read()
    c_base_events = do_one_ics(events_ics, 'mainhall')
    regulars_ics = urllib.request.urlopen('https://c.c-base.org/calendar/regulars.ics').read()
    regular_events = do_one_ics(regulars_ics, 'mainhall')
    online_ics = urllib.request.urlopen('https://c.c-base.org/calendar/online.ics').read()
    online_events = do_one_ics(online_ics, 'https://jitsi.c-base.org/mainhall')
    url = "https://c.c-base.org/calendar/seminars.ics"
    seminars_ics = urllib.request.urlopen(url).read()
    seminar_events = do_one_ics(seminars_ics, "seminarraum")

    # No errors happened. Make it known to the world!
    with open(os.path.realpath(error_name), mode="w") as outfh:
        outfh.write('window.c_base_errors = "";\n')
except Exception as e:
    traceback.print_exc(file=sys.stdout)
    print('### ERROR : ', str(e))
    with open(os.path.realpath(error_name), mode="w") as outfh:
        outfh.write('window.c_base_errors = ' + json.dumps(str(e)) + ";\n")
    exit(1)

with open(os.path.realpath(export_name), mode="w") as outfh:
    outfh.write("window.c_base_regulars = " + json.dumps(regular_events, indent=4, sort_keys=True) + ";\n")
    outfh.write("window.c_base_events = " + json.dumps(c_base_events, indent=4, sort_keys=True) + ";\n")
    outfh.write("window.c_base_seminars= " + json.dumps(seminar_events, indent=4, sort_keys=True) + ";\n")
    outfh.write("window.c_base_online = " + json.dumps(online_events, indent=4, sort_keys=True) + ";\n")
    outfh.write("window.lastUpdate = \"" + datetime.now().isoformat() +" UTC\";\n")

all_events = {
    "c_base_regulars": regular_events,
    "c_base_events": c_base_events,
    "c_base_seminars": seminar_events,
    "c_base_online": online_events,
    "lastUpdate": datetime.now().isoformat() +" UTC"
}

with open(os.path.realpath(export_json_name), mode="w") as outfh:
    outfh.write(json.dumps(all_events, indent=4, sort_keys=True) + "\n")

with open(os.path.join(os.path.dirname(__file__), 'html', 'exported', 'events.ics'), 'wb') as f:
    f.write(events_ics)

with open(os.path.join(os.path.dirname(__file__), 'html', 'exported', 'regulars.ics'), 'wb') as f:
    f.write(regulars_ics)

with open(os.path.join(os.path.dirname(__file__), 'html', 'exported', 'seminars.ics'), 'wb') as f:
    f.write(seminars_ics)

with open(os.path.join(os.path.dirname(__file__), 'html', 'exported', 'online.ics'), 'wb') as f:
    f.write(online_ics)

with open(os.path.realpath(merged_name) , 'wb') as f:
    f.write(newcal.to_ical())
    f.close()

with open(os.path.realpath(error_name), mode="w") as outfh:
    outfh.write('window.c_base_errors = "None";\n')

exit(0)


text:
namespace King.Service.Tests.Unit
{

    public class AdaptiveHelper : AdaptiveTask
    {
        public bool Work
        {
            get;
            set;
        }
        public override void Run(out bool workWasDone)
        {
            workWasDone = this.Work;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "sky/private_sky.h"
#include "sky/oskar_sky.h"

#ifdef __cplusplus
extern "C" {
#endif

void oskar_sky_set_spectral_index(oskar_Sky* sky, int index,
        double ref_frequency, double spectral_index, int* status)
{
    if (*status) return;

    oskar_mem_set_element_real(sky->reference_freq_hz, index,
            ref_frequency, status);
    oskar_mem_set_element_real(sky->spectral_index, index,
            spectral_index, status);
}

#ifdef __cplusplus
}
#endif


text:
package os

import (
	"internal/syscall/unix"
	"syscall"
)

// Pipe returns a connected pair of Files; reads from r return bytes written to w.
// It returns the files and an error, if any.
func Pipe() (r *File, w *File, err error) {
	var p [2]int

	e := unix.Pipe2(p[0:], syscall.O_CLOEXEC)
	if e != nil {
		return nil, nil, NewSyscallError("pipe", e)
	}

	return newFile(uintptr(p[0]), "|0", kindPipe), newFile(uintptr(p[1]), "|1", kindPipe), nil
}


text:
body.page-preview
{
padding-top:10px; padding-left:10px;
}
.page-preview .rnr-c-masterlistheader,
  .rnr-pagewrapper .page-preview .rnr-c-masterlistheader,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-masterlistheader
{
margin-bottom:5px;
}
.page-preview .rnr-b-masterlistheader,
  .rnr-pagewrapper .page-preview .rnr-b-masterlistheader,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-masterlistheader
{
white-space: nowrap;
}
.page-preview .rnr-b-masterlistheader,
  .rnr-pagewrapper .page-preview .rnr-b-masterlistheader,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-masterlistheader
{
text-align: left;
}
.page-preview .rnr-b-masterlistheader > *,
  .rnr-pagewrapper .page-preview .rnr-b-masterlistheader > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-masterlistheader > *
{

}
.page-preview .rnr-c-mastergrid,
  .rnr-pagewrapper .page-preview .rnr-c-mastergrid,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-mastergrid
{
margin-bottom:5px;
}
.page-preview .rnr-c-mastergrid,
  .rnr-pagewrapper .page-preview .rnr-c-mastergrid,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-mastergrid
{
min-width:100px;
}
.page-preview .rnr-b-masterlistfields,
  .rnr-pagewrapper .page-preview .rnr-b-masterlistfields,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-masterlistfields
{
white-space: normal;
}
.page-preview .rnr-b-masterlistfields,
  .rnr-pagewrapper .page-preview .rnr-b-masterlistfields,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-masterlistfields
{
text-align: left;
}
.page-preview .rnr-b-masterlistfields > *,
  .rnr-pagewrapper .page-preview .rnr-b-masterlistfields > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-masterlistfields > *
{

}
body.page-preview .rnr-bare
{
padding-right: 5px;
}


text:
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'build';

const presets = [];
const plugins = [];

switch (env) {
  case 'build':
  default:
    presets.push([
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
        modules: false,
      },
    ]);

    break;
}

export default { presets, plugins };


text:
*  String animation for UILabel text.

## Contents

* Currently contains these animations

	* **ZZDrawAnimation**
	* **ZZGradualAnimation**
	* **ZZWaveAnimation**
	* **ZZPathAnimation**

## Example usage

* **ZZDrawAnimation**

	![Examples](_Gifs/draw.gif)

	```objc
	ZZDrawAnimation *drawAnimation = [ZZDrawAnimation new];
    drawAnimation.duration = 5;
    [self.label zz_startAnimation:drawAnimation];
    ```
* **ZZGradualAnimation**

	![Examples](_Gifs/gradual.gif)

	```objc
	ZZGradualAnimation *gradualAnimation = [ZZGradualAnimation new];
    gradualAnimation.duration = 5;
    [self.label zz_startAnimation:gradualAnimation];
    ```
* **ZZWaveAnimation**

	![Examples](_Gifs/wave.gif)

	```objc
	ZZWaveAnimation *waveAnimation = [ZZWaveAnimation new];
    waveAnimation.duration = 5;
    [self.label zz_startAnimation:waveAnimation];
    ```
* **ZZPathAnimation**

	![Examples](_Gifs/path.gif)

	```objc
	ZZPathAnimation *pathAnimation = [ZZPathAnimation new];
    pathAnimation.duration = 5;
    pathAnimation.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(25, 400, 300, 150)];
    [self.label zz_startAnimation:pathAnimation];
    ```


text:
class AddCommentIp < ActiveRecord::Migration
  def up
    add_column :comments, :ip, :string
  end

  def down
    remove_column :comments, :ip
  end
end


text:
import _reduce from 'fast.js/array/reduce';
import invariant from 'invariant';

export const reduce = {
  method: function(reduceFn, initial) {
    invariant(
      typeof reduceFn === 'function',
      'reduce(...): reducer argument must be a function'
    );

    this._addPipeline('reduce', reduceFn, initial);
    return this;
  },

  process: function(docs, pipeObj) {
    return _reduce(docs, pipeObj.value, pipeObj.args[0]);
  },
};


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[
		[TestAction.create_mini_vm, 'vm1', 'cluster=cluster2'],
		[TestAction.change_vm_ha, 'vm1'],
		[TestAction.create_volume, 'volume1', 'cluster=cluster2', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume1'],
		[TestAction.create_volume_backup, 'volume1', 'volume1-backup1'],
		[TestAction.change_vm_ha, 'vm1'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.create_mini_vm, 'vm2', 'cluster=cluster1'],
		[TestAction.create_image_from_volume, 'vm2', 'vm2-image1'],
		[TestAction.poweroff_only, 'cluster=cluster1'],
		[TestAction.create_volume, 'volume2', 'cluster=cluster1', 'flag=scsi'],
		[TestAction.attach_volume, 'vm2', 'volume2'],
		[TestAction.delete_volume, 'volume2'],
		[TestAction.add_image, 'image2', 'root', 'http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2'],
		[TestAction.create_volume, 'volume3', 'cluster=cluster2', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume3'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.create_volume_backup, 'volume3', 'volume3-backup2'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.delete_volume_backup, 'volume3-backup2'],
		[TestAction.delete_image, 'vm2-image1'],
		[TestAction.expunge_image, 'vm2-image1'],
		[TestAction.create_volume, 'volume4', 'cluster=cluster1', 'flag=scsi'],
		[TestAction.attach_volume, 'vm2', 'volume4'],
		[TestAction.start_vm, 'vm2'],
		[TestAction.create_volume_backup, 'volume4', 'volume4-backup3'],
		[TestAction.stop_vm, 'vm2'],
		[TestAction.change_vm_ha, 'vm2'],
		[TestAction.poweroff_only, 'cluster=cluster1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.migrate_vm, 'vm1'],
		[TestAction.detach_volume, 'volume3'],
		[TestAction.create_volume, 'volume5', 'cluster=cluster1', 'flag=thin,scsi'],
		[TestAction.delete_volume_backup, 'volume1-backup1'],
		[TestAction.destroy_vm, 'vm1'],
		[TestAction.expunge_vm, 'vm1'],
		[TestAction.delete_volume, 'volume4'],
		[TestAction.expunge_volume, 'volume4'],
		[TestAction.create_mini_vm, 'vm3', 'cluster=cluster1'],
		[TestAction.create_mini_vm, 'vm4', 'cluster=cluster2'],
		[TestAction.create_vm_backup, 'vm4', 'vm4-backup4'],
		[TestAction.resize_data_volume, 'volume5', 5*1024*1024],
		[TestAction.poweroff_only, 'cluster=cluster2'],
		[TestAction.delete_vm_backup, 'vm4-backup4'],
])

'''
The final status:
Running:['vm2', 'vm3']
Stopped:['vm4']
Enadbled:['volume4-backup3', 'image2']
attached:[]
Detached:['volume3', 'volume5', 'volume1']
Deleted:['volume2', 'volume3-backup2', 'volume1-backup1', 'vm4-backup4']
Expunged:['vm1', 'volume4', 'vm2-image1']
Ha:['vm2']
Group:
'''


text:
using System;
using System.Windows.Forms;

namespace PrayerTime
{
    internal class ContextMenus
    {
        /// <summary>
        /// Is the About box displayed?
        /// </summary>
        private bool isAboutLoaded = false;

        /// <summary>
        /// Creates this instance.
        /// </summary>
        /// <returns>ContextMenuStrip</returns>
        public ContextMenuStrip Create()
        {
            // Add the default menu options.
            ContextMenuStrip menu = new ContextMenuStrip();
            ToolStripMenuItem item;
            ToolStripSeparator sep;

            // Separator.
            sep = new ToolStripSeparator();
            menu.Items.Add(sep);

            // Exit.
            item = new ToolStripMenuItem();
            item.Text = "Exit";
            item.Click += new System.EventHandler(Exit_Click);
            item.Image = Properties.Resources.Exit;
            menu.Items.Add(item);

            return menu;
        }

        /// <summary>
        /// Processes a menu item.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Exit_Click(object sender, EventArgs e)
        {
            // Quit without further ado.
            Application.Exit();
        }
    }
}


text:
module Gitlab
  module Ci
    class Config
      module Entry
        module Validatable
          extend ActiveSupport::Concern

          class_methods do
            def validator
              @validator ||= Class.new(Entry::Validator).tap do |validator|
                if defined?(@validations)
                  @validations.each { |rules| validator.class_eval(&rules) }
                end
              end
            end

            private

            def validations(&block)
              (@validations ||= []).append(block)
            end
          end
        end
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Sylake\SyliusConsumerPlugin\Denormalizer;

use Sylake\SyliusConsumerPlugin\Event\GroupUpdated;
use Sylake\SyliusConsumerPlugin\Model\Translations;

final class GroupUpdatedDenormalizer extends AkeneoDenormalizer
{
    /**
     * {@inheritdoc}
     */
    protected function denormalizePayload(array $payload)
    {
        return new GroupUpdated($payload['code'], new Translations($payload['labels']));
    }

    /**
     * {@inheritdoc}
     */
    protected function getSupportedMessageType(): string
    {
        return 'akeneo_group_updated';
    }
}


text:
package scala.compat.java8;

@FunctionalInterface
public interface JFunction1$mcII$sp extends JFunction1 {
    abstract int apply$mcII$sp(int v1);

    default Object apply(Object t) { return (Integer) apply$mcII$sp((Integer) t); }
}


text:
import unittest
from typing import Dict

from azure.cli.testsdk import ScenarioTest

class VersionTest(ScenarioTest):

    def test_version(self):
        output = self.cmd('az version').get_output_in_json()
        self.assertIn('azure-cli', output)
        self.assertIn('azure-cli-core', output)
        self.assertIn('azure-cli-telemetry', output)
        self.assertIn('extensions', output)
        self.assertIsInstance(output['extensions'], Dict)

if __name__ == '__main__':
    unittest.main()