text:
package com.armandgray.taap.detail.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

import com.armandgray.taap.R;
import com.armandgray.taap.detail.DrillDetailActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowAlertDialog;
import org.robolectric.shadows.ShadowDialog;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.DialogFragment;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.robolectric.Shadows.shadowOf;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class TimerDialogTest {

    private ActivityController<DrillDetailActivity> activityController;
    private DrillDetailActivity activity;
    private TimerDialog dialog;

    @Before
    public void setUp() {
//        Intent intent = new Intent(RuntimeEnvironment.application, DrillDetailActivity.class);
//        intent.putExtra(SELECTED_DRILL, new Drill("Beat-the-Pro (Mid-Range)",
//                R.drawable.ic_fitness_center_white_24dp,
//                Drill.UserPreferenceCategory.SHOOTING_ONLY));
//        activityController = Robolectric.buildActivity(DrillDetailActivity.class).newIntent(intent);
//        activity = activityController.createBehavior().start().resume().visible().get();
//        dialog = new TimerDialog();
//        dialog.show(activity.getSupportFragmentManager(), DIALOG);
    }

    @Test @Ignore
    public void canTimerDialog() {
        assertNotNull(new TimerDialog());
    }

    @Test @Ignore
    public void canCreateTimerDialog_TestOnCreateDialog() {
        Bundle savedInstanceState = new Bundle();
        assertNotNull(dialog.onCreateDialog(savedInstanceState));
    }

    @Test @Ignore
    public void doesImplementDialogFragment() {
        DialogFragment dialogFragment = dialog;
        assertNotNull(dialogFragment);
    }

    @Test @Ignore
    public void existsLayout_TimerDialogLayout() {
        CoordinatorLayout TimerDialogLayout = (CoordinatorLayout) View
                .inflate(activity, R.layout.timer_dialog_layout, null);
        assertNotNull(TimerDialogLayout);
    }

    @Test @Ignore
    public void existsView_Chronometer_TimerDialogLayout() {
        CoordinatorLayout TimerDialogLayout = (CoordinatorLayout) View
                .inflate(activity, R.layout.timer_dialog_layout, null);
        assertNotNull(TimerDialogLayout.findViewById(R.id.chronometer));
    }

    @Test @Ignore
    public void existsView_Fab_TimerDialogLayout() {
        CoordinatorLayout TimerDialogLayout = (CoordinatorLayout) View
                .inflate(activity, R.layout.timer_dialog_layout, null);
        assertNotNull(TimerDialogLayout.findViewById(R.id.fab));
    }

    @Test @Ignore
    public void doesFillEntireScreen_DialogGetWindow() {
        Window window = dialog.getDialog().getWindow();

        // TODO add test for window layout params & background
        assertNotNull(window);
        assertNotNull(window.getAttributes());
    }

    @Test @Ignore
    public void doesHaveCustomView_TestOnCreateDialog() {
        Window window = dialog.getDialog().getWindow();

        assertNotNull(window);
        assertNotNull(window.findViewById(R.id.timerDialogContainer));
    }

    @Test @Ignore
    public void doesStartTimer_TestOnCreateDialog() {
        Bundle savedInstanceState = new Bundle();
        AlertDialog resultDialog = (AlertDialog) dialog.onCreateDialog(savedInstanceState);
        ShadowAlertDialog shadowDialog = shadowOf(resultDialog);

        // TODO add test for chronometer started
    }

    @Test @Ignore
    public void canClickFabToDismissDialog() throws Exception {
        Dialog dialog = ShadowDialog.getLatestDialog();
        assertNotNull(dialog);
        assertTrue(dialog.isShowing());

        FloatingActionButton fab = (FloatingActionButton) dialog.findViewById(R.id.fab);
        assertNotNull(fab);
        fab.performClick();

        assertFalse(dialog.isShowing());
    }

    @After
    public void tearDown() {
//        dialog.dismiss();
//        activity.getContentResolver().delete(CONTENT_URI_DELETE_ALL_DATA, null, null);
//        activity.finish();
//        activityController.pause().stop().destroy();
//        activity = null;
//        dialog = null;
    }

}


text:
Libnotify and OS X Notification output for [Midje][midje]

[midje]: http://github.com/marick/midje

## Installation

Add the following to your `:dev` `:dependencies` in `project.clj`:

[![Clojars Project](http://clojars.org/midje-notifier/latest-version.svg)](http://clojars.org/midje-notifier)

In the REPL, prior to calling `midje.repl/autotest`, run the following

```
user=> (use 'midje.notifier)
user=> (notify-me)
```

You can then work using the standard Midje workflow.

Midje-notifier currently requires that you have either the `notify-send` binary
on Linux or `terminal-notifier` on OS X somewhere in your PATH. The former comes
standard with libnotify, and the latter can be installed [here][tn].

[tn]: https://github.com/alloy/terminal-notifier

## License

Copyright © 2018 Griffin Smith

Distributed under the MIT License

redpajama_set_name: RedPajamaGithub


text:
. /vagrant/scripts/node.sh

# Install bower
echo "Installing bower"
npm install -g bower

echo '{ "allow_root": true }' > /root/.bowerrc

echo "Bower installed"

#for themedir in /var/www/html/themes/*
#do
#	if [ -r "$themedir/bower.json" ]
#	then
#		bower install --allow-root --config.cwd=$themedir
#	fi
#done


text:
for file in HoaxImages/*
do
    python ela.py $file
done


text:
var config = require('../config/config');
var passport = require('passport');
var EyeemStrategy = require('passport-eyeem').Strategy;
var setup = require('./setup');

// analog of persistent storage
var users = {};

module.exports = function setupPassport (app) {
	setup(app);

	passport.serializeUser(function (user, done) {
		users[user.userId] = user;
		done(null, user.userId);
	});

	passport.deserializeUser(function (id, done) {
		var user = users[id];
		done(null, user);
	});
	passport.use(new EyeemStrategy({
			clientID: config.auth.clientId,
			clientSecret: config.auth.clientSecret,
			callbackURL: config.auth.authCallbackUrl
		},
		function (accessToken, refreshToken, profile, done) {
			console.log('Access token', accessToken);
			profile.token = token;
			return done(null, profile);
		}
	));
};


text:
package org.opencb.opencga.catalog.managers;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.opencb.commons.datastore.core.Event;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.utils.ListUtils;
import org.opencb.opencga.catalog.audit.AuditManager;
import org.opencb.opencga.catalog.audit.AuditRecord;
import org.opencb.opencga.catalog.auth.authorization.AuthorizationManager;
import org.opencb.opencga.catalog.db.DBAdaptorFactory;
import org.opencb.opencga.catalog.db.api.DBIterator;
import org.opencb.opencga.catalog.db.api.InterpretationDBAdaptor;
import org.opencb.opencga.catalog.exceptions.CatalogAuthorizationException;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.models.InternalGetDataResult;
import org.opencb.opencga.catalog.utils.ParamUtils;
import org.opencb.opencga.catalog.utils.UuidUtils;
import org.opencb.opencga.core.common.TimeUtils;
import org.opencb.opencga.core.config.Configuration;
import org.opencb.opencga.core.models.clinical.*;
import org.opencb.opencga.core.models.common.Enums;
import org.opencb.opencga.core.models.study.Study;
import org.opencb.opencga.core.response.OpenCGAResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.*;
import java.util.function.Function;

public class InterpretationManager extends ResourceManager<Interpretation> {

    protected static Logger logger = LoggerFactory.getLogger(InterpretationManager.class);

    private UserManager userManager;
    private StudyManager studyManager;

    public static final QueryOptions INCLUDE_INTERPRETATION_IDS = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
            InterpretationDBAdaptor.QueryParams.ID.key(), InterpretationDBAdaptor.QueryParams.UID.key(),
            InterpretationDBAdaptor.QueryParams.UUID.key(), InterpretationDBAdaptor.QueryParams.VERSION.key()));

    public InterpretationManager(AuthorizationManager authorizationManager, AuditManager auditManager, CatalogManager catalogManager,
                                 DBAdaptorFactory catalogDBAdaptorFactory, Configuration configuration) {
        super(authorizationManager, auditManager, catalogManager, catalogDBAdaptorFactory, configuration);

        this.userManager = catalogManager.getUserManager();
        this.studyManager = catalogManager.getStudyManager();
    }

    @Override
    Enums.Resource getEntity() {
        return Enums.Resource.INTERPRETATION;
    }

    @Override
    OpenCGAResult<Interpretation> internalGet(long studyUid, String entry, @Nullable Query query, QueryOptions options, String user)
            throws CatalogException {
        ParamUtils.checkIsSingleID(entry);
        Query queryCopy = query == null ? new Query() : new Query(query);
        queryCopy.put(InterpretationDBAdaptor.QueryParams.STUDY_UID.key(), studyUid);

        if (UuidUtils.isOpenCgaUuid(entry)) {
            queryCopy.put(InterpretationDBAdaptor.QueryParams.UUID.key(), entry);
        } else {
            queryCopy.put(InterpretationDBAdaptor.QueryParams.ID.key(), entry);
        }

        QueryOptions queryOptions = new QueryOptions(ParamUtils.defaultObject(options, QueryOptions::new));

//        QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
//                InterpretationDBAdaptor.QueryParams.UUID.key(), InterpretationDBAdaptor.QueryParams.CLINICAL_ANALYSIS.key(),
//                InterpretationDBAdaptor.QueryParams.UID.key(), InterpretationDBAdaptor.QueryParams.STUDY_UID.key(),
//                InterpretationDBAdaptor.QueryParams.ID.key(), InterpretationDBAdaptor.QueryParams.STATUS.key()));
        OpenCGAResult<Interpretation> interpretationDataResult = interpretationDBAdaptor.get(studyUid, queryCopy, queryOptions, user);
        if (interpretationDataResult.getNumResults() == 0) {
            interpretationDataResult = interpretationDBAdaptor.get(queryCopy, queryOptions);
            if (interpretationDataResult.getNumResults() == 0) {
                throw new CatalogException("Interpretation " + entry + " not found");
            } else {
                throw new CatalogAuthorizationException("Permission denied. " + user + " is not allowed to see the interpretation "
                        + entry);
            }
        } else if (interpretationDataResult.getNumResults() > 1) {
            throw new CatalogException("More than one interpretation found based on " + entry);
        } else {
            // We perform this query to check permissions because interpretations doesn't have ACLs
            try {
                catalogManager.getClinicalAnalysisManager().internalGet(studyUid,
                        interpretationDataResult.first().getClinicalAnalysisId(),
                        ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, user);
            } catch (CatalogException e) {
                throw new CatalogAuthorizationException("Permission denied. " + user + " is not allowed to see the interpretation "
                        + entry);
            }

            return interpretationDataResult;
        }
    }

    @Override
    InternalGetDataResult<Interpretation> internalGet(long studyUid, List<String> entryList, @Nullable Query query, QueryOptions options,
                                                      String user, boolean ignoreException) throws CatalogException {
        if (ListUtils.isEmpty(entryList)) {
            throw new CatalogException("Missing interpretation entries.");
        }
        List<String> uniqueList = ListUtils.unique(entryList);

        QueryOptions queryOptions = new QueryOptions(ParamUtils.defaultObject(options, QueryOptions::new));
        Query queryCopy = query == null ? new Query() : new Query(query);
        queryCopy.put(InterpretationDBAdaptor.QueryParams.STUDY_UID.key(), studyUid);

        Function<Interpretation, String> interpretationStringFunction = Interpretation::getId;
        InterpretationDBAdaptor.QueryParams idQueryParam = null;
        for (String entry : uniqueList) {
            InterpretationDBAdaptor.QueryParams param = InterpretationDBAdaptor.QueryParams.ID;
            if (UuidUtils.isOpenCgaUuid(entry)) {
                param = InterpretationDBAdaptor.QueryParams.UUID;
                interpretationStringFunction = Interpretation::getUuid;
            }
            if (idQueryParam == null) {
                idQueryParam = param;
            }
            if (idQueryParam != param) {
                throw new CatalogException("Found uuids and ids in the same query. Please, choose one or do two different queries.");
            }
        }
        queryCopy.put(idQueryParam.key(), uniqueList);

        // Ensure the field by which we are querying for will be kept in the results
        queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key());

        OpenCGAResult<Interpretation> interpretationDataResult = interpretationDBAdaptor.get(studyUid, queryCopy, queryOptions, user);

        if (interpretationDataResult.getNumResults() != uniqueList.size() && !ignoreException) {
            throw CatalogException.notFound("interpretations",
                    getMissingFields(uniqueList, interpretationDataResult.getResults(), interpretationStringFunction));
        }

        ArrayList<Interpretation> interpretationList = new ArrayList<>(interpretationDataResult.getResults());
        Iterator<Interpretation> iterator = interpretationList.iterator();
        while (iterator.hasNext()) {
            Interpretation interpretation = iterator.next();
            // Check if the user has access to the corresponding clinical analysis
            try {
                catalogManager.getClinicalAnalysisManager().internalGet(studyUid,
                        interpretation.getClinicalAnalysisId(), ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, user);
            } catch (CatalogAuthorizationException e) {
                if (ignoreException) {
                    // Remove interpretation. User will not have permissions
                    iterator.remove();
                } else {
                    throw new CatalogAuthorizationException("Permission denied. " + user + " is not allowed to see some or none of the"
                            + " interpretations", e);
                }
            }
        }

        interpretationDataResult.setResults(interpretationList);
        interpretationDataResult.setNumResults(interpretationList.size());
        interpretationDataResult.setNumMatches(interpretationList.size());

        return keepOriginalOrder(uniqueList, interpretationStringFunction, interpretationDataResult, ignoreException, false);
    }

    public OpenCGAResult<Interpretation> create(String studyStr, Interpretation entry, QueryOptions options, String sessionId)
            throws CatalogException {
        throw new CatalogException("Missing primary field. Use other create methods");
    }

    public OpenCGAResult<Interpretation> addPrimaryInterpretation(String studyStr, String clinicalAnalysisStr,
                                                                  Interpretation interpretation, QueryOptions options, String token)
            throws CatalogException {
        return create(studyStr, clinicalAnalysisStr, interpretation, true, options, token);
    }

    public OpenCGAResult<Interpretation> addSecondaryInterpretation(String studyStr, String clinicalAnalysisStr,
                                                                  Interpretation interpretation, QueryOptions options, String token)
            throws CatalogException {
        return create(studyStr, clinicalAnalysisStr, interpretation, false, options, token);
    }

    public OpenCGAResult<Interpretation> create(String studyStr, String clinicalAnalysisStr, Interpretation interpretation,
                                                boolean primary, QueryOptions options, String token) throws CatalogException {
        // We check if the user can create interpretations in the clinical analysis
        String userId = userManager.getUserId(token);
        Study study = studyManager.resolveId(studyStr, userId);

        ObjectMap auditParams = new ObjectMap()
                .append("study", studyStr)
                .append("clinicalAnalysis", clinicalAnalysisStr)
                .append("interpretation", interpretation)
                .append("options", options)
                .append("token", token);

        try {
            ClinicalAnalysis clinicalAnalysis = catalogManager.getClinicalAnalysisManager().internalGet(study.getUid(), clinicalAnalysisStr,
                    ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, userId).first();

            authorizationManager.checkClinicalAnalysisPermission(study.getUid(), clinicalAnalysis.getUid(),
                    userId, ClinicalAnalysisAclEntry.ClinicalAnalysisPermissions.UPDATE);

            options = ParamUtils.defaultObject(options, QueryOptions::new);
            ParamUtils.checkObj(interpretation, "interpretation");
            ParamUtils.checkAlias(interpretation.getId(), "id");

            interpretation.setClinicalAnalysisId(clinicalAnalysis.getId());

            interpretation.setCreationDate(TimeUtils.getTime());
            interpretation.setDescription(ParamUtils.defaultString(interpretation.getDescription(), ""));
            interpretation.setInternal(ParamUtils.defaultObject(interpretation.getInternal(), InterpretationInternal::new));
            interpretation.getInternal().setStatus(ParamUtils.defaultObject(interpretation.getInternal().getStatus(),
                    InterpretationStatus::new));
            interpretation.setAttributes(ParamUtils.defaultObject(interpretation.getAttributes(), Collections.emptyMap()));

            interpretation.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.INTERPRETATION));

            OpenCGAResult result = interpretationDBAdaptor.insert(study.getUid(), interpretation, primary);
            OpenCGAResult<Interpretation> queryResult = interpretationDBAdaptor.get(study.getUid(), interpretation.getId(),
                    QueryOptions.empty());
            queryResult.setTime(result.getTime() + queryResult.getTime());

            auditManager.auditCreate(userId, Enums.Resource.INTERPRETATION, interpretation.getId(), "", study.getId(),
                    study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS));

            return queryResult;
        } catch (CatalogException e) {
            auditManager.auditCreate(userId, Enums.Resource.INTERPRETATION, interpretation.getId(), "", study.getId(),
                    study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError()));
            throw e;
        }
    }

    public OpenCGAResult<Interpretation> update(String studyStr, Query query, InterpretationUpdateParams updateParams, QueryOptions options,
                                                String token) throws CatalogException {
        return update(studyStr, query, updateParams, false, options, token);
    }

    public OpenCGAResult<Interpretation> update(String studyStr, Query query, InterpretationUpdateParams updateParams,
                                                boolean ignoreException, QueryOptions options, String token) throws CatalogException {
        options = ParamUtils.defaultObject(options, QueryOptions::new);

        String userId = userManager.getUserId(token);
        Study study = studyManager.resolveId(studyStr, userId);

        String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT);

        ObjectMap updateMap;
        try {
            updateMap = updateParams != null ? updateParams.getUpdateMap() : null;
        } catch (JsonProcessingException e) {
            throw new CatalogException("Could not parse InterpretationUpdateParams object: " + e.getMessage(), e);
        }

        ObjectMap auditParams = new ObjectMap()
                .append("study", studyStr)
                .append("query", query)
                .append("updateParams", updateMap)
                .append("ignoreException", ignoreException)
                .append("options", options)
                .append("token", token);

        Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new));

        DBIterator<Interpretation> iterator;
        try {
            finalQuery.append(InterpretationDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
            iterator = interpretationDBAdaptor.iterator(study.getUid(), finalQuery, INCLUDE_INTERPRETATION_IDS, userId);
        } catch (CatalogException e) {
            auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, "", "", study.getId(), study.getUuid(),
                    auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError()));
            throw e;
        }

        auditManager.initAuditBatch(operationId);
        OpenCGAResult<Interpretation> result = OpenCGAResult.empty();
        while (iterator.hasNext()) {
            Interpretation interpretation = iterator.next();
            try {
                OpenCGAResult writeResult = update(study, interpretation, updateParams, options, userId);
                auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretation.getId(),
                        interpretation.getUuid(), study.getId(), study.getUuid(), auditParams,
                        new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS));

                result.append(writeResult);
            } catch (CatalogException e) {
                Event event = new Event(Event.Type.ERROR, interpretation.getId(), e.getMessage());
                result.getEvents().add(event);

                logger.error("Cannot update interpretation {}: {}", interpretation.getId(), e.getMessage(), e);
                auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretation.getId(),
                        interpretation.getUuid(), study.getId(), study.getUuid(), auditParams,
                        new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError()));
            }
        }
        auditManager.finishAuditBatch(operationId);

        return endResult(result, ignoreException);
    }

    public OpenCGAResult<Interpretation> update(String studyStr, String clinicalAnalysisId, InterpretationUpdateParams updateParams,
                                                QueryOptions options, String token) throws CatalogException {
        options = ParamUtils.defaultObject(options, QueryOptions::new);

        String userId = userManager.getUserId(token);
        Study study = studyManager.resolveId(studyStr, userId);

        String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT);

        ObjectMap updateMap;
        try {
            updateMap = updateParams != null ? updateParams.getUpdateMap() : null;
        } catch (JsonProcessingException e) {
            throw new CatalogException("Could not parse InterpretationUpdateParams object: " + e.getMessage(), e);
        }

        ObjectMap auditParams = new ObjectMap()
                .append("study", studyStr)
                .append("clinicalAnalysisId", clinicalAnalysisId)
                .append("updateParams", updateMap)
                .append("options", options)
                .append("token", token);

        OpenCGAResult<Interpretation> result = OpenCGAResult.empty();
        String interpretationId = "";
        String interpretationUuid = "";
        try {
            OpenCGAResult<ClinicalAnalysis> clinicalResult = catalogManager.getClinicalAnalysisManager().internalGet(study.getUid(),
                    clinicalAnalysisId, ClinicalAnalysisManager.INCLUDE_CLINICAL_INTERPRETATIONS, userId);

            if (clinicalResult.first().getInterpretation() == null
                    || StringUtils.isEmpty(clinicalResult.first().getInterpretation().getId())) {
                throw new CatalogException("No available interpretation to update in Clinical Analysis.");
            }

            Interpretation interpretation = clinicalResult.first().getInterpretation();

            // We set the proper values for the audit
            interpretationId = interpretation.getId();
            interpretationUuid = interpretation.getUuid();

            OpenCGAResult writeResult = update(study, interpretation, updateParams, options, userId);
            result.append(writeResult);

            auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretation.getId(),
                    interpretation.getUuid(), study.getId(), study.getUuid(), auditParams,
                    new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS));
        } catch (CatalogException e) {
            CatalogException e1 = new CatalogException("Cannot update interpretation '" + interpretationId + "' of clinical analysis '"
                    + clinicalAnalysisId + "': " + e.getMessage(), e);
            Event event = new Event(Event.Type.ERROR, interpretationId, e1.getMessage());
            result.getEvents().add(event);

            logger.error("{}", e1.getMessage(), e);
            auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretationId, interpretationUuid,
                    study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e1.getError()));
            throw e1;
        }

        return result;
    }

    /**
     * Update interpretations from catalog.
     *
     * @param studyStr   Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy].
     * @param interpretationIds List of interpretation ids. Could be either the id or uuid.
     * @param updateParams Data model filled only with the parameters to be updated.
     * @param options      QueryOptions object.
     * @param token  Session id of the user logged in.
     * @return A OpenCGAResult.
     * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not
     *                          exist or is not allowed to be updated.
     */
    public OpenCGAResult<Interpretation> update(String studyStr, List<String> interpretationIds, InterpretationUpdateParams updateParams,
                                                QueryOptions options, String token) throws CatalogException {
        return update(studyStr, interpretationIds, updateParams, false, options, token);
    }

    public OpenCGAResult<Interpretation> update(String studyStr, List<String> interpretationIds, InterpretationUpdateParams updateParams,
                                                boolean ignoreException, QueryOptions options, String token) throws CatalogException {
        options = ParamUtils.defaultObject(options, QueryOptions::new);

        String userId = userManager.getUserId(token);
        Study study = studyManager.resolveId(studyStr, userId);

        String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT);

        ObjectMap updateMap;
        try {
            updateMap = updateParams != null ? updateParams.getUpdateMap() : null;
        } catch (JsonProcessingException e) {
            throw new CatalogException("Could not parse InterpretationUpdateParams object: " + e.getMessage(), e);
        }

        ObjectMap auditParams = new ObjectMap()
                .append("study", studyStr)
                .append("interpretationIds", interpretationIds)
                .append("updateParams", updateMap)
                .append("ignoreException", ignoreException)
                .append("options", options)
                .append("token", token);

        auditManager.initAuditBatch(operationId);
        OpenCGAResult<Interpretation> result = OpenCGAResult.empty();
        for (String id : interpretationIds) {
            String interpretationId = id;
            String interpretationUuid = "";

            try {
                OpenCGAResult<Interpretation> tmpResult = internalGet(study.getUid(), interpretationId, INCLUDE_INTERPRETATION_IDS, userId);
                if (tmpResult.getNumResults() == 0) {
                    throw new CatalogException("Interpretation '" + interpretationId + "' not found");
                }
                Interpretation interpretation = tmpResult.first();

                // We set the proper values for the audit
                interpretationId = interpretation.getId();
                interpretationUuid = interpretation.getUuid();

                OpenCGAResult writeResult = update(study, interpretation, updateParams, options, userId);
                result.append(writeResult);

                auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretation.getId(),
                        interpretation.getUuid(), study.getId(), study.getUuid(), auditParams,
                        new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS));
            } catch (CatalogException e) {
                Event event = new Event(Event.Type.ERROR, id, e.getMessage());
                result.getEvents().add(event);

                logger.error("Cannot update interpretation {}: {}", interpretationId, e.getMessage(), e);
                auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretationId, interpretationUuid,
                        study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError()));
            }
        }
        auditManager.finishAuditBatch(operationId);

        return endResult(result, ignoreException);
    }

    private OpenCGAResult update(Study study, Interpretation interpretation, InterpretationUpdateParams updateParams, QueryOptions options,
                                 String userId) throws CatalogException {
        // Check if user has permissions to write clinical analysis
        ClinicalAnalysis clinicalAnalysis = catalogManager.getClinicalAnalysisManager().internalGet(study.getUid(),
                interpretation.getClinicalAnalysisId(), ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, userId).first();
        authorizationManager.checkClinicalAnalysisPermission(study.getUid(), clinicalAnalysis.getUid(), userId,
                ClinicalAnalysisAclEntry.ClinicalAnalysisPermissions.UPDATE);

        ObjectMap parameters = new ObjectMap();
        if (updateParams != null) {
            try {
                parameters = updateParams.getUpdateMap();
            } catch (JsonProcessingException e) {
                throw new CatalogException("Could not parse InterpretationUpdateParams object: " + e.getMessage(), e);
            }
        }

        if (ListUtils.isNotEmpty(interpretation.getPrimaryFindings()) && (parameters.size() > 1
                || !parameters.containsKey(InterpretationDBAdaptor.QueryParams.REPORTED_VARIANTS.key()))) {
            throw new CatalogException("Interpretation already has reported variants. Only array of reported variants can be updated.");
        }

        if (parameters.containsKey(InterpretationDBAdaptor.QueryParams.ID.key())) {
            ParamUtils.checkAlias(parameters.getString(InterpretationDBAdaptor.QueryParams.ID.key()),
                    InterpretationDBAdaptor.QueryParams.ID.key());
        }

        return interpretationDBAdaptor.update(interpretation.getUid(), parameters, options);
    }

    @Override
    public DBIterator<Interpretation> iterator(String studyStr, Query query, QueryOptions options, String sessionId)
            throws CatalogException {
        return null;
    }

    @Override
    public OpenCGAResult<Interpretation> search(String studyId, Query query, QueryOptions options, String token)
            throws CatalogException {
        query = ParamUtils.defaultObject(query, Query::new);
        options = ParamUtils.defaultObject(options, QueryOptions::new);

        String userId = catalogManager.getUserManager().getUserId(token);
        Study study = catalogManager.getStudyManager().resolveId(studyId, userId);

        query.append(InterpretationDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());

        OpenCGAResult<Interpretation> queryResult = interpretationDBAdaptor.get(study.getUid(), query, options, userId);

        List<Interpretation> results = new ArrayList<>(queryResult.getResults().size());
        for (Interpretation interpretation : queryResult.getResults()) {
            if (StringUtils.isNotEmpty(interpretation.getClinicalAnalysisId())) {
                try {
                    catalogManager.getClinicalAnalysisManager().internalGet(study.getUid(),
                            interpretation.getClinicalAnalysisId(), ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS,
                            userId);
                    results.add(interpretation);
                } catch (CatalogException e) {
                    logger.debug("Removing interpretation " + interpretation.getUuid() + " from results. User " + userId + " does not have "
                            + "proper permissions");
                }
            }
        }

        queryResult.setResults(results);
        queryResult.setNumMatches(results.size());
        queryResult.setNumResults(results.size());
        return queryResult;
    }

    @Override
    public OpenCGAResult<Interpretation> count(String studyId, Query query, String token) throws CatalogException {
        return null;
    }

    @Override
    public OpenCGAResult delete(String studyStr, List<String> ids, ObjectMap params, String token) throws CatalogException {
        return null;
    }

    @Override
    public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, String sessionId) {
        return null;
    }

    @Override
    public OpenCGAResult rank(String studyStr, Query query, String field, int numResults, boolean asc, String sessionId)
            throws CatalogException {
        return null;
    }

    @Override
    public OpenCGAResult groupBy(@Nullable String studyStr, Query query, List<String> fields, QueryOptions options, String sessionId)
            throws CatalogException {
        return null;
    }
}


text:
<?php
declare(strict_types=1);

namespace Plank\Mediable;

use Closure;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

/**
 * Collection of Mediable Models.
 */
class MediableCollection extends Collection
{
    /**
     * Lazy eager load media attached to items in the collection.
     * @param string|string[] $tags
     * If one or more tags are specified, only media attached to those tags will be loaded.
     * @param bool $matchAll If true, only load media attached to all tags simultaneously
     * @param bool $withVariants If true, also load the variants and/or originalMedia relation of each Media
     * @return $this
     */
    public function loadMedia(
        $tags = [],
        bool $matchAll = false,
        bool $withVariants = false
    ): self {
        if ($this->isEmpty()) {
            return $this;
        }

        $tags = (array)$tags;

        if (empty($tags)) {
            if ($withVariants) {
                return $this->load(['media.originalMedia.variants', 'media.variants']);
            } else {
                return $this->load('media');
            }
        }

        if ($matchAll) {
            $closure = function (MorphToMany $q) use ($tags, $withVariants) {
                $this->addMatchAllToEagerLoadQuery($q, $tags);

                if ($withVariants) {
                    $q->with(['originalMedia.variants', 'variants']);
                }
            };
            $closure = Closure::bind($closure, $this->first(), $this->first());

            return $this->load(['media' => $closure]);
        }

        return $this->load(
            [
                'media' => function (MorphToMany $q) use ($tags, $withVariants) {
                    $q->wherePivotIn('tag', $tags);

                    if ($withVariants) {
                        $q->with(['originalMedia.variants', 'variants']);
                    }
                }
            ]
        );
    }

    /**
     * Lazy eager load media attached to items in the collection, as well as their variants.
     * @param string|string[] $tags
     * If one or more tags are specified, only media attached to those tags will be loaded.
     * @param bool $matchAll If true, only load media attached to all tags simultaneously
     * @return $this
     */
    public function loadMediaWithVariants($tags = [], bool $matchAll = false): self
    {
        return $this->loadMedia($tags, $matchAll, true);
    }

    /**
     * Lazy eager load media attached to items in the collection bound all of the provided
     * tags simultaneously.
     * @param  string|string[] $tags
     * @param bool $withVariants If true, also load the variants and/or originalMedia relation of each Media
     * If one or more tags are specified, only media attached to all of those tags will be loaded.
     * @return $this
     */
    public function loadMediaMatchAll($tags = [], bool $withVariants = false): self
    {
        return $this->loadMedia($tags, true, $withVariants);
    }

    /**
     * Lazy eager load media attached to items in the collection bound all of the provided
     * tags simultaneously, as well as the variants of those media.
     * @param  string|string[] $tags
     * If one or more tags are specified, only media attached to all of those tags will be loaded.
     * @return $this
     */
    public function loadMediaWithVariantsMatchAll($tags = []): self
    {
        return $this->loadMedia($tags, true, true);
    }

    public function delete(): void
    {
        if (count($this) == 0) {
            return;
        }

        /** @var MorphToMany $relation */
        $relation = $this->first()->media();
        $query = $relation->newPivotStatement();
        $classes = [];

        $this->each(
            function (Model $item) use ($query, $relation, &$classes) {
                // collect list of ids of each class in case not all
                // items belong to the same class
                $classes[get_class($item)][] = $item->getKey();
            }
        );

        // delete each item by class
        collect($classes)->each(
            function (array $ids, string $class) use ($query, $relation) {
                // select pivots matching each item for deletion
                $query->orWhere(
                    function (Builder $q) use ($class, $ids, $relation) {
                        $q->where($relation->getMorphType(), $class);
                        $q->whereIn(
                            $relation->getQualifiedForeignPivotKeyName(),
                            $ids
                        );
                    }
                );

                $class::whereIn((new $class)->getKeyName(), $ids)->delete();
            }
        );

        // delete pivots
        $query->delete();
    }
}


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<link rel="stylesheet" type="text/css" href="../../CSS/Contents.css"></link>

<title>Zips.Zip<T, U, V, Q> Method (IEnumerable<T>, IEnumerable<U>, IEnumerable<V>, IEnumerable<Q>)</title>

Documentation Project

Zips.Zip<T, U, V, Q> Method (IEnumerable<T>, IEnumerable<U>, IEnumerable<V>, IEnumerable<Q>)

Syntax

Collapse All

Zip the elements of four streams.

Declaring type: Zips

Namespace: Sasa.Linq

Assembly: Sasa

Syntax

<col width="100%" />
C#

public static IEnumerable<Quad<T, U, V, Q>> Zip<T, U, V, Q> (
        IEnumerable<T> first,
        IEnumerable<U> second,
        IEnumerable<V> third,
        IEnumerable<Q> fourth
)

Type Parameters

T

The type of the first stream.

U

The type of the second stream.

V

The type of the third stream.

Q

The type of the fourth stream.

Parameters

first

The first stream.

second

The second stream.

third

The third stream.

fourth

The fourth stream.

Return Value

A stream of tupled values.

Top

Generated by ImmDoc .NET.


text:
#include "webrtc/sdk/android/src/jni/jni_helpers.h"

#include "webrtc/sdk/android/src/jni/classreferenceholder.h"

#include <asm/unistd.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <vector>

namespace webrtc_jni {

static JavaVM* g_jvm = nullptr;

static pthread_once_t g_jni_ptr_once = PTHREAD_ONCE_INIT;

// Key for per-thread JNIEnv* data.  Non-NULL in threads attached to |g_jvm| by
// AttachCurrentThreadIfNeeded(), NULL in unattached threads and threads that
// were attached by the JVM because of a Java->native call.
static pthread_key_t g_jni_ptr;

JavaVM *GetJVM() {
  RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?";
  return g_jvm;
}

// Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
JNIEnv* GetEnv() {
  void* env = nullptr;
  jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
  RTC_CHECK(((env != nullptr) && (status == JNI_OK)) ||
            ((env == nullptr) && (status == JNI_EDETACHED)))
      << "Unexpected GetEnv return: " << status << ":" << env;
  return reinterpret_cast<JNIEnv*>(env);
}

static void ThreadDestructor(void* prev_jni_ptr) {
  // This function only runs on threads where |g_jni_ptr| is non-NULL, meaning
  // we were responsible for originally attaching the thread, so are responsible
  // for detaching it now.  However, because some JVM implementations (notably
  // Oracle's http://goo.gl/eHApYT) also use the pthread_key_create mechanism,
  // the JVMs accounting info for this thread may already be wiped out by the
  // time this is called. Thus it may appear we are already detached even though
  // it was our responsibility to detach!  Oh well.
  if (!GetEnv())
    return;

  RTC_CHECK(GetEnv() == prev_jni_ptr)
      << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
  jint status = g_jvm->DetachCurrentThread();
  RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
  RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???";
}

static void CreateJNIPtrKey() {
  RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
      << "pthread_key_create";
}

jint InitGlobalJniVariables(JavaVM *jvm) {
  RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!";
  g_jvm = jvm;
  RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?";

  RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";

  JNIEnv* jni = nullptr;
  if (jvm->GetEnv(reinterpret_cast<void**>(&jni), JNI_VERSION_1_6) != JNI_OK)
    return -1;

  return JNI_VERSION_1_6;
}

// Return thread ID as a string.
static std::string GetThreadId() {
  char buf[21];  // Big enough to hold a kuint64max plus terminating NULL.
  RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld",
                        static_cast<long>(syscall(__NR_gettid))),
               sizeof(buf))
      << "Thread id is bigger than uint64??";
  return std::string(buf);
}

// Return the current thread's name.
static std::string GetThreadName() {
  char name[17] = {0};
  if (prctl(PR_GET_NAME, name) != 0)
    return std::string("<noname>");
  return std::string(name);
}

// Return a |JNIEnv*| usable on this thread.  Attaches to |g_jvm| if necessary.
JNIEnv* AttachCurrentThreadIfNeeded() {
  JNIEnv* jni = GetEnv();
  if (jni)
    return jni;
  RTC_CHECK(!pthread_getspecific(g_jni_ptr))
      << "TLS has a JNIEnv* but not attached?";

  std::string name(GetThreadName() + " - " + GetThreadId());
  JavaVMAttachArgs args;
  args.version = JNI_VERSION_1_6;
  args.name = &name[0];
  args.group = nullptr;
  // Deal with difference in signatures between Oracle's jni.h and Android's.
#ifdef _JAVASOFT_JNI_H_  // Oracle's jni.h violates the JNI spec!
  void* env = nullptr;
#else
  JNIEnv* env = nullptr;
#endif
  RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args))
      << "Failed to attach thread";
  RTC_CHECK(env) << "AttachCurrentThread handed back NULL!";
  jni = reinterpret_cast<JNIEnv*>(env);
  RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
  return jni;
}

// Return a |jlong| that will correctly convert back to |ptr|.  This is needed
// because the alternative (of silently passing a 32-bit pointer to a vararg
// function expecting a 64-bit param) picks up garbage in the high 32 bits.
jlong jlongFromPointer(void* ptr) {
  static_assert(sizeof(intptr_t) <= sizeof(jlong),
                "Time to rethink the use of jlongs");
  // Going through intptr_t to be obvious about the definedness of the
  // conversion from pointer to integral type.  intptr_t to jlong is a standard
  // widening by the static_assert above.
  jlong ret = reinterpret_cast<intptr_t>(ptr);
  RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr);
  return ret;
}

// JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and
// found object/class/method/field is non-null.
jmethodID GetMethodID(
    JNIEnv* jni, jclass c, const std::string& name, const char* signature) {
  jmethodID m = jni->GetMethodID(c, name.c_str(), signature);
  CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", "
                       << signature;
  RTC_CHECK(m) << name << ", " << signature;
  return m;
}

jmethodID GetStaticMethodID(
    JNIEnv* jni, jclass c, const char* name, const char* signature) {
  jmethodID m = jni->GetStaticMethodID(c, name, signature);
  CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", "
                       << signature;
  RTC_CHECK(m) << name << ", " << signature;
  return m;
}

jfieldID GetFieldID(
    JNIEnv* jni, jclass c, const char* name, const char* signature) {
  jfieldID f = jni->GetFieldID(c, name, signature);
  CHECK_EXCEPTION(jni) << "error during GetFieldID";
  RTC_CHECK(f) << name << ", " << signature;
  return f;
}

jfieldID GetStaticFieldID(JNIEnv* jni,
                          jclass c,
                          const char* name,
                          const char* signature) {
  jfieldID f = jni->GetStaticFieldID(c, name, signature);
  CHECK_EXCEPTION(jni) << "error during GetStaticFieldID";
  RTC_CHECK(f) << name << ", " << signature;
  return f;
}

jclass GetObjectClass(JNIEnv* jni, jobject object) {
  jclass c = jni->GetObjectClass(object);
  CHECK_EXCEPTION(jni) << "error during GetObjectClass";
  RTC_CHECK(c) << "GetObjectClass returned NULL";
  return c;
}

jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
  jobject o = jni->GetObjectField(object, id);
  CHECK_EXCEPTION(jni) << "error during GetObjectField";
  RTC_CHECK(!IsNull(jni, o)) << "GetObjectField returned NULL";
  return o;
}

jobject GetStaticObjectField(JNIEnv* jni, jclass c, jfieldID id) {
  jobject o = jni->GetStaticObjectField(c, id);
  CHECK_EXCEPTION(jni) << "error during GetStaticObjectField";
  RTC_CHECK(!IsNull(jni, o)) << "GetStaticObjectField returned NULL";
  return o;
}

jobject GetNullableObjectField(JNIEnv* jni, jobject object, jfieldID id) {
  jobject o = jni->GetObjectField(object, id);
  CHECK_EXCEPTION(jni) << "error during GetObjectField";
  return o;
}

jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
  return static_cast<jstring>(GetObjectField(jni, object, id));
}

jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
  jlong l = jni->GetLongField(object, id);
  CHECK_EXCEPTION(jni) << "error during GetLongField";
  return l;
}

jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
  jint i = jni->GetIntField(object, id);
  CHECK_EXCEPTION(jni) << "error during GetIntField";
  return i;
}

bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
  jboolean b = jni->GetBooleanField(object, id);
  CHECK_EXCEPTION(jni) << "error during GetBooleanField";
  return b;
}

bool IsNull(JNIEnv* jni, jobject obj) {
  return jni->IsSameObject(obj, nullptr);
}

// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
  jstring jstr = jni->NewStringUTF(native.c_str());
  CHECK_EXCEPTION(jni) << "error during NewStringUTF";
  return jstr;
}

// Given a jstring, reinterprets it to a new native string.
std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
  // Invoke String.getBytes(String charsetName) method to convert |j_string|
  // to a byte array.
  const jclass string_class = GetObjectClass(jni, j_string);
  const jmethodID get_bytes =
      GetMethodID(jni, string_class, "getBytes", "(Ljava/lang/String;)[B");
  const jstring charset_name = jni->NewStringUTF("ISO-8859-1");
  CHECK_EXCEPTION(jni) << "error during NewStringUTF";
  const jbyteArray j_byte_array =
      (jbyteArray)jni->CallObjectMethod(j_string, get_bytes, charset_name);
  CHECK_EXCEPTION(jni) << "error during CallObjectMethod";

  const size_t len = jni->GetArrayLength(j_byte_array);
  CHECK_EXCEPTION(jni) << "error during GetArrayLength";
  std::vector<char> buf(len);
  jni->GetByteArrayRegion(j_byte_array, 0, len,
                          reinterpret_cast<jbyte*>(&buf[0]));
  CHECK_EXCEPTION(jni) << "error during GetByteArrayRegion";

  return std::string(buf.begin(), buf.end());
}

// Return the (singleton) Java Enum object corresponding to |index|;
jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
                          const std::string& state_class_name, int index) {
  jmethodID state_values_id = GetStaticMethodID(
      jni, state_class, "values", ("()[L" + state_class_name  + ";").c_str());
  jobjectArray state_values = static_cast<jobjectArray>(
      jni->CallStaticObjectMethod(state_class, state_values_id));
  CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
  jobject ret = jni->GetObjectArrayElement(state_values, index);
  CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
  return ret;
}

std::string GetJavaEnumName(JNIEnv* jni,
                            const std::string& className,
                            jobject j_enum) {
  jclass enumClass = FindClass(jni, className.c_str());
  jmethodID nameMethod =
      GetMethodID(jni, enumClass, "name", "()Ljava/lang/String;");
  jstring name =
      reinterpret_cast<jstring>(jni->CallObjectMethod(j_enum, nameMethod));
  CHECK_EXCEPTION(jni) << "error during CallObjectMethod for " << className
                       << ".name";
  return JavaToStdString(jni, name);
}

jobject NewGlobalRef(JNIEnv* jni, jobject o) {
  jobject ret = jni->NewGlobalRef(o);
  CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
  RTC_CHECK(ret);
  return ret;
}

void DeleteGlobalRef(JNIEnv* jni, jobject o) {
  jni->DeleteGlobalRef(o);
  CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
}

// Scope Java local references to the lifetime of this object.  Use in all C++
// callbacks (i.e. entry points that don't originate in a Java callstack
// through a "native" method call).
ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
  RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
}
ScopedLocalRefFrame::~ScopedLocalRefFrame() {
  jni_->PopLocalFrame(nullptr);
}

// Creates an iterator representing the end of any collection.
Iterable::Iterator::Iterator() : iterator_(nullptr) {}

// Creates an iterator pointing to the beginning of the specified collection.
Iterable::Iterator::Iterator(JNIEnv* jni, jobject iterable) : jni_(jni) {
  jclass j_class = GetObjectClass(jni, iterable);
  jmethodID iterator_id =
      GetMethodID(jni, j_class, "iterator", "()Ljava/util/Iterator;");
  iterator_ = jni->CallObjectMethod(iterable, iterator_id);
  CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
  RTC_CHECK(iterator_ != nullptr);

  jclass iterator_class = GetObjectClass(jni, iterator_);
  has_next_id_ = GetMethodID(jni, iterator_class, "hasNext", "()Z");
  next_id_ = GetMethodID(jni, iterator_class, "next", "()Ljava/lang/Object;");

  // Start at the first element in the collection.
  ++(*this);
}

// Move constructor - necessary to be able to return iterator types from
// functions.
Iterable::Iterator::Iterator(Iterator&& other)
    : jni_(std::move(other.jni_)),
      iterator_(std::move(other.iterator_)),
      value_(std::move(other.value_)),
      has_next_id_(std::move(other.has_next_id_)),
      next_id_(std::move(other.next_id_)),
      thread_checker_(std::move(other.thread_checker_)){};

// Advances the iterator one step.
Iterable::Iterator& Iterable::Iterator::operator++() {
  RTC_CHECK(thread_checker_.CalledOnValidThread());
  if (AtEnd()) {
    // Can't move past the end.
    return *this;
  }
  bool has_next = jni_->CallBooleanMethod(iterator_, has_next_id_);
  CHECK_EXCEPTION(jni_) << "error during CallBooleanMethod";
  if (!has_next) {
    iterator_ = nullptr;
    value_ = nullptr;
    return *this;
  }

  value_ = jni_->CallObjectMethod(iterator_, next_id_);
  CHECK_EXCEPTION(jni_) << "error during CallObjectMethod";
  return *this;
}

// Provides a way to compare the iterator with itself and with the end iterator.
// Note: all other comparison results are undefined, just like for C++ input
// iterators.
bool Iterable::Iterator::operator==(const Iterable::Iterator& other) {
  // Two different active iterators should never be compared.
  RTC_DCHECK(this == &other || AtEnd() || other.AtEnd());
  return AtEnd() == other.AtEnd();
}

jobject Iterable::Iterator::operator*() {
  RTC_CHECK(!AtEnd());
  return value_;
}

bool Iterable::Iterator::AtEnd() const {
  RTC_CHECK(thread_checker_.CalledOnValidThread());
  return jni_ == nullptr || IsNull(jni_, iterator_);
}

}  // namespace webrtc_jni


text:
package reborncore.common.util;

import org.apache.commons.lang3.Range;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public final class RangeUtil {
	private RangeUtil() {
	}

	public static List<Range<Integer>> joinAdjacent(List<Range<Integer>> list) {
		var in = list.stream().sorted(Comparator.comparing(Range::getMinimum)).toList();
		var out = new LinkedList<Range<Integer>>();

		for (var range : in) {
			if (out.isEmpty()) {
				out.add(range);
				continue;
			}

			var last = out.getLast();
			if (last.getMaximum() >= range.getMinimum() -1) {
				out.removeLast();
				out.add(Range.between(last.getMinimum(), Math.max(last.getMaximum(), range.getMaximum())));
			} else {
				out.add(range);
			}
		}

		return Collections.unmodifiableList(out);
	}
}


text:
$computers="FILLTHISVALUES"

# Working Paths
$location="c:\temp\checkKB3080079"
$BATlocation="$location\checkKB3080079.bat"
$ResultFile=$location\Result.log

# Clean up folder
remove-item -Path $location\* -Exclude *.bat

foreach ($computer in $computers){
	#Set Remote Path
	$remotepath="\\$computer\c$\temp"
	#Copy bat file
	copy-item $BATlocation $remotepath\temp.bat -force
	if ($?){
		#Execute the bat on the remote machine
		psexec "\\$computer" c:\temp\temp.bat
		#Copy the logs and clean everything from the remote machine
		copy-item $remotepath\temp.log $location\$computer.log
		remove-item -Path $remotepath\temp.log
		remove-item -Path $remotepath\temp.bat

		#Check if the patch was installed
		$helper=get-content $location\$computer.log
		if (!$helper){
			Write-Output "$computer;NOT INSTALLED" >> $ResultFile
		}else{
			Write-Output "$computer;INSTALLED" >> $ResultFile
		}

	}else{
		#If the copy fails
		Write-Output "$computer;ERROR" >> $ResultFile
	}
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.07.27 at 02:36:42 PM CST
//

package org.shaolin.bmdp.datamodel.common;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VariableCategoryType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="VariableCategoryType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="JavaPrimitive"/>
 *     <enumeration value="JavaClass"/>
 *     <enumeration value="BusinessEntity"/>
 *     <enumeration value="ConstantEntity"/>
 *     <enumeration value="UIEntity"/>
 *     <enumeration value="JoinTable"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "VariableCategoryType")
@XmlEnum
public enum VariableCategoryType {

    @XmlEnumValue("JavaPrimitive")
    JAVA_PRIMITIVE("JavaPrimitive"),
    @XmlEnumValue("JavaClass")
    JAVA_CLASS("JavaClass"),
    @XmlEnumValue("BusinessEntity")
    BUSINESS_ENTITY("BusinessEntity"),
    @XmlEnumValue("ConstantEntity")
    CONSTANT_ENTITY("ConstantEntity"),
    @XmlEnumValue("UIEntity")
    UI_ENTITY("UIEntity"),
    @XmlEnumValue("JoinTable")
    JOIN_TABLE("JoinTable");
    private final String value;

    VariableCategoryType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static VariableCategoryType fromValue(String v) {
        for (VariableCategoryType c: VariableCategoryType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
interface IterableObject<T> {
  [k: string]: T;
}

/**
 * Iterate over enumarable keys of object and build an array
 *
 * @param {object} [obj] The object to iterate over
 *
 * @returns {array} array of object values
 */
export default function objectValues<T>(obj: object) {
  return Object.keys(obj).map(k => (<IterableObject<T>>obj)[k]);
}


text:
<!DOCTYPE html>

    <?php

    /**
     * Create a class called "Rectangle".
     * Your class should have a constructor that takes two parameters: a width and height.
     *
     * Add three public functions to your class:
     *   getArea() : Calculate and return the area of the rectangle
     *   getPerimeter() : Calculate and return the perimeter of the rectangle
     *   isSquare() : Return true of the rectangle is a square, false otherwise.
     */

    ///////////////////////////
    // Put your code here!
    ///////////////////////////

    $width = 160;
    $height = 75;

    echo "
With a width of $width and a height of $height...
";

    $r = new Rectangle($width, $height);

    echo '
The area of the rectangle is ' . $r->getArea() . '
';
    echo '
The perimeter of the rectangle is ' . $r->getPerimeter() . '
';

    echo '
This rectangle is ';
    if ($r->isSquare()) {
        echo 'also';
    } else {
        echo 'not';
    }
    echo ' a square.
';

    ?>


text:
@interface ELShareServiceDelegate : NSObject

@end


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form3
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form3))
        Me.SuspendLayout()
        '
        'Form3
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackgroundImage = CType(resources.GetObject("$this.BackgroundImage"), System.Drawing.Image)
        Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center
        Me.ClientSize = New System.Drawing.Size(287, 275)
        Me.DoubleBuffered = True
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "Form3"
        Me.Text = "Bitcoin Donate"
        Me.ResumeLayout(False)

    End Sub
End Class


text:
package com.intellij.ide.projectView.impl;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.projectView.actions.MoveModulesToGroupAction;
import com.intellij.ide.projectView.actions.MoveModulesToSubGroupAction;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MoveModuleToGroup extends ActionGroup {
  private final ModuleGroup myModuleGroup;

  public MoveModuleToGroup(ModuleGroup moduleGroup) {
    myModuleGroup = moduleGroup;
    setPopup(true);
  }

  @Override
  public void update(AnActionEvent e){
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    final Module[] modules = LangDataKeys.MODULE_CONTEXT_ARRAY.getData(dataContext);
    boolean active = project != null && modules != null && modules.length != 0;
    final Presentation presentation = e.getPresentation();
    presentation.setVisible(active);
    presentation.setText(myModuleGroup.presentableText());
  }

  @Override
  @NotNull
  public AnAction[] getChildren(@Nullable AnActionEvent e) {
    if (e == null) return EMPTY_ARRAY;

    List<ModuleGroup> children = new ArrayList<ModuleGroup>(myModuleGroup.childGroups(e.getDataContext()));
    Collections.sort ( children, new Comparator<ModuleGroup>() {
      @Override
      public int compare(final ModuleGroup moduleGroup1, final ModuleGroup moduleGroup2) {
        assert moduleGroup1.getGroupPath().length == moduleGroup2.getGroupPath().length;
        return moduleGroup1.toString().compareToIgnoreCase(moduleGroup2.toString());
      }
    });

    List<AnAction> result = new ArrayList<AnAction>();
    result.add(new MoveModulesToGroupAction(myModuleGroup, IdeBundle.message("action.move.module.to.this.group")));
    result.add(new MoveModulesToSubGroupAction(myModuleGroup));
     result.add(Separator.getInstance());
    for (final ModuleGroup child : children) {
      result.add(new MoveModuleToGroup(child));
    }

    return result.toArray(new AnAction[result.size()]);
  }
}


text:
namespace Microsoft.Azure.Management.Network.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// Effective NetworkSecurityRules
    /// </summary>
    public partial class EffectiveNetworkSecurityRule
    {
        /// <summary>
        /// Initializes a new instance of the EffectiveNetworkSecurityRule
        /// class.
        /// </summary>
        public EffectiveNetworkSecurityRule() { }

        /// <summary>
        /// Initializes a new instance of the EffectiveNetworkSecurityRule
        /// class.
        /// </summary>
        public EffectiveNetworkSecurityRule(string name = default(string), string protocol = default(string), string sourcePortRange = default(string), string destinationPortRange = default(string), string sourceAddressPrefix = default(string), string destinationAddressPrefix = default(string), IList<string> expandedSourceAddressPrefix = default(IList<string>), IList<string> expandedDestinationAddressPrefix = default(IList<string>), string access = default(string), int? priority = default(int?), string direction = default(string))
        {
            Name = name;
            Protocol = protocol;
            SourcePortRange = sourcePortRange;
            DestinationPortRange = destinationPortRange;
            SourceAddressPrefix = sourceAddressPrefix;
            DestinationAddressPrefix = destinationAddressPrefix;
            ExpandedSourceAddressPrefix = expandedSourceAddressPrefix;
            ExpandedDestinationAddressPrefix = expandedDestinationAddressPrefix;
            Access = access;
            Priority = priority;
            Direction = direction;
        }

        /// <summary>
        /// Gets the name of the security rule specified by the user (if
        /// created by the user)
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets Network protocol this rule applies to. Possible values
        /// include: 'Tcp', 'Udp', '*'
        /// </summary>
        [JsonProperty(PropertyName = "protocol")]
        public string Protocol { get; set; }

        /// <summary>
        /// Gets source port or range
        /// </summary>
        [JsonProperty(PropertyName = "sourcePortRange")]
        public string SourcePortRange { get; set; }

        /// <summary>
        /// Gets destination port or range
        /// </summary>
        [JsonProperty(PropertyName = "destinationPortRange")]
        public string DestinationPortRange { get; set; }

        /// <summary>
        /// Gets source address prefix
        /// </summary>
        [JsonProperty(PropertyName = "sourceAddressPrefix")]
        public string SourceAddressPrefix { get; set; }

        /// <summary>
        /// Gets destination address prefix
        /// </summary>
        [JsonProperty(PropertyName = "destinationAddressPrefix")]
        public string DestinationAddressPrefix { get; set; }

        /// <summary>
        /// Gets expanded source address prefix
        /// </summary>
        [JsonProperty(PropertyName = "expandedSourceAddressPrefix")]
        public IList<string> ExpandedSourceAddressPrefix { get; set; }

        /// <summary>
        /// Gets expanded destination address prefix
        /// </summary>
        [JsonProperty(PropertyName = "expandedDestinationAddressPrefix")]
        public IList<string> ExpandedDestinationAddressPrefix { get; set; }

        /// <summary>
        /// Gets network traffic is allowed or denied. Possible values
        /// include: 'Allow', 'Deny'
        /// </summary>
        [JsonProperty(PropertyName = "access")]
        public string Access { get; set; }

        /// <summary>
        /// Gets the priority of the rule
        /// </summary>
        [JsonProperty(PropertyName = "priority")]
        public int? Priority { get; set; }

        /// <summary>
        /// Gets the direction of the rule. Possible values include:
        /// 'Inbound', 'Outbound'
        /// </summary>
        [JsonProperty(PropertyName = "direction")]
        public string Direction { get; set; }

    }
}


text:
<?php namespace App\Http\Controllers;

use Input;
use Redirect;
use App\Blog;
use App\Http\Requests;

use App\Http\Requests\BlogRequest;

use App\Http\Controllers\Controller;

//use Illuminate\Http\Requests\StoreBlogsRequest;

class BlogsController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $blogs = Blog::all();
        return view('blogs.index', compact('blogs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return view('blogs.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */

    /**
     * Display the specified resource.
     *
     * @param  \App\Project $project
     * @return Response
     */
    public function show(Blog $blog)
    {
        return view('blogs.show01', compact('blog'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Project $project
     * @return Response
     */
    public function edit(Blog $blog)
    {

        return view('blogs.edit', compact('blog'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Project $project
     * @return Response
     */

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Project $project
     * @return Response
     */

    public function store(BlogRequest $request)
    {
        $input = Input::all();
        Blog::create( $input );

        return Redirect::route('blogs.index')->with('message', 'Blog created');
    }

    public function update(Blog $blog)
    {
        $input = array_except(Input::all(), '_method');
        $blog->update($input);

        return Redirect::route('blogs.show', $blog->slug)->with('message', 'Blog updated.');
    }

    public function destroy(Blog $blog)
    {
        $blog->delete();

        return Redirect::route('blogs.index')->with('message', 'Blog deleted.');
    }

}


text:
<?php

namespace ubud\dashboard\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use ubud\dashboard\models\Warga_anggota;

/**
 * Warga_anggotaSearch represents the model behind the search form about `ubud\dashboard\models\Warga_anggota`.
 */
class Warga_anggotaSearch extends Warga_anggota
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ID', 'NO_WARGA'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Warga_anggota::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'ID' => $this->ID,
            'NO_WARGA' => $this->NO_WARGA,
        ]);

        return $dataProvider;
    }
}


text:
package syscall

import (
	errorspkg "errors"
	"internal/bytealg"
	"runtime"
	"sync"
	"unsafe"
)

// Lock synchronizing creation of new file descriptors with fork.
//
// We want the child in a fork/exec sequence to inherit only the
// file descriptors we intend. To do that, we mark all file
// descriptors close-on-exec and then, in the child, explicitly
// unmark the ones we want the exec'ed program to keep.
// Unix doesn't make this easy: there is, in general, no way to
// allocate a new file descriptor close-on-exec. Instead you
// have to allocate the descriptor and then mark it close-on-exec.
// If a fork happens between those two events, the child's exec
// will inherit an unwanted file descriptor.
//
// This lock solves that race: the create new fd/mark close-on-exec
// operation is done holding ForkLock for reading, and the fork itself
// is done holding ForkLock for writing. At least, that's the idea.
// There are some complications.
//
// Some system calls that create new file descriptors can block
// for arbitrarily long times: open on a hung NFS server or named
// pipe, accept on a socket, and so on. We can't reasonably grab
// the lock across those operations.
//
// It is worse to inherit some file descriptors than others.
// If a non-malicious child accidentally inherits an open ordinary file,
// that's not a big deal. On the other hand, if a long-lived child
// accidentally inherits the write end of a pipe, then the reader
// of that pipe will not see EOF until that child exits, potentially
// causing the parent program to hang. This is a common problem
// in threaded C programs that use popen.
//
// Luckily, the file descriptors that are most important not to
// inherit are not the ones that can take an arbitrarily long time
// to create: pipe returns instantly, and the net package uses
// non-blocking I/O to accept on a listening socket.
// The rules for which file descriptor-creating operations use the
// ForkLock are as follows:
//
// 1) Pipe. Does not block. Use the ForkLock.
// 2) Socket. Does not block. Use the ForkLock.
// 3) Accept. If using non-blocking mode, use the ForkLock.
//             Otherwise, live with the race.
// 4) Open. Can block. Use O_CLOEXEC if available (Linux).
//             Otherwise, live with the race.
// 5) Dup. Does not block. Use the ForkLock.
//             On Linux, could use fcntl F_DUPFD_CLOEXEC
//             instead of the ForkLock, but only for dup(fd, -1).

var ForkLock sync.RWMutex

// StringSlicePtr converts a slice of strings to a slice of pointers
// to NUL-terminated byte arrays. If any string contains a NUL byte
// this function panics instead of returning an error.
//
// Deprecated: Use SlicePtrFromStrings instead.
func StringSlicePtr(ss []string) []*byte {
	bb := make([]*byte, len(ss)+1)
	for i := 0; i < len(ss); i++ {
		bb[i] = StringBytePtr(ss[i])
	}
	bb[len(ss)] = nil
	return bb
}

// SlicePtrFromStrings converts a slice of strings to a slice of
// pointers to NUL-terminated byte arrays. If any string contains
// a NUL byte, it returns (nil, EINVAL).
func SlicePtrFromStrings(ss []string) ([]*byte, error) {
	n := 0
	for _, s := range ss {
		if bytealg.IndexByteString(s, 0) != -1 {
			return nil, EINVAL
		}
		n += len(s) + 1 // +1 for NUL
	}
	bb := make([]*byte, len(ss)+1)
	b := make([]byte, n)
	n = 0
	for i, s := range ss {
		bb[i] = &b[n]
		copy(b[n:], s)
		n += len(s) + 1
	}
	return bb, nil
}

func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) }

func SetNonblock(fd int, nonblocking bool) (err error) {
	flag, err := fcntl(fd, F_GETFL, 0)
	if err != nil {
		return err
	}
	if nonblocking {
		flag |= O_NONBLOCK
	} else {
		flag &^= O_NONBLOCK
	}
	_, err = fcntl(fd, F_SETFL, flag)
	return err
}

// Credential holds user and group identities to be assumed
// by a child process started by StartProcess.
type Credential struct {
	Uid         uint32   // User ID.
	Gid         uint32   // Group ID.
	Groups      []uint32 // Supplementary group IDs.
	NoSetGroups bool     // If true, don't set supplementary groups
}

// ProcAttr holds attributes that will be applied to a new process started
// by StartProcess.
type ProcAttr struct {
	Dir   string    // Current working directory.
	Env   []string  // Environment.
	Files []uintptr // File descriptors.
	Sys   *SysProcAttr
}

var zeroProcAttr ProcAttr
var zeroSysProcAttr SysProcAttr

func forkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error) {
	var p [2]int
	var n int
	var err1 Errno
	var wstatus WaitStatus

	if attr == nil {
		attr = &zeroProcAttr
	}
	sys := attr.Sys
	if sys == nil {
		sys = &zeroSysProcAttr
	}

	// Convert args to C form.
	argv0p, err := BytePtrFromString(argv0)
	if err != nil {
		return 0, err
	}
	argvp, err := SlicePtrFromStrings(argv)
	if err != nil {
		return 0, err
	}
	envvp, err := SlicePtrFromStrings(attr.Env)
	if err != nil {
		return 0, err
	}

	if (runtime.GOOS == "freebsd" || runtime.GOOS == "dragonfly") && len(argv[0]) > len(argv0) {
		argvp[0] = argv0p
	}

	var chroot *byte
	if sys.Chroot != "" {
		chroot, err = BytePtrFromString(sys.Chroot)
		if err != nil {
			return 0, err
		}
	}
	var dir *byte
	if attr.Dir != "" {
		dir, err = BytePtrFromString(attr.Dir)
		if err != nil {
			return 0, err
		}
	}

	// Both Setctty and Foreground use the Ctty field,
	// but they give it slightly different meanings.
	if sys.Setctty && sys.Foreground {
		return 0, errorspkg.New("both Setctty and Foreground set in SysProcAttr")
	}
	if sys.Setctty && sys.Ctty >= len(attr.Files) {
		return 0, errorspkg.New("Setctty set but Ctty not valid in child")
	}

	// Acquire the fork lock so that no other threads
	// create new fds that are not yet close-on-exec
	// before we fork.
	ForkLock.Lock()

	// Allocate child status pipe close on exec.
	if err = forkExecPipe(p[:]); err != nil {
		ForkLock.Unlock()
		return 0, err
	}

	// Kick off child.
	pid, err1 = forkAndExecInChild(argv0p, argvp, envvp, chroot, dir, attr, sys, p[1])
	if err1 != 0 {
		Close(p[0])
		Close(p[1])
		ForkLock.Unlock()
		return 0, Errno(err1)
	}
	ForkLock.Unlock()

	// Read child error status from pipe.
	Close(p[1])
	for {
		n, err = readlen(p[0], (*byte)(unsafe.Pointer(&err1)), int(unsafe.Sizeof(err1)))
		if err != EINTR {
			break
		}
	}
	Close(p[0])
	if err != nil || n != 0 {
		if n == int(unsafe.Sizeof(err1)) {
			err = Errno(err1)
		}
		if err == nil {
			err = EPIPE
		}

		// Child failed; wait for it to exit, to make sure
		// the zombies don't accumulate.
		_, err1 := Wait4(pid, &wstatus, 0, nil)
		for err1 == EINTR {
			_, err1 = Wait4(pid, &wstatus, 0, nil)
		}
		return 0, err
	}

	// Read got EOF, so pipe closed on exec, so exec succeeded.
	return pid, nil
}

// Combination of fork and exec, careful to be thread safe.
func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error) {
	return forkExec(argv0, argv, attr)
}

// StartProcess wraps ForkExec for package os.
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
	pid, err = forkExec(argv0, argv, attr)
	return pid, 0, err
}

// Implemented in runtime package.
func runtime_BeforeExec()
func runtime_AfterExec()

// execveLibc is non-nil on OS using libc syscall, set to execve in exec_libc.go; this
// avoids a build dependency for other platforms.
var execveLibc func(path uintptr, argv uintptr, envp uintptr) Errno
var execveDarwin func(path *byte, argv **byte, envp **byte) error
var execveOpenBSD func(path *byte, argv **byte, envp **byte) error

// Exec invokes the execve(2) system call.
func Exec(argv0 string, argv []string, envv []string) (err error) {
	argv0p, err := BytePtrFromString(argv0)
	if err != nil {
		return err
	}
	argvp, err := SlicePtrFromStrings(argv)
	if err != nil {
		return err
	}
	envvp, err := SlicePtrFromStrings(envv)
	if err != nil {
		return err
	}
	runtime_BeforeExec()

	var err1 error
	if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" || runtime.GOOS == "aix" {
		// RawSyscall should never be used on Solaris, illumos, or AIX.
		err1 = execveLibc(
			uintptr(unsafe.Pointer(argv0p)),
			uintptr(unsafe.Pointer(&argvp[0])),
			uintptr(unsafe.Pointer(&envvp[0])))
	} else if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
		// Similarly on Darwin.
		err1 = execveDarwin(argv0p, &argvp[0], &envvp[0])
	} else if runtime.GOOS == "openbsd" && (runtime.GOARCH == "386" || runtime.GOARCH == "amd64" || runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
		// Similarly on OpenBSD.
		err1 = execveOpenBSD(argv0p, &argvp[0], &envvp[0])
	} else {
		_, _, err1 = RawSyscall(SYS_EXECVE,
			uintptr(unsafe.Pointer(argv0p)),
			uintptr(unsafe.Pointer(&argvp[0])),
			uintptr(unsafe.Pointer(&envvp[0])))
	}
	runtime_AfterExec()
	return err1
}


text:
package org.apache.olingo.server.tecsvc.processor.queryoptions.options;

import java.util.Calendar;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Locale;

import javax.xml.bind.DatatypeConverter;

import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.EntityCollection;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.search.SearchBinary;
import org.apache.olingo.server.api.uri.queryoption.search.SearchBinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.search.SearchExpression;
import org.apache.olingo.server.api.uri.queryoption.search.SearchTerm;

public class SearchHandler {

  public static void applySearchSystemQueryOption(final SearchOption searchOption, EntityCollection entitySet)
      throws ODataApplicationException {
    if (searchOption != null) {
      SearchExpression se = searchOption.getSearchExpression();
      Iterator<Entity> it = entitySet.getEntities().iterator();
      while (it.hasNext()) {
        boolean keep = false;
        Entity entity = it.next();
        keep = isTrue(se, entity);
        if (!keep) {
          it.remove();
        }
      }
    }
  }

  private static boolean isTrue(final SearchTerm term, final Property property) {
    if (property.isNull()) {
      return false;
    } else if (property.isPrimitive()) {
      if (property.isCollection()) {
        for (final Object primitive : property.asCollection()) {
          final String propertyString = asString(primitive);
          if (propertyString != null && propertyString.contains(term.getSearchTerm())) {
            return true;
          }
        }
        return false;
      } else {
        final String propertyString = asString(property.asPrimitive());
        return propertyString != null && propertyString.contains(term.getSearchTerm());
      }
    } else if (property.isComplex()) {
      if (property.isCollection()) {
        for (final Object member : property.asCollection()) {
          if (isTrue(term, (Property) member)) {
            return true;
          }
        }
        return false;
      } else {
        for (final Property innerProperty : property.asComplex().getValue()) {
          if (isTrue(term, innerProperty)) {
            return true;
          }
        }
        return false;
      }
    } else {
      return false;
    }
  }

  private static String asString(final Object primitive) {
    // TODO: improve 'string' conversion; maybe consider only String properties
    if (primitive instanceof String) {
      return (String) primitive;
    } else if (primitive instanceof Calendar) {
      return DatatypeConverter.printDateTime((Calendar) primitive);
    } else if (primitive instanceof byte[]) {
      return DatatypeConverter.printBase64Binary((byte[]) primitive);
    } else {
      return primitive.toString();
    }
  }

  private static boolean isTrue(final SearchBinary binary, final Entity entity) throws ODataApplicationException {
    SearchExpression left = binary.getLeftOperand();
    SearchExpression right = binary.getRightOperand();
    if (binary.getOperator() == SearchBinaryOperatorKind.AND) {
      if (left.isSearchBinary() && right.isSearchBinary()) {
        return isTrue(left, entity) && isTrue(right, entity);
      } else if (left.isSearchUnary() && right.isSearchBinary()) {
        return isTrue(left, entity) && isTrue(right, entity);
      } else if (left.isSearchBinary() && right.isSearchUnary()) {
        return isTrue(left, entity) && isTrue(right, entity);
      } else if (left.isSearchUnary() && right.isSearchUnary()) {
        return isTrue(left, entity) && isTrue(right, entity);
      }
      ListIterator<Property> properties = entity.getProperties().listIterator();
      boolean leftValid = false;
      boolean rightValid = false;
      while (properties.hasNext()) {
        Property property = properties.next();
        if (!leftValid) {
          leftValid = isTrue(left, property);
        }
        if (!rightValid) {
          rightValid = isTrue(right, property);
        }
      }
      return leftValid && rightValid;
    } else if (binary.getOperator() == SearchBinaryOperatorKind.OR) {
      if (left.isSearchBinary() && right.isSearchBinary()) {
        return isTrue(left, entity) || isTrue(right, entity);
      } else if (left.isSearchUnary() && right.isSearchBinary()) {
        return isTrue(left, entity) || isTrue(right, entity);
      } else if (left.isSearchBinary() && right.isSearchUnary()) {
        return isTrue(left, entity) || isTrue(right, entity);
      } else if (left.isSearchUnary() && right.isSearchUnary()) {
        return isTrue(left, entity) || isTrue(right, entity);
      }
      ListIterator<Property> properties = entity.getProperties().listIterator();
      boolean leftValid = false;
      boolean rightValid = false;
      while (properties.hasNext()) {
        Property property = properties.next();
        if (!leftValid) {
          leftValid = isTrue(left, property);
        }
        if (!rightValid) {
          rightValid = isTrue(right, property);
        }
      }
      return leftValid || rightValid;
    } else {
      throw new ODataApplicationException("Found unknown SearchBinaryOperatorKind: " + binary.getOperator(),
          HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
    }
  }

  private static boolean isTrue(final SearchBinary binary, final Property property) throws ODataApplicationException {
    SearchExpression left = binary.getLeftOperand();
    SearchExpression right = binary.getRightOperand();
    if (binary.getOperator() == SearchBinaryOperatorKind.AND) {
      return isTrue(left, property) && isTrue(right, property);
    } else if (binary.getOperator() == SearchBinaryOperatorKind.OR) {
      return isTrue(left, property) || isTrue(right, property);
    } else {
      throw new ODataApplicationException("Found unknown SearchBinaryOperatorKind: " + binary.getOperator(),
          HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
    }
  }

  private static boolean isTrue(final SearchExpression searchExpression, final Entity entity)
      throws ODataApplicationException {
    if (searchExpression.isSearchBinary()) {
      return isTrue(searchExpression.asSearchBinary(), entity);
    } else if (searchExpression.isSearchTerm()) {
      ListIterator<Property> properties = entity.getProperties().listIterator();
      boolean keep = false;
      while (properties.hasNext()) {
        Property property = properties.next();
        if (!keep) {
          keep = isTrue(searchExpression.asSearchTerm(), property);
        }
      }
      return keep;
    } else if (searchExpression.isSearchUnary()) {
      return !isTrue(searchExpression.asSearchUnary().getOperand(), entity);
    }
    throw new ODataApplicationException("Found unknown SearchExpression: " + searchExpression,
        HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
  }

  private static boolean isTrue(final SearchExpression searchExpression, final Property property)
      throws ODataApplicationException {
    if (searchExpression.isSearchBinary()) {
      return isTrue(searchExpression.asSearchBinary(), property);
    } else if (searchExpression.isSearchTerm()) {
      return isTrue(searchExpression.asSearchTerm(), property);
    } else if (searchExpression.isSearchUnary()) {
      return !isTrue(searchExpression.asSearchUnary().getOperand(), property);
    }
    throw new ODataApplicationException("Found unknown SearchExpression: " + searchExpression,
        HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
  }
}


text:
"""Pose embedding model training with TFRecord inputs."""

from absl import app
from absl import flags
import tensorflow.compat.v1 as tf

from poem.core import common
from poem.core import input_generator
from poem.core import keypoint_profiles
from poem.core import models
from poem.pr_vipe import train_base

tf.disable_v2_behavior()

FLAGS = flags.FLAGS

flags.adopt_module_key_flags(train_base)

flags.DEFINE_string('master', '', 'BNS name of the TensorFlow master to use.')

def main(_):
  train_base.run(
      master=FLAGS.master,
      input_dataset_class=tf.data.TFRecordDataset,
      common_module=common,
      keypoint_profiles_module=keypoint_profiles,
      models_module=models,
      input_example_parser_creator=None,
      keypoint_preprocessor_3d=input_generator.preprocess_keypoints_3d,
      keypoint_distance_config_override={},
      create_model_input_fn_kwargs={},
      embedder_fn_kwargs={})

if __name__ == '__main__':
  app.run(main)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>StrategyRegistrationProviderList (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.jpa.boot.spi

Interface StrategyRegistrationProviderList

public interface StrategyRegistrationProviderList

Method Summary

Methods

Modifier and Type
Method and Description

List<StrategyRegistrationProvider>
getStrategyRegistrationProviders()

Method Detail

getStrategyRegistrationProviders

List<StrategyRegistrationProvider> getStrategyRegistrationProviders()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
require 'rails_helper'
require 'shared_examples_for_failures'

RSpec.describe Api::Users::PasswordsController, type: :request do
  describe 'POST #create' do
    context 'with reset token' do
      let(:user) { create :user, user_trait, :password_reseted }
      let(:user_trait) { :activated }
      let(:payload) do
        {
          user: {
            password: password,
          },
          token: token,
        }
      end

      subject { post api_users_passwords_path, params: payload, as: :json }

      context 'with valid attributes' do
        let(:password) { 'secret' }
        let(:token) { user.reset_password_token }

        before { subject }

        it 'succeeds' do
          expect(response).to have_http_status(:ok)
        end

        it 'matches the users/passwords/create schema' do
          expect(response).to match_response_schema('users/passwords/create')
        end

        it 'sets the reset token to nil' do
          expect(user.reload.reset_password_token).to be_nil
        end

        it 'returns the user' do
          json_user = JSON.parse(response.body)['data']
          expect(json_user['id']).to eq(user.id)
          expect(json_user['attributes']['username']).to eq(user.username)
          expect(json_user['attributes']['email']).to eq(user.email)
        end

        it 'returns a token valid for 1 month' do
          token = JSON.parse(response.body)['meta']['token']
          decoded_token = JsonWebToken.decode(token)
          expect(decoded_token[:exp]).to eq(1.month.from_now.to_i)
        end
      end

      context 'with missing attribute' do
        let(:password) { nil }
        let(:token) { user.reset_password_token }

        before { subject }

        it_behaves_like 'API errors', :unprocessable_entity, errors: [{
          status: '422 Unprocessable Entity',
          code: 'parameter_missing',
          title: 'Parameter is missing',
          detail: 'A parameter is missing or empty but it is required.',
          source: { pointer: '/user/password' },
        }]
      end

      context 'with invalid token' do
        let(:password) { 'secret' }
        let(:token) { 'not-the-token' }

        before { subject }

        it_behaves_like 'API errors', :not_found, errors: [{
          status: '404 Not Found',
          code: 'record_not_found',
          title: 'Record not found',
          detail: 'Record cannot be found, it has been deleted or you may not have access to it.',
          source: { pointer: '/user' },
        }]
      end

      context 'with an inactive user' do
        let(:user_trait) { :inactive }
        let(:password) { 'secret' }
        let(:token) { user.reset_password_token }

        before { subject }

        it_behaves_like 'API errors', :forbidden, errors: [{
          status: '403 Forbidden',
          code: 'user_inactive',
          title: 'User is inactive',
          detail: 'The user did not activate its account.',
          source: { pointer: '/user' },
        }]
      end
    end

    context 'with auth token' do
      let(:user) { create :user, user_trait }
      let(:user_trait) { :activated }
      let(:payload) do
        {
          user: {
            password: password,
          },
        }
      end

      subject do
        post api_users_passwords_path, params: payload,
                                       headers: { 'Authorization': token },
                                       as: :json
      end

      context 'with valid attributes' do
        let(:password) { 'secret' }
        let(:token) { user.token(sudo: true) }

        before { subject }

        it 'succeeds' do
          expect(response).to have_http_status(:ok)
        end

        it 'matches the users/passwords/create schema' do
          expect(response).to match_response_schema('users/passwords/create')
        end

        it 'returns the user' do
          json_user = JSON.parse(response.body)['data']
          expect(json_user['id']).to eq(user.id)
          expect(json_user['attributes']['username']).to eq(user.username)
          expect(json_user['attributes']['email']).to eq(user.email)
        end

        it 'does not return a token' do
          json_response = JSON.parse(response.body)
          expect(json_response['meta']).to be nil
        end
      end

      context 'with missing attribute' do
        let(:password) { nil }
        let(:token) { user.token(sudo: true) }

        before { subject }

        it_behaves_like 'API errors', :unprocessable_entity, errors: [{
          status: '422 Unprocessable Entity',
          code: 'parameter_missing',
          title: 'Parameter is missing',
          detail: 'A parameter is missing or empty but it is required.',
          source: { pointer: '/user/password' },
        }]
      end

      context 'with not sudo token' do
        let(:password) { 'secret' }
        let(:token) { user.token(sudo: false) }

        before { subject }

        it_behaves_like 'API errors', :forbidden, errors: [{
          status: '403 Forbidden',
          code: 'sudo_required',
          title: 'Sudo authorization token is required',
          detail: 'Resource you try to reach requires higher permissions.',
        }]
      end

      context 'with an inactive user' do
        let(:user_trait) { :inactive }
        let(:password) { 'secret' }
        let(:token) { user.token(sudo: true) }

        before { subject }

        it_behaves_like 'API errors', :forbidden, errors: [{
          status: '403 Forbidden',
          code: 'user_inactive',
          title: 'User is inactive',
          detail: 'The user did not activate its account.',
          source: { pointer: '/user' },
        }]
      end
    end

    context 'with no authentication' do
      let(:user) { create :user, :activated }
      let(:payload) do
        {
          user: {
            password: 'secret',
          },
        }
      end

      subject { post api_users_passwords_path, params: payload, as: :json }

      before { subject }

      it_behaves_like 'API errors', :unauthorized, errors: [{
        status: '401 Unauthorized',
        code: 'unauthorized',
        title: 'Authorization is required',
        detail: 'Resource you try to reach requires a valid Authorization token.',
      }]
    end
  end
end