text:
from nose.plugins.attrib import attr

# project
from tests.checks.common import AgentCheckTest

MINIMAL_INSTANCE = {
    'host': '.',
}

INSTANCE = {
    'host': '.',
    'sites': ['Default Web Site', 'Test-Website-1', 'Non Existing Website'],
}

INVALID_HOST_INSTANCE = {
    'host': 'nonexistinghost'
}

@attr('windows')
@attr(requires='windows')
class IISTest(AgentCheckTest):
    CHECK_NAME = 'iis'

    IIS_METRICS = (
        'iis.uptime',
        # Network
        'iis.net.bytes_sent',
        'iis.net.bytes_rcvd',
        'iis.net.bytes_total',
        'iis.net.num_connections',
        'iis.net.files_sent',
        'iis.net.files_rcvd',
        'iis.net.connection_attempts',
        # HTTP Methods
        'iis.httpd_request_method.get',
        'iis.httpd_request_method.post',
        'iis.httpd_request_method.head',
        'iis.httpd_request_method.put',
        'iis.httpd_request_method.delete',
        'iis.httpd_request_method.options',
        'iis.httpd_request_method.trace',
        # Errors
        'iis.errors.not_found',
        'iis.errors.locked',
        # Users
        'iis.users.anon',
        'iis.users.nonanon',
        # Requests
        'iis.requests.cgi',
        'iis.requests.isapi',
    )

    def test_basic_check(self):
        self.run_check_twice({'instances': [MINIMAL_INSTANCE]})

        for metric in self.IIS_METRICS:
            self.assertMetric(metric, tags=[], count=1)

        self.assertServiceCheckOK('iis.site_up', tags=["site:{0}".format('Total')], count=1)
        self.coverage_report()

    def test_check_on_specific_websites(self):
        self.run_check_twice({'instances': [INSTANCE]})

        site_tags = ['Default_Web_Site', 'Test_Website_1']
        for metric in self.IIS_METRICS:
            for site_tag in site_tags:
                self.assertMetric(metric, tags=["site:{0}".format(site_tag)], count=1)

        self.assertServiceCheckOK('iis.site_up',
                                  tags=["site:{0}".format('Default_Web_Site')], count=1)
        self.assertServiceCheckOK('iis.site_up',
                                  tags=["site:{0}".format('Test_Website_1')], count=1)
        self.assertServiceCheckCritical('iis.site_up',
                                        tags=["site:{0}".format('Non_Existing_Website')], count=1)

        self.coverage_report()

    def test_service_check_with_invalid_host(self):
        self.run_check({'instances': [INVALID_HOST_INSTANCE]})

        self.assertServiceCheckCritical('iis.site_up', tags=["site:{0}".format('Total')])

        self.coverage_report()


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xml.actions.xmlbeans;

import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.XmlRecursiveElementVisitor;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.schema.XmlNSDescriptorImpl;
import com.intellij.xml.util.XmlUtil;
import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.tool.CommandLine;
import org.apache.xmlbeans.impl.xsd2inst.SampleXmlUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author Konstantin Bulenkov
 */
public class Xsd2InstanceUtils {
    public static String generate(String[] args) {
        Set flags = new HashSet();
        Set opts = new HashSet();
        flags.add("h");
        flags.add("help");
        flags.add("usage");
        flags.add("license");
        flags.add("version");
        flags.add("dl");
        flags.add("noupa");
        flags.add("nopvr");
        flags.add("partial");
        opts.add("name");

        CommandLine cl = new CommandLine(args, flags, opts);

        String[] badOpts = cl.getBadOpts();
        if (badOpts.length > 0) {
                throw new IllegalArgumentException("Unrecognized option: " + badOpts[0]);

        }

        boolean dl = (cl.getOpt("dl") != null);
        boolean nopvr = (cl.getOpt("nopvr") != null);
        boolean noupa = (cl.getOpt("noupa") != null);

        File[] schemaFiles = cl.filesEndingWith(".xsd");
        String rootName = cl.getOpt("name");

        if (rootName == null) {
            throw new IllegalArgumentException("Required option \"-name\" must be present");
        }

        // Process Schema files
        List sdocs = new ArrayList();
      for (File schemaFile : schemaFiles) {
        try {
          sdocs.add(XmlObject.Factory.parse(schemaFile,
                                            (new XmlOptions()).setLoadLineNumbers().setLoadMessageDigest()));
        }
        catch (Exception e) {
          throw new IllegalArgumentException("Can not load schema file: " + schemaFile + ": " + e.getLocalizedMessage());
        }
      }

        XmlObject[] schemas = (XmlObject[]) sdocs.toArray(new XmlObject[0]);

        SchemaTypeSystem sts = null;
        if (schemas.length > 0)
        {
            XmlOptions compileOptions = new XmlOptions();
            if (dl)
                compileOptions.setCompileDownloadUrls();
            if (nopvr)
                compileOptions.setCompileNoPvrRule();
            if (noupa)
                compileOptions.setCompileNoUpaRule();

          try {
            sts = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions);
          }
          catch (XmlException e) {
            StringBuilder out = new StringBuilder("Schema compilation errors: ");
            Collection errors = e.getErrors();
            for (Object error : errors) out.append("\n").append(error);
              throw new IllegalArgumentException(out.toString());
          }
        }

        if (sts == null)
        {
            throw new IllegalArgumentException("No Schemas to process.");
        }
        SchemaType[] globalElems = sts.documentTypes();
        SchemaType elem = null;
      for (SchemaType globalElem : globalElems) {
        if (rootName.equals(globalElem.getDocumentElementName().getLocalPart())) {
          elem = globalElem;
          break;
        }
      }

        if (elem == null) {
            throw new IllegalArgumentException("Could not find a global element with name \"" + rootName + "\"");
        }

        // Now generate it
        return SampleXmlUtil.createSampleForType(elem);
    }

  public static XmlElementDescriptor getDescriptor(XmlTag tag, String elementName) {
    final PsiMetaData metaData = tag.getMetaData();

    if (metaData instanceof XmlNSDescriptorImpl) {
      final XmlNSDescriptorImpl nsDescriptor = (XmlNSDescriptorImpl) metaData;
      return nsDescriptor.getElementDescriptor(elementName, nsDescriptor.getDefaultNamespace());
    }

    return null;
  }

  public static List<String> addVariantsFromRootTag(XmlTag rootTag) {
    PsiMetaData metaData = rootTag.getMetaData();
    if (metaData instanceof XmlNSDescriptorImpl) {
      XmlNSDescriptorImpl nsDescriptor = (XmlNSDescriptorImpl) metaData;

      List<String> elementDescriptors = new ArrayList<>();
      XmlElementDescriptor[] rootElementsDescriptors = nsDescriptor.getRootElementsDescriptors(PsiTreeUtil.getParentOfType(rootTag, XmlDocument.class));
      for(XmlElementDescriptor e:rootElementsDescriptors) {
        elementDescriptors.add(e.getName());
      }

      return elementDescriptors;
    }
    return Collections.emptyList();
  }

  public static @NotNull String processAndSaveAllSchemas(@NotNull XmlFile file, @NotNull final Map<String, String> scannedToFileName,
                                                         final @NotNull SchemaReferenceProcessor schemaReferenceProcessor) {
    final String fileName = file.getName();

    String previous = scannedToFileName.get(fileName);

    if (previous != null) return previous;

    scannedToFileName.put(fileName, fileName);

    final StringBuilder result = new StringBuilder();

    file.acceptChildren(new XmlRecursiveElementVisitor() {
      @Override public void visitElement(@NotNull PsiElement psiElement) {
        super.visitElement(psiElement);
        if (psiElement instanceof LeafPsiElement) {
          final String text = psiElement.getText();
          result.append(text);
        }
      }

      @Override public void visitXmlAttribute(XmlAttribute xmlAttribute) {
        boolean replaced = false;

        if (xmlAttribute.isNamespaceDeclaration()) {
          replaced = true;
          final String value = xmlAttribute.getValue();
          result.append(xmlAttribute.getText()).append(" ");

          if (!scannedToFileName.containsKey(value)) {
            final XmlNSDescriptor nsDescriptor = xmlAttribute.getParent().getNSDescriptor(value, true);

            if (nsDescriptor != null) {
              processAndSaveAllSchemas(nsDescriptor.getDescriptorFile(), scannedToFileName, schemaReferenceProcessor);
            }
          }
        } else if ("schemaLocation".equals(xmlAttribute.getName())) {
          final PsiReference[] references = xmlAttribute.getValueElement().getReferences();

          PsiReference reference = ArrayUtil.getLastElement(references);
          if (reference != null) {
            PsiElement psiElement = reference.resolve();

            if (psiElement instanceof XmlFile) {
              final String s = processAndSaveAllSchemas(((XmlFile) psiElement), scannedToFileName, schemaReferenceProcessor);
              result.append(xmlAttribute.getName()).append("='").append(s).append('\'');
              replaced = true;
            }
          }
        }
        if (!replaced) result.append(xmlAttribute.getText());
      }
    });

    final VirtualFile virtualFile = file.getVirtualFile();
    final String content = result.toString();

    byte[] bytes;
    if (virtualFile != null) {
      bytes = content.getBytes(virtualFile.getCharset());
    } else {
      try {
        final String charsetName = XmlUtil.extractXmlEncodingFromProlog(content.getBytes(StandardCharsets.UTF_8));
        bytes = charsetName != null ? content.getBytes(charsetName) : content.getBytes(StandardCharsets.UTF_8);
      } catch (UnsupportedEncodingException e) {
        bytes = content.getBytes(StandardCharsets.UTF_8);
      }
    }

    schemaReferenceProcessor.processSchema(fileName, bytes);
    return fileName;
  }

  public interface SchemaReferenceProcessor {
    void processSchema(String schemaFileName, byte[] schemaContent);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.codepath.apps.tweetaway.activities;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.FrameLayout;

import com.codepath.apps.tweetaway.R;
import com.codepath.apps.tweetaway.adapters.UserProfilePagerAdapter;
import com.codepath.apps.tweetaway.fragments.ProfileHeaderFragment;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by rpraveen on 11/5/16.
 */

public class UserProfileActivity extends AppCompatActivity {

  @BindView(R.id.flUserProfileContainer) FrameLayout mFlContainer;
  @BindView(R.id.tabsUserProfile) TabLayout mTabsUserProfile;
  @BindView(R.id.pagerUserProfile) ViewPager mUserProfileViewPager;
  @BindView(R.id.toolBar) Toolbar mToolbar;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_profile);
    ButterKnife.bind(this);

    String user_screen_name = getIntent().getStringExtra("screen_name");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(user_screen_name);

    ProfileHeaderFragment profileHeader = ProfileHeaderFragment.newInstance(user_screen_name);
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flUserProfileContainer, profileHeader).commit();
    mUserProfileViewPager.setAdapter(new UserProfilePagerAdapter(fragmentManager, this, user_screen_name));
    mTabsUserProfile.setupWithViewPager(mUserProfileViewPager);
  }

  /**
   * react to the user tapping the back/up icon in the action bar
   */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        // this takes the user 'back', as if they pressed the left-facing triangle icon on the main android toolbar.
        // if this doesn't work as desired, another possibility is to call `finish()` here.
        this.onBackPressed();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }
}


text:
package deliveryservice

import (
	"database/sql"
	"fmt"
	"net/http"

	"github.com/apache/trafficcontrol/lib/go-log"
	"github.com/apache/trafficcontrol/lib/go-tc"
	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
)

const safeUpdateQuery = `
UPDATE deliveryservice
SET display_name=$1,
    info_url=$2,
    long_desc=$3,
    long_desc_1=$4
WHERE id = $5
RETURNING id
`

// UpdateSafe is the handler for PUT requests to /deliveryservices/{{ID}}/safe.
//
// The only fields which are "safe" to modify are the displayName, infoURL, longDesc, and longDesc1.
func UpdateSafe(w http.ResponseWriter, r *http.Request) {
	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"id"}, []string{"id"})
	tx := inf.Tx.Tx
	if userErr != nil || sysErr != nil {
		api.HandleErr(w, r, tx, errCode, userErr, sysErr)
		return
	}
	defer inf.Close()

	dsID := inf.IntParams["id"]

	userErr, sysErr, errCode = tenant.CheckID(tx, inf.User, dsID)
	if userErr != nil || sysErr != nil {
		api.HandleErr(w, r, tx, errCode, userErr, sysErr)
		return
	}

	var dsr tc.DeliveryServiceSafeUpdateRequest
	if err := api.Parse(r.Body, tx, &dsr); err != nil {
		api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %s", err), nil)
		return
	}
	if ok, err := updateDSSafe(tx, dsID, dsr); err != nil {
		api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("Updating Delivery Service (safe): %s", err))
		return
	} else if !ok {
		userErr = fmt.Errorf("No Delivery Service exists by ID '%d'", dsID)
		api.HandleErr(w, r, tx, http.StatusNotFound, userErr, nil)
		return
	}
	useIMS := false
	config, e := api.GetConfig(r.Context())
	if e == nil && config != nil {
		useIMS = config.UseIMS
	} else {
		log.Warnf("Couldn't get config %v", e)
	}
	dses, userErr, sysErr, errCode, _ := readGetDeliveryServices(r.Header, inf.Params, inf.Tx, inf.User, useIMS)
	if userErr != nil || sysErr != nil {
		api.HandleErr(w, r, tx, errCode, userErr, sysErr)
		return
	}
	if len(dses) != 1 {
		sysErr = fmt.Errorf("Updating Delivery Service (safe): expected one Delivery Service returned from read, got %v", len(dses))
		api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr)
		return
	}

	ds := dses[0]

	alertMsg := "Delivery Service safe update successful."
	if inf.Version != nil && inf.Version.Major == 1 && inf.Version.Minor < 5 {
		switch inf.Version.Minor {
		case 4:
			api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV14{ds.DeliveryServiceNullableV14})
		case 3:
			api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV13{ds.DeliveryServiceNullableV13})
		default:
			api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV12{ds.DeliveryServiceNullableV12})
		}
	} else {
		api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV30{ds})
	}

	api.CreateChangeLogRawTx(api.ApiChange, fmt.Sprintf("DS: %s, ID: %d, ACTION: Updated safe fields", *ds.XMLID, *ds.ID), inf.User, tx)
}

// updateDSSafe updates the given delivery service in the database. Returns whether the DS existed, and any error.
func updateDSSafe(tx *sql.Tx, dsID int, ds tc.DeliveryServiceSafeUpdateRequest) (bool, error) {
	res, err := tx.Exec(safeUpdateQuery, ds.DisplayName, ds.InfoURL, ds.LongDesc, ds.LongDesc1, dsID)
	if err != nil {
		return false, err
	}
	rowsAffected, err := res.RowsAffected()
	if err != nil {
		return false, fmt.Errorf("Checking rows affected: %s", err)
	}
	if rowsAffected < 1 {
		return false, nil
	}
	if rowsAffected > 1 {
		return false, fmt.Errorf("Too many rows affected: %v", rowsAffected)
	}
	return true, nil
}


text:
<?php

namespace Tests\Magium\MagentoEE113\Action;

use Magium\Magento\AbstractMagentoTestCase;
use Magium\Magento\Actions\Search\Search;
use Magium\Magento\Extractors\Catalog\Search\SearchSuggestions;
use Magium\Magento\Themes\MagentoEE113\ThemeConfiguration;

class SearchTest extends \Tests\Magium\Magento\Action\SearchTest
{
    protected $fullSearch = 'shirt';
    protected $partialSearch = 'sh';

    protected function setUp()
    {
        parent::setUp();
        $this->switchThemeConfiguration(ThemeConfiguration::THEME);
    }
}


text:
"""Mean Shift unsupervised hierarchical classification for machine learning.

Mean Shift is very similar to the K-Means algorithm, except for one very
important factor: you do not need to specify the number of groups prior to
training. The Mean Shift algorithm finds clusters on its own. For this reason,
it is even more of an "unsupervised" machine learning algorithm than K-Means.

The way Mean Shift works is to go through each featureset
(a datapoint on a graph), and proceed to do a hill climb operation. Hill
Climbing is just as it sounds: The idea is to continually increase, or go up,
until you cannot anymore. We don't have for sure just one local maximal value.
We might have only one, or we might have ten. Our "hill" in this case will be
the number of featuresets/datapoints within a given radius. The radius is also
called a bandwidth, and the entire window is your Kernel. The more data within
the window, the better. Once we can no longer take another step without
decreasing the number of featuresets/datapoints within the radius, we take the
mean of all data in that region and we have located a cluster center. We do
this starting from each data point. Many data points will lead to the same
cluster center, which should be expected, but it is also possible that other
data points will take you to a completely separate cluster center.

This algorithm is usually used for research and finding structure and is not
expected to be super precise.

Example:

        $ python regularMeanShift.py

Todo:
    *
"""
import numpy as np
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import style
style.use("ggplot")

# Create training data
centers = [[1, 1, 1], [5, 5, 5], [3, 10, 10]]
X, _ = make_blobs(n_samples=100, centers=centers, cluster_std=1)

# Create Mean Shift object and fit data
ms = MeanShift()
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
print(cluster_centers)
n_clusters_ = len(np.unique(labels))
print("Number of estimated clusters: ", n_clusters_)

# Plot
colors = 10 * ['r', 'g', 'b', 'c', 'y', 'm']
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range(len(X)):
    ax.scatter(X[i][0], X[i][1], X[i][2], c=colors[labels[i]], marker='o')
ax.scatter(cluster_centers[:, 0], cluster_centers[:, 1], cluster_centers[:, 2],
           marker="x", color='k', s=150, linewidths=5, zorder=10)
plt.show()


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>FTP 下载</title>

镜像更新

	<?php

		// set up variables -- change these to suit application
		$host =  "210.34.246.224";
		$user = "teacher";
		$password = "22693529";
		$remotefile = "/teach/cxg/Office2013.pdf";
		$localfile = "./tmp/Office2013.pdf";

		// connect to host
		$conn = ftp_connect($host);
		if (!$conn){
			echo 'Error: Could not connect to ftp server
';
			exit;
		}
		echo "Connected to $host.
";

		// log in to host
		$result = @ftp_login($conn, $user, $password);
		if (!$result) {
			echo "Error: Could not log on as $user
";
			ftp_quit($conn);
			exit;
		}
		echo "Logged in as $user
";

		// check file times to see if an update is required
		echo 'Checking file time...
';
		if (file_exists($localfile)){
			$localtime = filemtime($localfile);
			echo 'Local file last updated ';
			echo date('G:i j-M-Y', $localtime);
			echo '
';
		} else {
			echo "Local file does not exist.
";
			$localtime = 0;
		}

		$remotetime = ftp_mdtm($conn, $remotefile);
		if( !($remotetime >= 0) ){
			//server my not support mod time
			echo 'Can\'t access remote file time.
';
			$remotetime = $localtime + 1; // make sure of an update
		} else {
			echo 'Remote file last updated ';
			echo date('G:i j-M-Y', $remotetime);
			echo '
';
		}

		if (!($remotetime > $localtime)){
			echo 'Local copy is up to date.
';
			exit;
		}

		// download file
		echo 'Getting file from server...
';
		$fp = fopen($localfile, 'w');
		if(!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY) ){
			echo 'Error: Could not download file';
			ftp_quit($conn);
			exit;
		}
		fclose($fp);
		echo 'File downloaded successfully';

		// close connection to host
		ftp_quit($conn);
	?>


text:
from functools import reduce

from ..function import Function

class _DimReduceFunction(Function):

    def __init__(self, dim=None):
        super(_DimReduceFunction, self).__init__()
        self.dim = dim

    def forward(self, input):
        self.input_size = input.size()
        fn = getattr(input, self.fn_name)
        if self.dim is None:
            return input.new((fn(),))
        else:
            return fn(self.dim)

class Sum(_DimReduceFunction):
    fn_name = 'sum'

    def backward(self, grad_output):
        if self.dim is None:
            return grad_output.new(self.input_size).fill_(grad_output[0])
        else:
            repeats = [1 for _ in self.input_size]
            repeats[self.dim] = self.input_size[self.dim]
            return grad_output.repeat(*repeats),

class Prod(_DimReduceFunction):

    def forward(self, input):
        self.input_size = input.size()
        if self.dim is None:
            self.result = input.prod()
            self.save_for_backward(input)
            return input.new((self.result,))
        else:
            output = input.prod(self.dim)
            self.save_for_backward(input, output)
            return output

    def backward(self, grad_output):
        if self.dim is None:
            input, = self.saved_tensors
            zero_idx = (input == 0).nonzero()
            if zero_idx.dim() == 0:
                return grad_output.mul(self.result).expand_as(input).div(input)
            elif zero_idx.size(0) > 1:
                return grad_output.new(self.input_size).zero_()
            else:
                grad_input = grad_output.new(self.input_size).zero_()
                zero_idx = tuple(zero_idx[0].cpu())
                input_copy = input.clone()
                input_copy[zero_idx] = 1.
                grad_input[zero_idx] = grad_output[0] * input_copy.prod()
                return grad_input
        else:
            input, output = self.saved_tensors
            zero_mask = input == 0
            slice_zero_count = zero_mask.sum(self.dim)
            total_zeros = slice_zero_count.sum()
            grad_input = grad_output.mul(output).expand_as(input).div(input)
            if total_zeros == 0:
                return grad_input

            some_zeros = slice_zero_count.gt(0).expand_as(grad_input)
            grad_input[some_zeros] = 0

            single_zero_idx = slice_zero_count.eq(1).nonzero()
            for idx in single_zero_idx:
                idx_tuple = tuple(idx.cpu())
                input_idx_tuple = idx_tuple[:self.dim] + (slice(0, None),) + idx_tuple[self.dim + 1:]

                # slice_mask and input_copy are 1D
                slice_mask = zero_mask[input_idx_tuple]
                input_copy = input[input_idx_tuple].clone()
                zero_idx = slice_mask.nonzero()[0, 0]
                input_copy[zero_idx] = 1.

                grad_idx_tuple = idx_tuple[:self.dim] + (zero_idx,) + idx_tuple[self.dim + 1:]
                grad_input[grad_idx_tuple] = grad_output[idx_tuple] * input_copy.prod()

            return grad_input

class Mean(_DimReduceFunction):
    fn_name = 'mean'

    def backward(self, grad_output):
        if self.dim is None:
            grad_input_val = grad_output[0]
            grad_input_val /= reduce(lambda x, y: x * y, self.input_size, 1)
            return grad_output.new(*self.input_size).fill_(grad_input_val)
        else:
            repeats = [1 for _ in self.input_size]
            dim_size = self.input_size[self.dim]
            repeats[self.dim] = dim_size
            return grad_output.repeat(*repeats).div_(dim_size)

class _SelectionFunction(Function):
    has_all_reduce = True
    # additional_args is prepended before dim when calling the tensor
    # function. It's a no-op for subclasses other than kthvalue.
    # kthvalue not only requires us to pass a dim, but also preceed it with k.
    additional_args = tuple()

    def __init__(self, dim=None):
        super(_SelectionFunction, self).__init__()
        self.dim = dim

    def forward(self, input):
        fn = getattr(input, type(self).__name__.lower())
        self.input_size = input.size()
        if self.dim is None and self.has_all_reduce:
            value = fn(*self.additional_args)
            self.indices = tuple(input.eq(value).nonzero()[0])
            return input.new((value,))
        else:
            if self.dim is None:
                dim = input.dim() - 1
            else:
                dim = self.dim
            args = (dim,)
            if self.additional_args:
                args = self.additional_args + args
            output, indices = fn(*args)
            self.save_for_backward(indices)
            self.mark_non_differentiable(indices)
            return output, indices

    def backward(self, grad_output, grad_indices=None):
        grad_input = grad_output.new(*self.input_size).zero_()
        if self.dim is None and self.has_all_reduce:
            grad_input[self.indices] = grad_output[0]
        else:
            if self.dim is None:
                dim = input.dim() - 1
            else:
                dim = self.dim
            indices, = self.saved_tensors
            grad_input.scatter_(dim, indices, grad_output)
        return grad_input

class Max(_SelectionFunction):
    pass

class Min(_SelectionFunction):
    pass

class Mode(_SelectionFunction):
    has_all_reduce = False

class Median(_SelectionFunction):
    has_all_reduce = False

class Kthvalue(_SelectionFunction):
    has_all_reduce = False

    def __init__(self, k, dim=None):
        super(Kthvalue, self).__init__(dim)
        self.additional_args = (k,)

class Norm(Function):

    def __init__(self, norm_type=2, dim=None):
        super(Norm, self).__init__()
        self.norm_type = norm_type
        self.dim = dim

    def forward(self, input):
        if self.dim is None:
            self.norm = input.norm(self.norm_type)
            self.save_for_backward(input)
            return input.new((self.norm,))
        else:
            output = input.norm(self.norm_type, self.dim)
            self.save_for_backward(input, output)
            return output

    def backward(self, grad_output):
        if self.dim is None:
            input, = self.saved_tensors
            if self.norm_type == 2:
                return input.mul(grad_output[0] / self.norm)
            else:
                pow = input.abs().pow(self.norm_type - 2)
                scale = grad_output[0] / self.norm ** (self.norm_type - 1)
                return input.mul(pow).mul(scale)
        else:
            input, output = self.saved_tensors
            big_grad_output = grad_output.expand_as(input)
            if self.norm_type == 2:
                big_output = output.expand_as(input)
                return input.mul(big_grad_output).div(big_output)
            else:
                pow = input.abs().pow(self.norm_type - 2)
                big_output = output.pow(self.norm_type - 1).expand_as(input)
                return input.mul(pow).mul(big_grad_output).div(big_output)

# TODO: renorm
# TODO: std
# TODO: var


text:
package com.weijiangzhu.minaserver.message;

public class MessageType {
	public static final Integer USERINFO = 1000;
}


text:
id -u $SERVICE_USER_NAME &>/dev/null | useradd -u $SERVICE_USER_ID $SERVICE_USER_NAME -d /home/$SERVICE_USER_NAME -s /bin/bash

# setting run user from environment

sed -i "s/www-data/$SERVICE_USER_ID/g" /usr/local/etc/php-fpm.d/www.conf

if [[ -z "$EPP_XDEBUG_REMOTE_HOST" ]]; then
  EPP_XDEBUG_CONNECT_BACK=1
else
  EPP_XDEBUG_CONNECT_BACK=0
fi

if [ "true" == "$EPP_XDEBUG" ]; then
  echo -e "xdebug.remote_host = $EPP_XDEBUG_REMOTE_HOST \n
xdebug.max_nesting_level = 1000 \n
xdebug.remote_enable = 1 \n
xdebug.remote_connect_back = $EPP_XDEBUG_CONNECT_BACK \n
xdebug.remote_port = 9000 \n
xdebug.remote_handler = dbgp \n
xdebug.remote_mode = req \n
xdebug.max_nesting_level=500 \n
xdebug.profiler_enable_trigger = 1 \n
" > /usr/local/etc/php/conf.d/docker-php-ext-xdebug-esono.ini
else
  rm -f /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
fi

if [ "true" == "$EPP_BLACKFIRE" ]; then
  mv /tmp/blackfire-*.so $(php -r "echo ini_get('extension_dir');")/blackfire.so
  printf "extension=blackfire.so\nblackfire.agent_socket=tcp://blackfire:8707\n" > /usr/local/etc/php/conf.d/blackfire.ini
fi

if [ "true" == "$EPP_SHOW_ERRORS" ]; then
  sed -i "s/display_errors = Off/display_errors = On/g" /usr/local/etc/php/php.ini
fi

. /usr/local/bin/tools/create-ssh-config.sh

if [ "$1" = 'php-fpm' ]; then
    exec "$@"
else
    exec gosu $SERVICE_USER_ID:$SERVICE_USER_ID "$@"
fi


text:
class CouponsController < ApplicationController

  get '/' do
      @coupons = CoupsModel.all
      erb :coupons_index
  end

##create coupons
get '/create' do
  erb :coupons_create
end

post '/create' do
  @coupon = CoupsModel.new
  @coupon.title = params[:title]
  @coupon.description = params[:description]
  @coupon.product = params[:product]
  @coupon.discount = params[:discount]
  @coupon.exp_date = params[:exp_date]
  @coupon.save

  erb :coupons_create_sucess
end

  get '/edit/:id' do
    @id = params[:id]
    @coupon = CoupsModel.find(@id)

    erb :coupons_edit
  end

  post '/edit' do
    @coupon.title = params[:title]
    @coupon.description = params[:description]
    @coupon.product = params[:product]
    @coupon.discount = params[:discount]
    @coupon.exp_date = params[:exp_date]
    @coupon.save

    erb :coupons_edit_success

  end

  ## delete (destroy) students
  post '/delete' do
    @id = params[:id]
    @coupon = CoupsModel.find(@id)
    @coupon.destroy

    erb :coupons_delete_success
  end

end


text:
sessionStorage.iframeID = "dom-distiller-result-iframe";
(() => !!document.getElementById(sessionStorage.iframeID))();


text:
package org.artifactory.webapp.wicket.page.browse.treebrowser.tabs.zipentry;

import org.apache.wicket.markup.html.panel.Panel;
import org.artifactory.addon.AddonsManager;
import org.artifactory.addon.wicket.FilteredResourcesWebAddon;
import org.artifactory.api.context.ContextHelper;
import org.artifactory.fs.ZipEntryInfo;
import org.artifactory.webapp.actionable.model.ArchivedItemActionableItem;

/**
 * General info panel displayed in the artifacts tree browser.
 *
 * @author Yossi Shaul
 */
public class ZipEntryGeneralTabPanel extends Panel {
    public ZipEntryGeneralTabPanel(String id, ZipEntryInfo zipEntry, ArchivedItemActionableItem repoItem) {
        super(id);
        setOutputMarkupId(true);

        add(new ZipEntryPanel("generalInfoPanel", zipEntry));
        FilteredResourcesWebAddon filteredAddon = ContextHelper.get().beanForType(
                AddonsManager.class).addonByType(FilteredResourcesWebAddon.class);
        add(filteredAddon.getZipEntryActions("actionsPanel", repoItem));
    }
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.google.common.collect.ImmutableList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;

@Private
@Unstable
public class FSParentQueue extends FSQueue {
  private static final Log LOG = LogFactory.getLog(
      FSParentQueue.class.getName());

  private final List<FSQueue> childQueues = new ArrayList<>();
  private Resource demand = Resources.createResource(0);
  private int runnableApps;

  private ReadWriteLock rwLock = new ReentrantReadWriteLock();
  private Lock readLock = rwLock.readLock();
  private Lock writeLock = rwLock.writeLock();

  public FSParentQueue(String name, FairScheduler scheduler,
      FSParentQueue parent) {
    super(name, scheduler, parent);
  }

  public void addChildQueue(FSQueue child) {
    writeLock.lock();
    try {
      childQueues.add(child);
    } finally {
      writeLock.unlock();
    }
  }

  public void removeChildQueue(FSQueue child) {
    writeLock.lock();
    try {
      childQueues.remove(child);
    } finally {
      writeLock.unlock();
    }
  }

  @Override
  public void recomputeShares() {
    readLock.lock();
    try {
      policy.computeShares(childQueues, getFairShare());
      for (FSQueue childQueue : childQueues) {
        childQueue.getMetrics().setFairShare(childQueue.getFairShare());
        childQueue.recomputeShares();
      }
    } finally {
      readLock.unlock();
    }
  }

  public void recomputeSteadyShares() {
    readLock.lock();
    try {
      policy.computeSteadyShares(childQueues, getSteadyFairShare());
      for (FSQueue childQueue : childQueues) {
        childQueue.getMetrics()
            .setSteadyFairShare(childQueue.getSteadyFairShare());
        if (childQueue instanceof FSParentQueue) {
          ((FSParentQueue) childQueue).recomputeSteadyShares();
        }
      }
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public void updatePreemptionVariables() {
    super.updatePreemptionVariables();
    // For child queues

    readLock.lock();
    try {
      for (FSQueue childQueue : childQueues) {
        childQueue.updatePreemptionVariables();
      }
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public Resource getDemand() {
    readLock.lock();
    try {
      return Resource.newInstance(demand.getMemory(), demand.getVirtualCores());
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public Resource getResourceUsage() {
    Resource usage = Resources.createResource(0);
    readLock.lock();
    try {
      for (FSQueue child : childQueues) {
        Resources.addTo(usage, child.getResourceUsage());
      }
    } finally {
      readLock.unlock();
    }
    return usage;
  }

  @Override
  public void updateDemand() {
    // Compute demand by iterating through apps in the queue
    // Limit demand to maxResources
    Resource maxRes = scheduler.getAllocationConfiguration()
        .getMaxResources(getName());
    writeLock.lock();
    try {
      demand = Resources.createResource(0);
      for (FSQueue childQueue : childQueues) {
        childQueue.updateDemand();
        Resource toAdd = childQueue.getDemand();
        if (LOG.isDebugEnabled()) {
          LOG.debug("Counting resource from " + childQueue.getName() + " " +
              toAdd + "; Total resource consumption for " + getName() +
              " now " + demand);
        }
        demand = Resources.add(demand, toAdd);
        demand = Resources.componentwiseMin(demand, maxRes);
        if (Resources.equals(demand, maxRes)) {
          break;
        }
      }
    } finally {
      writeLock.unlock();
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("The updated demand for " + getName() + " is " + demand +
          "; the max is " + maxRes);
    }
  }

  private QueueUserACLInfo getUserAclInfo(UserGroupInformation user) {
    List<QueueACL> operations = new ArrayList<>();
    for (QueueACL operation : QueueACL.values()) {
      if (hasAccess(operation, user)) {
        operations.add(operation);
      }
    }
    return QueueUserACLInfo.newInstance(getQueueName(), operations);
  }

  @Override
  public List<QueueUserACLInfo> getQueueUserAclInfo(UserGroupInformation user) {
    List<QueueUserACLInfo> userAcls = new ArrayList<QueueUserACLInfo>();

    // Add queue acls
    userAcls.add(getUserAclInfo(user));

    // Add children queue acls
    readLock.lock();
    try {
      for (FSQueue child : childQueues) {
        userAcls.addAll(child.getQueueUserAclInfo(user));
      }
    } finally {
      readLock.unlock();
    }

    return userAcls;
  }

  @Override
  public Resource assignContainer(FSSchedulerNode node) {
    Resource assigned = Resources.none();

    // If this queue is over its limit, reject
    if (!assignContainerPreCheck(node)) {
      return assigned;
    }

    // Hold the write lock when sorting childQueues
    writeLock.lock();
    try {
      Collections.sort(childQueues, policy.getComparator());
    } finally {
      writeLock.unlock();
    }

    /*
     * We are releasing the lock between the sort and iteration of the
     * "sorted" list. There could be changes to the list here:
     * 1. Add a child queue to the end of the list, this doesn't affect
     * container assignment.
     * 2. Remove a child queue, this is probably good to take care of so we
     * don't assign to a queue that is going to be removed shortly.
     */
    readLock.lock();
    try {
      for (FSQueue child : childQueues) {
        assigned = child.assignContainer(node);
        if (!Resources.equals(assigned, Resources.none())) {
          break;
        }
      }
    } finally {
      readLock.unlock();
    }
    return assigned;
  }

  @Override
  public RMContainer preemptContainer() {
    RMContainer toBePreempted = null;

    // Find the childQueue which is most over fair share
    FSQueue candidateQueue = null;
    Comparator<Schedulable> comparator = policy.getComparator();

    readLock.lock();
    try {
      for (FSQueue queue : childQueues) {
        if (candidateQueue == null ||
            comparator.compare(queue, candidateQueue) > 0) {
          candidateQueue = queue;
        }
      }
    } finally {
      readLock.unlock();
    }

    // Let the selected queue choose which of its container to preempt
    if (candidateQueue != null) {
      toBePreempted = candidateQueue.preemptContainer();
    }
    return toBePreempted;
  }

  @Override
  public List<FSQueue> getChildQueues() {
    readLock.lock();
    try {
      return ImmutableList.copyOf(childQueues);
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public void setPolicy(SchedulingPolicy policy)
      throws AllocationConfigurationException {
    boolean allowed =
        SchedulingPolicy.isApplicableTo(policy, (parent == null)
            ? SchedulingPolicy.DEPTH_ROOT
            : SchedulingPolicy.DEPTH_INTERMEDIATE);
    if (!allowed) {
      throwPolicyDoesnotApplyException(policy);
    }
    super.policy = policy;
  }

  public void incrementRunnableApps() {
    writeLock.lock();
    try {
      runnableApps++;
    } finally {
      writeLock.unlock();
    }
  }

  public void decrementRunnableApps() {
    writeLock.lock();
    try {
      runnableApps--;
    } finally {
      writeLock.unlock();
    }
  }

  @Override
  public int getNumRunnableApps() {
    readLock.lock();
    try {
      return runnableApps;
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public void collectSchedulerApplications(
      Collection<ApplicationAttemptId> apps) {
    readLock.lock();
    try {
      for (FSQueue childQueue : childQueues) {
        childQueue.collectSchedulerApplications(apps);
      }
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public ActiveUsersManager getActiveUsersManager() {
    // Should never be called since all applications are submitted to LeafQueues
    return null;
  }

  @Override
  public void recoverContainer(Resource clusterResource,
      SchedulerApplicationAttempt schedulerAttempt, RMContainer rmContainer) {
    // TODO Auto-generated method stub

  }
}


text:
'use strict';
const bot = require('./../../index.js');
const axios = require('axios');
const log = require('./../../logger.js');

bot.registerCommand('roll', (msg, args) => {
    if (args.length === 0 || !/^\d+d{1}\d+/.test(args.join(' '))) return `**${msg.author.username}**, Invalid syntax. e.g. ${msg.prefix}roll 1d6.`;
    let uri = encodeURIComponent(args.join(' '));
    axios.get('https://rolz.org/api/?' + uri + '.json').then((response) => {
        if (typeof response.data.result === 'string' && response.data.result.startsWith('invalid dice code')) {
            bot.createMessage(msg.channel.id, `**${msg.author.username}**, ${response.data.result}`).catch(error => log.errC(error));
        } else {
            let roll = response.data;
            if (roll.details == null) bot.createMessage(msg.channel.id, `**${msg.author.username}**, ${roll.result}`).catch(error => log.errC(error));
            if (roll.details.length <= 100) bot.createMessage(msg.channel.id, `**${msg.author.username}**, 🎲 Your ${roll.input} resulted in ${roll.result} ${roll.details}`).catch(error => log.errC(error));
            else bot.createMessage(msg.channel.id, `**${msg.author.username}**, 🎲 Your ${roll.input} resulted in ${roll.result}.`).catch(error => log.errC(error));
        }
    }).catch((response) => {
        log.errC(response);
        if (response.status === 429) {
            log.errC(`rate limit hit: ${response}`);
            bot.createMessage(msg.channel.id, `**${msg.author.username}**, wew, looks like it's rate limit time. Chill out on the command usage and retry later.`).catch(error => log.errC(error));
        } else if (response.status !== 200) {
            bot.createMessage(msg.channel.id, `**${msg.author.username}**, sorry, I ran into a problem.`).catch(error => log.errC(error));
        }
    });
}, {
    aliases: ['dice'],
    caseInsensitive: true,
    deleteCommand: true,
    description: 'roll dice.',
    fullDescription: 'RPG dice roller.',
    usage: '<dice roll> e.g 1d6+2d4/2',
    cooldown: 5000
});


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_EXAMPLE_H_INCLUDED
#define CONF_EXAMPLE_H_INCLUDED

#define EXAMPLE_LED LED0

/** Using button PB0 on SAM4L-EK to trigger an interrupt */
#define EXAMPLE_BUTTON_INT    GPIO_PUSH_BUTTON_0

/** Using PC08 on SAM4L-EK to trigger an event */
#define EXAMPLE_PIN_EVENT     PIN_PC08
#define EXAMPLE_PIN_NAME      "PC08"

#define EXAMPLE_GND_NAME      "J4/PIN9"

/** PDCA ID for USART TX */
#define PDCA_PID_USART_TX    20

#endif  /* CONF_EXAMPLE_H_INCLUDED */


text:
/*
 * null
 *
 * [FhirComposite("ProvenanceEntityComponent")]
 * [Serializable]
 */

#import "FHIRElement.h"

#import "FHIRProvenance.h"

@class FHIRCode;
@class FHIRCoding;
@class FHIRUri;
@class FHIRString;
@class FHIRProvenanceAgentComponent;

@interface FHIRProvenanceEntityComponent : FHIRElement

/*
 * derivation | revision | quotation | source
 */
@property (nonatomic, strong) FHIRCode/*<code>*/ *roleElement;

@property (nonatomic) kProvenanceEntityRole role;

/*
 * Resource Type, or something else
 */
@property (nonatomic, strong) FHIRCoding *type;

/*
 * Identity of participant (urn or url)
 */
@property (nonatomic, strong) FHIRUri *referenceElement;

@property (nonatomic, strong) NSString *reference;

/*
 * Human description of participant
 */
@property (nonatomic, strong) FHIRString *displayElement;

@property (nonatomic, strong) NSString *display;

/*
 * Entity is attributed to this agent
 */
@property (nonatomic, strong) FHIRProvenanceAgentComponent *agent;

- (FHIRErrorList *)validate;

@end


text:
int32_t SystemNative_EnumerateInterfaceAddresses(IPv4AddressFound onIpv4Found,
                                               IPv6AddressFound onIpv6Found,
                                               LinkLayerAddressFound onLinkLayerFound)
{
    struct ifaddrs* headAddr;
    if (getifaddrs(&headAddr) == -1)
    {
        return -1;
    }

    for (struct ifaddrs* current = headAddr; current != NULL; current = current->ifa_next)
    {
        if (current->ifa_addr == NULL)
        {
            continue;
        }
        uint32_t interfaceIndex = if_nametoindex(current->ifa_name);
        // ifa_name may be an aliased interface name.
        // Use if_indextoname to map back to the true device name.
        char actualName[IF_NAMESIZE];
        char* result = if_indextoname(interfaceIndex, actualName);
        if (result == NULL)
        {
            freeifaddrs(headAddr);
            return -1;
        }

        assert(result == actualName);
        int family = current->ifa_addr->sa_family;
        if (family == AF_INET)
        {
            if (onIpv4Found != NULL)
            {
                // IP Address
                IpAddressInfo iai;
                memset(&iai, 0, sizeof(IpAddressInfo));
                iai.InterfaceIndex = interfaceIndex;
                iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;

                struct sockaddr_in* sain = (struct sockaddr_in*)current->ifa_addr;
                memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr));

                // Net Mask
                IpAddressInfo maskInfo;
                memset(&maskInfo, 0, sizeof(IpAddressInfo));
                maskInfo.InterfaceIndex = interfaceIndex;
                maskInfo.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;

                struct sockaddr_in* mask_sain = (struct sockaddr_in*)current->ifa_netmask;
                memcpy_s(maskInfo.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &mask_sain->sin_addr.s_addr, sizeof(mask_sain->sin_addr.s_addr));

                onIpv4Found(actualName, &iai, &maskInfo);
            }
        }
        else if (family == AF_INET6)
        {
            if (onIpv6Found != NULL)
            {
                IpAddressInfo iai;
                memset(&iai, 0, sizeof(IpAddressInfo));
                iai.InterfaceIndex = interfaceIndex;
                iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS;

                struct sockaddr_in6* sain6 = (struct sockaddr_in6*)current->ifa_addr;
                memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), sain6->sin6_addr.s6_addr, sizeof(sain6->sin6_addr.s6_addr));
                uint32_t scopeId = sain6->sin6_scope_id;
                onIpv6Found(actualName, &iai, &scopeId);
            }
        }

#if defined(AF_PACKET)
        else if (family == AF_PACKET)
        {
            if (onLinkLayerFound != NULL)
            {
                struct sockaddr_ll* sall = (struct sockaddr_ll*)current->ifa_addr;

                if (sall->sll_halen > sizeof(sall->sll_addr))
                {
                    // sockaddr_ll->sll_addr has a maximum capacity of 8 bytes (unsigned char sll_addr[8])
                    // so if we get a address length greater than that, we truncate it to 8 bytes.
                    // This is following the kernel docs where they always treat physical addresses with a maximum of 8 bytes.
                    // However in WSL we hit an issue where sll_halen was 16 bytes so the memcpy_s below would fail because it was greater.
                    sall->sll_halen = sizeof(sall->sll_addr);
                }

                LinkLayerAddressInfo lla;
                memset(&lla, 0, sizeof(LinkLayerAddressInfo));
                lla.InterfaceIndex = interfaceIndex;
                lla.NumAddressBytes = sall->sll_halen;
                lla.HardwareType = MapHardwareType(sall->sll_hatype);

                memcpy_s(&lla.AddressBytes, sizeof_member(LinkLayerAddressInfo, AddressBytes), &sall->sll_addr, sall->sll_halen);
                onLinkLayerFound(current->ifa_name, &lla);
            }
        }
#elif defined(AF_LINK)
        else if (family == AF_LINK)
        {
            if (onLinkLayerFound != NULL)
            {
                struct sockaddr_dl* sadl = (struct sockaddr_dl*)current->ifa_addr;

                LinkLayerAddressInfo lla;
                memset(&lla, 0, sizeof(LinkLayerAddressInfo));
                lla.InterfaceIndex = interfaceIndex;
                lla.NumAddressBytes = sadl->sdl_alen;
                lla.HardwareType = MapHardwareType(sadl->sdl_type);

                memcpy_s(&lla.AddressBytes, sizeof_member(LinkLayerAddressInfo, AddressBytes), (uint8_t*)LLADDR(sadl), sadl->sdl_alen);
                onLinkLayerFound(current->ifa_name, &lla);
            }
        }
#endif
    }

    freeifaddrs(headAddr);
    return 0;
}

#if HAVE_RT_MSGHDR
int32_t SystemNative_EnumerateGatewayAddressesForInterface(uint32_t interfaceIndex, GatewayAddressFound onGatewayFound)
{
    static struct in6_addr anyaddr = IN6ADDR_ANY_INIT;
    int routeDumpName[] = {CTL_NET, AF_ROUTE, 0, 0, NET_RT_DUMP, 0};

    size_t byteCount;

    if (sysctl(routeDumpName, 6, NULL, &byteCount, NULL, 0) != 0)
    {
        return -1;
    }

    uint8_t* buffer = malloc(byteCount);
    if (buffer == NULL)
    {
        errno = ENOMEM;
        return -1;
    }

    while (sysctl(routeDumpName, 6, buffer, &byteCount, NULL, 0) != 0)
    {
        buffer = realloc(buffer, byteCount);
        if (buffer == NULL)
        {
            errno = ENOMEM;
            return -1;
        }
    }

    struct rt_msghdr* hdr;
    for (size_t i = 0; i < byteCount; i += hdr->rtm_msglen)
    {
        hdr = (struct rt_msghdr*)&buffer[i];
        int flags = hdr->rtm_flags;
        int isGateway = flags & RTF_GATEWAY;
        int gatewayPresent = hdr->rtm_addrs & RTA_GATEWAY;

        if (isGateway && gatewayPresent && ((int)interfaceIndex == -1 || interfaceIndex == hdr->rtm_index))
        {
            IpAddressInfo iai;
            struct sockaddr_storage* sock = (struct sockaddr_storage*)(hdr + 1);
            memset(&iai, 0, sizeof(IpAddressInfo));
            iai.InterfaceIndex = hdr->rtm_index;

            if (sock->ss_family == AF_INET)
            {
                iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
                struct sockaddr_in* sain = (struct sockaddr_in*)sock;
                if (sain->sin_addr.s_addr != 0)
                {
                    // filter out normal routes.
                    continue;
                }

                sain = sain + 1; // Skip over the first sockaddr, the destination address. The second is the gateway.
                memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr));
            }
            else if (sock->ss_family == AF_INET6)
            {
                struct sockaddr_in6* sain6 = (struct sockaddr_in6*)sock;
                iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS;
                if (memcmp(&anyaddr, &sain6->sin6_addr, sizeof(sain6->sin6_addr)) != 0)
                {
                    // filter out normal routes.
                    continue;
                }

                sain6 = sain6 + 1; // Skip over the first sockaddr, the destination address. The second is the gateway.
                if ((sain6->sin6_addr.__u6_addr.__u6_addr16[0] & htons(0xfe80)) == htons(0xfe80))
                {
                    // clear embedded if index.
                    sain6->sin6_addr.__u6_addr.__u6_addr16[1] = 0;
                }

                memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain6->sin6_addr, sizeof(sain6->sin6_addr));
            }
            else
            {
                // Ignore other address families.
                continue;
            }
            onGatewayFound(&iai);
        }
    }

    free(buffer);
    return 0;
}
#endif // HAVE_RT_MSGHDR


text:
package com.blog.start.jpa.service;

import com.blog.start.exception.RssException;
import com.blog.start.jpa.entity.Item;
import com.blog.start.rss.ObjectFactory;
import com.blog.start.rss.TRss;
import com.blog.start.rss.TRssChannel;
import com.blog.start.rss.TRssItem;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by MahfuzCSE'11 on 14-Oct-16.
 */
@Service
public class RssService {

    public List<Item> getItems(File file) throws RssException {
        return getItems(new StreamSource(file));
    }

    public List<Item> getItems(String url) throws RssException {
        return getItems(new StreamSource(url));
    }

    private List<Item> getItems(Source source) throws RssException {
        ArrayList<Item> list = new ArrayList<Item>();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            JAXBElement<TRss> jaxbElement = unmarshaller.unmarshal(source, TRss.class);
            TRss rss = jaxbElement.getValue();

            List<TRssChannel> channels = rss.getChannel();
            for (TRssChannel channel : channels) {
                List<TRssItem> items = channel.getItem();
                for (TRssItem rssItem : items) {
                    Item item = new Item();
                    item.setTitle(rssItem.getTitle());
                    item.setDescription(rssItem.getDescription());
                    item.setLink(rssItem.getLink());
                    Date pubDate = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH).parse(rssItem.getPubDate());
                    item.setPublishedDate(pubDate);
                    list.add(item);
                }
            }
        } catch (JAXBException e) {
            throw new RssException(e);
        } catch (ParseException e) {
            throw new RssException(e);
        }
        return list;
    }
}


text:
require "benchmark"

class Foo
  def ping
  end
end

block = Proc.new {
  ping
}

object = Foo.new

TESTS = 100_000
Benchmark.bmbm do |results|
  results.report("noop:") { TESTS.times { } }
  results.report("instance_eval:") { TESTS.times { object.instance_eval(&block) } }
  results.report("instance_exec:") { TESTS.times { object.instance_exec(&block) } }
end


text:
.gameContext {
  flex: 1;
  display: flex;
  flex-direction: column;
}


text:
import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { NgForm } from '@angular/forms';
import * as firebase from 'firebase';
import * as _ from 'underscore/underscore';
import {AuthProvider} from "../../providers/auth/auth";
import { LoginPage } from '../login/login';
import {FirebaseProvider} from "../../providers/firebase/firebase";

@IonicPage()
@Component({
    selector: 'points-page',
    templateUrl: 'points.html'
})

export class PointsPage {
    @ViewChild('commentText') commentText;
    name: any;
    address: any;
    number: any;
    description: any;
    key: any;
    public comments: any[];
    image: any;
    date: any;
    showAdd: any;
    user: any;

    constructor(public navCtrl: NavController, public navParams: NavParams, public loading: LoadingController, private toast: ToastController, public authData: AuthProvider, public database: FirebaseProvider) {

        this.name = this.navParams.get('name');
        this.address = this.navParams.get('address');
        this.number = this.navParams.get('number');
        this.description = this.navParams.get('description');
        this.key = String(this.navParams.get('key'));
        if (this.navParams.get('key') > 163) {
            this.image =  "../../assets/images/uhLogo.jpg";
        } else {
            if (!isNaN(this.navParams.get('key'))) {
                this.image = "https://manoanow.org/app/map/images/" + this.key + ".png";
            } else {
                this.image = "../../assets/images/uhLogo.jpg";
            }
        }
        this.date = new Date();
        this.showAdd = false;
        this.user = firebase.auth().currentUser;
        }

    ionViewDidLoad() {
      this.showComments();
    }

    /***************** PAGE LOAD FUNCTION ****************/

    /**
     *  Loads all of the user comments for the particular point
     *  @param none
     *  @return none
     */

    showComments() {
        var item = [];
        this.database.masterData.child(this.key).child("comments").once("value")
            .then((dataPoints) => {
                item = dataPoints.val();
                this.comments = _.toArray(item);
        });

    }

    /***************** COMMENTS FUNCTION ****************/

    /**
     *  Takes data from the leave comments form and places it into the master data firebase db
     *  @param {Object} - NgForm data
     *  @return none
     */
    addComments(formData: NgForm){
        if(this.user) {
            this.date = new Date().toString();
            Object.assign(formData.value, {'dateTime': this.date});
            Object.assign(formData.value, {'userName': this.user.displayName});
            let comments = this.database.masterData.child(this.key);
            comments.child('/comments').push(formData.value);
            this.showComments();
            this.toggleAddButton();
            this.commentText.value = "";
        }
    }

    /***************** TOGGLE COMMENTS FUNCTION ****************/

    /**
     *  Allows the user to hide the comments
     *  @param none
     *  @return none
     */
    toggleAddButton() {
        this.showAdd = !this.showAdd;
    }

    /***************** GET CURRENT DATE/TIME FUNCTION ****************/

    /**
     *  When a user submits a comments, this function gets the current data so it can be associated with the
     *  @param none
     *  @return {Date Object} - The current date
     */
    getDate(comment: any) {
        return new Date(comment.dateTime).getMonth() + 1 + '/' + new Date(comment.dateTime).getDate() + '/' + new Date(comment.dateTime).getFullYear()
    }

    /***************** DIRECT TO LOGIN FUNCTION ****************/

    /**
     *  A user can only comment if they are logged in, this directs a non-logged in user to the login page
     *  @param none
     *  @return none
     */
    logIn(){
        this.navCtrl.push(LoginPage);
    }

}


text:
__author__ = 'Yan'

import pandas
import sklearn.metrics
import statistics
import numpy as np
import matplotlib.pylab as plt
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier

# bug fix for display formats to avoid run time errors
pandas.set_option('display.float_format', lambda x:'%.2f'%x)

#load the data
data = pandas.read_csv('..\separatedData.csv')

# convert to numeric format
data["breastCancer100th"] = pandas.to_numeric(data["breastCancer100th"], errors='coerce')
data["meanSugarPerson"]   = pandas.to_numeric(data["meanSugarPerson"], errors='coerce')
data["meanFoodPerson"]   = pandas.to_numeric(data["meanFoodPerson"], errors='coerce')
data["meanCholesterol"]   = pandas.to_numeric(data["meanCholesterol"], errors='coerce')

# listwise deletion of missing values
sub1 = data[['breastCancer100th', 'meanFoodPerson', 'meanCholesterol', 'meanSugarPerson']].dropna()

# Create the conditions to a new variable named incidence_cancer that will categorize the meanSugarPerson answers
meanIncidence = statistics.mean(sub1['breastCancer100th'])

def incidence_cancer (row):
    if row['breastCancer100th'] <= meanIncidence : return 0   # Incidence of breast cancer is below the
                                                              # average of the incidence of all countries.
    if row['breastCancer100th'] > meanIncidence  : return 1   # Incidence of breast cancer is above the average
                                                              # of the incidence of all countries.

# Add the new variable sugar_consumption to subData
sub1['incidence_cancer'] = sub1.apply (lambda row: incidence_cancer (row),axis=1)

#Split into training and testing sets
predictors = sub1[[ 'meanSugarPerson', 'meanFoodPerson', 'meanCholesterol']]
targets = sub1['incidence_cancer']

#Train = 60%, Test = 40%
pred_train, pred_test, tar_train, tar_test = train_test_split(predictors, targets, test_size=.4)

#Build model on training data
classifier=RandomForestClassifier(n_estimators=25)
classifier=classifier.fit(pred_train,tar_train)

predictions=classifier.predict(pred_test)

confusion_matrix = sklearn.metrics.confusion_matrix(tar_test,predictions)
accuracy_score = sklearn.metrics.accuracy_score(tar_test, predictions)

print (confusion_matrix)
print (accuracy_score)

# fit an Extra Trees model to the data
model = ExtraTreesClassifier()
model.fit(pred_train,tar_train)
# display the relative importance of each attribute
print(model.feature_importances_)

"""
Running a different number of trees and see the effect
 of that on the accuracy of the prediction
"""

trees=range(25)
accuracy=np.zeros(25)

for idx in range(len(trees)):
    classifier=RandomForestClassifier(n_estimators=idx + 1)
    classifier=classifier.fit(pred_train,tar_train)
    predictions=classifier.predict(pred_test)
    accuracy[idx]=sklearn.metrics.accuracy_score(tar_test, predictions)

plt.cla()
plt.plot(trees, accuracy)

print(accuracy)
print(statistics.mean(accuracy))


text:
package br.com.battista.arcadia.caller.controller.advice;

import static br.com.battista.arcadia.caller.builder.ResponseEntityBuilder.buildResponseErro;

import java.util.Map;

import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import br.com.battista.arcadia.caller.exception.AuthenticationException;
import br.com.battista.arcadia.caller.exception.EntityAlreadyExistsException;
import br.com.battista.arcadia.caller.exception.EntityNotFoundException;
import br.com.battista.arcadia.caller.exception.RepositoryException;
import br.com.battista.arcadia.caller.exception.ValidatorException;
import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
public class AppControllerAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleUncaughtException(Exception e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, Object>> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(EntityAlreadyExistsException.class)
    public ResponseEntity<Map<String, Object>> handleHttpMessageNotReadableException(EntityAlreadyExistsException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.CONFLICT);
    }

    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity<Map<String, Object>> handleHttpMessageNotReadableException(EntityNotFoundException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<Map<String, Object>> handleAuthenticationException(AuthenticationException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(RepositoryException.class)
    public ResponseEntity<Map<String, Object>> handleRepositoryException(RepositoryException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Map<String, Object>> handleConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Map<String, Object>> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ValidatorException.class)
    public ResponseEntity<Map<String, Object>> handleValidatorException(ValidatorException e) {
        log.error(e.getLocalizedMessage(), e);
        return buildResponseErro(e, e.builderMessagesValidator(), HttpStatus.BAD_REQUEST);
    }

}


text:
package com.google.schemaorg;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import java.util.List;
import javax.annotation.Nullable;

/** Superclass to be extended by any concrete {@code ValueType}. */
abstract class BaseTypeImpl implements ValueType {
  protected final ImmutableListMultimap<String, ValueType> properties;

  abstract static class BuilderImpl<T extends ValueType.Builder> implements ValueType.Builder {
    protected final Multimap<String, ValueType> properties;

    BuilderImpl() {
      properties = LinkedListMultimap.create();
    }

    protected T addPropertyValue(String name, @Nullable ValueType value) {
      Preconditions.checkNotNull(name, "property name is null");
      properties.put(name, value == null ? NullValue.VALUE : value);
      return (T) this;
    }

    protected T setSingleValueProperty(String name, @Nullable ValueType value) {
      Preconditions.checkNotNull(name, "property name is null");
      properties.removeAll(name);
      properties.put(name, value == null ? NullValue.VALUE : value);
      return (T) this;
    }
  }

  BaseTypeImpl(Multimap<String, ValueType> properties) {
    this.properties = ImmutableListMultimap.copyOf(properties);
  }

  protected boolean containsProperty(String name) {
    return properties.containsKey(name);
  }

  @Nullable
  protected ValueType getSingleValueProperty(String name) throws SchemaOrgException {
    List<ValueType> list = getPropertyList(name);
    if (list.size() == 0) {
      return null;
    }
    if (list.size() > 1) {
      throw new SchemaOrgException(
          String.format("Multiple value found in the single-value property %s", name));
    }
    ValueType res = list.get(0);
    return res == NullValue.VALUE ? null : res;
  }

  protected ImmutableList<ValueType> getPropertyList(String property) {
    return properties.get(property);
  }

  ImmutableListMultimap<String, ValueType> getAllProperties() {
    return properties;
  }
}


text:
public class Rational {

    private int num;
    private int denom;

    public Rational() {
	this.num = 1;
	this.denom = 1;
    }

    public Rational(int num, int denom) {
	this.num = num;
	this.denom = denom;
    }

}


text:
package run.bach.toolbox;

import java.net.URI;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import run.bach.Bach;
import run.bach.ExternalAssetsRepository;
import run.bach.ToolCall;
import run.bach.ToolOperator;
import run.bach.internal.PathSupport;

public record InstallTool(String name) implements ToolOperator {
  public InstallTool() {
    this("install");
  }

  @Override
  public void run(Operation operation) {
    var bach = operation.bach();
    var cli = new CLI().withParsingCommandLineArguments(operation.arguments());
    if (cli.help()) {
      bach.info("Usage: %s [--from <repository>] <tools...>".formatted(name()));
      return;
    }
    var index = ExternalAssetsRepository.Info.EXTERNAL_TOOL_DIRECTORY;
    var from = cli.from();
    var names = cli.names();

    bach.debug("Install tool directory info file from repository: %s".formatted(from.home()));
    if (names.isEmpty() || names.contains("?")) {
      var walker = ExternalAssetsRepository.walk(bach.browser().client(), from);
      var tools = walker.map().get(index);
      if (tools == null || tools.isEmpty()) {
        bach.info("No tool directory index files found in " + from);
        return;
      }
      var joiner = new StringJoiner("\n");
      for (var tool : tools) {
        var command = ToolCall.of("bach");
        command = command.with(name()); // "install"
        if (cli.__from().isPresent()) command = command.with("--from", cli.__from().get());
        command = command.with(index.name(tool));
        joiner.add(command.toCommandLine(" "));
      }
      var size = tools.size();
      joiner.add("    %d tool directory info file%s".formatted(size, size == 1 ? "" : "s"));
      bach.info(joiner.toString());
      return;
    }

    for (var name : cli.names()) {
      var source = from.source(index, name);
      var target = bach.paths().externalTools().resolve(name + index.extension());
      acquireToolDirectory(bach, source, target);
      explodeToolDirectory(bach, target);
    }
  }

  void acquireToolDirectory(Bach bach, String source, Path target) {
    bach.run(LoadTool.class, "file", source, target.toString());
  }

  void explodeToolDirectory(Bach bach, Path file) {
    var properties = PathSupport.properties(file);
    var name = file.getFileName().toString();
    var extension = ExternalAssetsRepository.Info.EXTERNAL_TOOL_DIRECTORY.extension();
    var parent = file.resolveSibling(name.substring(0, name.length() - extension.length()));
    for (var key : properties.stringPropertyNames()) {
      if (key.startsWith("@")) continue;
      var value = properties.getProperty(key);
      if (!value.startsWith("http")) {
        bach.debug("Unsupported protocol: " + value);
        continue;
      }
      var source = URI.create(value);
      var target = parent.resolve(key);
      bach.run(LoadTool.class, "file", source.toString(), target.toString());
    }
  }

  record CLI(Optional<Boolean> __help, Optional<String> __from, List<String> names) {
    CLI() {
      this(Optional.empty(), Optional.empty(), List.of());
    }

    boolean help() {
      return __help.orElse(false);
    }

    ExternalAssetsRepository from() {
      return __from.map(ExternalAssetsRepository::of).orElse(ExternalAssetsRepository.DEFAULT);
    }

    CLI withParsingCommandLineArguments(List<String> args) {
      var arguments = new ArrayDeque<>(args);
      var help = __help.orElse(null);
      var from = __from.orElse(null);
      var names = new ArrayList<>(names());
      while (!arguments.isEmpty()) {
        var argument = arguments.removeFirst();
        /* parse flags */ {
          if (run.bach.CLI.HELP_FLAGS.contains(argument)) {
            help = Boolean.TRUE;
            continue;
          }
        }
        /* parse key-value pairs */ {
          int sep = argument.indexOf('=');
          var key = sep == -1 ? argument : argument.substring(0, sep);
          if (key.equals("--from")) {
            from = sep == -1 ? arguments.removeFirst() : argument.substring(sep + 1);
            continue;
          }
        }
        // restore argument because first unhandled option marks the beginning of the tool names
        arguments.addFirst(argument);
        break;
      }
      // parse variadic elements from remaining arguments
      names.addAll(arguments);
      // compose from components
      return new CLI(Optional.ofNullable(help), Optional.ofNullable(from), List.copyOf(names));
    }
  }
}


text:
package org.kie.pmml.models.drools.tree.tests;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.assertj.core.api.Assertions;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.kie.api.pmml.PMML4Result;
import org.kie.pmml.evaluator.api.executor.PMMLRuntime;

@RunWith(Parameterized.class)
public class SampleMineTreeModelTest extends AbstractPMMLTreeTest {

    private static final String MODEL_NAME = "SampleMineTreeModel";
    private static final String TARGET_FIELD = "decision";
    private static PMMLRuntime pmmlRuntime;

    private double temperature;
    private double humidity;
    private String expectedResult;

    public SampleMineTreeModelTest(double temperature, double humidity, String expectedResult) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.expectedResult = expectedResult;
    }

    @BeforeClass
    public static void setupClass() {
        pmmlRuntime = getPMMLRuntime(MODEL_NAME);
    }

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {30.0, 10.0, "sunglasses"},
                {5.0, 70.0, "umbrella"},
                {10.0, 15.0, "nothing"}
        });
    }

    @Test
    public void testTree() {
        final Map<String, Object> inputData = new HashMap<>();
        inputData.put("temperature", temperature);
        inputData.put("humidity", humidity);
        PMML4Result pmml4Result = evaluate(pmmlRuntime, inputData, MODEL_NAME);

        Assertions.assertThat(pmml4Result.getResultVariables().get(TARGET_FIELD)).isNotNull();
        Assertions.assertThat(pmml4Result.getResultVariables().get(TARGET_FIELD)).isEqualTo(expectedResult);
    }
}


text: Energy Flexibility Interface (EFI)


text:
@font-face {
	font-family: 'Pixel Art';
	src: url('phatone.eot');
	src: local('☺'), url('phatone.woff') format('woff'), url('phatone.ttf') format('truetype'), url('phatone.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}


text:
package statvar

import (
	"context"

	pb "github.com/datacommonsorg/mixer/internal/proto"
	"github.com/datacommonsorg/mixer/internal/server/resource"
	"github.com/datacommonsorg/mixer/internal/store"
	"github.com/datacommonsorg/mixer/internal/store/bigtable"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
)

const (
	// SvgRoot is the root stat var group of the hierarchy. It's a virtual entity
	// that links to the top level category stat var groups.
	SvgRoot = "dc/g/Root"
)

// Note this function modifies validSVG inside.
func markValidSVG(
	svgResp *pb.StatVarGroups,
	svgID string,
	validSVG map[string]struct{},
) bool {
	// Already checked
	if _, ok := validSVG[svgID]; ok {
		return true
	}
	svChildren := svgResp.StatVarGroups[svgID].ChildStatVars
	svgChildren := svgResp.StatVarGroups[svgID].ChildStatVarGroups
	// If there are non-empty sv chldren, then this svg is valid
	if len(svChildren) > 0 {
		validSVG[svgID] = struct{}{}
		return true
	}
	// Recursively check child svg, if there is any valid svg child, then this
	// is valid too
	for _, svgChild := range svgChildren {
		if markValidSVG(svgResp, svgChild.Id, validSVG) {
			validSVG[svgID] = struct{}{}
			return true
		}
	}
	return false
}

// Filter StatVarGroups based on given stat vars. This does not modify the input
// data but create a filtered copy of it.
func filterSVG(in *pb.StatVarGroups, statVars []string) *pb.StatVarGroups {
	result := &pb.StatVarGroups{StatVarGroups: map[string]*pb.StatVarGroupNode{}}
	// Build set for all the given stat vars as valid stat vars.
	validSV := map[string]struct{}{}
	for _, sv := range statVars {
		validSV[sv] = struct{}{}
	}

	// Step 1: iterate over stat var group, and only keep stat var children with
	// valid stat vars.
	for svgID, svgData := range in.StatVarGroups {
		filteredChildSV := []*pb.StatVarGroupNode_ChildSV{}
		for _, childSV := range svgData.ChildStatVars {
			if _, ok := validSV[childSV.Id]; ok {
				filteredChildSV = append(filteredChildSV, childSV)
			}
		}
		result.StatVarGroups[svgID] = &pb.StatVarGroupNode{
			ChildStatVars:      filteredChildSV,
			ChildStatVarGroups: svgData.ChildStatVarGroups,
		}
	}
	// Step 2: recursively check if a stat var group is valid. A stat var group
	// is valid if it has any descendent stat var group with non-empty stat vars

	// All the svg with valid stat vars.
	validSVG := map[string]struct{}{}
	for svgID := range result.StatVarGroups {
		markValidSVG(result, svgID, validSVG)
	}

	// Step3: another iteration to only keep valid svg
	for svgID, svgData := range result.StatVarGroups {
		filteredChildren := []*pb.StatVarGroupNode_ChildSVG{}
		for _, c := range svgData.ChildStatVarGroups {
			if _, ok := validSVG[c.Id]; ok {
				filteredChildren = append(filteredChildren, c)
			}
		}
		result.StatVarGroups[svgID].ChildStatVarGroups = filteredChildren
		d := result.StatVarGroups[svgID]
		if len(d.ChildStatVars) == 0 && len(d.ChildStatVarGroups) == 0 {
			delete(result.StatVarGroups, svgID)
		}
	}
	return result
}

// GetStatVarGroup implements API for Mixer.GetStatVarGroup.
func GetStatVarGroup(
	ctx context.Context,
	in *pb.GetStatVarGroupRequest,
	store *store.Store,
	cache *resource.Cache,
) (*pb.StatVarGroups, error) {
	entities := in.GetEntities()
	var statVars []string
	// Only read entity stat vars when the entity is provided.
	// User can provide any arbitrary dcid, which might not be associated with
	// stat vars. In this case, an empty response is returned.
	if len(entities) > 0 {
		svUnionResp, err := GetEntityStatVarsUnionV1(
			ctx,
			&pb.GetEntityStatVarsUnionRequest{Dcids: entities},
			store,
		)
		if err != nil {
			return nil, err
		}
		statVars = svUnionResp.StatVars
	}

	var result *pb.StatVarGroups
	if cache == nil {
		// Read stat var group cache from the frequent import group table. It has
		// the latest and trustworthy stat var schemas and no need to merge with
		// other import groups.
		btDataList, err := bigtable.Read(
			ctx,
			store.BtGroup,
			bigtable.BtStatVarGroup,
			[][]string{{""}},
			func(jsonRaw []byte) (interface{}, error) {
				var svgResp pb.StatVarGroups
				if err := proto.Unmarshal(jsonRaw, &svgResp); err != nil {
					return nil, err
				}
				return &svgResp, nil
			},
		)
		if err != nil {
			return nil, err
		}
		found := false
		for _, btData := range btDataList {
			for _, row := range btData {
				svg, ok := row.Data.(*pb.StatVarGroups)
				if ok && svg.StatVarGroups != nil {
					result = svg
					found = true
					break
				}
			}
			if found {
				break
			}
		}
	} else {
		result = &pb.StatVarGroups{StatVarGroups: cache.RawSvg}
	}
	// Merge in the private import svg if exists
	if store.MemDb != nil && store.MemDb.GetSvg() != nil {
		for sv, data := range store.MemDb.GetSvg() {
			result.StatVarGroups[sv] = data
		}
		result.StatVarGroups[SvgRoot].ChildStatVarGroups = append(
			result.StatVarGroups[SvgRoot].ChildStatVarGroups,
			&pb.StatVarGroupNode_ChildSVG{
				Id:                store.MemDb.GetManifest().RootSvg,
				SpecializedEntity: store.MemDb.GetManifest().ImportName,
				DisplayName:       store.MemDb.GetManifest().ImportName,
			},
		)
	}
	if len(entities) > 0 {
		result = filterSVG(result, statVars)
	}
	return result, nil
}

// GetStatVarGroupNode implements API for Mixer.GetStatVarGroupNode.
func GetStatVarGroupNode(
	ctx context.Context,
	in *pb.GetStatVarGroupNodeRequest,
	store *store.Store,
	cache *resource.Cache,
) (*pb.StatVarGroupNode, error) {
	entities := in.GetEntities()
	svg := in.GetStatVarGroup()

	if svg == "" {
		return nil, status.Errorf(
			codes.InvalidArgument, "Missing required argument: stat_var_group")
	}

	result := &pb.StatVarGroupNode{}
	if r, ok := cache.RawSvg[svg]; ok {
		// Clone into result, otherwise the server cache is modified.
		result = proto.Clone(r).(*pb.StatVarGroupNode)
	}
	for _, item := range result.ChildStatVarGroups {
		item.DisplayName = cache.RawSvg[item.Id].AbsoluteName
		item.DescendentStatVarCount = cache.RawSvg[item.Id].DescendentStatVarCount
	}
	for _, item := range result.ChildStatVars {
		item.HasData = true
	}
	result.ParentStatVarGroups = cache.ParentSvg[svg]

	// Filter result based on entities
	if len(entities) > 0 {
		// Get the stat var and stat var group IDs to check if they are valid for
		// given entities.
		allIDs := []string{svg}
		for _, item := range result.ChildStatVarGroups {
			allIDs = append(allIDs, item.Id)
		}
		for _, item := range result.ChildStatVars {
			allIDs = append(allIDs, item.Id)
		}
		allIDs = append(allIDs, result.ParentStatVarGroups...)
		// Check if stat data exists for given entities
		statVarCount, err := Count(ctx, store, allIDs, entities)
		if err != nil {
			return nil, err
		}
		// Count for current node.
		result.DescendentStatVarCount = 0
		if existence, ok := statVarCount[svg]; ok && len(existence) > 0 {
			for _, count := range existence {
				// Use the largest count among all entities.
				if count > result.GetDescendentStatVarCount() {
					result.DescendentStatVarCount = count
				}
			}
		}
		// Filter child stat var groups
		for _, item := range result.ChildStatVarGroups {
			item.DescendentStatVarCount = 0
			if existence, ok := statVarCount[item.Id]; ok && len(existence) > 0 {
				for _, count := range existence {
					// Use the largest count among all entities
					if count > item.DescendentStatVarCount {
						item.DescendentStatVarCount = count
					}
				}
			}
		}
		// Filter child stat vars
		for _, item := range result.ChildStatVars {
			if existence, ok := statVarCount[item.Id]; !ok || len(existence) == 0 {
				item.HasData = false
			}
		}
	}
	return result, nil
}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  Copyright (C) 2014 ohmage

  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.
  -->

<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
    android:contentAuthority="org.ohmage.responses"
    android:accountType="org.ohmage.ACCOUNT"
    android:userVisible="true"
    android:supportsUploading="true"
    android:allowParallelSyncs="false"
    android:isAlwaysSyncable="true" />


text:
package poly.algebra

import poly.algebra.factory._
import poly.algebra.hkt._
import poly.algebra.specgroup._

/**
 * Represents a weak order endowed with a hashing function.
 *
 * @author Tongfei Chen
 * @since 0.3.3
 */
trait OrderedHashing[@sp(fdi) -X] extends Order[X] with Hashing[X] { self =>

  override def contramap[@sp(Int) Y](f: Y => X): OrderedHashing[Y] = new OrderedHashing[Y] {
    def cmp(x: Y, y: Y) = self.cmp(f(x), f(y))
    def hash(x: Y) = self.hash(f(x))
  }

}

object OrderedHashing extends ImplicitGetter[OrderedHashing] {

  implicit object ContravariantFunctor extends ContravariantFunctor[OrderedHashing] {
    def contramap[X, Y](mx: OrderedHashing[X])(f: Y => X) = mx contramap f
  }

}


text:
**********************************
sysbench
**********************************

Description
===========
kewpie's sysbench mode allows a user to run a specific iteration of a sysbench test (eg an oltp readonly run at concurrency = 16)

Requirements
============

The SYSBENCH command requires that the Drizzle library header be installed. Simply build Drizzle and do::

    $> sudo make install

This will install the right headers.

The SYSBENCH command also requires installation of the drizzle-sysbench program, which can be installed from source like so::

    $> bzr branch lp:~drizzle-developers/sysbench/trunk  drizzle-sysbench
    $> cd drizzle-sysbench
    $> ./autogen.sh && ./configure && make && sudo make install

Make sure sysbench is then in your path

sysbench / kewpie tests
=====================

A sysbench test defines a run for a particular concurrency.  There are suites for readonly and readwrite.
They are currently broken down this way as an experiment - we are open to other ways of organizing these tests::

    [test_info]
    comment = 16 threads

    [test_command]
    command = sysbench --max-time=240 --max-requests=0 --test=oltp --db-ps-mode=disable --drizzle-table-engine=innodb --oltp-read-only=on --oltp-table-size=1000000 --drizzle-mysql=on --drizzle-user=root --drizzle-db=test --drizzle-port=$MASTER_MYPORT --drizzle-host=localhost --db-driver=drizzle --num-threads=16

    [test_servers]
    servers = [[innodb.buffer-pool-size=256M innodb.log-file-size=64M innodb.log-buffer-size=8M innodb.thread-concurrency=0 innodb.additional-mem-pool-size=16M table-open-cache=4096 table-definition-cache=4096 mysql-protocol.max-connections=2048]]

Running tests
=========================

There are several different ways to run tests using :doc:`kewpie` 's sysbench mode.

It should be noted that unless :option:`--force` is used, the program will
stop execution upon encountering the first failing test.
:option:`--force` is recommended if you are running several tests - it will
allow you to view all successes and failures in one run.

Running individual tests
------------------------
If one only wants to run a few, specific tests, they may do so this way::

    ./kewpie --mode=sysbench [OPTIONS] test1 [test2 ... testN]

Running all tests within a suite
--------------------------------
Many of the tests supplied with Drizzle are organized into suites.

The tests within drizzle/tests/randgen_tests/main are considered the 'main' suite.
Other suites are also subdirectories of drizzle/tests/randgen_tests.

To run the tests in a specific suite::

    ./kewpie --mode=sysbench [OPTIONS] --suite=SUITENAME

Running specific tests within a suite
--------------------------------------
To run a specific set of tests within a suite::

    ./kewpie --mode=sysbench [OPTIONS] --suite=SUITENAME TEST1 [TEST2..TESTN]

Calling tests using <suitename>.<testname> currently does not work.
One must specify the test suite via the :option:`--suite` option.

Running all available tests
---------------------------
One would currently have to name all suites, but the majority of the working tests live in the main suite
Other suites utilize more exotic server combinations and we are currently tweaking them to better integrate with the
kewpie system.  The slave-plugin suite does currently have a good config file for setting up simple replication setups for testing.
To execute several suites' worth of tests::

    ./kewpie --mode=sysbench [OPTIONS] --suite=SUITE1, SUITE2, ...SUITEN

Interpreting test results
=========================
The output of the test runner is quite simple.  Every test should pass.
In the event of a test failure, please take the time to file a bug here:
*https://bugs.launchpad.net/drizzle*

During a run, the program will provide the user with:
  * test name (suite + name)
  * test status (pass/fail/skipped)
  * time spent executing each test

Example output::

    20110601-191706  ===============================================================
    20110601-191706  TEST NAME                                  [ RESULT ] TIME (ms)
    20110601-191706  ===============================================================
    20110601-191706  readonly.concurrency_16                    [ pass ]   240019
    20110601-191706  max_req_lat_ms: 21.44
    20110601-191706  rwreqps: 4208.2
    20110601-191706  min_req_lat_ms: 6.31
    20110601-191706  deadlocksps: 0.0
    20110601-191706  tps: 150.29
    20110601-191706  avg_req_lat_ms: 6.65
    20110601-191706  95p_req_lat_ms: 7.02
    20110601-191706  ===============================================================
    20110601-191706 INFO Test execution complete in 275 seconds
    20110601-191706 INFO Summary report:
    20110601-191706 INFO Executed 1/1 test cases, 100.00 percent
    20110601-191706 INFO STATUS: PASS, 1/1 test cases, 100.00 percent executed
    20110601-191706 INFO Spent 240 / 275 seconds on: TEST(s)
    20110601-191706 INFO Test execution complete
    20110601-191706 INFO Stopping all running servers...


text: Python on RaspberryPi and similar boards


text:
<?php

namespace Colibri\Query\Expr\Func;

use Colibri\Exception\BadCallMethodException;
use Colibri\Query\Expr\Func;

class Ifnull extends Func
{

    /**
     * Ifnull constructor.
     * MySQL Function IFNULL
     *
     * @param array $parameters
     *
     * @throws BadCallMethodException
     */
    public function __construct(...$parameters)
    {
        parent::__construct('IFNULL', $parameters);
    }

}


text:
# AWS SDK for Rust
![aws-sdk-rust](https://img.shields.io/crates/v/aws-sdk-rust.svg) [![Crates.io](https://img.shields.io/crates/d/aws-sdk-rust.svg)]() [![Crates.io](https://img.shields.io/crates/l/aws-sdk-rust.svg)]()

[Documentation](https://lambdastackio.github.io/aws-sdk-rust/aws_sdk_rust/aws/index.html)

AWS SDK with initial emphasis on S3. Supports both V2 and V4 authentication signatures. Allows for custom app config, environment variables, standard /.aws/credentials and future Iam credentials. No environmental assumptions or opinions are made on how your access to AWS should be handled.

## JSON and Examples
See below...

## S3
The initial access is for solid AWS S3 support. The SDK is built to allow non-aws environments that support an S3 API interface such as Ceph and other object stores to accessible from Rust.

## Proxy
In many corporate environments the use of proxies are mandatory. Proxies are usually handled by setting the following environment variables:
```
http_proxy=<whatever your proxy url>:<whatever port if any>
https_proxy=<whatever your proxy url>:<whatever port if any>
no_proxy=<whatever IPs, domains, hosts, etc that should not go through a proxy (separate by commas)>
```

You can also pass in the proxy settings via Url to the S3Client or pass in `None`. This will allow you to use your own config file if desired so that you can read in the proxy settings and pass them S3Client.

## Configuring Credentials

Before using the SDK, ensure that you've configured credentials. The best
way to configure credentials on a development machine is to use the
`~/.aws/credentials` file, which might look like:

```
[default]
aws_access_key_id = <whatever access_key_id>
aws_secret_access_key = <whatever secret_access_key>
```

You can learn more about the credentials file from this
[blog post](http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs).

Alternatively, you can set the following environment variables:

```
AWS_ACCESS_KEY_ID=<whatever access_key_id>
AWS_SECRET_ACCESS_KEY=<whatever secret_access_key>
```

## Using the Rust SDK

To use a service in the SDK, create a service variable by calling the `S3Client::new(...)`
function. Once you have a service client, you can call API operations which each
return response data and a possible error.

## Simple Sample
To list buckets from S3, you could run:

```rust
// NOTE: See the src/main.rs for more examples...

extern crate aws_sdk_rust;
extern crate url;
extern crate hyper;

use aws_sdk_rust::aws::common::credentials::DefaultCredentialsProvider;
use aws_sdk_rust::aws::common::region::Region;
use aws_sdk_rust::aws::s3::endpoint::Endpoint;
use aws_sdk_rust::aws::s3::s3client::S3Client;

fn main() {
    // DefaultCredentialsProvider will end up cycling through the credentials provider list in
    // the following order:
    // 1. Environment - Checks the envrionment variables:
    //      AWS_ACCESS_KEY_ID
    //      AWS_SECRET_ACCESS_KEY
    //      AWS_SESSION_TOKEN
    // 2. Parameters passed in via ParametersProvider (see example below)
    // 3. Profile provider - ~/.aws/credentials
    // 4. IAM Provider

    // Option to initialize the ParametersProvider
    /* Example of using parameters for passing the credentials.
    use aws_sdk_rust::aws::common::credentials::{DefaultCredentialsProvider, ParametersProvider};

    let param_provider: Option<ParametersProvider>;
    param_provider = Some(
        ParametersProvider::with_params(
            "<whatever your access_key_id>",
            "<whatever your secret_access_key>",
            None).unwrap()
    );

    let provider = DefaultCredentialsProvider::new(param_provider).unwrap();
    */

    // Allow the defaults w/o ParametersProvider - pass in 'None' in ::new(None)
    let provider = DefaultCredentialsProvider::new(None).unwrap();

    // V4 is the default signature for AWS. However, other systems also use V2.
    let endpoint = Endpoint::new(Region::UsEast1, Signature::V4, None, None, None);
    let client = S3Client::new(provider, endpoint);

    match client.list_buckets() {
      Ok(output) => {
        println!("{:#?}", output);
      }
      Err(error) => {
        println!("Error: {:#?}", error);
      }
    }
}
```

## Robust Sample
Look at /examples/s3.rs. This example is used for testing all features and it goes through the process of
creating a bucket loading objects (including multipart uploads), versioning etc and ends with removing
the bucket it created. However, the bucket removal may throw an error because you may have versions of
objects. If that is the case then simply login to the S3 Console and remove them. We may also provide a
delete_all to clear out versions if the bucket is versioned.

## Inspiration
If you need access to other AWS systems instead of S3 then take a look at rusoto (https://github.com/rusoto/rusoto). Initial inspiration comes from there, Python Boto3 and aws-sdk-go.

## Library Development
### Paths
Structure is broken down into the following paths:

common

errors

s3

### XML
AWS S3 uses XML for transmitting and receiving (headers too). At this time there are no good implementations of
XML Serialization (serde works for Deserialization) so each XML construct for sending and receiving from S3
had to be defined with a parser/writer (project rusoto did a lot of the heavy lifting in this area).

Other AWS Services primarily use JSON and De/Serialization is possible for those service.

### JSON
The library now supports JSON for almost all structs. There are a few structs that use [u8] slices that are not
easily serialized or deserialized so those few structs will support one or the other (serialize/deserialize)
and the documentation notes it.


text:
module AliyunOpenSearch
  VERSION = "0.6.0"
end