text:
@implementation NSDate (extend)
- (BOOL)isToday
{
    return [[NSDate dateStartOfDay:self] isEqualToDate:[NSDate dateStartOfDay:[NSDate date]]];
}

+ (NSDate *)dateStartOfDay:(NSDate *)date {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *components =
    [gregorian               components:(NSCalendarUnitYear | NSCalendarUnitMonth |
                                         NSCalendarUnitDay) fromDate:date];
    return [gregorian dateFromComponents:components];
}

+ (BOOL)isSameDayWithTime:(NSTimeInterval )firstTime andTime:(NSTimeInterval )secondTime{
    NSDate *firstDate = [NSDate dateWithTimeIntervalSince1970:firstTime];
    NSDate *secondDate = [NSDate dateWithTimeIntervalSince1970:secondTime];
    return [firstDate isSameDayWithDate:secondDate];
}

+ (BOOL)isSameDayWithDate:(NSDate *)firstDate andDate:(NSDate *)secondDate {
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:firstDate];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:secondDate];

    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}

- (BOOL)isSameDayWithDate:(NSDate*)date {
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:self];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date];

    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}

+ (NSDate*)acquireTimeFromDate:(NSDate*)date {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comps = [calendar components:unitFlags fromDate:date];
    NSDate* result = [calendar dateFromComponents:comps];
    return result;
}

+ (NSInteger)acquireWeekDayFromDate:(NSDate*)date {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitWeekday;
    NSDateComponents* comps = [calendar components:unitFlags fromDate:date];
    return [comps weekday];
}

- (NSInteger)day {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitDay fromDate:self];
    return [components day];
}

- (NSInteger)month {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitMonth fromDate:self];
    return [components month];
}

- (NSInteger)year {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitYear fromDate:self];
    return [components year];
}

+(NSString *)stringWithTimestamp:(NSTimeInterval)tt format:(NSString *)format
{
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:tt];
	NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:format];
	return [formatter stringFromDate:date];
}
@end


text:
package org.apache.solr.core;

import org.apache.lucene.index.ConcurrentMergeScheduler;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.TieredMergePolicy;
import org.apache.lucene.util.InfoStream;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.handler.admin.ShowFileRequestHandler;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.IndexSchemaFactory;
import org.apache.solr.update.SolrIndexConfig;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.XPathConstants;
import java.io.IOException;
import java.io.InputStream;

public class TestConfig extends SolrTestCaseJ4 {

  @BeforeClass
  public static void beforeClass() throws Exception {
    initCore("solrconfig-test-misc.xml","schema-reversed.xml");
  }

  @Test
  public void testLib() throws IOException {
    SolrResourceLoader loader = h.getCore().getResourceLoader();
    InputStream data = null;
    String[] expectedFiles = new String[] { "empty-file-main-lib.txt",
            "empty-file-a1.txt",
            "empty-file-a2.txt",
            "empty-file-b1.txt",
            "empty-file-b2.txt",
            "empty-file-c1.txt" };
    for (String f : expectedFiles) {
      data = loader.openResource(f);
      assertNotNull("Should have found file " + f, data);
      data.close();
    }
    String[] unexpectedFiles = new String[] { "empty-file-c2.txt",
            "empty-file-d2.txt" };
    for (String f : unexpectedFiles) {
      data = null;
      try {
        data = loader.openResource(f);
      } catch (Exception e) { /* :NOOP: (un)expected */ }
      assertNull("should not have been able to find " + f, data);
    }
  }
  @Test
  public void testDisableRequetsHandler() throws Exception {
    assertNull(h.getCore().getRequestHandler("disabled"));
    assertNotNull(h.getCore().getRequestHandler("enabled"));
  }

  @Test
  public void testJavaProperty() {
    // property values defined in build.xml

    String s = solrConfig.get("propTest");
    assertEquals("prefix-proptwo-suffix", s);

    s = solrConfig.get("propTest/@attr1", "default");
    assertEquals("propone-${literal}", s);

    s = solrConfig.get("propTest/@attr2", "default");
    assertEquals("default-from-config", s);

    s = solrConfig.get("propTest[@attr2='default-from-config']", "default");
    assertEquals("prefix-proptwo-suffix", s);

    NodeList nl = (NodeList) solrConfig.evaluate("propTest", XPathConstants.NODESET);
    assertEquals(1, nl.getLength());
    assertEquals("prefix-proptwo-suffix", nl.item(0).getTextContent());

    Node node = solrConfig.getNode("propTest", true);
    assertEquals("prefix-proptwo-suffix", node.getTextContent());
  }

  // sometime if the config referes to old things, it must be replaced with new stuff
  @Test
  public void testAutomaticDeprecationSupport() {
    // make sure the "admin/file" handler is registered
    ShowFileRequestHandler handler = (ShowFileRequestHandler) h.getCore().getRequestHandler("/admin/file");
    assertTrue("file handler should have been automatically registered", handler != null);

  }

  // If defaults change, add test methods to cover each version
  @Test
  public void testDefaults() throws Exception {

    int numDefaultsTested = 0;
    int numNullDefaults = 0;

    SolrConfig sc = new SolrConfig(new SolrResourceLoader("solr/collection1"), "solrconfig-defaults.xml", null);
    SolrIndexConfig sic = sc.indexConfig;

    ++numDefaultsTested; assertEquals("default useCompoundFile", false, sic.getUseCompoundFile());

    ++numDefaultsTested; assertEquals("default maxBufferedDocs", -1, sic.maxBufferedDocs);
    ++numDefaultsTested; assertEquals("default maxMergeDocs", -1, sic.maxMergeDocs);
    ++numDefaultsTested; assertEquals("default mergeFactor", -1, sic.mergeFactor);

    ++numDefaultsTested; assertEquals("default ramBufferSizeMB", 100.0D, sic.ramBufferSizeMB, 0.0D);
    ++numDefaultsTested; assertEquals("default writeLockTimeout", -1, sic.writeLockTimeout);
    ++numDefaultsTested; assertEquals("default LockType", SolrIndexConfig.LOCK_TYPE_NATIVE, sic.lockType);

    ++numDefaultsTested; assertEquals("default infoStream", InfoStream.NO_OUTPUT, sic.infoStream);

    ++numDefaultsTested; ++numNullDefaults; assertNull("default mergePolicyInfo", sic.mergePolicyInfo);
    ++numDefaultsTested; ++numNullDefaults; assertNull("default mergeSchedulerInfo", sic.mergeSchedulerInfo);
    ++numDefaultsTested; ++numNullDefaults; assertNull("default mergedSegmentWarmerInfo", sic.mergedSegmentWarmerInfo);

    IndexSchema indexSchema = IndexSchemaFactory.buildIndexSchema("schema.xml", solrConfig);
    IndexWriterConfig iwc = sic.toIndexWriterConfig(h.getCore());

    assertNotNull("null mp", iwc.getMergePolicy());
    assertTrue("mp is not TMP", iwc.getMergePolicy() instanceof TieredMergePolicy);

    assertNotNull("null ms", iwc.getMergeScheduler());
    assertTrue("ms is not CMS", iwc.getMergeScheduler() instanceof ConcurrentMergeScheduler);

    assertNull("non-null mergedSegmentWarmer", iwc.getMergedSegmentWarmer());

    final int numDefaultsMapped = sic.toMap().size();
    assertEquals("numDefaultsTested vs. numDefaultsMapped+numNullDefaults ="+sic.toMap().keySet(), numDefaultsTested, numDefaultsMapped+numNullDefaults);
  }

  // sanity check that sys propertis are working as expected
  public void testSanityCheckTestSysPropsAreUsed() throws Exception {

    SolrConfig sc = new SolrConfig(new SolrResourceLoader("solr/collection1"), "solrconfig-basic.xml", null);
    SolrIndexConfig sic = sc.indexConfig;

    assertEquals("ramBufferSizeMB sysprop",
                 Double.parseDouble(System.getProperty("solr.tests.ramBufferSizeMB")),
                                    sic.ramBufferSizeMB, 0.0D);
    assertEquals("useCompoundFile sysprop",
                 Boolean.parseBoolean(System.getProperty("useCompoundFile")), sic.getUseCompoundFile());
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/US2ValidatorNumeric.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/US2ValidatorNumeric</TokenIdentifier>
			<Abstract type="html">The number validator checks for number string.</Abstract>
			<DeclaredIn>US2ValidatorNumeric.h</DeclaredIn>

			<NodeRef refid="16"/>
		</Token>

	</File>
</Tokens>


text:
using System;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;

using SharpVectors.Dom.Css;
using SharpVectors.Dom.Svg;

using SharpVectors.Runtime;

namespace SharpVectors.Renderers.Wpf
{
    public sealed class WpfPathRendering : WpfRendering
    {
        #region Constructors and Destructor

        public WpfPathRendering(SvgElement element)
            : base(element)
		{
		}

        #endregion

        #region Public Methods

        public override void BeforeRender(WpfDrawingRenderer renderer)
        {
            if (renderer == null)
            {
                return;
            }

            WpfDrawingContext context = renderer.Context;

            SetQuality(context);
            SetTransform(context);
            SetMask(context);
        }

        public override void Render(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;
            if (hint != SvgRenderingHint.Shape || hint == SvgRenderingHint.Clipping)
            {
                return;
            }
            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (String.Equals(_svgElement.ParentNode.LocalName, "clipPath") &&
                !context.RenderingClipRegion)
            {
                return;
            }

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            string sVisibility = styleElm.GetPropertyValue("visibility");
            string sDisplay    = styleElm.GetPropertyValue("display");
            if (String.Equals(sVisibility, "hidden") || String.Equals(sDisplay, "none"))
            {
                return;
            }

            DrawingGroup drawGroup = context.Peek();
            Debug.Assert(drawGroup != null);

            Geometry geometry = CreateGeometry(_svgElement, context.OptimizePath);

            if (geometry != null && !geometry.IsEmpty())
            {
                SetClip(context);

                WpfSvgPaint fillPaint = new WpfSvgPaint(context, styleElm, "fill");

                string fileValue = styleElm.GetAttribute("fill");

                Brush brush = fillPaint.GetBrush(geometry);

                WpfSvgPaint strokePaint = new WpfSvgPaint(context, styleElm, "stroke");
                Pen pen = strokePaint.GetPen();

                if (brush != null || pen != null)
                {
                    Transform transform = this.Transform;
                    if (transform != null && !transform.Value.IsIdentity)
                    {
                        geometry.Transform = transform;
                        if (brush != null)
                        {
                            Transform brushTransform = brush.Transform;
                            if (brushTransform == null || brushTransform == Transform.Identity)
                            {
                                brush.Transform = transform;
                            }
                            else
                            {
                                TransformGroup groupTransform = new TransformGroup();
                                groupTransform.Children.Add(brushTransform);
                                groupTransform.Children.Add(transform);
                                brush.Transform = groupTransform;
                            }
                        }
                    }
                    else
                    {
                        transform = null; // render any identity transform useless...
                    }

                    GeometryDrawing drawing = new GeometryDrawing(brush, pen, geometry);

                    string elementId = this.GetElementName();
                    if (!String.IsNullOrEmpty(elementId) && !context.IsRegisteredId(elementId))
                    {
                        drawing.SetValue(FrameworkElement.NameProperty, elementId);

                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetId(drawing, elementId);
                        }
                    }

                    Brush maskBrush = this.Masking;
                    Geometry clipGeom = this.ClipGeometry;
                    if (clipGeom != null || maskBrush != null)
                    {
                        //Geometry clipped = Geometry.Combine(geometry, clipGeom,
                        //    GeometryCombineMode.Exclude, null);

                        //if (clipped != null && !clipped.IsEmpty())
                        //{
                        //    geometry = clipped;
                        //}
                        DrawingGroup clipMaskGroup = new DrawingGroup();

                        Rect geometryBounds = geometry.Bounds;

                        if (clipGeom != null)
                        {
                            clipMaskGroup.ClipGeometry = clipGeom;

                            SvgUnitType clipUnits = this.ClipUnits;
                            if (clipUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }

                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                transformGroup.Children.Add(
                                    new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                                transformGroup.Children.Add(
                                    new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                                clipGeom.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    clipGeom.Transform = transform;
                                }
                            }
                        }
                        if (maskBrush != null)
                        {
                            SvgUnitType maskUnits = this.MaskUnits;
                            if (maskUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }

                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                transformGroup.Children.Add(
                                    new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                                transformGroup.Children.Add(
                                    new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                                DrawingGroup maskGroup = ((DrawingBrush)maskBrush).Drawing as DrawingGroup;
                                if (maskGroup != null)
                                {
                                    DrawingCollection maskDrawings = maskGroup.Children;
                                    for (int i = 0; i < maskDrawings.Count; i++)
                                    {
                                        Drawing maskDrawing = maskDrawings[i];
                                        GeometryDrawing maskGeomDraw = maskDrawing as GeometryDrawing;
                                        if (maskGeomDraw != null)
                                        {
                                            if (maskGeomDraw.Brush != null)
                                            {
                                                ConvertColors(maskGeomDraw.Brush);
                                            }
                                            if (maskGeomDraw.Pen != null)
                                            {
                                                ConvertColors(maskGeomDraw.Pen.Brush);
                                            }
                                        }
                                    }
                                }

                                //if (transformGroup != null)
                                //{
                                //    drawingBounds = transformGroup.TransformBounds(drawingBounds);
                                //}

                                //maskBrush.Viewbox = drawingBounds;
                                //maskBrush.ViewboxUnits = BrushMappingMode.Absolute;

                                //maskBrush.Stretch = Stretch.Uniform;

                                //maskBrush.Viewport = drawingBounds;
                                //maskBrush.ViewportUnits = BrushMappingMode.Absolute;

                                maskBrush.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    maskBrush.Transform = transform;
                                }
                            }

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

                        clipMaskGroup.Children.Add(drawing);
                        drawGroup.Children.Add(clipMaskGroup);
                    }
                    else
                    {
                        drawGroup.Children.Add(drawing);
                    }
                }
            }

            RenderMarkers(renderer, styleElm, context);
        }

        //==========================================================================
        private static float AlphaComposition(Color color)
        {
            float max = Math.Max(Math.Max(color.ScR, color.ScG), color.ScB);
            float min = Math.Min(Math.Min(color.ScR, color.ScG), color.ScB);

            return (min + max) / 2.0f;
        }

        //==========================================================================
        private static float AlphaComposition(Brush brush)
        {
            float alphaValue = 1.0f;

            if (brush != null)
            {
                if (brush is SolidColorBrush)
                {
                    float nextValue = AlphaComposition((brush as SolidColorBrush).Color);
                    if (nextValue > 0 && nextValue < 1)
                    {
                        alphaValue = nextValue;
                    }
                }
                else if (brush is GradientBrush)
                {
                    foreach (GradientStop gradient_stop in (brush as GradientBrush).GradientStops)
                    {
                        float nextValue = AlphaComposition(gradient_stop.Color);
                        if (nextValue > 0 && nextValue < 1)
                        {
                            alphaValue = nextValue;
                        }
                    }
                }
                //else if (brush is DrawingBrush)
                //{
                //    ConvertColors((brush as DrawingBrush).Drawing);
                //}
                else
                    throw new NotSupportedException();

            }

            return alphaValue;
        }

        //==========================================================================
        private static Color ConvertColor(Color color)
        {
            float max = Math.Max(Math.Max(color.ScR, color.ScG), color.ScB);
            float min = Math.Min(Math.Min(color.ScR, color.ScG), color.ScB);

            return Color.FromScRgb((min + max) / 2.0f, color.ScR, color.ScG, color.ScB);
        }

        //==========================================================================
        private static void ConvertColors(Brush brush)
        {
            if (brush != null)
            {
                SolidColorBrush solidBrush = null;
                GradientBrush gradientBrush = null;

                if (DynamicCast.Cast(brush, out solidBrush))
                {
                    solidBrush.Color = ConvertColor(solidBrush.Color);
                }
                else if (DynamicCast.Cast(brush, out gradientBrush))
                {
                    GradientStopCollection stopColl = gradientBrush.GradientStops;

                    foreach (GradientStop stop in stopColl)
                    {
                        stop.Color = ConvertColor(stop.Color);
                    }
                }
                //else if (brush is DrawingBrush)
                //{
                //    ConvertColors((brush as DrawingBrush).Drawing);
                //}
                else
                    throw new NotSupportedException();

            }
        }

        #endregion
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.HybridContainerService.Models;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.HybridContainerService
{
    public partial class HybridContainerServiceAgentPoolData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(ExtendedLocation))
            {
                writer.WritePropertyName("extendedLocation");
                writer.WriteObjectValue(ExtendedLocation);
            }
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("location");
            writer.WriteStringValue(Location);
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(Count))
            {
                writer.WritePropertyName("count");
                writer.WriteNumberValue(Count.Value);
            }
            if (Optional.IsCollectionDefined(AvailabilityZones))
            {
                writer.WritePropertyName("availabilityZones");
                writer.WriteStartArray();
                foreach (var item in AvailabilityZones)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(MaxCount))
            {
                writer.WritePropertyName("maxCount");
                writer.WriteNumberValue(MaxCount.Value);
            }
            if (Optional.IsDefined(MaxPods))
            {
                writer.WritePropertyName("maxPods");
                writer.WriteNumberValue(MaxPods.Value);
            }
            if (Optional.IsDefined(MinCount))
            {
                writer.WritePropertyName("minCount");
                writer.WriteNumberValue(MinCount.Value);
            }
            if (Optional.IsDefined(Mode))
            {
                writer.WritePropertyName("mode");
                writer.WriteStringValue(Mode.Value.ToString());
            }
            if (Optional.IsCollectionDefined(NodeLabels))
            {
                writer.WritePropertyName("nodeLabels");
                writer.WriteStartObject();
                foreach (var item in NodeLabels)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            if (Optional.IsCollectionDefined(NodeTaints))
            {
                writer.WritePropertyName("nodeTaints");
                writer.WriteStartArray();
                foreach (var item in NodeTaints)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(OSType))
            {
                writer.WritePropertyName("osType");
                writer.WriteStringValue(OSType.Value.ToString());
            }
            if (Optional.IsDefined(NodeImageVersion))
            {
                writer.WritePropertyName("nodeImageVersion");
                writer.WriteStringValue(NodeImageVersion);
            }
            if (Optional.IsDefined(VmSize))
            {
                writer.WritePropertyName("vmSize");
                writer.WriteStringValue(VmSize);
            }
            if (Optional.IsDefined(CloudProviderProfile))
            {
                writer.WritePropertyName("cloudProviderProfile");
                writer.WriteObjectValue(CloudProviderProfile);
            }
            if (Optional.IsDefined(Status))
            {
                writer.WritePropertyName("status");
                writer.WriteObjectValue(Status);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static HybridContainerServiceAgentPoolData DeserializeHybridContainerServiceAgentPoolData(JsonElement element)
        {
            Optional<AgentPoolExtendedLocation> extendedLocation = default;
            Optional<IDictionary<string, string>> tags = default;
            AzureLocation location = default;
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            Optional<int> count = default;
            Optional<IList<string>> availabilityZones = default;
            Optional<int> maxCount = default;
            Optional<int> maxPods = default;
            Optional<int> minCount = default;
            Optional<Mode> mode = default;
            Optional<IDictionary<string, string>> nodeLabels = default;
            Optional<IList<string>> nodeTaints = default;
            Optional<OSType> osType = default;
            Optional<string> nodeImageVersion = default;
            Optional<string> vmSize = default;
            Optional<CloudProviderProfile> cloudProviderProfile = default;
            Optional<AgentPoolProvisioningState> provisioningState = default;
            Optional<AgentPoolProvisioningStatusStatus> status = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("extendedLocation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    extendedLocation = AgentPoolExtendedLocation.DeserializeAgentPoolExtendedLocation(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("count"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            count = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("availabilityZones"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<string> array = new List<string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            availabilityZones = array;
                            continue;
                        }
                        if (property0.NameEquals("maxCount"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            maxCount = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("maxPods"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            maxPods = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("minCount"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            minCount = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("mode"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            mode = new Mode(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("nodeLabels"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                            foreach (var property1 in property0.Value.EnumerateObject())
                            {
                                dictionary.Add(property1.Name, property1.Value.GetString());
                            }
                            nodeLabels = dictionary;
                            continue;
                        }
                        if (property0.NameEquals("nodeTaints"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<string> array = new List<string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            nodeTaints = array;
                            continue;
                        }
                        if (property0.NameEquals("osType"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            osType = new OSType(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("nodeImageVersion"))
                        {
                            nodeImageVersion = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("vmSize"))
                        {
                            vmSize = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("cloudProviderProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            cloudProviderProfile = CloudProviderProfile.DeserializeCloudProviderProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new AgentPoolProvisioningState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("status"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            status = AgentPoolProvisioningStatusStatus.DeserializeAgentPoolProvisioningStatusStatus(property0.Value);
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new HybridContainerServiceAgentPoolData(id, name, type, systemData.Value, Optional.ToDictionary(tags), location, extendedLocation.Value, Optional.ToNullable(count), Optional.ToList(availabilityZones), Optional.ToNullable(maxCount), Optional.ToNullable(maxPods), Optional.ToNullable(minCount), Optional.ToNullable(mode), Optional.ToDictionary(nodeLabels), Optional.ToList(nodeTaints), Optional.ToNullable(osType), nodeImageVersion.Value, vmSize.Value, cloudProviderProfile.Value, Optional.ToNullable(provisioningState), status.Value);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using HttpEx;
using HttpEx.REST;
using Library.DataTransferObjects;
using Library.DomainModel;

namespace Library.WebApi
{
    public class AuthorResourceAssembler : ResourceAssembler<Author, AuthorResource>
    {
        IAuthorService AuthorService { get; set; }
        IBookService BookService { get; set; }
        Lazy<BookResourceAssembler> LazyBookAssembler;

        BookResourceAssembler BookAssembler
        {
            get { return LazyBookAssembler.Value; }
        }

        public AuthorResourceAssembler( IAuthorService authorService, IBookService bookService, Lazy<BookResourceAssembler> assemblerLazy, IUrlProvider urlProvider )
            : base( urlProvider )
        {
            AuthorService = authorService;
            BookService = bookService;
            LazyBookAssembler = assemblerLazy;
        }

        public override async Task<AuthorResource> ConvertToResourceAsync( Author model, ExpandQuery expand )
        {
            var resource = new AuthorResource();

            resource.Href       = UrlProvider.UriStringFor<AuthorController>( c => c.GetByIdAsync( model.Id, expand.Value ) );
            resource.FirstName  = model.FirstName;
            resource.LastName   = model.LastName;

            IEnumerable<Hyperlink<BookResource>> booksCollection;
            if( expand.Contains( () => resource.Books ) )
            {
                var books = await BookService.GetBooksByIdsAsync( model.BookIds.ToArray() );
                booksCollection = await BookAssembler.ConvertToResourceEnumerableAsync( books );
            }
            else
            {
                //unexpanded hyperlinks
                var linksCollection = new List<Hyperlink<BookResource>>();
                foreach( var bookId in model.BookIds )
                {
                    string href = BookAssembler.GetSingleResourceLink( bookId );
                    linksCollection.Add( href );
                }
                booksCollection = linksCollection;
            }
            resource.Books = booksCollection;

            return resource;
        }

        internal async Task<AuthorResource> GetResourceByIdAsync( string id )
        {
            Author author = await AuthorService.GetAuthorByIdAsync( id );
            if( author == null ) return null;

            return await ConvertToResourceAsync( author );
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         verbose="true"
         bootstrap="tests/regression/bootstrap.php"
         forceCoversAnnotation="true">

    <testsuites>
        <testsuite name="Phive">
            <directory suffix="Test.php">tests/regression</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>


text:
using Synology.FileStation.Common.Results;

namespace Synology.FileStation.Search.Results
{
    /// <summary>
    /// File time result.
    /// </summary>
    internal class FileTimeResult : TaskFileTimeResult, IFileTimeResult
	{
	}
}


text:
package stone;
import static stone.Parser.rule;
import stone.ast.ClassBody;
import stone.ast.ClassStmnt;
import stone.ast.Dot;

public class ClassParser extends ClosureParser {
    Parser member = rule().or(def, simple);
    Parser class_body = rule(ClassBody.class).sep("{").option(member)
                            .repeat(rule().sep(";", Token.EOL).option(member))
                            .sep("}");
    Parser defclass = rule(ClassStmnt.class).sep("class").identifier(reserved)
                          .option(rule().sep("extends").identifier(reserved))
                          .ast(class_body);
    public ClassParser() {
        postfix.insertChoice(rule(Dot.class).sep(".").identifier(reserved));
        program.insertChoice(defclass);
    }
}


text: This is a random quote generator with the Andruxnet API, made as a FreeCodeCamp project.


text:
export class AbstractStore {
    constructor(db, manager) {
        this.db = db;
        this.manager = manager;
    }

    toVO(result) {
        return this.manager.toVO(result);
    }

    toId(id) {
        return id;
    }

    get keyPath() {
        return this.manager.VO.keyPath || 'id';
    }

    updateByKey(options) {
        var keyPath = this.keyPath;
        if (!options.key) {
            throw new Error('Missing property key in options');
        }
        options.partialUpdate = options.data !== options.fullData;
        options.criteria = {};
        options.criteria[keyPath] = options.key;
        options.data = Object.assign({}, options.data);
        delete options.data[keyPath];
        return this.update(options).then((count) => {
            if (count !== undefined && count !== 1) {
                throw new Error('Failed to updateByKey ' +
                                this.manager.VO.name + ': ' + options.key + ' (' + count + ')');
            }
        });
    }

    removeByKey(options) {
        var keyPath = this.keyPath;
        if (!options.key) {
            throw new Error('Missing property key in options');
        }
        options.criteria = {};
        options.criteria[keyPath] = options.key;
        return this.remove(options).then((count) => {
            if (count !== undefined && count !== 1) {
                throw new Error('Failed to removeByKey ' +
                                this.manager.VO.name + ': ' + options.key + ' (' + count + ')');
            }
        });
    }
}


text:
var uc = require('./index');

uc.build_array(uc.crawl_images);


text:
package org.ovirt.engine.ui.uicompat;

public class TaskContext {

//	private Dispatcher dispatcher;
	private Object privateState;
	public Object getState()
	{
		return privateState;
	}
	private void setState(Object value)
	{
		privateState = value;
	}

	public TaskContext(Dispatcher dispatcher, Object state)
	{
//		this.dispatcher = dispatcher;
		setState(state);
	}

	public void InvokeUIThread(ITaskTarget target, Object state)
	{
		setState(state);
		target.run(this);
	}
}


text:
from builtins import str, zip
import os
import glob
import logging
from neon import NervanaObject

logger = logging.getLogger(__name__)

class Indexer(NervanaObject):
    """
    Create index file for dataloader.
    """
    def __init__(self, path, index_file, pattern='*'):
        self.path = path
        self.index_file = index_file
        self.pattern = pattern

    def run(self):
        """
        Create index file for dataloader.
        """
        if os.path.exists(self.index_file):
            return
        logger.warning('%s not found. Attempting to create...' % self.index_file)
        assert os.path.exists(self.path)
        subdirs = glob.iglob(os.path.join(self.path, '*'))
        subdirs = [x for x in subdirs if os.path.isdir(x)]
        classes = sorted([os.path.basename(x) for x in subdirs])
        class_map = {key: val for key, val in zip(classes, list(range(len(classes))))}
        with open(self.index_file, 'w') as fd:
            fd.write('filename,label1\n')
            for subdir in subdirs:
                label = class_map[os.path.basename(subdir)]
                files = glob.iglob(os.path.join(subdir, self.pattern))
                for filename in files:
                    rel_path = os.path.join(os.path.basename(subdir),
                                            os.path.basename(filename))
                    fd.write(rel_path + ',' + str(label) + '\n')
        logger.info('Created index file: %s' % self.index_file)


text:
use crate::{components::table as t, generated::css_classes::C, sleep_with_handle, GMsg};
use chrono::offset::{TimeZone, Utc};
use futures::channel::oneshot;
use number_formatter::format_bytes;
use seed::{prelude::*, *};
use std::time::Duration;

#[derive(serde::Deserialize, serde::Serialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub(crate) struct INodeCount {
    count: u64,
    size: i64,
    uid: String,
    timestamp: i64,
}

pub struct Model {
    pub(crate) fs_name: String,
    pub(crate) last_known_scan: Option<String>,
    inodes: Vec<INodeCount>,
    cancel: Option<oneshot::Sender<()>>,
}

impl Model {
    pub fn new(fs_name: &str) -> Self {
        Self {
            fs_name: fs_name.to_string(),
            inodes: Default::default(),
            cancel: Default::default(),
            last_known_scan: Default::default(),
        }
    }
}

#[derive(Clone, Debug)]
pub enum Msg {
    FetchInodes,
    InodesFetched(Box<fetch::ResponseDataResult<InfluxResults>>),
    Noop,
}

#[derive(serde::Deserialize, Clone, Debug)]
pub struct InfluxSeries {
    #[serde(skip)]
    name: String,
    #[serde(skip)]
    columns: Vec<String>,
    values: Vec<(i64, String, u64, i64)>,
}

#[derive(serde::Deserialize, Clone, Debug)]
pub struct InfluxResult {
    #[serde(skip)]
    statement_id: u16,
    series: Option<Vec<InfluxSeries>>,
}

#[derive(serde::Deserialize, Clone, Debug)]
pub struct InfluxResults {
    results: Vec<InfluxResult>,
}

pub(crate) fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {
    match msg {
        Msg::FetchInodes => {
            model.cancel = None;
            let url:String = format!("/influx?db=iml_stratagem_scans&epoch=ns&q=SELECT%20counter_name,%20count,%20size%20FROM%20stratagem_scan%20WHERE%20group_name=%27user_distribution%27%20and%20fs_name=%27{}%27%20limit%2020", &model.fs_name);
            let request = seed::fetch::Request::new(url);

            orders
                .skip()
                .perform_cmd(request.fetch_json_data(|x| Msg::InodesFetched(Box::new(x))));
        }
        Msg::InodesFetched(fetch_object) => {
            match *fetch_object {
                Ok(response) => {
                    model.inodes = response
                        .results
                        .into_iter()
                        .take(1)
                        .filter_map(|result| result.series)
                        .flatten()
                        .take(1)
                        .map(|v| v.values)
                        .flatten()
                        .map(|(timestamp, uid, count, size)| INodeCount {
                            timestamp,
                            uid,
                            count,
                            size,
                        })
                        .collect();

                    model.inodes.sort_by(|a, b| b.cmp(a));

                    model.last_known_scan = model.inodes.first().map(|x| get_date_time(x.timestamp));
                }
                Err(fail_reason) => {
                    error!(fail_reason);
                    orders.skip();
                }
            }

            let (cancel, fut) = sleep_with_handle(Duration::from_secs(60), Msg::FetchInodes, Msg::Noop);
            model.cancel = Some(cancel);
            orders.perform_cmd(fut);
        }
        Msg::Noop => {
            orders.skip();
        }
    }
}

fn get_date_time(timestamp: i64) -> String {
    let dt = Utc.timestamp_nanos(timestamp);

    dt.format("%A, %B %d, %Y %H:%M:%S %Z").to_string()
}

pub(crate) fn view(model: &Model) -> Node<Msg> {
    div![
        class![
            C.bg_white,
            C.border,
            C.border_b,
            C.border_t,
            C.mt_24,
            C.rounded_lg,
            C.shadow,
        ],
        div![
            class![C.flex, C.justify_between, C.px_6, C._mb_px, C.bg_gray_200],
            h3![class![C.py_4, C.font_normal, C.text_lg], "Top inode Users"],
            p![
                class![C.py_4, C.text_gray_600],
                "Last Scanned: ",
                model.last_known_scan.as_ref().unwrap_or(&"---".to_string())
            ]
        ],
        table![
            class![C.table_fixed, C.w_full],
            style! {
                St::BorderSpacing => px(10),
                St::BorderCollapse => "initial"
            },
            vec![
                t::thead_view(vec![
                    t::th_view(plain!["Name"]),
                    t::th_view(plain!["Count"]),
                    t::th_view(plain!["Space Used"])
                ]),
                tbody![model.inodes.iter().map(|i| tr![
                    t::td_view(plain![i.uid.clone()]),
                    t::td_center(plain![i.count.to_string()]),
                    t::td_center(plain![format_bytes(i.size as f64, None)])
                ])]
            ]
        ]
    ]
}


text:
Get current temperature and weather conditions by providing zip code, through SMS

Will eventually provide more relevant weather information.

![screenshot](ss.png)

### Motivation

Main motivation was to just get more hands-on experience working with cool APIs and to get more familiar with routing calls in Node.js.

Secondary motivation was to simply provide a way to get the current weather without accessing the Internet. Perhaps this could be useful for those without Internet on their phones, or for flip-phone users.

### Breakdown
* User sends SMS containing a zip code to Twilio number
* Twilio makes POST (or GET) request to API endpoint specified (on my end)
* Route call to appropriate file
* Geonames API call to get latitude and longitude from the given zip code
* Forecast API call with the above coordinates to get current weather
* Twilio SMS response containing temperature and weather conditions (hoping to expand this more)

### Tech

Forecast SMS takes advantage of:
* Node.js, with the following modules
  * twilio
  * async
  * body-parser
  * express
  * request
* Twilio API (for SMS)
* Forecast API (for weather)
* MongoDB (maps zip codes to coordinates/other info)

### General
Currently only working for verified phone numbers because I'm on a Twilio trial account (and I'm too cheap to upgrade)

Hosted on main site at the moment and until I decide to separate the two (sorry), routing will be handled like so on the Node.js web server:

```
// Some stuff above this line
var app          = express();
var router       = express.Router();
// Handle route in forecast_sms.js
var forecast_sms = require('./routes/forecast_sms').router;
app.use('/API_ENDPOINT_HERE', forecast_sms);
// Some stuff below this line
```
### Changelog
3/7/15 - Removed Geonames API and replaced with MongoDB to fetch coordinates (loaded in data using a CSV file from 2000 Census). Text response sends out a bit faster now after removing extraneous API call.


text:
void callback_link(hotspot *p_hotspot, void *param, SDL_Renderer *renderer){
#ifdef DEV
  printf("CALLBACK LINK WITH PARAM %s\n", (char*)p_hotspot->param);
#endif
  game *p_game = (game*)param;
  char *id = (char*)p_hotspot->param;
  game_change_place(p_game, id, renderer);
}

void callback_user_function(hotspot *p_hotspot, void *param, SDL_Renderer *renderer){
  game *p_game = (game*)param;
  char *function_name = (char*)p_hotspot->param;

#ifdef DEV
  printf("Call Lua function '%s' from namespace %s\n", function_name, p_game->p_place->id);
#endif

  game_call_lua(p_game, function_name);

}


text:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Overlays.Music;
using osuTK;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestScenePlaylistOverlay : OsuTestScene
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(PlaylistOverlay),
            typeof(Playlist)
        };

        private readonly BindableList<BeatmapSetInfo> beatmapSets = new BindableList<BeatmapSetInfo>();

        [SetUp]
        public void Setup() => Schedule(() =>
        {
            PlaylistOverlay overlay;

            Child = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Size = new Vector2(300, 500),
                Child = overlay = new PlaylistOverlay
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.X,
                    State = { Value = Visibility.Visible }
                }
            };

            beatmapSets.Clear();

            for (int i = 0; i < 100; i++)
            {
                beatmapSets.Add(new BeatmapSetInfo
                {
                    Metadata = new BeatmapMetadata
                    {
                        // Create random metadata, then we can check if sorting works based on these
                        Artist = "Some Artist " + RNG.Next(0, 9),
                        Title = $"Some Song {i + 1}",
                        AuthorString = "Some Guy " + RNG.Next(0, 9),
                    },
                    DateAdded = DateTimeOffset.UtcNow,
                });
            }

            overlay.BeatmapSets.BindTo(beatmapSets);
        });
    }
}


text:
@class SHKUploadInfo;

@interface SHKUploadsViewCell : UITableViewCell

@property (strong, nonatomic) UILabel *filenameLabel;
@property (strong, nonatomic) UILabel *progressLabel;
@property (strong, nonatomic) UIProgressView *progressView;
@property (strong, nonatomic) UILabel *statusLabel;
@property (strong, nonatomic) UIButton *actionButton;

- (void)setupLayout;
- (void)updateWithUploadInfo:(SHKUploadInfo *)uploadInfo;

@end


text:
. /root/dockerfiles/start_scripts/build.sh $@ # && (echo "Parent build.sh failed"; exit 1)

# Rebuild hwxu/hdp_node to make sure students have a fix to the timeline server start script
echo -e "\n*** Building hwxu/hdp_node ***\n"
cd /root/dockerfiles/hdp_node
docker build -t hwxu/hdp_node .
echo -e "\n*** Build of hwxu/hdp_node complete! ***\n"

#If this script is execute multiple times, untagged images get left behind
#This command removes any untagged Docker images
docker rmi -f $(docker images | grep '^<none>' | awk '{print $3}')

cp /root/dockerfiles/hdp_node/configuration_files/core_hadoop/yarn-site.xml /etc/hadoop/conf

#Unzip eclipse
if [[ ! -d "/root/eclipse" ]]; then
	cd /root/
	tar -xvf /root/eclipse.tgz
	chown -R root:root /root/eclipse
fi

mkdir -p /root/yarn/workspace

echo -e "\n*** The lab environment has successfully been built for this classroom VM ***\n"


text:
var GameObject = require('../../GameObject');

var BitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera)
{
    var text = src.text;
    var textLength = text.length;

    if (GameObject.RENDER_MASK !== src.renderFlags || textLength === 0 || (src.cameraFilter > 0 && (src.cameraFilter & camera._id)))
    {
        return;
    }

    var textureFrame = src.frame;

    var cameraScrollX = camera.scrollX * src.scrollFactorX;
    var cameraScrollY = camera.scrollY * src.scrollFactorY;

    var chars = src.fontData.chars;
    var lineHeight = src.fontData.lineHeight;

    var xAdvance = 0;
    var yAdvance = 0;

    var indexCount = 0;
    var charCode = 0;

    var glyph = null;
    var glyphX = 0;
    var glyphY = 0;
    var glyphW = 0;
    var glyphH = 0;

    var x = 0;
    var y = 0;

    var lastGlyph = null;
    var lastCharCode = 0;

    var ctx = renderer.currentContext;
    var image = src.frame.source.image;

    var textureX = textureFrame.cutX;
    var textureY = textureFrame.cutY;

    var rotation = 0;
    var scale = (src.fontSize / src.fontData.size);

    //  Blend Mode
    if (renderer.currentBlendMode !== src.blendMode)
    {
        renderer.currentBlendMode = src.blendMode;
        ctx.globalCompositeOperation = renderer.blendModes[src.blendMode];
    }

    //  Alpha
    if (renderer.currentAlpha !== src.alpha)
    {
        renderer.currentAlpha = src.alpha;
        ctx.globalAlpha = src.alpha;
    }

    //  Smoothing
    if (renderer.currentScaleMode !== src.scaleMode)
    {
        renderer.currentScaleMode = src.scaleMode;
    }

    ctx.save();
    ctx.translate((src.x - cameraScrollX) + src.frame.x, (src.y - cameraScrollY) + src.frame.y);
    ctx.rotate(src.rotation);
    ctx.scale(src.scaleX, src.scaleY);

    // ctx.fillStyle = 'rgba(255,0,255,0.5)';

    for (var index = 0; index < textLength; ++index)
    {
        charCode = text.charCodeAt(index);

        if (charCode === 10)
        {
            xAdvance = 0;
            indexCount = 0;
            yAdvance += lineHeight;
            lastGlyph = null;
            continue;
        }

        glyph = chars[charCode];

        if (!glyph)
        {
            continue;
        }

        glyphX = textureX + glyph.x;
        glyphY = textureY + glyph.y;

        glyphW = glyph.width;
        glyphH = glyph.height;

        x = indexCount + glyph.xOffset + xAdvance;
        y = glyph.yOffset + yAdvance;

        if (lastGlyph !== null)
        {
            var kerningOffset = glyph.kerning[lastCharCode];
            x += (kerningOffset !== undefined) ? kerningOffset : 0;
        }

        x *= scale;
        y *= scale;

        xAdvance += glyph.xAdvance;
        indexCount += 1;
        lastGlyph = glyph;
        lastCharCode = charCode;

        //  Nothing to render or a space? Then skip to the next glyph
        if (glyphW === 0 || glyphH === 0 || charCode === 32)
        {
            continue;
        }

        ctx.save();
        ctx.translate(x, y);
        ctx.scale(scale, scale);
        // ctx.fillRect(0, 0, glyphW, glyphH);
        ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH);
        ctx.restore();
    }

    ctx.restore();
};

module.exports = BitmapTextCanvasRenderer;


text:
* **Project Week Preparation**

## Other Resources
* [Grading Rubrics](../../resources/)
* [Lecture Slides]()


text:
<?php

namespace WebinoConfigLib\Cache;

use WebinoConfigLib\AbstractConfig;

/**
 * Class Memory
 */
class Memory extends AbstractConfig
{
    /**
     * @param string $namespace
     * @param null $limit
     */
    public function __construct($namespace, $limit = null)
    {
        $this->mergeArray([
            'adapter' => [
                'name' => 'memory',
                'options' => [
                    'namespace'   => $namespace,
                    'memoryLimit' => $limit,
                ],
            ],
        ]);
    }
}


text:
using namespace akin;
using namespace std;

SolverX::SolverX() :
    step_size(1.0),
    max_steps(300),
    max_attempts(1),
    max_perturbation(3.0),
    perturb_seed(true),
    random_resolution(10000),
    _mandatory(NULL),
    _optimal(NULL),
    _expectedConfigSize(0)
{
    srand(time(NULL));
}

bool SolverX::setMandatoryConstraint(ConstraintBase *constraint, size_t config_size)
{
    _mandatory = constraint;
    _expectedConfigSize = config_size;
    _min_limits.resize(config_size);
    _max_limits.resize(config_size);
    return true;
}

ConstraintBase* SolverX::getMandatoryConstraint()
{
    return _mandatory;
}

bool SolverX::setOptimalConstraint(ConstraintBase *constraint)
{
    _optimal = constraint;
    return true;
}

ConstraintBase* SolverX::getOptimalConstraint()
{
    return _optimal;
}

bool SolverX::checkLimits(const Eigen::VectorXd &config) const
{
    if(config.size() != (int)_expectedConfigSize)
        return false;

    for(int i=0; i<config.size(); ++i)
        if( config[i] < _min_limits[i] || _max_limits[i] < config[i] )
            return false;

    return true;
}

void SolverX::_enforceLimits(Eigen::VectorXd &config) const
{
    for(int i=0; i<config.size(); ++i)
    {
        if(config[i] < _min_limits[i])
            config[i] = _min_limits[i];
        else if(_max_limits[i] < config[i])
            config[i] = _max_limits[i];
    }
}

bool SolverX::checkForNan(const Eigen::VectorXd &config) const
{
    for(int i=0; i<config.size(); ++i)
    {
        if( config[i] != config[i] )
        {
            std::cout << "NaN found in component #" << i << "!" << std::endl;
            return false;
        }
    }
    return true;
}

bool SolverX::checkValidity(const Eigen::VectorXd &config) const
{
    if(_mandatory == NULL)
        return true;

    return _mandatory->getValidityX(config).valid;
}

bool SolverX::randomizeConfig(Eigen::VectorXd &config) const
{
    if(config.size() != (int)_expectedConfigSize)
        return false;

    double original = 0;
    for(int i=0; i<config.size(); ++i)
    {
        original = config[i];
        if(std::isinf(_max_limits[i]) || std::isinf(_min_limits[i]))
            config[i] = (2*((double)(rand()%random_resolution)/(double)(random_resolution-1))-1)
                        * max_perturbation;
        else
            config[i] = ((double)(rand()%random_resolution)/(double)(random_resolution-1))
                        * (_max_limits[i] - _min_limits[i]) + _min_limits[i];

        if(fabs(config[i]-original) > max_perturbation)
            config[i] = config[i]-original > 0?
                            original+max_perturbation : original-max_perturbation;
    }

    return true;
}

bool SolverX::solve(Eigen::VectorXd &config) const
{
    return _satisfy(config, _mandatory, max_attempts);
}

bool SolverX::optimize(Eigen::VectorXd &config) const
{
    return _satisfy(config, _optimal, 1);
}

size_t SolverX::expectedConfigSize() const { return _expectedConfigSize; }

const Eigen::VectorXd& SolverX::min_limits() const { return _min_limits; }

bool SolverX::min_limits(const Eigen::VectorXd &newLimits)
{
    if(newLimits.size()!=(int)_expectedConfigSize)
        return false;

    _min_limits = newLimits;
    return true;
}

const Eigen::VectorXd& SolverX::max_limits() const { return _max_limits; }

bool SolverX::max_limits(const Eigen::VectorXd &newLimits)
{
    if(newLimits.size()!=(int)_expectedConfigSize)
        return false;

    _max_limits = newLimits;
    return true;
}

bool SolverX::_satisfy(Eigen::VectorXd& config, ConstraintBase* constraint, size_t max_attempts_) const
{
    if(config.size() != _min_limits.size() || config.size() != _max_limits.size())
    {
        std::cout << "Configuration-Space sizes do not match:\n"
                  << " -- Input Dimensions:" << config.size()
                  << " | Min Limit Dimensions:" << _min_limits.size()
                  << " | Max Limit Dimensions:" << _max_limits.size() << std::endl;
        return false;
    }

    if(constraint == NULL)
        return true;

    const Eigen::VectorXd original_config = config;
    Eigen::VectorXd rConfig(config.size());
    Validity v = Validity::Invalid();
    Eigen::VectorXd gradient(config.size());
    size_t attempt_count = 1;

    do {

        size_t step_count = 1;
        do {

            v = constraint->getGradientX(gradient, config);
            if(!v.valid)
            {
                config = config - step_size*gradient;
            }

            if(!checkForNan(config))
                break;

            _enforceLimits(config);

            if(v.stuck)
                break;

            ++step_count;
            if(max_steps > 0 && step_count > max_steps)
                break;

        } while( !v.valid && !v.stuck );

        ++attempt_count;
        if(max_attempts_ > 0 && attempt_count > max_attempts_)
            break;

        if(!v.valid)
        {
            randomizeConfig(rConfig);
            double stochasticFactor = ((double)(rand()%random_resolution))
                                      /(double)(random_resolution-1);
            if(perturb_seed)
                config = original_config + (rConfig-original_config)*stochasticFactor;
            else
                config = config + (rConfig-config)*stochasticFactor;
        }

    } while( !v.valid );

    return checkValidity(config);
}

RobotSolverX::RobotSolverX(Robot &robot) :
    _robot(&robot)
{

}

bool RobotSolverX::setMandatoryConstraint(RobotConstraintBase *constraint)
{
    if(constraint==NULL)
    {
        _mandatory = NULL;
        return true;
    }

    if(constraint->getRobot() != _robot)
        return false;

    _mandatory = constraint;
    _dofs = constraint->getDofs();
    _expectedConfigSize = _dofs.size();

    resetLimits();
    return true;
}

bool RobotSolverX::setOptimalConstraint(RobotConstraintBase *constraint)
{
    if(constraint==NULL)
    {
        _optimal = NULL;
        return true;
    }

    if(constraint->getRobot() != _robot)
        return false;

    _optimal = constraint;
    _dofs = constraint->getDofs();
    resetLimits();
    return true;
}

void RobotSolverX::resetLimits()
{
    _min_limits.resize(_dofs.size());
    _max_limits.resize(_dofs.size());

    for(size_t i=0; i<_dofs.size(); ++i)
    {
        _min_limits[i] = _robot->dof(_dofs[i]).min();
        _max_limits[i] = _robot->dof(_dofs[i]).max();
    }
}

Robot* RobotSolverX::getRobot()
{
    return _robot;
}


text:
Internal Server Error!

Yes! As you can see something bad happen. I got notified about it and will see how I can resolve it.

While I am doing the same you can freely navigate yourself back to the home page!

500


text:
using Aspose.Cloud;
using System;
namespace Aspose.Cells.Cloud.Examples.Workbook
{
    class DecryptWorkbook
    {
        static void Main()
        {
            string dataDir = Common.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            string input = "sample1.xlsx";
            string output = "ouput.xlsx";

            Common.StorageService.File.UploadFile(dataDir+input, input, storage: Common.STORAGE);

            CellsProtectParameter cellsProtectParameter = new CellsProtectParameter(CellsProtectionType.All);
            cellsProtectParameter.Password = "Aspose";

            WorkbookEncryptionRequest workbookEncryptionRequest = new WorkbookEncryptionRequest(WorkbookEncryptionType.XOR, 128, "Aspose");

            Common.CellsService.Workbook.DecryptDocument(input, Common.FOLDER, workbookEncryptionRequest, storage: Common.STORAGE);

            Common.StorageService.File.DownloadFile(input, dataDir+output, storage: Common.STORAGE);

        }
    }
}


text:
"""Wallpaper classes."""

import logging
import zlib

import RedditWallpaperChooser.constants
import RedditWallpaperChooser.utils

__author__ = 'aldur'

logger = logging.getLogger(__name__)

class WebWallpaper(object):

    """A wallpaper from the web."""

    def __init__(self, title, url, size, subreddit):
        self.title = title
        self.url = url
        self.size = size
        self.subreddit = subreddit

        # Produce a deterministic identifier starting form the url.
        self.id = str(zlib.adler32(self.url.encode()))

        # Store the image ratio
        self.ratio = round(float(self.size.width) / self.size.height, 5)

        self.image_type = None

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.url == other.url

    def __hash__(self):
        return hash(self.url)

    def __str__(self):
        return self.__repr__()

    def __repr__(self):
        return "{} - {} - [{}x{}]".format(self.title, self.url, *self.size)

    def set_image_type(self, content_type):
        """
        Set the image type, based on the HTTP content type.
        """
        content_types = RedditWallpaperChooser.constants.ACCEPTED_CONTENT_TYPES
        if content_type not in content_types:
            logger.warning(
                "Unknown content type %s. Falling back to JPG.",
                content_type
            )

        self.image_type = content_types.get(content_type, "jpg")

    def fits(self, target_size, target_ratio):
        """
        :param target_size: A target size (can be None).
        :param target_ratio: A target ratio (can be None).

        :return: True if the wallpaper is bigger than the provided size and respects the ratio requirements.
        """
        if not target_size and not target_ratio:
            return True

        size_fits = False
        aspect_ratio_fits = False

        if target_size:
            size_fits = all((
                self.size.height >= target_size.height,
                self.size.width >= target_size.width,
            ))

        if target_ratio:
            aspect_ratio_fits = target_ratio == self.ratio

        if target_size and target_ratio:
            return size_fits and aspect_ratio_fits
        elif target_size:
            return size_fits
        else:  # aspect_ratio_fits
            return aspect_ratio_fits

    @property
    def info(self):
        """
        Info for this wallpaper.
        """
        return {
            "title": self.title,
            "url": self.url,
            "width": self.size.width,
            "height": self.size.height,
            "image_type": self.image_type,
            "subreddit": self.subreddit,
        }

    @property
    def info_path(self):
        """
        The path of the wallpaper's info on disk.
        """
        return "{}.json".format(self.id)

    @property
    def output_path(self):
        """
        The output path of the stored wallpaper on disk.
        """
        assert self.image_type is not None, \
            "I need the image type to generate the output path."
        return "{}.{}".format(self.id, self.image_type)


text:
package com.alibaba.druid.sql.dialect.oracle.ast.stmt;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.druid.sql.ast.SQLHint;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.dialect.oracle.ast.clause.OracleErrorLoggingClause;
import com.alibaba.druid.sql.dialect.oracle.ast.clause.OracleReturningClause;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitor;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;

public class OracleInsertStatement extends SQLInsertStatement implements OracleStatement {

    private OracleReturningClause    returning;
    private OracleErrorLoggingClause errorLogging;
    private List<SQLHint>            hints = new ArrayList<SQLHint>();

    public List<SQLHint> getHints() {
        return hints;
    }

    public void setHints(List<SQLHint> hints) {
        this.hints = hints;
    }

    public OracleReturningClause getReturning() {
        return returning;
    }

    public void setReturning(OracleReturningClause returning) {
        this.returning = returning;
    }

    public OracleErrorLoggingClause getErrorLogging() {
        return errorLogging;
    }

    public void setErrorLogging(OracleErrorLoggingClause errorLogging) {
        this.errorLogging = errorLogging;
    }

    @Override
    protected void accept0(SQLASTVisitor visitor) {
        this.accept0((OracleASTVisitor) visitor);
    }

    public void accept0(OracleASTVisitor visitor) {
        if (visitor.visit(this)) {
            this.acceptChild(visitor, tableSource);
            this.acceptChild(visitor, columns);
            this.acceptChild(visitor, values);
            this.acceptChild(visitor, query);
            this.acceptChild(visitor, returning);
            this.acceptChild(visitor, errorLogging);
        }

        visitor.endVisit(this);
    }
}


text:
<!DOCTYPE html>
<html>
    <head>
        <title>Timepicki - free Time picker jquery plugin</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="css/timepicki.css"/>
        <style>
            body{ font-family: 'arial'}
            a{ text-decoration: none; color: #66666B;}
            a span{ font-size: 12px;}
            input{ margin: 0px 30px; float: left}
        </style>
    </head>
    <body>
        <h1>Timepicki - probando... </h1>
        <input type="text" name="time"/>
        <input type="text" name="time2"/>
        <input type="text" id="time3"/>
        <script src="https://code.jquery.com/jquery-2.1.1.min.js">
        </script>
        <script src="js/timepicki.js">
        </script>
        <script>
            $("input[id=time3]").timepicki();
        </script>
    </body>
</html>


text:
local runner = require('user_modules/script_runner')
local common = require('test_scripts/Smoke/commonSmoke')

--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false

--[[ Local Variables ]]
local requestParams = {
  syncMsgVersion = {
    majorVersion = 5,
    minorVersion = 0,
  },
  appName = "SyncProxyTester",
  ttsName = {
    {
      text ="SyncProxyTester",
      type ="TEXT",
    },
  },
  ngnMediaScreenAppName = "SPT",
  vrSynonyms = {
    "VRSyncProxyTester",
  },
  isMediaApplication = true,
  languageDesired = "EN-US",
  hmiDisplayLanguageDesired = "EN-US",
  appHMIType = {
    "DEFAULT",
  },
  appID = "123",
  fullAppID = "123456",
  deviceInfo = {
    hardware = "hardware",
    firmwareRev = "firmwareRev",
    os = "os",
    osVersion = "osVersion",
    carrier = "carrier",
    maxNumberRFCOMMPorts = 5
  }
}

local function SetNotificationParams()
  local notificationParams = {
    application = {}
  }
  notificationParams.application.appName = requestParams.appName
  notificationParams.application.ngnMediaScreenAppName = requestParams.ngnMediaScreenAppName
  notificationParams.application.isMediaApplication = requestParams.isMediaApplication
  notificationParams.application.hmiDisplayLanguageDesired = requestParams.hmiDisplayLanguageDesired
  notificationParams.application.appType = requestParams.appHMIType
  notificationParams.application.deviceInfo = {
    name = common.getDeviceName(),
    id = common.getDeviceMAC(),
    transportType = common.getDeviceTransportType(),
    isSDLAllowed = true
  }
  notificationParams.application.policyAppID = requestParams.fullAppID
  notificationParams.ttsName = requestParams.ttsName
  notificationParams.vrSynonyms = requestParams.vrSynonyms
  return notificationParams
end

--[[ Local Functions ]]
local function unregisterAppInterface()
  local cid = common.getMobileSession():SendRPC("UnregisterAppInterface", { })
  common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered",
    { appID = common.getHMIAppId(), unexpectedDisconnect = false })
  common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end

local function registerAppInterface()
  local CorIdRAI = common.getMobileSession():SendRPC("RegisterAppInterface", requestParams)
  local notificationParams = SetNotificationParams()
  common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppRegistered", notificationParams)
  common.getMobileSession():ExpectResponse(CorIdRAI, { success = true, resultCode = "SUCCESS" })
  common.getMobileSession():ExpectNotification("OnHMIStatus",
    { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" })
  common.getMobileSession():ExpectNotification("OnPermissionsChange")
end

--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Update Preloaded PT", common.updatePreloadedPT)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Step("UnregisterAppInterface Positive Case", unregisterAppInterface)

runner.Title("Test")
runner.Step("RegisterAppInterface Positive Case", registerAppInterface)

runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Numbers\V2\RegulatoryCompliance;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Values;
use Twilio\Version;

class SupportingDocumentTypeContext extends InstanceContext {
    /**
     * Initialize the SupportingDocumentTypeContext
     *
     * @param Version $version Version that contains the resource
     * @param string $sid The unique string that identifies the Supporting Document
     *                    Type resource
     */
    public function __construct(Version $version, $sid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = ['sid' => $sid, ];

        $this->uri = '/RegulatoryCompliance/SupportingDocumentTypes/' . \rawurlencode($sid) . '';
    }

    /**
     * Fetch the SupportingDocumentTypeInstance
     *
     * @return SupportingDocumentTypeInstance Fetched SupportingDocumentTypeInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch(): SupportingDocumentTypeInstance {
        $payload = $this->version->fetch('GET', $this->uri);

        return new SupportingDocumentTypeInstance($this->version, $payload, $this->solution['sid']);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        $context = [];
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Numbers.V2.SupportingDocumentTypeContext ' . \implode(' ', $context) . ']';
    }
}