text:
package com.nasageek.utexasutilities.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nasageek.utexasutilities.AuthCookie;
import com.nasageek.utexasutilities.MyBus;
import com.nasageek.utexasutilities.NotAuthenticatedException;
import com.nasageek.utexasutilities.R;
import com.nasageek.utexasutilities.UTLoginTask;
import com.nasageek.utexasutilities.UTilitiesApplication;
import com.nasageek.utexasutilities.activities.CampusMapActivity;
import com.nasageek.utexasutilities.model.LoadFailedEvent;
import com.squareup.okhttp.Request;
import com.squareup.otto.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.nasageek.utexasutilities.UTilitiesApplication.UTD_AUTH_COOKIE_KEY;

public class ExamScheduleFragment extends ScheduleFragment implements ActionModeFragment,
        ActionMode.Callback, AdapterView.OnItemClickListener {

    private ArrayList<String> exams = new ArrayList<>();
    private ListView examListview;
    private LinearLayout progressLayout;
    private TextView errorTextView;
    private View errorLayout;
    private ActionMode mode;
    private AuthCookie utdAuthCookie;
    private String TASK_TAG;
    private String selectedExam;
    private UTilitiesApplication mApp = UTilitiesApplication.getInstance();

    public static ExamScheduleFragment newInstance() {
        return new ExamScheduleFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View vg = inflater.inflate(R.layout.exam_schedule_fragment_layout, container, false);
        progressLayout = (LinearLayout) vg.findViewById(R.id.examschedule_progressbar_ll);
        examListview = (ListView) vg.findViewById(R.id.examschedule_listview);
        errorLayout = vg.findViewById(R.id.examschedule_error);
        errorTextView = (TextView) vg.findViewById(R.id.tv_failure);

        if (savedInstanceState != null) {
            switch (loadStatus) {
                case NOT_STARTED:
                    // defaults should suffice
                    break;
                case LOADING:
                    progressLayout.setVisibility(View.VISIBLE);
                    errorLayout.setVisibility(View.GONE);
                    examListview.setVisibility(View.GONE);
                    break;
                case SUCCEEDED:
                    progressLayout.setVisibility(View.GONE);
                    errorLayout.setVisibility(View.GONE);
                    examListview.setVisibility(View.VISIBLE);
                    break;
                case FAILED:
                    progressLayout.setVisibility(View.GONE);
                    errorLayout.setVisibility(View.VISIBLE);
                    examListview.setVisibility(View.GONE);
                    break;
            }
        }

        if (!utdAuthCookie.hasCookieBeenSet()) {
            progressLayout.setVisibility(View.GONE);
            errorTextView.setText(getString(R.string.login_first));
            errorTextView.setVisibility(View.VISIBLE);
        } else if (loadStatus == LoadStatus.NOT_STARTED && mApp.getCachedTask(TASK_TAG) == null){
            loadStatus = LoadStatus.LOADING;
            prepareToLoad();
            FetchExamDataTask task = new FetchExamDataTask(TASK_TAG);
            task.execute(false);
        } else {
            setupAdapter();
        }
        return vg;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            exams = savedInstanceState.getStringArrayList("exams");
        }
        utdAuthCookie = mApp.getAuthCookie(UTD_AUTH_COOKIE_KEY);
        TASK_TAG = getClass().getSimpleName();
    }

    @Override
    public void onStart() {
        super.onStart();
        MyBus.getInstance().register(this);
    }

    @Override
    public void onStop() {
        MyBus.getInstance().unregister(this);
        super.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putStringArrayList("exams", exams);
    }

    private void setupAdapter() {
        ExamAdapter adapter = new ExamAdapter(getActivity(), exams);
        examListview.setAdapter(adapter);
    }

    @Override
    public ActionMode getActionMode() {
        return mode;
    }

    private void prepareToLoad() {
        progressLayout.setVisibility(View.VISIBLE);
        examListview.setVisibility(View.GONE);
        errorLayout.setVisibility(View.GONE);
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.setTitle("Exam Info");
        MenuInflater inflater = getActivity().getMenuInflater();
        String[] elements = selectedExam.split("\\^");
        if (elements.length >= 3) { // TODO: check this?
            if (elements[2].contains("The department")
                    || elements[2]
                    .contains("Information on final exams is available for Nine-Week Summer Session(s) only.")
                    || elements.length <= 4) {
                return true;
            }
        } else {
            return true;
        }
        inflater.inflate(R.menu.schedule_action_mode, menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.locate_class:
                ArrayList<String> building = new ArrayList<>();
                Intent map = new Intent(getActivity().getString(R.string.building_intent), null,
                        getActivity(), CampusMapActivity.class);

                String[] elements = selectedExam.split("\\^");
                if (elements.length >= 5) {
                    building.add(elements[4].split(" ")[0]);
                    map.putStringArrayListExtra("buildings", building);
                    // map.setData(Uri.parse(elements[4].split(" ")[0]));
                    getActivity().startActivity(map);
                    return true;
                } else {
                    Toast.makeText(getActivity(), "Your exam's location could not be found",
                            Toast.LENGTH_SHORT).show();
                }
        }
        return true;

    }

    @Override
    public void onDestroyActionMode(ActionMode mode) { }

    static class FetchExamDataTask extends UTLoginTask<Boolean, Void, List<String>> {

        public FetchExamDataTask(String tag) {
            super(tag, "https://utdirect.utexas.edu/registrar/exam_schedule.WBX");
        }

        @Override
        protected List<String> doInBackground(Boolean... params) {
            Boolean recursing = params[0];
            List<String> examlist = new ArrayList<>();

            Request request = new Request.Builder()
                    .url(reqUrl)
                    .build();
            String pagedata;

            try {
                pagedata = fetchData(request);
            } catch (IOException e) {
                errorMsg = "UTilities could not fetch your exam schedule";
                e.printStackTrace();
                cancel(true);
                return null;
            } catch (NotAuthenticatedException e) {
                e.printStackTrace();
                cancel(true);
                return null;
            }

            if (pagedata.contains("will be available approximately three weeks")) {
                cancel(true);
                errorMsg = "'Tis not the season for final exams.\nTry back later!" +
                            "\n(about 3 weeks before they begin)";
                return null;
            } else if (pagedata.contains("Our records indicate that you are not enrolled" +
                    " for the current semester.")) {
                cancel(true);
                errorMsg = "You aren't enrolled for the current semester.";
                return null;
            }

            Pattern rowpattern = Pattern.compile("
.*?
", Pattern.DOTALL);
            Matcher rowmatcher = rowpattern.matcher(pagedata);

            while (rowmatcher.find()) {
                String rowstring = "";
                String row = rowmatcher.group();
                if (row.contains("Unique") || row.contains("Home Page")) {
                    continue;
                }

                Pattern fieldpattern = Pattern.compile("(.*?)	", Pattern.DOTALL);
                Matcher fieldmatcher = fieldpattern.matcher(row);
                while (fieldmatcher.find()) {
                    String field = fieldmatcher.group(1).replace(" ", " ").trim()
                            .replace("\t", "");
                    Spanned span = Html.fromHtml(field);
                    String out = span.toString();
                    rowstring += out + "^";
                }
                examlist.add(rowstring);
            }
            return examlist;
        }

        @Override
        protected void onPostExecute(List<String> result) {
            super.onPostExecute(result);
            MyBus.getInstance().post(new LoadSucceededEvent(getTag(), result));
        }
    }

    @Subscribe
    public void loadFailed(LoadFailedEvent event) {
        if (event.tag.equals(TASK_TAG)) {
            loadStatus = LoadStatus.FAILED;
            progressLayout.setVisibility(View.GONE);
            examListview.setVisibility(View.GONE);
            errorTextView.setText(event.errorMessage);
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe
    public void loadSucceeded(LoadSucceededEvent event) {
        if (event.tag.equals(TASK_TAG)) {
            loadStatus = LoadStatus.SUCCEEDED;
            exams.clear();
            exams.addAll(event.exams);
            progressLayout.setVisibility(View.GONE);
            setupAdapter();
            examListview.setOnItemClickListener(this);
            examListview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectedExam = exams.get(position);
        mode = ((AppCompatActivity)getActivity()).startSupportActionMode(this);
    }

    static class ExamAdapter extends ArrayAdapter<String> {

        public ExamAdapter(Context c, ArrayList<String> objects) {
            super(c, 0, objects);
        }

        @Override
        public boolean areAllItemsEnabled() {
            return true;
        }

        @Override
        public boolean isEnabled(int i) {
            return true;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            String[] examdata = getItem(position).split("\\^");
            boolean examRequested = false, summerSession = false;
            String id = "", name = "", date = "", location = "", unique = "";

            // TODO: I hate doing these try/catches, find a better solution so I
            // know when stuff goes wrong? ACRA?
            try {
                examRequested = !examdata[2].contains("The department");
                summerSession = examdata[2]
                        .contains("Information on final exams is available for Nine-Week Summer Session(s) only.");

                unique = examdata[0];
                id = examdata[1];
                name = examdata[2];
                date = "";
                location = "";
                if (examRequested && !summerSession) {
                    if (examdata.length >= 4) {
                        date = examdata[3];
                    }
                    if (examdata.length >= 5) {
                        location = examdata[4];
                    }
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                ex.printStackTrace();
            }
            String course;

            View vg = convertView;
            if (vg == null) {
                vg = LayoutInflater.from(getContext())
                        .inflate(R.layout.exam_item_view, parent, false);
            }
            TextView courseview = (TextView) vg.findViewById(R.id.exam_item_header_text);
            TextView left = (TextView) vg.findViewById(R.id.examdateview);
            TextView right = (TextView) vg.findViewById(R.id.examlocview);

            if (!examRequested || summerSession) {
                course = id + " - " + unique;
                left.setText(name);
                right.setVisibility(View.INVISIBLE);
            } else {
                course = id + " " + name;
                left.setText(date);
                right.setVisibility(View.VISIBLE);
                right.setText(location);
            }
            courseview.setText(course);
            return vg;
        }
    }

    static class LoadSucceededEvent {
        public List<String> exams;
        public String tag;

        public LoadSucceededEvent(String tag, List<String> exams) {
            this.tag = tag;
            this.exams = exams;
        }
    }
}


text:
package com.cloud.agent.resource.secondarystorage;

import static io.netty.buffer.Unpooled.copiedBuffer;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

import com.cloud.legacymodel.exceptions.InvalidParameterValueException;
import com.cloud.legacymodel.storage.UploadEntity;
import com.cloud.utils.imagestore.ImageStoreUtil;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.DiskFileUpload;
import io.netty.handler.codec.http.multipart.FileUpload;
import io.netty.handler.codec.http.multipart.HttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    private static final Logger logger = LoggerFactory.getLogger(HttpUploadServerHandler.class.getName());

    private static final HttpDataFactory factory = new DefaultHttpDataFactory(true);
    private static final String HEADER_SIGNATURE = "X-signature";
    private static final String HEADER_METADATA = "X-metadata";
    private static final String HEADER_EXPIRES = "X-expires";
    private static final String HEADER_HOST = "X-Forwarded-Host";
    private final StringBuilder responseContent = new StringBuilder();
    private HttpRequest request;
    private HttpPostRequestDecoder decoder;
    private final NfsSecondaryStorageResource storageResource;
    private String uuid;
    private boolean requestProcessed = false;

    public HttpUploadServerHandler(final NfsSecondaryStorageResource storageResource) {
        this.storageResource = storageResource;
    }

    @Override
    public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {
        if (this.decoder != null) {
            this.decoder.cleanFiles();
        }
        this.requestProcessed = false;
    }

    @Override
    public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
        if (!this.requestProcessed) {
            final String message = "file receive failed or connection closed prematurely.";
            logger.error(message);
            this.storageResource.updateStateMapWithError(this.uuid, message);
        }
    }

    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        logger.warn(this.responseContent.toString(), cause);
        this.responseContent.append("\r\nException occurred: ").append(cause.getMessage());
        writeResponse(ctx.channel(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
        ctx.channel().close();
    }

    private void writeResponse(final Channel channel, final HttpResponseStatus statusCode) {
        // Convert the response content to a ChannelBuffer.
        final ByteBuf buf = copiedBuffer(this.responseContent.toString(), CharsetUtil.UTF_8);
        this.responseContent.setLength(0);
        // Decide whether to close the connection or not.
        final boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(this.request.headers().get(CONNECTION)) ||
                this.request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(this.request.headers().get(CONNECTION));
        // Build the response object.
        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, statusCode, buf);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        if (!close) {
            // There's no need to add 'Content-Length' header if this is the last response.
            response.headers().set(CONTENT_LENGTH, buf.readableBytes());
        }
        // Write the response.
        final ChannelFuture future = channel.writeAndFlush(response);
        // Close the connection after the write operation is done if necessary.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            final HttpRequest request = this.request = (HttpRequest) msg;
            this.responseContent.setLength(0);

            if (request.getMethod().equals(HttpMethod.POST)) {

                final URI uri = new URI(request.getUri());

                String signature = null;
                String expires = null;
                String metadata = null;
                String hostname = null;
                long contentLength = 0;

                for (final Entry<String, String> entry : request.headers()) {
                    switch (entry.getKey()) {
                        case HEADER_SIGNATURE:
                            signature = entry.getValue();
                            break;
                        case HEADER_METADATA:
                            metadata = entry.getValue();
                            break;
                        case HEADER_EXPIRES:
                            expires = entry.getValue();
                            break;
                        case HEADER_HOST:
                            hostname = entry.getValue();
                            break;
                        case HttpHeaders.Names.CONTENT_LENGTH:
                            contentLength = Long.parseLong(entry.getValue());
                            break;
                    }
                }
                logger.info("HEADER: signature=" + signature);
                logger.info("HEADER: metadata=" + metadata);
                logger.info("HEADER: expires=" + expires);
                logger.info("HEADER: hostname=" + hostname);
                logger.info("HEADER: Content-Length=" + contentLength);
                final QueryStringDecoder decoderQuery = new QueryStringDecoder(uri);
                final Map<String, List<String>> uriAttributes = decoderQuery.parameters();
                this.uuid = uriAttributes.get("uuid").get(0);
                logger.info("URI: uuid=" + this.uuid);

                UploadEntity uploadEntity = null;
                try {
                    // Validate the request here
                    this.storageResource.validatePostUploadRequest(signature, metadata, expires, hostname, contentLength, this.uuid);
                    //create an upload entity. This will fail if entity already exists.
                    uploadEntity = this.storageResource.createUploadEntity(this.uuid, metadata, contentLength);
                } catch (final InvalidParameterValueException ex) {
                    logger.error("post request validation failed", ex);
                    this.responseContent.append(ex.getMessage());
                    writeResponse(ctx.channel(), HttpResponseStatus.BAD_REQUEST);
                    this.requestProcessed = true;
                    return;
                }
                if (uploadEntity == null) {
                    logger.error("Unable to create upload entity. An exception occurred.");
                    this.responseContent.append("Internal Server Error");
                    writeResponse(ctx.channel(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    this.requestProcessed = true;
                    return;
                }
                //set the base directory to download the file
                DiskFileUpload.baseDirectory = uploadEntity.getInstallPathPrefix();
                logger.info("base directory: " + DiskFileUpload.baseDirectory);
                try {
                    //initialize the decoder
                    this.decoder = new HttpPostRequestDecoder(factory, request);
                } catch (final ErrorDataDecoderException e) {
                    logger.error("exception while initialising the decoder", e);
                    this.responseContent.append(e.getMessage());
                    writeResponse(ctx.channel(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    this.requestProcessed = true;
                    return;
                }
            } else {
                logger.warn("received a get request");
                this.responseContent.append("only post requests are allowed");
                writeResponse(ctx.channel(), HttpResponseStatus.BAD_REQUEST);
                this.requestProcessed = true;
                return;
            }
        }
        // check if the decoder was constructed before
        if (this.decoder != null) {
            if (msg instanceof HttpContent) {
                // New chunk is received
                final HttpContent chunk = (HttpContent) msg;
                try {
                    this.decoder.offer(chunk);
                } catch (final ErrorDataDecoderException e) {
                    logger.error("data decoding exception", e);
                    this.responseContent.append(e.getMessage());
                    writeResponse(ctx.channel(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    this.requestProcessed = true;
                    return;
                }
                if (chunk instanceof LastHttpContent) {
                    writeResponse(ctx.channel(), readFileUploadData());
                    reset();
                }
            }
        }
    }

    private HttpResponseStatus readFileUploadData() throws IOException {
        while (this.decoder.hasNext()) {
            final InterfaceHttpData data = this.decoder.next();
            if (data != null) {
                try {
                    logger.info("BODY FileUpload: " + data.getHttpDataType().name() + ": " + data);
                    if (data.getHttpDataType() == HttpDataType.FileUpload) {
                        final FileUpload fileUpload = (FileUpload) data;
                        if (fileUpload.isCompleted()) {
                            this.requestProcessed = true;
                            final String format = ImageStoreUtil.checkTemplateFormat(fileUpload.getFile().getAbsolutePath(), fileUpload.getFilename());
                            if (StringUtils.isNotBlank(format)) {
                                final String errorString = "File type mismatch between the sent file and the actual content. Received: " + format;
                                logger.error(errorString);
                                this.responseContent.append(errorString);
                                this.storageResource.updateStateMapWithError(this.uuid, errorString);
                                return HttpResponseStatus.BAD_REQUEST;
                            }
                            final String status = this.storageResource.postUpload(this.uuid, fileUpload.getFile().getName());
                            if (status != null) {
                                this.responseContent.append(status);
                                this.storageResource.updateStateMapWithError(this.uuid, status);
                                return HttpResponseStatus.INTERNAL_SERVER_ERROR;
                            } else {
                                this.responseContent.append("upload successful.");
                                return HttpResponseStatus.OK;
                            }
                        }
                    }
                } finally {
                    data.release();
                }
            }
        }
        this.responseContent.append("received entity is not a file");
        return HttpResponseStatus.UNPROCESSABLE_ENTITY;
    }

    private void reset() {
        this.request = null;
        // destroy the decoder to release all resources
        this.decoder.destroy();
        this.decoder = null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
It is often more obvious to pass the spy as a property of the object spied upon
instead of from a referencing variable.

The following are considered warnings:

```js
var someSpy = spyOn(someObj, 'someMethod');
// Handle someSpy, for example
// expect(someSpy).toHaveBeenCalled();
```

The following are not warnings:

```js
spyOn(someObj, 'someMethod');
// Handle someObj.someMethod, for example
// expect(someObj.someMethod).toHaveBeenCalled();
```


text:
package types

import (
	"github.com/pkg/errors"
)

// ErrInvalidArrayContainer is an error used when the array container is improperly structured
var ErrInvalidArrayContainer = errors.New("invalid array container")

// ArrayContainer is an abstract type for de/serializing a JSON structure shaped like:
// [ [string, any] ]
type arrayContainer []arrayContainerElement

func (a arrayContainer) Filter(key string) []*arrayContainerElement {
	result := []*arrayContainerElement{}
	for _, el := range a {
		if k, _ := el.Key(); k == key {
			result = append(result, &el)
		}
	}
	return result
}

type arrayContainerElement []interface{}

func (el arrayContainerElement) Key() (string, error) {
	if len(el) != 2 {
		return "", errors.Wrap(ErrInvalidArrayContainer, "container element must have length 2")
	}
	if key, ok := el[0].(string); ok {
		return key, nil
	}
	return "", errors.Wrap(ErrInvalidArrayContainer, "element[0] is not a string")
}

func (el arrayContainerElement) Value() (interface{}, error) {
	if len(el) != 2 {
		return "", errors.Wrap(ErrInvalidArrayContainer, "container element must have length 2")
	}
	return el[1], nil
}

func (el arrayContainerElement) UnmarshalValue(output interface{}) error {
	value, err := el.Value()
	if err != nil {
		return err
	}

	return reUnmarshal(value, output)
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/LongestUncommonSubsequenceI.dir/main.cpp.o"
  "LongestUncommonSubsequenceI.pdb"
  "LongestUncommonSubsequenceI"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/LongestUncommonSubsequenceI.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
using System;
using System.Diagnostics;
using System.IO;
using NUnit.Framework;

namespace Duality.Tests.Utility
{
	[TestFixture]
	public class PathHelperTest
	{
		[Test] public void FileHashEquality()
		{
			byte[] buffer = new byte[1024 * 1024];
			MathF.Rnd.NextBytes(buffer);
			try
			{
				File.WriteAllText("Test.txt", BitConverter.ToString(buffer));

				Assert.AreEqual(PathHelper.GetFileHash("Test.txt"), PathHelper.GetFileHash("Test.txt"));
			}
			finally
			{
				if (File.Exists("Test.txt"))
					File.Delete("Test.txt");
			}
		}
		[Test] public void FileEquality()
		{
			byte[] bufferA = new byte[1024 * 1024];
			MathF.Rnd.NextBytes(bufferA);

			byte[] bufferB = new byte[1024 * 1024];
			Buffer.BlockCopy(bufferA, 0, bufferB, 0, bufferA.Length);
			bufferB[0] = (byte)(bufferA[0] ^ 1);

			try
			{
				File.WriteAllText("Test1.txt", BitConverter.ToString(bufferA));
				File.WriteAllText("Test2.txt", BitConverter.ToString(bufferA));
				File.WriteAllText("Test3.txt", BitConverter.ToString(bufferB));

				Assert.IsTrue(PathHelper.FilesEqual("Test1.txt", "Test1.txt"));
				Assert.IsTrue(PathHelper.FilesEqual("Test1.txt", "Test2.txt"));
				Assert.IsFalse(PathHelper.FilesEqual("Test1.txt", "Test3.txt"));
			}
			finally
			{
				if (File.Exists("Test1.txt")) File.Delete("Test1.txt");
				if (File.Exists("Test2.txt")) File.Delete("Test2.txt");
				if (File.Exists("Test3.txt")) File.Delete("Test3.txt");
			}
		}
	}
}


text:
class Startship{
	public void act(){

	}
}
class StartShip1 extends Startship{
	public void act(){
		System.out.println("StartShip1");
	}
}
class StartShip2 extends Startship{
	public void act(){
		System.out.println("StartShip2");
	}
}
class StartShip3 extends Startship{
	public void act(){
		System.out.println("StartShip3");
	}
}
class  Change{
	private Startship ss=new StartShip1();
	public void changeTo2(){
		ss=new StartShip2();
	}
	public void changeTo3(){
		ss=new StartShip3();
	}
	public void perform(){
		ss.act();
	}
}
public class Test16 {
	public static void main(String args[]){
		Change change=new Change();
		change.perform();
		change.changeTo2();
		change.perform();
		change.changeTo3();
		change.perform();
	}

}


text:
<!DOCTYPE html>

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

        <link rel="shortcut icon" href="/static/img/favicon.ico" />
        <title>Parsing JSON with Ruby - 张海云</title>
        <meta name="author" content="张海云" />
        <meta name="description" content="Parsing JSON with Ruby" />
        <meta name="keywords" content="Parsing JSON with Ruby, 张海云, ruby" />
        <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

        <meta content="" property="fb:app_id">
        <meta content="张海云" property="og:site_name">

          <meta content="Parsing JSON with Ruby" property="og:title">

          <meta content="article" property="og:type">

          <meta content="My Personal Stack Problems" property="og:description">

          <meta content="https://seeacloud.github.io/ruby/2013/12/23/ruby-json.html" property="og:url">

          <meta content="2013-12-23T01:18:23+08:00" property="article:published_time">
          <meta content="https://seeacloud.github.io/about/" property="article:author">

          <meta content="https://seeacloud.github.io/static/img/logo-high-resolution.png" property="og:image">

          <meta content="ruby" property="article:section">

        <meta name="twitter:card" content="summary">
        <meta name="twitter:site" content="@">
        <meta name="twitter:creator" content="@">

          <meta name="twitter:title" content="Parsing JSON with Ruby">

          <meta name="twitter:url" content="https://seeacloud.github.io/ruby/2013/12/23/ruby-json.html">

          <meta name="twitter:description" content="My Personal Stack Problems">

        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

        <link rel="stylesheet" href="/static/css/syntax.css">

        <link href="/static/css/bootstrap.min.css" rel="stylesheet">

        <link href="//fonts.googleapis.com/css?family=Roboto+Condensed:400,300italic,300,400italic,700&subset=latin,latin-ext" rel="stylesheet" type="text/css">

        <link rel="stylesheet" href="/static/css/super-search.css">
        <link rel="stylesheet" href="/static/css/thickbox.css">
        <link rel="stylesheet" href="/static/css/projects.css">
        <link rel="stylesheet" href="/static/css/main.css">

          Alex

          工作笔记

          项目

Parsing JSON with Ruby

23 Dec 2013

    » ruby

Parsing JSON with Ruby is actually extremely easy. All you have to do is have the json gem installed (gem install json) and call the JSON.parse method on the JSON data to convert it to ruby hashes. If you look at this small program here, you can see how I have implemented parsing JSON in Ruby.

#!/usr/bin/env ruby

require 'json'
require 'net/http'
require 'libnotify'

def parsejson
    file = "http://api.openweathermap.org/data/2.5/find?q=London&mode=json"
    response = Net::HTTP.get_response(URI.parse(file))
    weatherjson = response.body
    actual = JSON.parse(weatherjson)

    # check for errors
    if actual.has_key? 'Error'
        raise "error with the url"
    end

    results = []

    actual["list"].each do |listitem|
        weather = listitem["weather"]
        weather.each do |weath|
            results.push(weath["description"])
        end
        main = listitem["main"]
        temp = main["temp"] - 273.15
        results.push ("%.2f" % temp)
    end

    return results
end

    Share this on →

     Tweet

    « Welcome to Jekyll!

    Welcome to Simply Grey »

                    © 张海云

                    - https://github.com/seeacloud - Powered by Jekyll.


text:
using PokemonGoRaidBot.Objects.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using PokemonGoRaidBot.Objects;

namespace PokemonGoRaidBot.Tests.MockedObjects
{
    class MockedChatServer : IChatServer
    {
        public MockedChatServer(ChatTypes? chatType = null, ulong id = 0, string name = null, IEnumerable<IChatRole> roles = null,
            IEnumerable<IChatChannel> channels = null, IEnumerable<IChatUser> users = null)
        {
            ChatType = chatType.HasValue ? chatType.Value : ChatTypes.Discord;
            Id = id;
            Name = name;
            if(roles != null) ((List<IChatRole>)Roles).AddRange(roles);
            if (channels != null) ((List<IChatChannel>)Channels).AddRange(channels);
            if(users != null) ((List<IChatUser>)Users).AddRange(users);
        }

        public ChatTypes ChatType { get; set; }

        public ulong Id { get; set; }

        public string Name { get; set; }

        public IEnumerable<IChatRole> Roles => new List<IChatRole>();

        public IEnumerable<IChatChannel> Channels => new List<IChatChannel>();

        public IEnumerable<IChatUser> Users => new List<IChatUser>();
    }
}


text:
package org.gradoop.flink.model.impl.functions.graphcontainment;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.functions.FunctionAnnotation;
import org.gradoop.common.model.impl.pojo.GraphElement;
import org.gradoop.common.model.impl.id.GradoopId;

/**
 * True, if an element is contained in a give graph.
 *
 * @param <EL> element type
 */
@FunctionAnnotation.ReadFields("graphIds")
public class InGraph<EL extends GraphElement>
  implements FilterFunction<EL> {

  /**
   * graph id
   */
  private final GradoopId graphId;

  /**
   * constructor
   * @param graphId graph id
   */
  public InGraph(GradoopId graphId) {
    this.graphId = graphId;
  }

  @Override
  public boolean filter(EL element) throws Exception {
    return element.getGraphIds().contains(this.graphId);
  }
}


text:
package org.jeecg.modules.test.feign.client;

import org.jeecg.common.api.vo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 动态feign接口定义
 */
public interface JeecgTestClientDyn {

    @PostMapping(value = "/test/getMessage")
    Result<String> getMessage(@RequestParam(value = "name",required = false) String name);
}


text:
"""
Component to monitor plants.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/plant/
"""
import logging
import asyncio

import voluptuous as vol

from homeassistant.const import (
    STATE_OK, STATE_PROBLEM, STATE_UNKNOWN, TEMP_CELSIUS, ATTR_TEMPERATURE,
    CONF_SENSORS, ATTR_UNIT_OF_MEASUREMENT, ATTR_ICON)
from homeassistant.components import group
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.core import callback
from homeassistant.helpers.event import async_track_state_change

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'plant'

READING_BATTERY = 'battery'
READING_TEMPERATURE = ATTR_TEMPERATURE
READING_MOISTURE = 'moisture'
READING_CONDUCTIVITY = 'conductivity'
READING_BRIGHTNESS = 'brightness'

ATTR_PROBLEM = 'problem'
PROBLEM_NONE = 'none'

CONF_MIN_BATTERY_LEVEL = 'min_' + READING_BATTERY
CONF_MIN_TEMPERATURE = 'min_' + READING_TEMPERATURE
CONF_MAX_TEMPERATURE = 'max_' + READING_TEMPERATURE
CONF_MIN_MOISTURE = 'min_' + READING_MOISTURE
CONF_MAX_MOISTURE = 'max_' + READING_MOISTURE
CONF_MIN_CONDUCTIVITY = 'min_' + READING_CONDUCTIVITY
CONF_MAX_CONDUCTIVITY = 'max_' + READING_CONDUCTIVITY
CONF_MIN_BRIGHTNESS = 'min_' + READING_BRIGHTNESS
CONF_MAX_BRIGHTNESS = 'max_' + READING_BRIGHTNESS

CONF_SENSOR_BATTERY_LEVEL = READING_BATTERY
CONF_SENSOR_MOISTURE = READING_MOISTURE
CONF_SENSOR_CONDUCTIVITY = READING_CONDUCTIVITY
CONF_SENSOR_TEMPERATURE = READING_TEMPERATURE
CONF_SENSOR_BRIGHTNESS = READING_BRIGHTNESS

SCHEMA_SENSORS = vol.Schema({
    vol.Optional(CONF_SENSOR_BATTERY_LEVEL): cv.entity_id,
    vol.Optional(CONF_SENSOR_MOISTURE): cv.entity_id,
    vol.Optional(CONF_SENSOR_CONDUCTIVITY): cv.entity_id,
    vol.Optional(CONF_SENSOR_TEMPERATURE): cv.entity_id,
    vol.Optional(CONF_SENSOR_BRIGHTNESS): cv.entity_id,
})

PLANT_SCHEMA = vol.Schema({
    vol.Required(CONF_SENSORS): vol.Schema(SCHEMA_SENSORS),
    vol.Optional(CONF_MIN_BATTERY_LEVEL): cv.positive_int,
    vol.Optional(CONF_MIN_TEMPERATURE): vol.Coerce(float),
    vol.Optional(CONF_MAX_TEMPERATURE): vol.Coerce(float),
    vol.Optional(CONF_MIN_MOISTURE): cv.positive_int,
    vol.Optional(CONF_MAX_MOISTURE): cv.positive_int,
    vol.Optional(CONF_MIN_CONDUCTIVITY): cv.positive_int,
    vol.Optional(CONF_MAX_CONDUCTIVITY): cv.positive_int,
    vol.Optional(CONF_MIN_BRIGHTNESS): cv.positive_int,
    vol.Optional(CONF_MAX_BRIGHTNESS): cv.positive_int,
})

DOMAIN = 'plant'
DEPENDENCIES = ['zone', 'group']

GROUP_NAME_ALL_PLANTS = 'all plants'
ENTITY_ID_ALL_PLANTS = group.ENTITY_ID_FORMAT.format('all_plants')

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: {
        cv.string: PLANT_SCHEMA
    },
}, extra=vol.ALLOW_EXTRA)

@asyncio.coroutine
def async_setup(hass, config):
    """Set up the Plant component."""
    component = EntityComponent(_LOGGER, DOMAIN, hass,
                                group_name=GROUP_NAME_ALL_PLANTS)

    entities = []
    for plant_name, plant_config in config[DOMAIN].items():
        _LOGGER.info("Added plant %s", plant_name)
        entity = Plant(plant_name, plant_config)
        sensor_entity_ids = list(plant_config[CONF_SENSORS].values())
        _LOGGER.debug("Subscribing to entity_ids %s", sensor_entity_ids)
        async_track_state_change(hass, sensor_entity_ids, entity.state_changed)
        entities.append(entity)

    yield from component.async_add_entities(entities)

    return True

class Plant(Entity):
    """Plant monitors the well-being of a plant.

    It also checks the measurements against
    configurable min and max values.
    """

    READINGS = {
        READING_BATTERY: {
            ATTR_UNIT_OF_MEASUREMENT:  '%',
            'min': CONF_MIN_BATTERY_LEVEL,
            'icon': 'mdi:battery-outline'
        },
        READING_TEMPERATURE: {
            ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS,
            'min': CONF_MIN_TEMPERATURE,
            'max': CONF_MAX_TEMPERATURE,
            'icon': 'mdi:thermometer'
        },
        READING_MOISTURE: {
            ATTR_UNIT_OF_MEASUREMENT: '%',
            'min': CONF_MIN_MOISTURE,
            'max': CONF_MAX_MOISTURE,
            'icon': 'mdi:water'
        },
        READING_CONDUCTIVITY: {
            ATTR_UNIT_OF_MEASUREMENT: 'µS/cm',
            'min': CONF_MIN_CONDUCTIVITY,
            'max': CONF_MAX_CONDUCTIVITY,
            'icon': 'mdi:emoticon-poop'
        },
        READING_BRIGHTNESS: {
            ATTR_UNIT_OF_MEASUREMENT: 'lux',
            'min': CONF_MIN_BRIGHTNESS,
            'max': CONF_MAX_BRIGHTNESS,
            'icon': 'mdi:white-balance-sunny'
        }
    }

    def __init__(self, name, config):
        """Initialize the Plant component."""
        self._config = config
        self._sensormap = dict()
        for reading, entity_id in config['sensors'].items():
            self._sensormap[entity_id] = reading
        self._state = STATE_UNKNOWN
        self._name = name
        self._battery = None
        self._moisture = None
        self._conductivity = None
        self._temperature = None
        self._brightness = None
        self._icon = 'mdi:help-circle'
        self._problems = PROBLEM_NONE

    @callback
    def state_changed(self, entity_id, _, new_state):
        """Update the sensor status.

        This callback is triggered, when the sensor state changes.
        """
        value = new_state.state
        _LOGGER.debug("Received callback from %s with value %s",
                      entity_id, value)
        if value == STATE_UNKNOWN:
            return

        reading = self._sensormap[entity_id]
        if reading == READING_MOISTURE:
            self._moisture = int(float(value))
        elif reading == READING_BATTERY:
            self._battery = int(float(value))
        elif reading == READING_TEMPERATURE:
            self._temperature = float(value)
        elif reading == READING_CONDUCTIVITY:
            self._conductivity = int(float(value))
        elif reading == READING_BRIGHTNESS:
            self._brightness = int(float(value))
        else:
            raise _LOGGER.error("Unknown reading from sensor %s: %s",
                                entity_id, value)
        self._update_state()

    def _update_state(self):
        """Update the state of the class based sensor data."""
        result = []
        for sensor_name in self._sensormap.values():
            params = self.READINGS[sensor_name]
            value = getattr(self, '_{}'.format(sensor_name))
            if value is not None:
                if 'min' in params and params['min'] in self._config:
                    min_value = self._config[params['min']]
                    if value < min_value:
                        result.append('{} low'.format(sensor_name))
                        self._icon = params['icon']

                if 'max' in params and params['max'] in self._config:
                    max_value = self._config[params['max']]
                    if value > max_value:
                        result.append('{} high'.format(sensor_name))
                        self._icon = params['icon']

        if result:
            self._state = STATE_PROBLEM
            self._problems = ','.join(result)
        else:
            self._state = STATE_OK
            self._icon = 'mdi:thumb-up'
            self._problems = PROBLEM_NONE
        _LOGGER.debug("New data processed")
        self.async_schedule_update_ha_state()

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the entity."""
        return self._state

    @property
    def state_attributes(self):
        """Return the attributes of the entity.

        Provide the individual measurements from the
        sensor in the attributes of the device.
        """
        attrib = {
            ATTR_ICON: self._icon,
            ATTR_PROBLEM: self._problems,
        }

        for reading in self._sensormap.values():
            attrib[reading] = getattr(self, '_{}'.format(reading))

        return attrib


text:
/*
 * GET home page.
 */

exports.index = function(req, res) {
	res.render('index', { title: 'JobLint' });
};

exports.lint = function(req, res) {
	var spec = req.body.spec,
		joblint = require('joblint', {verbose: true}),
		result = joblint(spec);

	if(isClean(result)) {
		result.clean = true;
	}
	res.set({'Content-Type': 'application/json'});
	res.send(result);
};

function isClean(result) {
	return (result.errors.length === 0 &&
			result.warnings.length === 0 &&
			result.notices.length === 0 &&
			result.failPoints.culture === 0 &&
			result.failPoints.realism === 0 &&
			result.failPoints.recruiter === 0 &&
			result.failPoints.tech === 0);
}


text:
<?php

namespace Magento\Shipping\Model\Tracking;

use Magento\Shipping\Model\Rate\Result as RateResult;
use Magento\Shipping\Model\Tracking\Result\AbstractResult;

class Result
{
    /**
     * @var array
     */
    protected $_trackings = [];

    /**
     * @var null|array
     */
    protected $_error = null;

    /**
     * Reset tracking
     *
     * @return $this
     */
    public function reset()
    {
        $this->_trackings = [];
        return $this;
    }

    /**
     * @param array $error
     * @return void
     */
    public function setError($error)
    {
        $this->_error = $error;
    }

    /**
     * @return array|null
     */
    public function getError()
    {
        return $this->_error;
    }

    /**
     * Add a tracking to the result
     *
     * @param AbstractResult|RateResult $result
     * @return $this
     */
    public function append($result)
    {
        if ($result instanceof AbstractResult) {
            $this->_trackings[] = $result;
        } elseif ($result instanceof RateResult) {
            $trackings = $result->getAllTrackings();
            foreach ($trackings as $track) {
                $this->append($track);
            }
        }
        return $this;
    }

    /**
     * Return all trackings in the result
     *
     * @return array
     */
    public function getAllTrackings()
    {
        return $this->_trackings;
    }
}


text:
package com.dawndevelop.blockmonitor.Storage;

import com.dawndevelop.blockmonitor.api.Event;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class MysqlHandler implements IStorageHandler {
    private HikariDataSource dataSource;

    @Override
    public void Setup(String InstallPath, String username, String password) {
        if (InstallPath == null){
            throw new IllegalArgumentException("Install path must contain the IP address of the mysql server");
        }

        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://" + InstallPath + "/blockmonitor");
        config.setMaximumPoolSize(100);

        if (username != null)
            config.setUsername(username);

        if (password != null)
            config.setPassword(password);

        dataSource = new HikariDataSource(config);

        try(Statement sqlStatement = dataSource.getConnection().createStatement()) {
            sqlStatement.execute(
                    "CREATE TABLE IF NOT EXISTS `block_monitor_events` (" +
                            "`id` BIGINT AUTO_INCREMENT NOT NULL," +
                            "`event_type` TEXT," +
                            "`event_information` LONGTEXT," +
                            "`player_information` LONGTEXT," +
                            "`block_information` LONGTEXT," +
                            "`itemStack_information` LONGTEXT," +
                            "`world_location` LONGTEXT," +
                            "`timestamp` TIMESTAMP" +
                            ");"
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void Insert(Event event) {
        try(Connection conn = dataSource.getConnection()) {
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO `block_monitor_events` (" +
                            "`id`, " +
                            "`event_type`,"+
                            "`event_information`, " +
                            "`player_information`," +
                            "`block_information`," +
                            "`itemStack_information`," +
                            "`world_location`," +
                            "`timestamp`" +
                            ") VALUES (?,?,?,?,?,?,?,?);"
            );

            preparedStatement.setLong(1, event.getId());
            preparedStatement.setString(2, event.getEventType().name());
            preparedStatement.setString(3, event.getEventInformation());
            preparedStatement.setString(4, event.getPlayerInformation());
            preparedStatement.setString(5, event.getBlockInformation());
            preparedStatement.setString(6, event.getItemStackInformation());
            preparedStatement.setTimestamp(8, event.getTimestamp());
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void Remove(long ID) {
        try(Connection conn = dataSource.getConnection()) {
            PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM `block_monitor_events` WHERE `id` = ?;");
            preparedStatement.setLong(1, ID);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void Shutdown() {
        dataSource.close();
    }
}


text:
using System;
using System.Configuration;
using System.IO;
using System.Xml;

namespace mpupdater.Properties
{
	public class AppDirectorySettingsProvider : SettingsProvider
	{
		private readonly string configPath = Path.Combine("./mpupdater.config");
		private readonly XmlDocument settingsDocument;
		private readonly XmlNode rootNode;

		private const string rootNodeName = "settings";
		private const string settingNodeName = "setting";
		private const string settingNodeIdAttributeName = "name";

		public AppDirectorySettingsProvider()
		{
			settingsDocument = new XmlDocument();

			try
			{
				settingsDocument.Load(configPath);
			}
			catch (FileNotFoundException)
			{
				SetupXml();
			}

			rootNode = settingsDocument.SelectSingleNode(rootNodeName);
			if (rootNode == null)
			{
				settingsDocument.RemoveAll();
				SetupXml();

				rootNode = settingsDocument.ChildNodes[1];
			}
		}

		private void SetupXml()
		{
			settingsDocument.AppendChild(settingsDocument.CreateXmlDeclaration("1.0", "utf-8", string.Empty));
			settingsDocument.AppendChild(settingsDocument.CreateElement(rootNodeName));
		}

		public override string ApplicationName
		{
			get
			{
				return System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
			}

			set { }
		}

		public override string Name => nameof(AppDirectorySettingsProvider);

		public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
		{
			base.Initialize(Name, config);
		}

		public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
		{
			var result = new SettingsPropertyValueCollection();

			foreach (SettingsProperty property in collection)
			{
				var settingNode = rootNode.SelectSingleNode($@"/{rootNodeName}/{settingNodeName}[@{settingNodeIdAttributeName}='{property.Name}']");
				var value = new SettingsPropertyValue(property);

				if (settingNode == null)
					value.SerializedValue = property.DefaultValue ?? string.Empty;
				else
					value.SerializedValue = settingNode.InnerText;

				result.Add(value);
			}

			return result;
		}

		public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
		{
			foreach(SettingsPropertyValue value in collection)
			{
				var settingNode = rootNode.SelectSingleNode($@"/{rootNodeName}/{settingNodeName}[@{settingNodeIdAttributeName}='{value.Name}']");

				if (settingNode == null)
				{
					settingNode = settingsDocument.CreateElement(settingNodeName);

					var idAttribute = settingsDocument.CreateAttribute(settingNodeIdAttributeName);
					idAttribute.InnerText = value.Name;

					settingNode.Attributes.Append(idAttribute);
					rootNode.AppendChild(settingNode);
				}

				settingNode.InnerText = GetSerializedValueString(value);
			}

			settingsDocument.Save(configPath);
		}

		private string GetSerializedValueString(SettingsPropertyValue value)
		{
			string serializedValue = value.SerializedValue as string;

			if (serializedValue == null && value.Property.SerializeAs == SettingsSerializeAs.Binary)
			{
				var buf = value.SerializedValue as byte[];
				if (buf != null)
					serializedValue = Convert.ToBase64String(buf);
			}

			return serializedValue ?? string.Empty;
		}
	}
}


text:
An android application that lists popular comics characters, animated movies and many more.

This app showcases the MVP pattern, RxJava 2 and Dagger 2.


text:
//  --------------------------------------------------------------------------------------------------------------------
//  <copyright file="XDocumentLoader.cs" company="PicklesDoc">
//  Copyright 2011 Jeffrey Cameron
//  Copyright 2012-present PicklesDoc team and community contributors
//
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//  </copyright>
//  --------------------------------------------------------------------------------------------------------------------

using System.IO;
using System.IO.Abstractions;
using System.Xml;
using System.Xml.Linq;

namespace PicklesDoc.Pickles.TestFrameworks
{
    public class XDocumentLoader
    {
        public XDocument Load(IFileInfo fileInfo)
        {
            XDocument document;
            using (var stream = fileInfo.OpenRead())
            {
                document = this.Load(stream);
            }

            return document;
        }

        public XDocument Load(Stream stream)
        {
            XmlReader xmlReader = XmlReader.Create(stream);
            var document = XDocument.Load(xmlReader);

            return document;
        }
    }
}


text:
<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class TournamentBundle extends Registrable
{
    const TYPE = 'bundle';

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Tournament", inversedBy="bundles")
     */
    protected $tournaments;

    public function __construct()
    {
        parent::__construct();
        $this->tournaments = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add tournaments
     *
     * @param \App\Entity\Tournament $tournaments
     * @return Group
     */
    public function addTournament(\App\Entity\Tournament $tournaments)
    {
        $this->tournaments[] = $tournaments;

        return $this;
    }

    /**
     * Remove tournaments
     *
     * @param \App\Entity\Tournament $tournaments
     */
    public function removeTournament(\App\Entity\Tournament $tournaments)
    {
        return $this->tournaments->removeElement($tournaments);

    }

    /**
     * Get tournaments
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTournaments()
    {
        return $this->tournaments;
    }

    /**
     * Check if has tournament
     *
     * @param \App\Entity\Tournament $tournaments
     * @return bool
     */
    public function hasTournament(\App\Entity\Tournament $tournament)
    {
        return $this->tournaments->contains($tournament);
    }

    /**
     * Get list of tournaments as string
     *
     * @return string
     */
    public function getTournamentsString()
    {
        return implode(', ', array_map(function($t) { return $t->getName(); }, $this->tournaments->toArray()));
    }

    /**
     * Get registration_limit : min of limit for each tournaments
     *
     * @return \integer
     */
    public function getRegistrationLimit()
    {
        $min = PHP_INT_MAX;

        foreach ($this->tournaments as $t)
            $min = min($min, $t->getRegistrationLimit());

        if ($this->registrationLimit > 0)
            $min = min($min, $this->registrationLimit);

        return $min;
    }

    /**
     * Get free slots : min of remaining slots on each tournaments
     *
     * @return \integer
     */
    public function getFreeSlots() {
        $min = PHP_INT_MAX;

        foreach ($this->tournaments as $t)
            $min = min($min, $t->getFreeSlots());

        if ($this->registrationLimit > 0)
            $min = min($min, $this->registrationLimit);

        return $min;
    }

    /**
     * Get validated slots : sum of validated slots on each tournaments
     *
     * @return \integer
     */
    public function getValidatedSlots()
    {
        $slots = 0;

        foreach ($this->tournaments as $t)
            $slots += $t->getValidatedSlots();
    }

}


text:
System.register([], function (exports, module) {
	'use strict';
	return {
		execute: function () {

			/* header retained */
			 /* lead
			retained */ console.log(2); // trail retained
			console.log(2); // trail retained

			/* lead retained */
			console.log(2); /* trail
			retained */ /* trail
			retained */

			console.log(2); // trail retained
			 console.log(2);

			if (globalVar) {
				// lead retained
				console.log(2); // trail retained
			}

			if (globalVar) {
				// lead retained
				console.log(2); // trail retained
			}

			if (globalVar) {
				// lead retained
				console.log(2); // trail retained
			}

			if (globalVar) {
				console.log(2);
			}

			if (globalVar) { /* retained */ console.log(2);}

			if (globalVar) { /* retained */ console.log(2);}

			if (globalVar) { /* retained */ console.log(2);}

			switch (globalVar) {
				case 1: // retained
					// lead retained
					console.log(2); // trail retained
				case 2: // retained
					// lead retained
					console.log(2); // trail retained
			 case 3: // retained
					// lead retained
					console.log(2); // trail retained

				case 4: /* lead retained */ console.log('3'); // trail retained
				default: // retained
					/* lead retained */
					console.log(2); // trail retained
			}

			// lead retained
			console.log(2); // trail retained

			/* footer retained */

		}
	};
});


text:
/*
 * Open Source Software published under the Apache Licence, Version 2.0.
 */

package io.github.vocabhunter.gui.controller;

import io.github.vocabhunter.gui.i18n.I18nKey;
import io.github.vocabhunter.gui.i18n.I18nManager;
import io.github.vocabhunter.gui.model.MainModel;
import javafx.beans.value.ChangeListener;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class TitleHandler {
    private static final int TITLE_BUFFER_SIZE = 100;

    private final MainModel model;

    private final I18nManager i18nManager;

    @Inject
    public TitleHandler(final MainModel model, final I18nManager i18nManager) {
        this.model = model;
        this.i18nManager = i18nManager;
    }

    public void initialise() {
        ChangeListener<Object> listener = (o, old, v) -> updateTitle();

        model.sessionFileProperty().addListener(listener);
        model.documentNameProperty().addListener(listener);
        model.changesSavedProperty().addListener(listener);
        model.localeProperty().addListener(listener);

        updateTitle();
    }

    private void updateTitle() {
        StringBuilder title = new StringBuilder(TITLE_BUFFER_SIZE);

        if (model.isSessionOpen()) {
            if (model.hasSessionFile()) {
                title.append(model.getSessionFile().getFileName());
            } else {
                title.append(i18nManager.text(I18nKey.MAIN_WINDOW_UNTITLED));
            }

            String documentName = model.getDocumentName();

            if (documentName != null) {
                title.append(" (").append(documentName).append(')');
            }

            if (!model.changesSavedProperty().get()) {
                title.append(" - ").append(i18nManager.text(I18nKey.MAIN_WINDOW_UNSAVED));
            }

            title.append(" - ");
        }

        title.append("VocabHunter");
        model.setTitle(title.toString());
    }
}


text:
<?php

/*
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

//require 'Yay/Mockery.php';
//require 'Yay/Expectation.php';
//require 'Yay/ExpectationProvider.php';
//require 'Yay/Invocation.php';
//require 'Yay/InvocationRecorder.php';
//require 'Yay/InvocationProxy.php';
//require 'Yay/Action.php';
//require 'Yay/Matcher.php';
//require 'Yay/Matchers/IdenticalMatcher.php';
//require 'Yay/State.php';
//require 'Yay/StatePredicate.php';
//require 'Yay/Sequence.php';
//require 'Yay/Description.php';
//require 'Yay/MockGenerator.php';

/**
 * A base Expectation which other Expectations extend.
 * @author Chris Corbyn <chris@w3style.co.uk>
 * @package Yay
 */
abstract class Yay_Expectations_AbstractExpectation
  implements Yay_Expectation, Yay_InvocationRecorder
{

  /**
   * The object to expect Invocations from.
   * @var Yay_MockObject
   * @access private
   */
  private $_object;

  /**
   * The method name to expect Invocations on.
   * @var string
   * @access private
   */
  private $_method;

  /**
   * The argument Matchers.
   * @var array
   * @access private
   */
  private $_matchers = array();

  /**
   * The Action to use if matched.
   * @var Yay_Action
   * @access private
   */
  private $_action;

  /**
   * A state predicate to check for.
   * @var Yay_StatePredicate
   * @access private
   */
  private $_statePredicate;

  /**
   * A state to effect if matched.
   * @var Yay_State
   * @access private
   */
  private $_state;

  /**
   * The ID wanted to be valid in the Sequence.
   * @var int
   * @access private
   */
  private $_wantedSequenceId;

  /**
   * The Sequence to check for validity (if any).
   * @var Yay_Sequence
   * @access private
   */
  private $_sequence;

  /**
   * Invoked when the expectation matches so any counters can be incremented
   * for example.
   * @param Yay_Invocation $invocation
   */
  abstract public function notifyMatchedInvocation(Yay_Invocation $invocation);

  /**
   * Describe the boundaries of how many invocations can occur.
   * @param Yay_Description $description
   */
  abstract public function describeBounds(Yay_Description $description);

  /**
   * Describe the current status of this expectation.
   * @param Yay_Description $description
   */
  abstract public function describeSatisfaction(Yay_Description $description);

  /**
   * Specify the MockObject which the Invocation will occur.
   * This method returns the mock object in record mode.
   * @param Yay_MockObject $mock
   * @return Yay_InvocationProxy
   */
  public function of(Yay_MockObject $mock)
  {
    $this->_object = $mock;
    return new Yay_InvocationProxy($this, $mock);
  }

  /**
   * Notify the Expectation of an Invocation and check if it matches.
   * @param Yay_Invocation $invocation
   * @return boolean
   */
  public function isExpected(Yay_Invocation $invocation)
  {
    $matches = true;
    $object = $invocation->getObject();
    if ($object === $this->_object)
    {
      if (isset($this->_statePredicate))
      {
        $matches = $this->_statePredicate->isActive();
      }

      if ($matches && isset($this->_method))
      {
        if ($this->_method == $invocation->getMethod())
        {
          $args =& $invocation->getArguments();
          foreach ($this->_matchers as $i => $m)
          {
            if (!array_key_exists($i, $args))
            {
              if ($m->isOptional())
              {
                break;
              }
              else
              {
                $matches = false;
                break;
              }
            }
            else
            {
              if (!$m->matches($args[$i]))
              {
                $matches = false;
                break;
              }
            }
          }
        }
        else
        {
          $matches = false;
        }
      }

      if ($matches && isset($this->_sequence))
      {
        $matches = $this->_sequence->isInSequence($this->_wantedSequenceId);
      }
    }
    else
    {
      $matches = false;
    }

    if ($matches)
    {
      $this->notifyMatchedInvocation($invocation);
    }

    return $matches;
  }

  /**
   * Specify the Action to run if a match occurs.
   * @param Yay_Action $action
   */
  public function will(Yay_Action $action)
  {
    $this->_action = $action;
    return $this;
  }

  /**
   * Only be expected when in the given State predicate.
   * @param Yay_StatePredicate $predicate
   */
  public function when(Yay_StatePredicate $predicate)
  {
    $this->_statePredicate = $predicate;
    return $this;
  }

  /**
   * Activate the given $state if a match occurs.
   * @param Yay_State $state
   */
  public function then(Yay_State $state)
  {
    $this->_state = $state;
    return $this;
  }

  /**
   * Constrain this expectation to be valid only if invoked in the given sequence.
   * @param Yay_Sequence $sequence
   */
  public function inSequence(Yay_Sequence $sequence)
  {
    $this->_wantedSequenceId = $sequence->requestSequenceId();
    $this->_sequence = $sequence;
    return $this;
  }

  /**
   * Get the Action for the given Invocation.
   * This may have been specified by a will() clause.
   * @param Yay_Invocation $invocation
   * @return Yay_Action
   */
  public function getAction(Yay_Invocation $invocation)
  {
    if (isset($this->_state))
    {
      $this->_state->activate();
    }
    return $this->_action;
  }

  /**
   * Record any Invocations on the MockObject whilst it's in record mode.
   * @param Yay_Invocation $invocation
   */
  public function recordInvocation(Yay_Invocation $invocation)
  {
    $this->_method = $invocation->getMethod();
    $matchers =& $invocation->getArguments();
    foreach ($matchers as $matcher)
    {
      if ($matcher instanceof Yay_Matcher)
      {
        $this->_matchers[] = $matcher;
      }
      else
      {
        $this->_matchers[] = new Yay_Matchers_IdenticalMatcher($matcher);
      }
    }
  }

  /**
   * Returns the Expectations.
   * @return array of Yay_Expectation
   */
  public function getExpectations()
  {
    return array($this);
  }

  /**
   * Describe this Expectation to $description.
   * @param Yay_Description $description
   */
  public function describeTo(Yay_Description $description)
  {
    $this->describeBounds($description);

    $description->appendText(sprintf(' of %s;', $this->_getInvocationSignature()));

    if (isset($this->_sequence))
    {
      $description->appendText(' in');
      $this->_sequence->describeTo($description);
    }

    if (isset($this->_statePredicate))
    {
      $description->appendText(' when');
      $this->_statePredicate->describeTo($description);
    }

    if (isset($this->_action))
    {
      $this->_action->describeTo($description);
    }

    $this->describeSatisfaction($description);
  }

  // -- Private methods

  private function _getInvocationSignature()
  {
    $class = Yay_MockGenerator::getInstance()
      ->reverseNamingScheme(get_class($this->_object));
    if (isset($this->_method))
    {
      $method = $this->_method;
    }
    else
    {
      $method = '<any method>';
    }
    if (!empty($this->_matchers))
    {
      $args = array();
      foreach ($this->_matchers as $matcher)
      {
        $args[] = $matcher->describeMatch('%s [%s]');
      }
      $params = implode(', ', $args);
    }
    else
    {
      $params = '';
    }
    return sprintf('%s::%s(%s)', $class, $method, $params);
  }

}


text:
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

#nullable enable

namespace NUnit.Framework.Internal.Commands
{
    /// <summary>
    /// EmptyTestCommand is a TestCommand that does nothing. It simply
    /// returns the current result from the context when executed. We
    /// use it to avoid testing for null when executing a chain of
    /// DelegatingTestCommands.
    /// </summary>
    public class EmptyTestCommand : TestCommand
    {
        /// <summary>
        /// Construct a NullCommand for a test
        /// </summary>
        public EmptyTestCommand(Test test) : base(test) { }

        /// <summary>
        /// Execute the command
        /// </summary>
        public override TestResult Execute(TestExecutionContext context)
        {
            return context.CurrentResult;
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace Nether.Data.Sql.Common
{
    public static class ConfigurationHelper
    {
        public static IConfiguration GetConfiguration(ILogger logger, string contentRootPath, string environmentName)
        {
            logger.LogInformation("Creating ConfigurationBuilder. ContentRootPath:{0}", contentRootPath);
            // TODO - should find a better way to share the config builder logic!
            var builder = new ConfigurationBuilder()
                                .SetBasePath(contentRootPath)
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                .AddJsonFile($"appsettings.{environmentName}.json", optional: true)
                                .AddEnvironmentVariables();
            var configuration = builder.Build();
            return configuration;
        }
    }
}


text:
                <form role="form" class="form-inline" ng-submit="submit($event)">

                            Foods

                            <input id="input" name="string" class="form-control" type="text" autocomplete="off" ng-model="query"
                            ng-keyup='getFilteredTipsList($event)'
                            key-navigation>

                              {{tip.name}}

                            <button type="submit" class="btn btn-success">Send</button>

                </form>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Vernonia chamissonis Less.

### Remarks
null


text:
<?php
/**
 * This file is part of knocker project
 * Created by Mikhail Peghasin
 * mikhail.pegasin@itmhouse.com
 */

namespace AppBundle\Controller;

use AppBundle\Entity\Booking;
use AppBundle\Entity\Service;
use Application\Sonata\UserBundle\Entity\User;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class ApiController
 * @package AppBundle\Controller
 * @Route("/{apiKey}/api")
 */
class ApiController extends FOSRestController{

    /**
     * @param $userKey
     * @param $bookingId
     * @return mixed|void
     * @Route("/user/{userKey}/{bookingId}")
     * $result = array ('userId', 'redirectUrl', 'services', 'eventCode')
     */
    public function getKnockerUser($userKey, $bookingId)
    {

        $user = $this->get('doctrine')->getRepository('ApplicationSonataUserBundle:User')->findOneBy(['userKey' => $userKey]);
        if (
            $user instanceof User &&
            $user->isAccountNonExpired() &&
            $user->isAccountNonLocked() &&
            $user->isEnabled() &&
            $user->isCredentialsNonExpired()
        ) {
            $result = array();
            $result['userKey'] = $user->getUserKey();
            $bookingManager = $this->get('booking.manager');
            $booking = $bookingManager->getBooking($bookingId);
            if ($booking && in_array($booking, $user->getBookings()->toArray())  && $booking instanceof Booking && $this->get('booking.manager')->isValidBooking($bookingId)) {
                $result['redirectUrl'] = $booking->getUrlPre() . '%articleNumber%' . $booking->getUrlPost();
                if (is_object($booking->getTariff()->getUsingFact())) {
                    $result['eventCode'] = $booking->getTariff()->getUsingFact()->getCode();
                }
                foreach ($booking->getServices() as $service) {
                    if ($service instanceof Service) {
                        $result['services'][] = $service->getSlug();
                    }
                }

            }
            $view = $this
                ->view($result, 200)
                ->setFormat('json');
        } else {
            $view = $this->view();
        };

        return $this->handleView($view);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <title></title>
</head>
<script src="/primus/primus.js"></script>
<script type="text/javascript" src="lib/Bacon.min.js"></script>
<script type="text/javascript" src="d3.v3/d3.v3.js"></script>
<script type="text/javascript" src="slidingTimeWindow.js"></script>

<style>
  .axis line,
  .axis circle {
    fill: none;
    stroke: #777;
    stroke-dasharray: 1, 4;
  }

  circle.perimeter {
    fill:none;
    stroke: #333;
    stroke-dasharray: none;
  }
</style>

<body>

</body>
<script>

  var margin = {top: 20, right: 15, bottom: 60, left: 60}
      , width = 960 - margin.left - margin.right
      , height = 960 - margin.top - margin.bottom;

  var chart = d3.select('body')
      .append('svg:svg')
      .attr('width', width + margin.right + margin.left)
      .attr('height', height + margin.top + margin.bottom)
      .attr('class', 'chart')

  var g = chart.append('g')
      .attr('transform', 'translate(' + (margin.left + width / 2) + ',' + (margin.top + height / 2) + ')')
      .attr('width', width)
      .attr('height', height)
      .attr('class', 'main');

  g.append('circle').attr('r', Math.min(width/2, height/2)).attr('class','perimeter');

  var ga = g.append("g")
      .attr("class", "a axis")
      .selectAll("g")
      .data(d3.range(0, 360, 30))
      .enter().append("g")
      .attr("transform", function (d) {
        return "rotate(" + -d + ")";
      });

  ga.append("line").attr("x2", Math.min(width, height) / 2);

  var gr = g.append("g")
      .attr("class", "r axis");

  function drawGridCircles(r) {
    var gridCircles = gr.selectAll("g").data(r.ticks(5), function(d){return d});

    gridCircles.select("circle").attr("r", function(d) {return r(d)});
    gridCircles.select("text")
        .text(function(d) {return d})
        .attr("x", function(d) { return r(d) + 4; })
    gridCircles.exit().remove();

    var gra = gridCircles.enter().append("g");

    gra.append("circle").attr("r", function(d) {return r(d)});
    gra.append("text")
        .attr("x", function(d) { return r(d) + 4; })
        .style("text-anchor", "middle")
        .text(function(d) { console.log(d);return d; });
  }

  gCircle = g.append("g");
  var primus = Primus.connect("http://" + window.location.host + "/?gaugedata=true",
      {reconnect: {
        maxDelay: 60000,
        minDelay: 500,
        retries: Infinity
      }});

  var messages = new Bacon.Bus();
  primus.on('data', function message(data) {
    messages.push(data);
  });

  var wind = messages.filter(function (msg) {
    return msg.type === 'wind' && msg.reference === 'true boat'
  });
  var heading = messages.filter(function (msg) {
    return msg.type === 'course'
  }).map('.heading');
  var windWithGroundwind = wind.combine(heading,function (windData, heading) {
    return {
      heading : Number(windData.heading),
      groundWind : Number(heading) + Number(windData.angle),
      speed: Number(windData.speed)
    }
  }).throttle(50);
  var windWithHistory = windWithGroundwind.slidingTimeWindow(10 * 60 * 1000).onValue(function (h) {
    draw(h)
  });

  function draw(history) {
    if (history.length !== undefined) {
      var windColor =
          d3.scale.linear()
              .domain([0, history.length * .2, history.length * .4, history.length * .6, history.length * .95,
                history.length])
              .range(['blue', 'green', 'yellow', 'orange', 'red']);
      var maxSpeed = d3.max(history, function (d) {
        return d.value.speed
      });
      var r = d3.scale.linear().domain([0, maxSpeed]).range([0, Math.min(height, width) / 2]).nice();
      drawGridCircles(r);
      var opacity = d3.scale.pow().exponent(1.7).domain([0.2, history.length]).range([0, 1]);
      var circleData = gCircle.selectAll('circle').data(history, function (d) {
        return d.timestamp
      });
      circleData.enter()
          .append("circle")
      circleData
          .attr("fill-opacity", function (d, i) {
            return opacity(i);
          })
          .attr("style", function (d, i) {
            return "fill:" + windColor(i);
          })
          .attr('cx', function (d) {
            return(r(d.value.speed * Math.cos((d.value.groundWind - 90) * Math.PI / 180)));
          })
          .attr('cy', function (d) {
            return(r(d.value.speed * Math.sin((d.value.groundWind - 90) * Math.PI / 180)));
          })
          .attr("r", 3);
      ;
      circleData.exit().remove();
      ;
    }
  }

</script>
</html>


text:
class Node < Formula
  desc "Platform built on V8 to build network applications"
  homepage "https://nodejs.org/"
  url "https://nodejs.org/dist/v14.8.0/node-v14.8.0.tar.xz"
  sha256 "9b9e68e4e641ab099b3fe2d49308c65820eebe60ed733b5f8b07c67adef9f06d"
  license "MIT"
  head "https://github.com/nodejs/node.git"

  bottle do
    cellar :any
    sha256 "ec85b0f1a6b5ab229ee1445ca604f6455e15dfa632efdb79839296e5c2fc6631" => :catalina
    sha256 "5e2de72f9e1fc18df29226a40ae6efe39bff083f1f91d765c5dbd9db308613ae" => :mojave
    sha256 "7129555cbbde75ed026b19506fb6f5184545a0ac30121cce63ab92d4310b99a3" => :high_sierra
    sha256 "d477035ef3332280d19f5b735f6771ba90f30a3a87b667711b63c2a6aa79bcac" => :x86_64_linux
  end

  depends_on "pkg-config" => :build
  depends_on "python@3.8" => :build
  depends_on "icu4c"

  # We track major/minor from upstream Node releases.
  # We will accept *important* npm patch releases when necessary.
  resource "npm" do
    url "https://registry.npmjs.org/npm/-/npm-6.14.7.tgz"
    sha256 "510091d3b42b60ab75c9d46cebb769ee5204d58d948a61bf913455437fa768c5"
  end

  def install
    # make sure subprocesses spawned by make are using our Python 3
    ENV["PYTHON"] = Formula["python@3.8"].opt_bin/"python3"

    # Never install the bundled "npm", always prefer our
    # installation from tarball for better packaging control.
    args = %W[--prefix=#{prefix} --without-npm --with-intl=system-icu]
    # Remove `--openssl-no-asm` workaround when upstream releases a fix
    # See also: https://github.com/nodejs/node/issues/34043
    args << "--openssl-no-asm" if Hardware::CPU.arm?
    args << "--tag=head" if build.head?

    system "./configure", *args
    system "make", "install"

    # Allow npm to find Node before installation has completed.
    ENV.prepend_path "PATH", bin

    bootstrap = buildpath/"npm_bootstrap"
    bootstrap.install resource("npm")
    system "node", bootstrap/"bin/npm-cli.js", "install", "-ddd", "--global",
            "--prefix=#{libexec}", resource("npm").cached_download

    # The `package.json` stores integrity information about the above passed
    # in `cached_download` npm resource, which breaks `npm -g outdated npm`.
    # This copies back over the vanilla `package.json` to fix this issue.
    cp bootstrap/"package.json", libexec/"lib/node_modules/npm"
    # These symlinks are never used & they've caused issues in the past.
    rm_rf libexec/"share"

    bash_completion.install bootstrap/"lib/utils/completion.sh" => "npm"
  end

  def post_install
    node_modules = HOMEBREW_PREFIX/"lib/node_modules"
    node_modules.mkpath
    # Kill npm but preserve all other modules across node updates/upgrades.
    rm_rf node_modules/"npm"

    cp_r libexec/"lib/node_modules/npm", node_modules
    # This symlink doesn't hop into homebrew_prefix/bin automatically so
    # we make our own. This is a small consequence of our
    # bottle-npm-and-retain-a-private-copy-in-libexec setup
    # All other installs **do** symlink to homebrew_prefix/bin correctly.
    # We ln rather than cp this because doing so mimics npm's normal install.
    ln_sf node_modules/"npm/bin/npm-cli.js", HOMEBREW_PREFIX/"bin/npm"
    ln_sf node_modules/"npm/bin/npx-cli.js", HOMEBREW_PREFIX/"bin/npx"

    # Create manpage symlinks (or overwrite the old ones)
    %w[man1 man5 man7].each do |man|
      # Dirs must exist first: https://github.com/Homebrew/legacy-homebrew/issues/35969
      mkdir_p HOMEBREW_PREFIX/"share/man/#{man}"
      # still needed to migrate from copied file manpages to symlink manpages
      rm_f Dir[HOMEBREW_PREFIX/"share/man/#{man}/{npm.,npm-,npmrc.,package.json.,npx.}*"]
      ln_sf Dir[node_modules/"npm/man/#{man}/{npm,package-,shrinkwrap-,npx}*"], HOMEBREW_PREFIX/"share/man/#{man}"
    end

    (node_modules/"npm/npmrc").atomic_write("prefix = #{HOMEBREW_PREFIX}\n")
  end

  test do
    path = testpath/"test.js"
    path.write "console.log('hello');"

    output = shell_output("#{bin}/node #{path}").strip
    assert_equal "hello", output
    output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"en-EN\").format(1234.56))'").strip
    assert_equal "1,234.56", output

    output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"de-DE\").format(1234.56))'").strip
    assert_equal "1.234,56", output

    # make sure npm can find node
    ENV.prepend_path "PATH", opt_bin
    ENV.delete "NVM_NODEJS_ORG_MIRROR"
    assert_equal which("node"), opt_bin/"node"
    assert_predicate HOMEBREW_PREFIX/"bin/npm", :exist?, "npm must exist"
    assert_predicate HOMEBREW_PREFIX/"bin/npm", :executable?, "npm must be executable"
    npm_args = ["-ddd", "--cache=#{HOMEBREW_CACHE}/npm_cache", "--build-from-source"]
    system "#{HOMEBREW_PREFIX}/bin/npm", *npm_args, "install", ("--unsafe-perm" if Process.uid.zero?), "npm@latest"
    unless head?
      system "#{HOMEBREW_PREFIX}/bin/npm", *npm_args, "install", ("--unsafe-perm" if Process.uid.zero?), "bufferutil"
    end
    assert_predicate HOMEBREW_PREFIX/"bin/npx", :exist?, "npx must exist"
    assert_predicate HOMEBREW_PREFIX/"bin/npx", :executable?, "npx must be executable"
    assert_match "< hello >", shell_output("#{HOMEBREW_PREFIX}/bin/npx cowsay hello")
  end
end


text:
title: "Git setup with fork"
date: 2022-09-25T19:19:37+02:00
---

When I work on a git project that I forked from some place, it's great to have an automatic setup that pulls from the original repo and push to the forked repo.

I name the fork repo `fork` and the original repo `upstream`.

Here's what could look like the `.git/config` file of a git repository

```toml
[core]
    # stuff

[remote]
    pushDefault = fork

[push]
    default = current

[remote "fork"]
    url = # fork_url
    # stuff

[remote "upstream"]
    url = # upstream_url
    # stuff

[branch "master"] # the main branch to pull from upstream
    remote = upstream
    # stuff

[branch "another_branch"] # a branch I'm working on locally
    remote = fork
    # stuff

# more branch configurations…
```

Then the working process is pretty simple. Of course, you can use your own alias for all of those.

```bash
git switch master
git pull # get changes from upstream
git push # push the changes from the original repo to the fork
git switch -c a-new-branch
# do changes, commits
git push --set-upstream # set-upstream is only needed the first time
```

This might not be the most optimized way, and I would be happy to be shown even more simpler way to have this sort of workflow.

Enjoy !


text:
""" Tests for the backup service base driver. """

import uuid

import mock

from cinder.backup import driver
from cinder import context
from cinder import db
from cinder import exception
from cinder.openstack.common import jsonutils
from cinder import test
from cinder.tests.backup import fake_service

_backup_db_fields = ['id', 'user_id', 'project_id',
                     'volume_id', 'host', 'availability_zone',
                     'display_name', 'display_description',
                     'container', 'status', 'fail_reason',
                     'service_metadata', 'service', 'size',
                     'object_count']

class BackupBaseDriverTestCase(test.TestCase):

    def _create_volume_db_entry(self, id, size):
        vol = {'id': id, 'size': size, 'status': 'available'}
        return db.volume_create(self.ctxt, vol)['id']

    def _create_backup_db_entry(self, backupid, volid, size):
        backup = {'id': backupid, 'size': size, 'volume_id': volid}
        return db.backup_create(self.ctxt, backup)['id']

    def setUp(self):
        super(BackupBaseDriverTestCase, self).setUp()
        self.ctxt = context.get_admin_context()

        self.volume_id = str(uuid.uuid4())
        self.backup_id = str(uuid.uuid4())

        self._create_backup_db_entry(self.backup_id, self.volume_id, 1)
        self._create_volume_db_entry(self.volume_id, 1)
        self.backup = db.backup_get(self.ctxt, self.backup_id)
        self.driver = fake_service.FakeBackupService(self.ctxt)

    def test_get_metadata(self):
        json_metadata = self.driver.get_metadata(self.volume_id)
        metadata = jsonutils.loads(json_metadata)
        self.assertEqual(metadata['version'], 1)

    def test_put_metadata(self):
        metadata = {'version': 1}
        self.driver.put_metadata(self.volume_id, jsonutils.dumps(metadata))

    def test_get_put_metadata(self):
        json_metadata = self.driver.get_metadata(self.volume_id)
        self.driver.put_metadata(self.volume_id, json_metadata)

    def test_export_record(self):
        export_string = self.driver.export_record(self.backup)
        export_dict = jsonutils.loads(export_string.decode("base64"))
        # Make sure we don't lose data when converting to string
        for key in _backup_db_fields:
            self.assertTrue(key in export_dict)
            self.assertEqual(self.backup[key], export_dict[key])

    def test_import_record(self):
        export_string = self.driver.export_record(self.backup)
        imported_backup = self.driver.import_record(export_string)
        # Make sure we don't lose data when converting from string
        for key in _backup_db_fields:
            self.assertTrue(key in imported_backup)
            self.assertEqual(imported_backup[key], self.backup[key])

class BackupMetadataAPITestCase(test.TestCase):

    def _create_volume_db_entry(self, id, size, display_name,
                                display_description):
        vol = {'id': id, 'size': size, 'status': 'available',
               'display_name': display_name,
               'display_description': display_description}
        return db.volume_create(self.ctxt, vol)['id']

    def setUp(self):
        super(BackupMetadataAPITestCase, self).setUp()
        self.ctxt = context.get_admin_context()
        self.volume_id = str(uuid.uuid4())
        self.volume_display_name = 'vol-1'
        self.volume_display_description = 'test vol'
        self._create_volume_db_entry(self.volume_id, 1,
                                     self.volume_display_name,
                                     self.volume_display_description)
        self.bak_meta_api = driver.BackupMetadataAPI(self.ctxt)

    def _add_metadata(self, vol_meta=False, vol_glance_meta=False):
        if vol_meta:
            # Add some VolumeMetadata
            db.volume_metadata_update(self.ctxt, self.volume_id,
                                      {'fee': 'fi'}, False)
            db.volume_metadata_update(self.ctxt, self.volume_id,
                                      {'fo': 'fum'}, False)

        if vol_glance_meta:
            # Add some GlanceMetadata
            db.volume_glance_metadata_create(self.ctxt, self.volume_id,
                                             'disk_format', 'bare')
            db.volume_glance_metadata_create(self.ctxt, self.volume_id,
                                             'container_type', 'ovf')

    def test_get(self):
        # Volume won't have anything other than base by default
        meta = self.bak_meta_api.get(self.volume_id)
        s1 = set(jsonutils.loads(meta).keys())
        s2 = ['version', self.bak_meta_api.TYPE_TAG_VOL_BASE_META]
        self.assertEqual(s1.symmetric_difference(s2), set())

        self._add_metadata(vol_glance_meta=True)

        meta = self.bak_meta_api.get(self.volume_id)
        s1 = set(jsonutils.loads(meta).keys())
        s2 = ['version', self.bak_meta_api.TYPE_TAG_VOL_BASE_META,
              self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META]
        self.assertEqual(s1.symmetric_difference(s2), set())

        self._add_metadata(vol_meta=True)

        meta = self.bak_meta_api.get(self.volume_id)
        s1 = set(jsonutils.loads(meta).keys())
        s2 = ['version', self.bak_meta_api.TYPE_TAG_VOL_BASE_META,
              self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META,
              self.bak_meta_api.TYPE_TAG_VOL_META]
        self.assertEqual(s1.symmetric_difference(s2), set())

    def test_put(self):
        meta = self.bak_meta_api.get(self.volume_id)
        self.bak_meta_api.put(self.volume_id, meta)

        self._add_metadata(vol_glance_meta=True)
        meta = self.bak_meta_api.get(self.volume_id)
        self.bak_meta_api.put(self.volume_id, meta)

        self._add_metadata(vol_meta=True)
        meta = self.bak_meta_api.get(self.volume_id)
        self.bak_meta_api.put(self.volume_id, meta)

    def test_put_invalid_version(self):
        container = jsonutils.dumps({'version': 2})
        self.assertRaises(exception.BackupMetadataUnsupportedVersion,
                          self.bak_meta_api.put, self.volume_id, container)

    def test_v1_restore_factory(self):
        fact = self.bak_meta_api._v1_restore_factory()

        keys = [self.bak_meta_api.TYPE_TAG_VOL_META,
                self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META]

        self.assertEqual(set(keys).symmetric_difference(set(fact.keys())),
                         set([]))

        meta_container = {self.bak_meta_api.TYPE_TAG_VOL_BASE_META:
                          {'display_name': 'vol-2',
                           'display_description': 'description'},
                          self.bak_meta_api.TYPE_TAG_VOL_META: {},
                          self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META: {}}
        for f in fact:
            func = fact[f][0]
            fields = fact[f][1]
            func(meta_container[f], self.volume_id, fields)

        vol = db.volume_get(self.ctxt, self.volume_id)
        self.assertEqual(self.volume_display_name, vol['display_name'])
        self.assertEqual(self.volume_display_description,
                         vol['display_description'])

    def test_restore_vol_glance_meta(self):
        fields = {}
        container = {}
        self.bak_meta_api._save_vol_glance_meta(container, self.volume_id)
        self.bak_meta_api._restore_vol_glance_meta(container, self.volume_id,
                                                   fields)
        self._add_metadata(vol_glance_meta=True)
        self.bak_meta_api._save_vol_glance_meta(container, self.volume_id)
        self.bak_meta_api._restore_vol_glance_meta(container, self.volume_id,
                                                   fields)

    def test_restore_vol_meta(self):
        fields = {}
        container = {}
        self.bak_meta_api._save_vol_meta(container, self.volume_id)
        self.bak_meta_api._restore_vol_meta(container, self.volume_id, fields)
        self._add_metadata(vol_meta=True)
        self.bak_meta_api._save_vol_meta(container, self.volume_id)
        self.bak_meta_api._restore_vol_meta(container, self.volume_id, fields)

    def test_filter(self):
        metadata = {'a': 1, 'b': 2, 'c': 3}
        self.assertEqual(metadata, self.bak_meta_api._filter(metadata, []))
        self.assertEqual({'b': 2}, self.bak_meta_api._filter(metadata, ['b']))
        self.assertEqual({}, self.bak_meta_api._filter(metadata, ['d']))
        self.assertEqual({'a': 1, 'b': 2},
                         self.bak_meta_api._filter(metadata, ['a', 'b']))

    def test_save_vol_glance_meta(self):
        container = {}
        self.bak_meta_api._save_vol_glance_meta(container, self.volume_id)

    def test_save_vol_meta(self):
        container = {}
        self.bak_meta_api._save_vol_meta(container, self.volume_id)

    def test_save_vol_base_meta(self):
        container = {}
        self.bak_meta_api._save_vol_base_meta(container, self.volume_id)

    def test_is_serializable(self):
        data = {'foo': 'bar'}
        if self.bak_meta_api._is_serializable(data):
            jsonutils.dumps(data)

    def test_is_not_serializable(self):
        data = {'foo': 'bar'}
        with mock.patch.object(jsonutils, 'dumps') as mock_dumps:
            mock_dumps.side_effect = TypeError
            self.assertFalse(self.bak_meta_api._is_serializable(data))
            mock_dumps.assert_called_once()


text:
<?php

namespace Magento\Framework\Filter\Template\Tokenizer;

/**
 * Template constructions tokenizer
 */
abstract class AbstractTokenizer
{
    /**
     * Current index in string
     *
     * @var int
     */
    protected $_currentIndex;

    /**
     * String for tokenize
     *
     * @var string
     */
    protected $_string;

    /**
     * Move current index to next char.
     *
     * If index out of bounds returns false
     *
     * @return boolean
     */
    public function next()
    {
        if ($this->_currentIndex + 1 >= strlen($this->_string)) {
            return false;
        }

        $this->_currentIndex++;
        return true;
    }

    /**
     * Move current index to previous char.
     *
     * If index out of bounds returns false
     *
     * @return boolean
     */
    public function prev()
    {
        if ($this->_currentIndex - 1 < 0) {
            return false;
        }

        $this->_currentIndex--;
        return true;
    }

    /**
     * Return current char
     *
     * @return string
     */
    public function char()
    {
        return $this->_string[$this->_currentIndex];
    }

    /**
     * Set string for tokenize
     *
     * @param string $value
     * @return void
     */
    public function setString($value)
    {
        $this->_string = urldecode($value);
        $this->reset();
    }

    /**
     * Move char index to begin of string
     *
     * @return void
     */
    public function reset()
    {
        $this->_currentIndex = 0;
    }

    /**
     * Return true if current char is white-space
     *
     * @return boolean
     */
    public function isWhiteSpace()
    {
        return trim($this->char()) != $this->char();
    }

    /**
     * Tokenize string
     *
     * @return array
     */
    abstract public function tokenize();
}


text:
"""
The tvm.meta_schedule.cost_model package.
"""
from .cost_model import CostModel, PyCostModel
from .random_model import RandomModel
from .xgb_model import XGBModel