max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,897
/**************************************************************************** * * Copyright 2020 Samsung Electronics All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ #ifndef __EXYNOS_MBOX_IPC_H__ #define __EXYNOS_MBOX_IPC_H__ #ifndef NUM_OF_MBOX_IPC #define NUM_OF_MBOX_IPC 1 #endif #if NUM_OF_MBOX_IPC == 0 #error "wrong NUM_OF_MBOX_IPC" #endif class ExynosMboxIpc { public: struct { unsigned int mbx_ap2cp_msg; unsigned int mbx_cp2ap_msg; unsigned int mbx_ap2cp_status; unsigned int mbx_cp2ap_status; int int_ap2cp_msg; int int_ap2cp_active; int int_ap2cp_status; int irq_cp2ap_msg; int irq_cp2ap_active; int irq_cp2ap_status; int irq_cp2ap_save; int irq_cp2ap_stop_req; int save_irq; int stop_irq; } mbox; public: void mbox_init(void); void mbox_deinit(void); void mbox_sw_reset(void); void mbox_update_value(unsigned int mbx_num, unsigned int msg, unsigned int mask, unsigned int pos); unsigned int mbox_extract_value(unsigned int mbx_num, unsigned int mask, unsigned int pos); void mbox_set_value(unsigned int mbx_num, unsigned int msg); unsigned int mbox_get_value(unsigned int mbx_num); void mbox_ipc_send_command(unsigned int int_num, unsigned short cmd); int mbox_ipc_unregister_handler(unsigned int int_num); int mbox_ipc_register_handler(unsigned int int_num, void (*handler)(void *), void *data); void mbox_set_interrupt(unsigned int int_num); int mbox_attach_isr(); int mbox_detach_isr(); public: ExynosMboxIpc(); ~ExynosMboxIpc(); }; #endif
868
406
package com.kunzisoft.switchdatetime; import android.app.Dialog; import android.content.DialogInterface; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.ImageButton; import android.widget.TextView; import android.widget.ViewAnimator; import androidx.annotation.NonNull; import androidx.annotation.StyleRes; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import com.kunzisoft.switchdatetime.date.OnYearSelectedListener; import com.kunzisoft.switchdatetime.date.widget.ListPickerYearView; import com.kunzisoft.switchdatetime.time.SwitchTimePicker; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A fragment that displays a dialog window with Date and Time who can be selected by switch button * * @author J-Jamet */ public class SwitchDateTimeDialogFragment extends DialogFragment { private static final String TAG = "SwitchDateTimeDialogFrg"; private static final String STATE_DATETIME = "STATE_DATETIME"; private static final String STATE_CURRENT_POSITION = "STATE_CURRENT_POSITION"; private static final int UNDEFINED_POSITION = -1; private Calendar dateTimeCalendar = Calendar.getInstance(); private Calendar minimumDateTime = new GregorianCalendar(1970, 1, 1); private Calendar maximumDateTime = new GregorianCalendar(2200, 1, 1); private TimeZone timeZone = TimeZone.getDefault(); private static final String TAG_LABEL = "LABEL"; private static final String TAG_POSITIVE_BUTTON = "POSITIVE_BUTTON"; private static final String TAG_NEGATIVE_BUTTON = "NEGATIVE_BUTTON"; private static final String TAG_NEUTRAL_BUTTON = "NEUTRAL_BUTTON"; private static final String TAG_DEFAULT_LOCALE = "DEFAULT_LOCALE"; private static final String DEFAULT_LOCALE = "en"; private String mLabel; private String mPositiveButton; private String mDefaultLocale; private String mNegativeButton; private String mNeutralButton; private OnButtonClickListener mListener; private boolean is24HoursMode = false; private boolean highlightAMPMSelection = false; private int startAtPosition = UNDEFINED_POSITION; private int currentPosition = 0; private int alertStyleId; private SimpleDateFormat dayAndMonthSimpleDate; private SimpleDateFormat yearSimpleDate; private ViewAnimator viewSwitcher; private SwitchTimePicker timePicker; private MaterialCalendarView materialCalendarView; private ListPickerYearView listPickerYearView; private TextView monthAndDayHeaderValues; private TextView yearHeaderValues; private boolean blockAnimationIn; private boolean blockAnimationOut; /** * Create a new instance of SwitchDateTimeDialogFragment * * @param label Title of dialog * @param positiveButton Text for positive button * @param negativeButton Text for negative button * @return DialogFragment */ public static SwitchDateTimeDialogFragment newInstance(String label, String positiveButton, String negativeButton) { return newInstance(label, positiveButton, negativeButton, null, DEFAULT_LOCALE); } /** * Create a new instance of SwitchDateTimeDialogFragment * * @param label Title of dialog * @param positiveButton Text for positive button * @param negativeButton Text for negative button * @param defaultLocale Text for default locale * @return DialogFragment */ public static SwitchDateTimeDialogFragment newInstance(String label, String positiveButton, String negativeButton, String neutralButton, String defaultLocale) { SwitchDateTimeDialogFragment switchDateTimeDialogFragment = new SwitchDateTimeDialogFragment(); // Add arguments Bundle args = new Bundle(); args.putString(TAG_LABEL, label); args.putString(TAG_POSITIVE_BUTTON, positiveButton); args.putString(TAG_NEGATIVE_BUTTON, negativeButton); args.putString(TAG_DEFAULT_LOCALE, defaultLocale); if (neutralButton != null) { args.putString(TAG_NEUTRAL_BUTTON, neutralButton); } switchDateTimeDialogFragment.setArguments(args); return switchDateTimeDialogFragment; } /** * Set listener for actions * * @param onButtonClickListener Listener for click */ public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) { this.mListener = onButtonClickListener; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the current datetime and position savedInstanceState.putLong(STATE_DATETIME, dateTimeCalendar.getTimeInMillis()); savedInstanceState.putInt(STATE_CURRENT_POSITION, currentPosition); timePicker.onSaveInstanceState(savedInstanceState); super.onSaveInstanceState(savedInstanceState); } @Override public @NonNull Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); assert getActivity() != null; assert getContext() != null; dateTimeCalendar.setTimeZone(timeZone); if (getArguments() != null) { mLabel = getArguments().getString(TAG_LABEL); mPositiveButton = getArguments().getString(TAG_POSITIVE_BUTTON); mNegativeButton = getArguments().getString(TAG_NEGATIVE_BUTTON); mNeutralButton = getArguments().getString(TAG_NEUTRAL_BUTTON); mDefaultLocale=getArguments().getString(TAG_DEFAULT_LOCALE); } setDefaultLocale(mDefaultLocale); if (savedInstanceState != null) { currentPosition = savedInstanceState.getInt(STATE_CURRENT_POSITION); dateTimeCalendar.setTime(new Date(savedInstanceState.getLong(STATE_DATETIME))); } // Throw exception if default select date isn't between minimumDateTime and maximumDateTime if (dateTimeCalendar.before(minimumDateTime) || dateTimeCalendar.after(maximumDateTime)) throw new RuntimeException("Default date " + dateTimeCalendar.getTime() + " must be between " + minimumDateTime.getTime() + " and " + maximumDateTime.getTime()); LayoutInflater inflater = LayoutInflater.from(getActivity()); getActivity().getTheme().applyStyle(R.style.Theme_SwitchDateTime, false); View dateTimeLayout = inflater.inflate(R.layout.dialog_switch_datetime_picker, (ViewGroup) getActivity().findViewById(R.id.datetime_picker)); // Set label TextView labelView = dateTimeLayout.findViewById(R.id.label); if (mLabel != null) labelView.setText(mLabel); else labelView.setText(getString(R.string.label_datetime_dialog)); // Lock animation for fast clicks blockAnimationIn = false; blockAnimationOut = false; viewSwitcher = dateTimeLayout.findViewById(R.id.dateSwitcher); viewSwitcher.getInAnimation().setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { blockAnimationIn = true; } @Override public void onAnimationEnd(Animation animation) { blockAnimationIn = false; currentPosition = viewSwitcher.getDisplayedChild(); } @Override public void onAnimationRepeat(Animation animation) { } }); viewSwitcher.getOutAnimation().setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { blockAnimationOut = true; } @Override public void onAnimationEnd(Animation animation) { blockAnimationOut = false; } @Override public void onAnimationRepeat(Animation animation) { } }); // Defined the start position if (startAtPosition != UNDEFINED_POSITION) currentPosition = startAtPosition; viewSwitcher.setDisplayedChild(currentPosition); // Button for switch between Hours/Minutes, Calendar and YearList ImageButton buttonSwitch = dateTimeLayout.findViewById(R.id.button_switch); buttonSwitch.setBackgroundColor(Color.TRANSPARENT); buttonSwitch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Utils.animLabelElement(view); if (!(blockAnimationIn && blockAnimationOut)) viewSwitcher.showNext(); } }); // Values header hourOfDay minutes View timeHeaderValues = dateTimeLayout.findViewById(R.id.time_header_values); View.OnClickListener onTimeClickListener = new OnClickHeaderElementListener(HeaderViewsPosition.VIEW_HOURS_AND_MINUTES.getPosition()); timeHeaderValues.setOnClickListener(onTimeClickListener); // Values header month day monthAndDayHeaderValues = dateTimeLayout.findViewById(R.id.date_picker_month_and_day); View.OnClickListener onMonthAndDayClickListener = new OnClickHeaderElementListener(HeaderViewsPosition.VIEW_MONTH_AND_DAY.getPosition()); monthAndDayHeaderValues.setOnClickListener(onMonthAndDayClickListener); // Values header year yearHeaderValues = dateTimeLayout.findViewById(R.id.date_picker_year); View.OnClickListener onYearClickListener = new OnClickHeaderElementListener(HeaderViewsPosition.VIEW_YEAR.getPosition()); yearHeaderValues.setOnClickListener(onYearClickListener); // Init simple date format if null if (dayAndMonthSimpleDate == null) dayAndMonthSimpleDate = new SimpleDateFormat("MMMM dd", Locale.getDefault()); if (yearSimpleDate == null) yearSimpleDate = new SimpleDateFormat("yyyy", Locale.getDefault()); dayAndMonthSimpleDate.setTimeZone(timeZone); yearSimpleDate.setTimeZone(timeZone); // Init headers yearHeaderValues.setText(yearSimpleDate.format(dateTimeCalendar.getTime())); monthAndDayHeaderValues.setText(dayAndMonthSimpleDate.format(dateTimeCalendar.getTime())); // Construct TimePicker SwitchTimePicker.OnTimeSelectedListener onTimeSelectedListener = new SwitchTimePicker.OnTimeSelectedListener() { @Override public void onTimeSelected(int hourOfDayTime, int minuteTime) { dateTimeCalendar.set(Calendar.HOUR_OF_DAY, hourOfDayTime); dateTimeCalendar.set(Calendar.MINUTE, minuteTime); } }; // Init time with saved elements timePicker = new SwitchTimePicker(getContext(), onTimeSelectedListener, savedInstanceState); timePicker.setIs24HourMode(is24HoursMode); timePicker.setHighlightAMPMSelection(highlightAMPMSelection); timePicker.setHourOfDay(dateTimeCalendar.get(Calendar.HOUR_OF_DAY)); timePicker.setMinute(dateTimeCalendar.get(Calendar.MINUTE)); timePicker.onCreateView(dateTimeLayout, savedInstanceState); timePicker.setOnClickTimeListener(onTimeClickListener); // Construct DatePicker materialCalendarView = dateTimeLayout.findViewById(com.kunzisoft.switchdatetime.R.id.datePicker); materialCalendarView.state().edit() .setMinimumDate(CalendarDay.from(minimumDateTime)) .setMaximumDate(CalendarDay.from(maximumDateTime)) .commit(); materialCalendarView.setCurrentDate(dateTimeCalendar); materialCalendarView.setDateSelected(dateTimeCalendar, true); materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() { @Override public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay calendarDay, boolean selected) { dateTimeCalendar.set(Calendar.YEAR, calendarDay.getYear()); dateTimeCalendar.set(Calendar.MONTH, calendarDay.getMonth()); dateTimeCalendar.set(Calendar.DAY_OF_MONTH, calendarDay.getDay()); listPickerYearView.assignCurrentYear(calendarDay.getYear()); yearHeaderValues.setText(yearSimpleDate.format(dateTimeCalendar.getTime())); monthAndDayHeaderValues.setText(dayAndMonthSimpleDate.format(dateTimeCalendar.getTime())); timePicker.clickHour(); } }); materialCalendarView.invalidate(); // Construct YearPicker listPickerYearView = dateTimeLayout.findViewById(R.id.yearPicker); listPickerYearView.setMinYear(minimumDateTime.get(Calendar.YEAR)); listPickerYearView.setMaxYear(maximumDateTime.get(Calendar.YEAR)); listPickerYearView.assignCurrentYear(dateTimeCalendar.get(Calendar.YEAR)); listPickerYearView.setDatePickerListener(new OnYearSelectedListener() { @Override public void onYearSelected(View view, int yearPicker) { dateTimeCalendar.set(Calendar.YEAR, yearPicker); yearHeaderValues.setText(yearSimpleDate.format(dateTimeCalendar.getTime())); // Unfortunately, we have lags here and thread isn't a solution :/ materialCalendarView.setCurrentDate(dateTimeCalendar.getTime().getTime()); materialCalendarView.setDateSelected(dateTimeCalendar, true); // For resolve bug of switch year materialCalendarView.goToNext(); materialCalendarView.goToPrevious(); } }); // Assign buttons AlertDialog.Builder db; if (alertStyleId != 0) { db = new AlertDialog.Builder(getContext(), alertStyleId); } else { db = new AlertDialog.Builder(getContext()); } db.setView(dateTimeLayout); if (mPositiveButton == null) mPositiveButton = getString(android.R.string.ok); db.setPositiveButton(mPositiveButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (mListener != null) { mListener.onPositiveButtonClick(dateTimeCalendar.getTime()); } } }); if (mNegativeButton == null) mNegativeButton = getString(android.R.string.cancel); db.setNegativeButton(mNegativeButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Close dialog if (mListener != null) { mListener.onNegativeButtonClick(dateTimeCalendar.getTime()); } } }); if (mNeutralButton != null) { db.setNeutralButton(mNeutralButton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mListener != null) { if (mListener instanceof OnButtonWithNeutralClickListener) ((OnButtonWithNeutralClickListener) mListener).onNeutralButtonClick(dateTimeCalendar.getTime()); } } }); } return db.create(); } private void setDefaultLocale(String mDefaultLocale) { Locale locale = new Locale(mDefaultLocale); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getResources().updateConfiguration(config,getResources().getDisplayMetrics()); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); startAtPosition = UNDEFINED_POSITION; } /** * Define "Time" as the first view to show */ public void startAtTimeView() { startAtPosition = HeaderViewsPosition.VIEW_HOURS_AND_MINUTES.getPosition(); } /** * Define "Calendar" as the first view to show */ public void startAtCalendarView() { startAtPosition = HeaderViewsPosition.VIEW_MONTH_AND_DAY.getPosition(); } /** * Define "Year" as the first view to show */ public void startAtYearView() { startAtPosition = HeaderViewsPosition.VIEW_YEAR.getPosition(); } /** * Assign default year at start */ public void setDefaultYear(int year) { this.dateTimeCalendar.set(Calendar.YEAR, year); } /** * @deprecated Does not change after launch * {@link #setDefaultYear(int)} */ @Deprecated public void setYear(int year) { setDefaultYear(year); } /** * Assign default month at start (ex: Calendar.DECEMBER) * * @see Calendar */ public void setDefaultMonth(int month) { this.dateTimeCalendar.set(Calendar.MONTH, month); } /** * @deprecated Does not change after launch * {@link #setDefaultMonth(int)} */ @Deprecated public void setMonth(int month) { setDefaultMonth(month); } /** * Assign default day at start */ public void setDefaultDay(int day) { this.dateTimeCalendar.set(Calendar.DAY_OF_MONTH, day); } /** * @deprecated Does not change after launch * {@link #setDefaultDay(int)} */ @Deprecated public void setDay(int day) { setDefaultDay(day); } /** * Assign default hour of day (in 24 hours) at start */ public void setDefaultHourOfDay(int hourOfDay) { this.dateTimeCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay); } /** * @deprecated Does not change after launch and 24 hours format * {@link #setDefaultHourOfDay(int)} */ @Deprecated public void setHour(int hour) { setDefaultHourOfDay(hour); } /** * Assign default minute at start */ public void setDefaultMinute(int minute) { this.dateTimeCalendar.set(Calendar.MINUTE, minute); } /** * @deprecated Does not change after launch * {@link #setDefaultMinute(int)} */ @Deprecated public void setMinute(int minute) { setDefaultMinute(minute); } /** * Get current year */ public int getYear() { return this.dateTimeCalendar.get(Calendar.YEAR); } /** * Get current month as Calendar.MONTH * * @see Calendar */ public int getMonth() { return this.dateTimeCalendar.get(Calendar.MONTH); } /** * Get current day */ public int getDay() { return this.dateTimeCalendar.get(Calendar.DAY_OF_MONTH); } /** * Get current hour of day (hour in 24 hours) */ public int getHourOfDay() { return this.dateTimeCalendar.get(Calendar.HOUR_OF_DAY); } /** * Get current minute */ public int getMinute() { return this.dateTimeCalendar.get(Calendar.MINUTE); } /** * Assign default DateTime at start */ public void setDefaultDateTime(Date date) { this.dateTimeCalendar.setTime(date); } /** * Assign minimum DateTime who can be selected */ public void setMinimumDateTime(Date date) { this.minimumDateTime.setTime(date); } /** * Assign maximum DateTime who can be selected */ public void setMaximumDateTime(Date date) { this.maximumDateTime.setTime(date); } /** * Get minimum DateTime who can be selected */ public Date getMinimumDateTime() { return minimumDateTime.getTime(); } /** * Get maximum DateTime who can be selected */ public Date getMaximumDateTime() { return maximumDateTime.getTime(); } /** * Return default SimpleDateFormat for Month and Day */ public SimpleDateFormat getSimpleDateMonthAndDayFormat() { return dayAndMonthSimpleDate; } /** * Assign a SimpleDateFormat like "d MMM" to show formatted DateTime * * @param simpleDateFormat Format to show month and day */ public void setSimpleDateMonthAndDayFormat(SimpleDateFormat simpleDateFormat) throws SimpleDateMonthAndDayFormatException { Pattern patternMonthAndDay = Pattern.compile("(M|w|W|D|d|F|E|u|\\.|\\s)*"); Matcher matcherMonthAndDay = patternMonthAndDay.matcher(simpleDateFormat.toPattern()); if (!matcherMonthAndDay.matches()) { throw new SimpleDateMonthAndDayFormatException(simpleDateFormat.toPattern() + "isn't allowed for " + patternMonthAndDay.pattern()); } this.dayAndMonthSimpleDate = simpleDateFormat; } /** * Define if time must be in 24 hours mode or in 12 hours, must be applied before "show" */ public void set24HoursMode(boolean is24HoursMode) { this.is24HoursMode = is24HoursMode; } /** * Highlight AM or PM selected, by default AM or PM selected is not highlight. Only works if 24 hours mode is activated * * @param highlightAMPMSelection true to visually highlight selected item */ public void setHighlightAMPMSelection(boolean highlightAMPMSelection) { this.highlightAMPMSelection = highlightAMPMSelection; } /** * Set timezone different from default */ public void setTimeZone(TimeZone timeZone) { if (timeZone != null) { this.timeZone = timeZone; } } /** * Define if the AlertDialog must be styled, must be applied before "show" */ public void setAlertStyle(@StyleRes int styleId) { this.alertStyleId = styleId; } /** * Class exception if SimpleDateFormat contains something else that "d" or/and "M" */ public static class SimpleDateMonthAndDayFormatException extends Exception { SimpleDateMonthAndDayFormatException(String message) { super(message); } } /** * Callback class for assign action on positive and negative button */ public interface OnButtonClickListener { void onPositiveButtonClick(Date date); void onNegativeButtonClick(Date date); } /** * Callback class for assign action on positive, negative and neutral button */ public interface OnButtonWithNeutralClickListener extends OnButtonClickListener { void onNeutralButtonClick(Date date); } /** * Enumeration of header views */ public enum HeaderViewsPosition { VIEW_HOURS_AND_MINUTES(0), VIEW_MONTH_AND_DAY(1), VIEW_YEAR(2); private final int positionSwitch; HeaderViewsPosition(int position) { this.positionSwitch = position; } public int getPosition() { return positionSwitch; } } /** * Listener for click on Header element */ public class OnClickHeaderElementListener implements View.OnClickListener { private final int positionView; OnClickHeaderElementListener(int positionView) { this.positionView = positionView; } @Override public void onClick(View view) { Utils.animLabelElement(view); if (viewSwitcher.getDisplayedChild() != positionView) viewSwitcher.setDisplayedChild(positionView); startAtPosition = positionView; } } }
9,609
1,872
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. # COM Interop tests for IronPython from iptest.assert_util import skiptest skiptest("win32") from iptest.cominterop_util import * from System import Type, Activator, Guid import clr dlrcomlib_guid = Guid("a50d2773-4b1b-428a-b5b4-9300e1b50484") def test_load_typelib(): for x in [dlrcomlib_guid, Activator.CreateInstance(Type.GetTypeFromProgID("DlrComLibrary.ParamsInRetval"))]: lib = clr.LoadTypeLibrary(x) #ComTypeLibInfo Members AreEqual(lib.Guid, dlrcomlib_guid) AreEqual(lib.Name, "DlrComLibraryLib") AreEqual(lib.VersionMajor, 1) AreEqual(lib.VersionMinor, 0) Assert("DlrComLibraryLib" in dir(lib)) #ComTypeLibDesc Members dlrComLib = lib.DlrComLibraryLib Assert("DlrComServer" in dir(lib.DlrComLibraryLib)) Assert("IDlrComServer" not in dir(lib.DlrComLibraryLib)) #ComTypeClassDesc Members dlrComServer = lib.DlrComLibraryLib.DlrComServer AreEqual(dlrComServer.TypeLib, lib.DlrComLibraryLib) AreEqual(dlrComServer.TypeName, "DlrComServer") AreEqual(str(dlrComServer.Kind), "Class") #Create an instance of the class and access members. obj = dlrComServer.CreateInstance() Assert("__ComObject" in str(obj.__class__)) AreEqual(12345, obj.SumArgs(1,2,3,4,5)) #Complete the circle back to the lib AreEqual(clr.LoadTypeLibrary(obj).Guid, lib.Guid) def test_import_typelib(): for x in [dlrcomlib_guid, Activator.CreateInstance(Type.GetTypeFromProgID("DlrComLibrary.ParamsInRetval"))]: clr.AddReferenceToTypeLibrary(x) try: DlrComLibrary.__class__ except NameError: pass else: Fail("Namespace already exists") import DlrComLibraryLib from DlrComLibraryLib import DlrComServer Assert("DlrComServer" in dir(DlrComLibraryLib)) #Create an instance of the class and access members. obj = DlrComServer.CreateInstance() Assert("__ComObject" in str(obj.__class__)) AreEqual(12345, obj.SumArgs(1,2,3,4,5)) del DlrComServer del DlrComLibraryLib def test_negative(): AssertError(ValueError, clr.LoadTypeLibrary, "DlrComLibrary.DlrComServer") AssertError(ValueError, clr.LoadTypeLibrary, 42) AssertError(EnvironmentError, clr.LoadTypeLibrary, Guid.NewGuid()) run_test(__name__)
1,247
1,826
<filename>flexmark-util-sequence/src/main/java/com/vladsch/flexmark/util/sequence/ReplacedTextMapper.java package com.vladsch.flexmark.util.sequence; import java.util.ArrayList; /** * Class which tracks text replacements to provide original offset from modified offset. * <p> * This is needed when the original based sequence needs to be un-escaped but offsets to original escaped text * are needed. * <p> * These replacements can be nested so that you can track replacements of replaced text. * To add nested replacements use startNestedReplacement() * <p> * when isModified() returns true then the text mapper is already used and nested replacements need to be applied */ // REFACTOR: to use segment builder with ISegmentBuilder.F_INCLUDE_ANCHORS and use segment information to find original offsets public class ReplacedTextMapper { private ReplacedTextMapper parent; private BasedSequence original; private ArrayList<ReplacedTextRegion> regions = new ArrayList<>(); private ArrayList<BasedSequence> replacedSegments = new ArrayList<>(); private int replacedLength = 0; private BasedSequence replacedSequence = null; public ReplacedTextMapper(BasedSequence original) { this.original = original; this.parent = null; } private ReplacedTextMapper(ReplacedTextMapper other) { this.parent = other.parent; this.original = other.original; this.regions = other.regions; this.replacedSegments = other.replacedSegments; this.replacedLength = other.replacedLength; this.replacedSequence = other.getReplacedSequence(); } public void startNestedReplacement(BasedSequence sequence) { assert sequence.equals(this.getReplacedSequence()); // create parent from our data and re-initialize this.parent = new ReplacedTextMapper(this); this.original = sequence; this.regions = new ArrayList<>(); this.replacedSegments = new ArrayList<>(); this.replacedLength = 0; this.replacedSequence = null; } public boolean isModified() { return replacedLength > 0; } public boolean isFinalized() { return replacedSequence != null; } private void finalizeMods() { if (replacedSequence == null) { replacedSequence = replacedSegments.isEmpty() ? BasedSequence.NULL : SegmentedSequence.create(original, replacedSegments); } } public ReplacedTextMapper getParent() { return parent; } public void addReplacedText(int startIndex, int endIndex, BasedSequence replacedSequence) { if (isFinalized()) throw new IllegalStateException("Cannot modify finalized ReplacedTextMapper"); regions.add(new ReplacedTextRegion(original.subSequence(startIndex, endIndex).getSourceRange(), Range.of(startIndex, endIndex), Range.of(replacedLength, replacedLength + replacedSequence.length()))); replacedLength += replacedSequence.length(); replacedSegments.add(replacedSequence); } public void addOriginalText(int startIndex, int endIndex) { if (isFinalized()) throw new IllegalStateException("Cannot modify finalized ReplacedTextMapper"); if (startIndex < endIndex) { BasedSequence originalSegment = original.subSequence(startIndex, endIndex); regions.add(new ReplacedTextRegion(originalSegment.getSourceRange(), Range.of(startIndex, endIndex), Range.of(replacedLength, replacedLength + originalSegment.length()))); replacedLength += originalSegment.length(); replacedSegments.add(originalSegment); } } public ArrayList<ReplacedTextRegion> getRegions() { finalizeMods(); return regions; } public ArrayList<BasedSequence> getReplacedSegments() { finalizeMods(); return replacedSegments; } public BasedSequence getReplacedSequence() { finalizeMods(); return replacedSequence; } public int getReplacedLength() { finalizeMods(); return replacedLength; } private int parentOriginalOffset(int originalIndex) { return parent != null ? parent.originalOffset(originalIndex) : originalIndex; } public int originalOffset(int replacedIndex) { finalizeMods(); if (regions.isEmpty()) return parentOriginalOffset(replacedIndex); if (replacedIndex == replacedLength) return parentOriginalOffset(original.length()); int originalIndex = replacedIndex; for (ReplacedTextRegion region : regions) { if (region.containsReplacedIndex(replacedIndex)) { originalIndex = region.getOriginalRange().getStart() + replacedIndex - region.getReplacedRange().getStart(); if (originalIndex > region.getOriginalRange().getEnd()) { originalIndex = region.getOriginalRange().getEnd(); } break; } } return parentOriginalOffset(originalIndex); } }
1,775
310
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.android.gui.settings.notification; import android.content.*; import android.os.*; import android.view.*; import android.widget.*; import net.java.sip.communicator.service.notification.*; import net.java.sip.communicator.service.notification.event.*; import net.java.sip.communicator.util.*; import org.jitsi.*; import org.jitsi.android.gui.*; import org.jitsi.service.osgi.*; import org.jitsi.service.resources.*; import java.util.*; /** * The <tt>Activity</tt> lists all notification events. When user selects one of * them the details screen is opened. * * @author <NAME> */ public class NotificationSettings extends OSGiActivity { /** * Notifications adapter. */ private NotificationsAdapter adapter; /** * Notification service instance. */ private NotificationService notificationService; /** * {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.notificationService = ServiceUtils.getService(AndroidGUIActivator.bundleContext, NotificationService.class); setContentView(R.layout.list_layout); } /** * {@inheritDoc} */ @Override protected void onResume() { super.onResume(); // Refresh the list each time is displayed adapter = new NotificationsAdapter(); ListView listView = (ListView) findViewById(R.id.list); listView.setAdapter(adapter); // And start listening for updates notificationService.addNotificationChangeListener(adapter); } /** * {@inheritDoc} */ @Override protected void onPause() { super.onPause(); // Do not listen for changes when paused notificationService.removeNotificationChangeListener(adapter); adapter = null; } /** * Adapter lists all notification events. */ class NotificationsAdapter extends BaseAdapter implements NotificationChangeListener { /** * List of event types */ private final ArrayList<String> events; /** * Resources service instance */ private final ResourceManagementService rms; /** * Creates new instance of <tt>NotificationsAdapter</tt>. */ NotificationsAdapter() { Iterator<String> eventsIter = notificationService.getRegisteredEvents().iterator(); this.events = new ArrayList<String>(); while (eventsIter.hasNext()) { events.add(eventsIter.next()); } this.rms = AndroidGUIActivator.getResourcesService(); } /** * {@inheritDoc} */ @Override public int getCount() { return events.size(); } /** * {@inheritDoc} */ @Override public Object getItem(int position) { return rms.getI18NString("plugin.notificationconfig.event." + events.get(position)); } /** * {@inheritDoc} */ @Override public long getItemId(int position) { return position; } /** * {@inheritDoc} */ @Override public View getView(final int position, View convertView, ViewGroup parent) { View row = getLayoutInflater().inflate(R.layout.notification_item, parent, false); row.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent details = NotificationDetails.getIntent( NotificationSettings.this, events.get(position)); startActivity(details); } }); TextView textView = (TextView)row.findViewById(R.id.text1); textView.setText((String)getItem(position)); CompoundButton enableBtn = (CompoundButton) row.findViewById(R.id.enable); enableBtn.setChecked( notificationService.isActive(events.get(position))); enableBtn.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { notificationService.setActive(events.get(position), isChecked); } }); return row; } /** * {@inheritDoc} */ @Override public void eventTypeAdded(final NotificationEventTypeEvent event) { runOnUiThread(new Runnable() { @Override public void run() { events.add(event.getEventType()); notifyDataSetChanged(); } }); } /** * {@inheritDoc} */ @Override public void eventTypeRemoved(final NotificationEventTypeEvent event) { runOnUiThread(new Runnable() { @Override public void run() { events.remove(event.getEventType()); notifyDataSetChanged(); } }); } /** * {@inheritDoc} */ @Override public void actionAdded(NotificationActionTypeEvent event){ } /** * {@inheritDoc} */ @Override public void actionRemoved(NotificationActionTypeEvent event){ } /** * {@inheritDoc} */ @Override public void actionChanged(NotificationActionTypeEvent event){ } } }
3,340
608
import time import serial def readTime(serialPort): '''Reads the time from the AVR over the serial port''' serialPort.flushInput() character = "" while(not character == "\n"): # loop until see end of line character = serialPort.read(1) ## The time string looks something like '011:045:023\r\n' timeString = serialPort.read(13) hms = timeString.split(":") hms = [int(x) for x in hms] # make hour, minute, second numeric return(hms) def setTime(serialPort, hours, minutes, seconds): '''Sends the time over the serial port''' serialPort.flushOutput() serialPort.write("S") time.sleep(0.1) # delay while AVR sends serialPort.write(str(hours) + "\r") time.sleep(0.2) # delay while AVR sends serialPort.write(str(minutes) + "\r") time.sleep(0.2) # delay while AVR sends serialPort.write(str(seconds) + "\r") def setTimeNow(serialPort): '''Sets the AVR clock to the current time''' hours, minutes, seconds = time.localtime()[3:6] setTime(serialPort, hours, minutes, seconds) return(time.time()) def calculateTimeDelay(serialPort): '''Gets AVR time and subtracts off actual (computer) time''' avrHMS = readTime(serialPort) hms = time.localtime()[3:6] hmsDifference = [x - y for x,y in zip(avrHMS, hms)] out = "AVR is fast by: {x[0]} hours, {x[1]} minutes, and {x[2]} seconds" print out.format(x=hmsDifference) return(hmsDifference) def calculateTimeDrift(serialPort, startTime): '''Calculates the ratio to multiply OVERFLOWS_PER_SECOND given a start time and current error''' h, m, s = calculateTimeDelay(serialPort) driftSeconds = 60*60*h + 60*m + s elapsed = time.time() - startTime print "After {:.0f} seconds, ".format(elapsed) return (driftSeconds / elapsed + 1) if __name__ == "__main__": ## Set time automatically, recording start time, ## then periodically calculate multiplication factor OVERFLOWS_PER_SECOND = 31250 # set this to equal the value in your code SLEEP_TIME = 10 ratioLog = [] s = serial.Serial("/dev/ttyUSB0", 9600, timeout=5) print "Setting time to current time...." ratio = 0 while not ratio == 1: # make sure starting time is right on startTime = setTimeNow(s) ratio = calculateTimeDrift(s, startTime) ## Note: you can either leave this running or ## you can re-run calculateTimeDrift() at any time in the future, ## as long as you don't overwrite the original startTime while(True): ratio = calculateTimeDrift(s, startTime) ratioLog.append([time.time()-startTime, ratio]) newOverflow = int(OVERFLOWS_PER_SECOND * ratio) print "OVERFLOWS_PER_SECOND should be {}\n\n".format(newOverflow) time.sleep(SLEEP_TIME) ## As you leave this routine running, you should see it bounce ## around a lot in the beginning and then settle down after ## running a few hours. Ironically, it'll converge to a good ## number faster if it's initially very out of sync. (If it ## drifts faster, you can figure out the drift rate sooner.) ## Leave it running for 24 hours and you'll get one-second-per-day ## accuracy.
1,273
945
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * <EMAIL>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <string> #include "H5Include.h" #include "H5Exception.h" #include "H5IdComponent.h" #include "H5DataSpace.h" #include "H5PropList.h" #include "H5LaccProp.h" #include "H5DaccProp.h" namespace H5 { #ifndef DOXYGEN_SHOULD_SKIP_THIS // This DOXYGEN_SHOULD_SKIP_THIS block is a work-around approach to control // the order of creation and deletion of the global constants. See Design Notes // in "H5PredType.cpp" for information. // Initialize a pointer for the constant DSetAccPropList* DSetAccPropList::DEFAULT_ = 0; //-------------------------------------------------------------------------- // Function: DSetAccPropList::getConstant // Purpose: Creates a DSetAccPropList object representing the HDF5 // constant H5P_DATASET_ACCESS, pointed to by // DSetAccPropList::DEFAULT_ // exception H5::PropListIException // Description // If DSetAccPropList::DEFAULT_ already points to an allocated // object, throw a PropListIException. This scenario should // not happen. // Programmer <NAME> - 2015 //-------------------------------------------------------------------------- DSetAccPropList* DSetAccPropList::getConstant() { // Tell the C library not to clean up, H5Library::termH5cpp will call // H5close - more dependency if use H5Library::dontAtExit() if (!IdComponent::H5dontAtexit_called) { (void) H5dont_atexit(); IdComponent::H5dontAtexit_called = true; } // If the constant pointer is not allocated, allocate it. Otherwise, // throw because it shouldn't be. if (DEFAULT_ == 0) DEFAULT_ = new DSetAccPropList(H5P_DATASET_ACCESS); else throw PropListIException("DSetAccPropList::getConstant", "DSetAccPropList::getConstant is being invoked on an allocated DEFAULT_"); return(DEFAULT_); } //-------------------------------------------------------------------------- // Function: DSetAccPropList::deleteConstants // Purpose: Deletes the constant object that DSetAccPropList::DEFAULT_ // points to. // Programmer <NAME> - 2015 //-------------------------------------------------------------------------- void DSetAccPropList::deleteConstants() { if (DEFAULT_ != 0) delete DEFAULT_; } //-------------------------------------------------------------------------- // Purpose Constant for dataset creation default property //-------------------------------------------------------------------------- const DSetAccPropList& DSetAccPropList::DEFAULT = *getConstant(); #endif // DOXYGEN_SHOULD_SKIP_THIS //-------------------------------------------------------------------------- // Function: DSetAccPropList default constructor ///\brief Default constructor: creates a stub dataset creation property list // Programmer <NAME> - 2000 //-------------------------------------------------------------------------- DSetAccPropList::DSetAccPropList() : LinkAccPropList(H5P_DATASET_ACCESS) {} //-------------------------------------------------------------------------- // Function: DSetAccPropList copy constructor ///\brief Copy constructor: same HDF5 object as \a original /// DSetAccPropList object // Programmer <NAME> - 2000 //-------------------------------------------------------------------------- DSetAccPropList::DSetAccPropList(const DSetAccPropList& orig) : LinkAccPropList(orig) {} //-------------------------------------------------------------------------- // Function: DSetAccPropList overloaded constructor ///\brief Creates a DSetAccPropList object using the id of an /// existing dataset creation property list. // Programmer <NAME> - 2000 //-------------------------------------------------------------------------- DSetAccPropList::DSetAccPropList(const hid_t plist_id) : LinkAccPropList(plist_id) {} //-------------------------------------------------------------------------- // Function: DSetAccPropList::setChunkCache ///\brief Sets the raw data chunk cache parameters. ///\param rdcc_nslots - IN: Number of chunk slots in the raw data chunk cache ///\param rdcc_nbytes - IN: Total size of the raw data chunk cache ///\param rdcc_w0 - IN: The chunk preemption policy for this dataset ///\exception H5::PropListIException ///\par Description /// The raw data chunk cache parameters includes the number of /// objects in the meta data cache and the maximum number of /// chunks and bytes in the raw data chunk cache. Once set, /// these values will override the values in the file access /// property list. /// /// For information, please refer to the H5Pset_chunk_cache API in /// the HDF5 C Reference Manual. // July 2018 //-------------------------------------------------------------------------- void DSetAccPropList::setChunkCache(size_t rdcc_nslots, size_t rdcc_nbytes, double rdcc_w0) const { herr_t ret_value = H5Pset_chunk_cache(id, rdcc_nslots, rdcc_nbytes, rdcc_w0); if (ret_value < 0) { throw PropListIException("DSetAccPropList::setChunkCache", "H5Pset_chunk_cache failed"); } } //-------------------------------------------------------------------------- // Function: DSetAccPropList::getChunkCache ///\brief Retrieves the raw data chunk cache parameters. ///\param rdcc_nslots - OUT: Number of chunk slots in the raw data chunk cache ///\param rdcc_nbytes - OUT: Total size of the raw data chunk cache ///\param rdcc_w0 - OUT: The chunk preemption policy for this dataset ///\exception H5::PropListIException ///\par Description /// For information, please refer to the H5Pget_chunk_cache API in /// the HDF5 C Reference Manual. // July 2018 //-------------------------------------------------------------------------- void DSetAccPropList::getChunkCache(size_t &rdcc_nslots, size_t &rdcc_nbytes, double &rdcc_w0) const { herr_t ret_value = H5Pget_chunk_cache(id, &rdcc_nslots, &rdcc_nbytes, &rdcc_w0); if (ret_value < 0) { throw PropListIException("DSetAccPropList::getChunkCache", "H5Pget_chunk_cache failed"); } } //-------------------------------------------------------------------------- // Function: DSetAccPropList destructor ///\brief Noop destructor. // Programmer <NAME> - 2000 //-------------------------------------------------------------------------- DSetAccPropList::~DSetAccPropList() {} } // end namespace
2,553
3,094
import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader import torchvision.datasets as datasets from tqdm import tqdm device = torch.device("cuda" if torch.cuda.is_available() else "cpu") train_set = datasets.CIFAR10(root="ds/", transform=transforms.ToTensor(), download=True) train_loader = DataLoader(dataset=train_set, batch_size=64, shuffle=True) def get_mean_std(loader): # var[X] = E[X**2] - E[X]**2 channels_sum, channels_sqrd_sum, num_batches = 0, 0, 0 for data, _ in tqdm(loader): channels_sum += torch.mean(data, dim=[0, 2, 3]) channels_sqrd_sum += torch.mean(data ** 2, dim=[0, 2, 3]) num_batches += 1 mean = channels_sum / num_batches std = (channels_sqrd_sum / num_batches - mean ** 2) ** 0.5 return mean, std mean, std = get_mean_std(train_loader) print(mean) print(std)
343
10,225
package io.quarkus.it.spring; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Scope("prototype") public @interface CustomPrototype { }
135
316
package com.mapbox.mapboxsdk.offline; import androidx.annotation.Keep; /** * A region's status includes its active/inactive state as well as counts * of the number of resources that have completed downloading, their total * size in bytes, and the total number of resources that are required. * <p> * Note that the total required size in bytes is not currently available. A * future API release may provide an estimate of this number. * </p> */ public class OfflineRegionStatus { @OfflineRegion.DownloadState private int downloadState; /** * The number of resources (inclusive of tiles) that have been fully downloaded * and are ready for offline access. */ private final long completedResourceCount; /** * The cumulative size, in bytes, of all resources (inclusive of tiles) that have * been fully downloaded. */ private final long completedResourceSize; /** * The number of tiles that have been fully downloaded and are ready for * offline access. */ private final long completedTileCount; /** * The cumulative size, in bytes, of all tiles that have been fully downloaded. */ private final long completedTileSize; /** * The number of resources that are known to be required for this region. See the * documentation for `requiredResourceCountIsPrecise` for an important caveat * about this number. */ private final long requiredResourceCount; /** * This property is true when the value of requiredResourceCount is a precise * count of the number of required resources, and false when it is merely a lower * bound. * <p> * Specifically, it is false during early phases of an offline download. Once * style and tile sources have been downloaded, it is possible to calculate the * precise number of required resources, at which point it is set to true. * </p> */ private final boolean requiredResourceCountIsPrecise; /* * Use setObserver(OfflineRegionObserver observer) to obtain a OfflineRegionStatus object. * * For JNI use only */ @Keep private OfflineRegionStatus(int downloadState, long completedResourceCount, long completedResourceSize, long completedTileCount, long completedTileSize, long requiredResourceCount, boolean requiredResourceCountIsPrecise) { this.downloadState = downloadState; this.completedResourceCount = completedResourceCount; this.completedResourceSize = completedResourceSize; this.completedTileCount = completedTileCount; this.completedTileSize = completedTileSize; this.requiredResourceCount = requiredResourceCount; this.requiredResourceCountIsPrecise = requiredResourceCountIsPrecise; } /** * Validates if the region download has completed * * @return true if download is complete, false if not */ public boolean isComplete() { return completedResourceCount >= requiredResourceCount; } /** * Returns the download state. * <p> * State is defined as * </p> * <ul> * <li>{@link OfflineRegion#STATE_ACTIVE}</li> * <li>{@link OfflineRegion#STATE_INACTIVE}</li> * </ul> * * @return the download state. */ @OfflineRegion.DownloadState public int getDownloadState() { return downloadState; } /** * Get the number of resources (inclusive of tiles) that have been fully downloaded * and are ready for offline access. * * @return the amount of resources that have finished downloading. */ public long getCompletedResourceCount() { return completedResourceCount; } /** * The cumulative size, in bytes, of all resources (inclusive of tiles) that have * been fully downloaded. * * @return the size of the resources that have finished downloading */ public long getCompletedResourceSize() { return completedResourceSize; } /** * Get the number of tiles that have been fully downloaded and are ready for * offline access. * * @return the completed tile count */ public long getCompletedTileCount() { return completedTileCount; } /** * Get the cumulative size, in bytes, of all tiles that have been fully downloaded. * * @return the completed tile size */ public long getCompletedTileSize() { return completedTileSize; } /** * Get the number of resources that are known to be required for this region. See the * documentation for `requiredResourceCountIsPrecise` for an important caveat * about this number. * * @return the amount of resources that are required */ public long getRequiredResourceCount() { return requiredResourceCount; } /** * Returns when the value of requiredResourceCount is a precise * count of the number of required resources, and false when it is merely a lower * bound. * <p> * Specifically, it is false during early phases of an offline download. Once * style and tile sources have been downloaded, it is possible to calculate the * precise number of required resources, at which point it is set to true. * </p> * * @return True if the required resource count is precise, false if not */ public boolean isRequiredResourceCountPrecise() { return requiredResourceCountIsPrecise; } }
1,542
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Naming { class ServiceGroupDescriptor { public: ServiceGroupDescriptor(); void ToPublicApi(__in Common::ScopedHeap & heap, __out FABRIC_SERVICE_GROUP_DESCRIPTION & serviceGroupDescription) const; static Common::ErrorCode Create(__in PartitionedServiceDescriptor const & serviceDescription, __out ServiceGroupDescriptor &); Common::ErrorCode GetServiceDescriptorForMember(__in Common::NamingUri const & name, __out PartitionedServiceDescriptor & memberServiceDescription); Naming::PartitionedServiceDescriptor get_PartitionedServiceDescriptor() { return serviceDescriptor_; } ServiceModel::CServiceGroupDescription get_CServiceGroupDescription() { return serviceGroupDescription_; } private: ServiceModel::CServiceGroupDescription serviceGroupDescription_; PartitionedServiceDescriptor serviceDescriptor_; }; }
344
471
<filename>corehq/ex-submodules/casexml/apps/phone/data_providers/case/load_testing.py from copy import deepcopy from casexml.apps.phone.data_providers.case.utils import CaseSyncUpdate from casexml.apps.phone.xml import get_case_element, tostring from corehq.apps.app_manager.const import USERCASE_TYPE def transform_loadtest_update(update, factor): """ Returns a new CaseSyncUpdate object (from an existing one) with all the case IDs and names mapped to have the factor appended. """ def _map_id(id, count): return '{}-{}'.format(id, count) case = deepcopy(update.case) case.set_case_id(_map_id(case.case_id, factor)) for index in case.live_indices: index.referenced_id = _map_id(index.referenced_id, factor) case.name = '{} ({})'.format(case.name, factor) return CaseSyncUpdate(case, update.sync_token, required_updates=update.required_updates) def get_xml_for_response(update, restore_state): """ Adds the XML from the case_update to the restore response. If factor is > 1 it will append that many updates to the response for load testing purposes. """ current_count = 0 original_update = update elements = [] while current_count < restore_state.loadtest_factor: element = get_case_element(update.case, update.required_updates, restore_state.version) elements.append(tostring(element)) current_count += 1 if current_count < restore_state.loadtest_factor: update = transform_loadtest_update(original_update, current_count) # only add user case on the first iteration if original_update.case.type == USERCASE_TYPE: break return elements
610
5,169
{ "name": "libjingle_peerconnection", "version": "6798.3", "summary": "An iOS WebRTC demo application hosted on App Engine. Builds by Pristine.io", "description": " The WebRTC native APIs are implemented based on the following [WebRTC spec.](http://dev.w3.org/2011/webrtc/editor/webrtc.html) \n\n The code that implements WebRTC native APIs (including the Stream and the PeerConnection APIs) are available in [libjingle](https://code.google.com/p/libjingle/source/browse/#svn%2Ftrunk%2Ftalk%2Fapp%2Fwebrtc). A [sample client application](https://code.google.com/p/libjingle/source/browse/#svn%2Ftrunk%2Ftalk%2Fexamples%2Fpeerconnection%2Fclient) is also provided there. \n\n The target audience of this document are those who want to use WebRTC Native APIs to develop native RTC applications.\n", "homepage": "https://bitbucket.org/pristineio/libjingle_peerconnection.git", "screenshots": [ "https://bytebucket.org/pristineio/libjingle_peerconnection/raw/7c9cd5c64496148b7b268445ad9722aca376b7c9/iphone-dev.png", "https://bytebucket.org/pristineio/libjingle_peerconnection/raw/7c9cd5c64496148b7b268445ad9722aca376b7c9/ipad-sim.png" ], "license": "http://www.webrtc.org/license-rights/license", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://bitbucket.org/pristineio/libjingle_peerconnection.git", "tag": "6798.3" }, "social_media_url": "https://twitter.com/bot_the_builder", "platforms": { "ios": "7.0" }, "requires_arc": true, "source_files": "Pod/Classes", "public_header_files": "Pod/Classes/**/*.h", "frameworks": [ "AVFoundation", "CoreGraphics", "CoreMedia", "GLKit", "UIKit" ], "libraries": [ "c", "sqlite3", "stdc++.6.0.9" ], "vendored_libraries": "Libraries/libWebRTC-6798-armv7-ia32-Debug.a" }
786
918
<reponame>mvachhani/incubator-gobblin<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.data.management.copy.replication; import java.util.List; import com.google.common.base.Optional; /** * Provide the basic optimizer implementation in pull mode. The subclass should override the {@link #getOptimizedCopyRoute(List)} function * @author mitu * */ public class CopyRouteGeneratorOptimizer extends CopyRouteGeneratorBase { @Override public Optional<CopyRoute> getPullRoute(ReplicationConfiguration rc, EndPoint copyTo) { if (rc.getCopyMode() == ReplicationCopyMode.PUSH) return Optional.absent(); DataFlowTopology topology = rc.getDataFlowToplogy(); List<DataFlowTopology.DataFlowPath> paths = topology.getDataFlowPaths(); for (DataFlowTopology.DataFlowPath p : paths) { List<CopyRoute> routes = p.getCopyRoutes(); if (routes.isEmpty()) { continue; } // All routes under a path pointing to the same copyTo (replica) if (routes.get(0).getCopyTo().equals(copyTo)) { return getOptimizedCopyRoute(routes); } } return Optional.absent(); } public Optional<CopyRoute> getOptimizedCopyRoute(List<CopyRoute> routes) { return Optional.absent(); } }
631
2,181
<reponame>yaplej/bro<filename>src/script_opt/CPP/InitsInfo.h<gh_stars>1000+ // See the file "COPYING" in the main distribution directory for copyright. // Classes for tracking information for initializing C++ values used by the // generated code. // Initialization is probably the most complex part of the entire compiler, // as there are a lot of considerations. There are two basic parts: (1) the // generation of C++ code for doing run-time initialization, which is covered // by the classes in this file, and (2) the execution of that code to do the // actual initialization, which is covered by the classes in RuntimeInits.h. // // There are two fundamental types of initialization, those that create values // (such as Zeek Type and Val objects) that will be used during the execution // of compiled scripts, and those that perform actions such as registering // the presence of a global or a lambda. In addition, for the former (values // used at run-time), some are grouped together into vectors, with the compiled // code using a hardwired index to get to a particular value; and some have // standalone globals (for example, one for each BiF that a compiled script // may call). // // For each of these types of initialization, our general approach is to a // class that manages a single instance of that type, and an an object that // manages all of those instances collectively. The latter object will, for // example, attend to determining the offset into the run-time vector associated // with a particular initialized value. // // An additional complexity is that often the initialization of a particular // value will depend on *other* values having already been initialized. For // example, a record type might have a field that is a table, and thus the // type corresponding to the table needs to be available before we can create // the record type. However, the table might have a set of attributes // associated with it, which have to be initialized before we can create the // table type, those in turn requiring the initialization of each of the // individual attributes in the set. One of those attributes might specify // a &default function for the table, requiring initializing *that* value // (not just the type, but also a way to refer to the particular instance of // the function) before initializing the attribute, etc. Worse, record types // can be *indirectly recursive*, which requires first initializing a "stub" // for the record type before doing the final initialization. // // The general strategy for dealing with all of these dependencies is to // compute for each initialization its "cohort". An initialization that // doesn't depend on any others is in cohort 0. An initialization X that // depends on an initialization Y will have cohort(X) = cohort(Y) + 1; or, // in general, one more than the highest cohort of any initialization it // depends on. (We cut a corner in that, due to how initialization information // is constructed, if X and Y are for the same type of object then we can // safely use cohort(X) = cohort(Y).) We then execute run-time initialization // in waves, one cohort at a time. // // Because C++ compilers can struggle when trying to optimize large quantities // of code - clang in particular could take many CPU *hours* back when our // compiler just generated C++ code snippets for each initialization - rather // than producing code that directly executes each given initialization, we // instead employ a table-driven approach. The C++ initializers for the // tables contain simple values - often just vectors of integers - that compile // quickly. At run-time we then spin through the elements of the tables (one // cohort at a time) to obtain the information needed to initialize any given // item. // // Many forms of initialization are specified in terms of indices into globals // that hold items of various types. Thus, the most common initialization // information is a vector of integers/indices. These data structures can // be recursive, too, namely we sometimes associate an index with a vector // of integers/indices and then we can track multiple such vectors using // another vector of integers/indices. #include "zeek/File.h" #include "zeek/Val.h" #include "zeek/script_opt/ProfileFunc.h" #pragma once namespace zeek::detail { class CPPCompile; // Abstract class for tracking information about a single initialization item. class CPP_InitInfo; // Abstract class for tracking information about a collection of initialization // items. class CPP_InitsInfo { public: CPP_InitsInfo(std::string _tag, std::string type) : tag(std::move(_tag)) { base_name = std::string("CPP__") + tag + "__"; CPP_type = tag + type; } virtual ~CPP_InitsInfo() { } // Returns the name of the C++ global that will hold the items' values // at run-time, once initialized. These are all vectors, for which // the generated code accesses a particular item by indexing the vector. const std::string& InitsName() const { return base_name; } // Returns the name of the C++ global used to hold the table we employ // for table-driven initialization. std::string InitializersName() const { return base_name + "init"; } // Returns the "name" of the given element in the run-time vector // associated with this collection of initialization items. It's not // really a name but rather a vector index, so for example Name(12) // might return "CPP__Pattern__[12]", but we use the term Name because // the representation used to be individualized globals, such as // "CPP__Pattern__12". std::string Name(int index) const; // Returns the name that will correspond to the next item added to // this set. std::string NextName() const { return Name(size); } // The largest initialization cohort of any item in this collection. int MaxCohort() const { return static_cast<int>(instances.size()) - 1; } // Returns the number of initializations in this collection that below // to the given cohort c. int CohortSize(int c) const { return c > MaxCohort() ? 0 : instances[c].size(); } // Returns the C++ type associated with this collection's run-time vector. // This might be, for example, "PatternVal" const std::string& CPPType() const { return CPP_type; } // Sets the associated C++ type. virtual void SetCPPType(std::string ct) { CPP_type = std::move(ct); } // Returns the type associated with the table used for initialization // (i.e., this is the type of the global returned by InitializersName()). std::string InitsType() const { return inits_type; } // Add a new initialization instance to the collection. void AddInstance(std::shared_ptr<CPP_InitInfo> g); // Emit code to populate the table used to initialize this collection. void GenerateInitializers(CPPCompile* c); protected: // Computes offset_set - see below. void BuildOffsetSet(CPPCompile* c); // Returns a declaration suitable for the run-time vector that holds // the initialized items in the collection. std::string Declare() const; // For a given cohort, generates the associated table elements for // creating it. void BuildCohort(CPPCompile* c, std::vector<std::shared_ptr<CPP_InitInfo>>& cohort); // Given the initialization type and initializers for with a given // cohort element, build the associated table element. virtual void BuildCohortElement(CPPCompile* c, std::string init_type, std::vector<std::string>& ivs); // Total number of initializers. int size = 0; // Each cohort is represented by a vector whose elements correspond // to the initialization information for a single item. This variable // holds a vector of cohorts, indexed by the number of the cohort. // (Note, some cohorts may be empty.) std::vector<std::vector<std::shared_ptr<CPP_InitInfo>>> instances; // Each cohort has associated with it a vector of offsets, specifying // positions in the run-time vector of the items in the cohort. // // We reduce each such vector to an index into the collection of // such vectors (as managed by an IndicesManager - see below). // // Once we've done that reduction, we can represent each cohort // using a single index, and thus all of the cohorts using a vector // of indices. We then reduce *that* vector to a single index, // again using the IndicesManager. We store that single index // in the "offset_set" variable. int offset_set = 0; // Tag used to distinguish a particular collection of constants. std::string tag; // C++ name for this collection of constants. std::string base_name; // C++ type associated with a single instance of these constants. std::string CPP_type; // C++ type associated with the collection of initializers. std::string inits_type; }; // A class for a collection of initialization items for which each item // has a "custom" initializer (that is, a bespoke C++ object, rather than // a simple C++ type or a vector of indices). class CPP_CustomInitsInfo : public CPP_InitsInfo { public: CPP_CustomInitsInfo(std::string _tag, std::string _type) : CPP_InitsInfo(std::move(_tag), std::move(_type)) { BuildInitType(); } void SetCPPType(std::string ct) override { CPP_InitsInfo::SetCPPType(std::move(ct)); BuildInitType(); } private: void BuildInitType() { inits_type = std::string("CPP_CustomInits<") + CPPType() + ">"; } }; // A class for a collection of initialization items corresponding to "basic" // constants, i.e., those that can be represented either directly as C++ // constants, or as indices into a vector of C++ objects. class CPP_BasicConstInitsInfo : public CPP_CustomInitsInfo { public: // In the following, if "c_type" is non-empty then it specifes the // C++ type used to directly represent the constant. If empty, it // indicates that we instead use an index into a separate vector. CPP_BasicConstInitsInfo(std::string _tag, std::string type, std::string c_type) : CPP_CustomInitsInfo(std::move(_tag), std::move(type)) { if ( c_type.empty() ) inits_type = std::string("CPP_") + tag + "Consts"; else inits_type = std::string("CPP_BasicConsts<") + CPP_type + ", " + c_type + ", " + tag + "Val>"; } void BuildCohortElement(CPPCompile* c, std::string init_type, std::vector<std::string>& ivs) override; }; // A class for a collection of initialization items that are defined using // other initialization items. class CPP_CompoundInitsInfo : public CPP_InitsInfo { public: CPP_CompoundInitsInfo(std::string _tag, std::string type) : CPP_InitsInfo(std::move(_tag), std::move(type)) { if ( tag == "Type" ) // These need a refined version of CPP_IndexedInits // in order to build different types dynamically. inits_type = "CPP_TypeInits"; else inits_type = std::string("CPP_IndexedInits<") + CPPType() + ">"; } void BuildCohortElement(CPPCompile* c, std::string init_type, std::vector<std::string>& ivs) override; }; // Abstract class for tracking information about a single initialization item. class CPP_InitInfo { public: // No constructor - basic initialization happens when the object is // added via AddInstance() to a CPP_InitsInfo object, which in turn // will lead to invocation of this object's SetOffset() method. virtual ~CPP_InitInfo() { } // Associates this item with an initialization collection and run-time // vector offset. void SetOffset(const CPP_InitsInfo* _inits_collection, int _offset) { inits_collection = _inits_collection; offset = _offset; } // Returns the offset for this item into the associated run-time vector. int Offset() const { return offset; } // Returns the name that should be used for referring to this // value in the generated code. std::string Name() const { return inits_collection->Name(offset); } // Returns this item's initialization cohort. int InitCohort() const { return init_cohort; } // Returns the type used for this initializer. virtual std::string InitializerType() const { return "<shouldn't-be-used>"; } // Returns values used for creating this value, one element per // constructor parameter. virtual void InitializerVals(std::vector<std::string>& ivs) const = 0; protected: // Returns an offset (into the run-time vector holding all Zeek // constant values) corresponding to the given value. Registers // the constant if needed. std::string ValElem(CPPCompile* c, ValPtr v); // By default, values have no dependencies on other values // being first initialized. Those that do must increase this // value in their constructors. int init_cohort = 0; // Tracks the collection to which this item belongs. const CPP_InitsInfo* inits_collection = nullptr; // Offset of this item in the collection, or -1 if no association. int offset = -1; }; // Information associated with initializing a basic (non-compound) constant. class BasicConstInfo : public CPP_InitInfo { public: BasicConstInfo(std::string _val) : val(std::move(_val)) { } void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(val); } private: // All we need to track is the C++ representation of the constant. std::string val; }; // Information associated with initializing a constant whose Val constructor // takes a string. class DescConstInfo : public CPP_InitInfo { public: DescConstInfo(CPPCompile* c, ValPtr v); void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(init); } private: std::string init; }; class EnumConstInfo : public CPP_InitInfo { public: EnumConstInfo(CPPCompile* c, ValPtr v); void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(std::to_string(e_type)); ivs.emplace_back(std::to_string(e_val)); } private: int e_type; // an index into the enum's Zeek type int e_val; // integer value of the enum }; class StringConstInfo : public CPP_InitInfo { public: StringConstInfo(CPPCompile* c, ValPtr v); void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(std::to_string(chars)); ivs.emplace_back(std::to_string(len)); } private: int chars; // index into vector of char*'s int len; // length of the string }; class PatternConstInfo : public CPP_InitInfo { public: PatternConstInfo(CPPCompile* c, ValPtr v); void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(std::to_string(pattern)); ivs.emplace_back(std::to_string(is_case_insensitive)); } private: int pattern; // index into string representation of pattern int is_case_insensitive; // case-insensitivity flag, 0 or 1 }; class PortConstInfo : public CPP_InitInfo { public: PortConstInfo(ValPtr v) : p(static_cast<UnsignedValImplementation*>(v->AsPortVal())->Get()) { } void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(std::to_string(p) + "U"); } private: bro_uint_t p; }; // Abstract class for compound items (those defined in terms of other items). class CompoundItemInfo : public CPP_InitInfo { public: // The first of these is used for items with custom Zeek types, // the second when the type is generic/inapplicable. CompoundItemInfo(CPPCompile* c, ValPtr v); CompoundItemInfo(CPPCompile* _c) : c(_c) { type = -1; } void InitializerVals(std::vector<std::string>& ivs) const override { if ( type >= 0 ) ivs.emplace_back(std::to_string(type)); for ( auto& v : vals ) ivs.push_back(v); } protected: CPPCompile* c; int type; std::vector<std::string> vals; // initialization values }; // This next set corresponds to compound Zeek constants of various types. class ListConstInfo : public CompoundItemInfo { public: ListConstInfo(CPPCompile* c, ValPtr v); }; class VectorConstInfo : public CompoundItemInfo { public: VectorConstInfo(CPPCompile* c, ValPtr v); }; class RecordConstInfo : public CompoundItemInfo { public: RecordConstInfo(CPPCompile* c, ValPtr v); }; class TableConstInfo : public CompoundItemInfo { public: TableConstInfo(CPPCompile* c, ValPtr v); }; class FileConstInfo : public CompoundItemInfo { public: FileConstInfo(CPPCompile* c, ValPtr v); }; class FuncConstInfo : public CompoundItemInfo { public: FuncConstInfo(CPPCompile* _c, ValPtr v); void InitializerVals(std::vector<std::string>& ivs) const override; private: FuncVal* fv; }; // Initialization information for single attributes and sets of attributes. class AttrInfo : public CompoundItemInfo { public: AttrInfo(CPPCompile* c, const AttrPtr& attr); }; class AttrsInfo : public CompoundItemInfo { public: AttrsInfo(CPPCompile* c, const AttributesPtr& attrs); }; // Information for initialization a Zeek global. class GlobalInitInfo : public CPP_InitInfo { public: GlobalInitInfo(CPPCompile* c, const ID* g, std::string CPP_name); std::string InitializerType() const override { return "CPP_GlobalInit"; } void InitializerVals(std::vector<std::string>& ivs) const override; protected: std::string Zeek_name; std::string CPP_name; int type; int attrs; std::string val; bool exported; }; // Information for initializing an item corresponding to a Zeek function // call, needed to associate complex expressions with attributes. class CallExprInitInfo : public CPP_InitInfo { public: CallExprInitInfo(CPPCompile* c, ExprPtr e, std::string e_name, std::string wrapper_class); std::string InitializerType() const override { return std::string("CPP_CallExprInit<") + wrapper_class + ">"; } void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(e_name); } // Accessors, since code to initialize these is generated separately // from that of most initialization collections. const ExprPtr& GetExpr() const { return e; } const std::string& Name() const { return e_name; } const std::string& WrapperClass() const { return wrapper_class; } protected: ExprPtr e; std::string e_name; std::string wrapper_class; }; // Information for registering the class/function assocaited with a lambda. class LambdaRegistrationInfo : public CPP_InitInfo { public: LambdaRegistrationInfo(CPPCompile* c, std::string name, FuncTypePtr ft, std::string wrapper_class, p_hash_type h, bool has_captures); std::string InitializerType() const override { return std::string("CPP_LambdaRegistration<") + wrapper_class + ">"; } void InitializerVals(std::vector<std::string>& ivs) const override; protected: std::string name; int func_type; std::string wrapper_class; p_hash_type h; bool has_captures; }; // Abstract class for representing information for initializing a Zeek type. class AbstractTypeInfo : public CPP_InitInfo { public: AbstractTypeInfo(CPPCompile* _c, TypePtr _t) : c(_c), t(std::move(_t)) { } void InitializerVals(std::vector<std::string>& ivs) const override { ivs.emplace_back(std::to_string(static_cast<int>(t->Tag()))); AddInitializerVals(ivs); } virtual void AddInitializerVals(std::vector<std::string>& ivs) const { } protected: CPPCompile* c; TypePtr t; // the type we're initializing }; // The following capture information for different Zeek types. class BaseTypeInfo : public AbstractTypeInfo { public: BaseTypeInfo(CPPCompile* _c, TypePtr _t) : AbstractTypeInfo(_c, std::move(_t)) { } }; class EnumTypeInfo : public AbstractTypeInfo { public: EnumTypeInfo(CPPCompile* _c, TypePtr _t) : AbstractTypeInfo(_c, std::move(_t)) { } void AddInitializerVals(std::vector<std::string>& ivs) const override; }; class OpaqueTypeInfo : public AbstractTypeInfo { public: OpaqueTypeInfo(CPPCompile* _c, TypePtr _t) : AbstractTypeInfo(_c, std::move(_t)) { } void AddInitializerVals(std::vector<std::string>& ivs) const override; }; class TypeTypeInfo : public AbstractTypeInfo { public: TypeTypeInfo(CPPCompile* c, TypePtr _t); void AddInitializerVals(std::vector<std::string>& ivs) const override; private: TypePtr tt; // the type referred to by t }; class VectorTypeInfo : public AbstractTypeInfo { public: VectorTypeInfo(CPPCompile* c, TypePtr _t); void AddInitializerVals(std::vector<std::string>& ivs) const override; private: TypePtr yield; }; class ListTypeInfo : public AbstractTypeInfo { public: ListTypeInfo(CPPCompile* c, TypePtr _t); void AddInitializerVals(std::vector<std::string>& ivs) const override; private: const std::vector<TypePtr>& types; }; class TableTypeInfo : public AbstractTypeInfo { public: TableTypeInfo(CPPCompile* c, TypePtr _t); void AddInitializerVals(std::vector<std::string>& ivs) const override; private: int indices; TypePtr yield; }; class FuncTypeInfo : public AbstractTypeInfo { public: FuncTypeInfo(CPPCompile* c, TypePtr _t); void AddInitializerVals(std::vector<std::string>& ivs) const override; private: FunctionFlavor flavor; TypePtr params; TypePtr yield; }; class RecordTypeInfo : public AbstractTypeInfo { public: RecordTypeInfo(CPPCompile* c, TypePtr _t); void AddInitializerVals(std::vector<std::string>& ivs) const override; private: std::vector<std::string> field_names; std::vector<TypePtr> field_types; std::vector<int> field_attrs; }; // Much of the table-driven initialization is based on vectors of indices, // which we represent as vectors of int's, where each int is used to index a // global C++ vector. This class manages such vectors. In particular, it // reduces a given vector-of-indices to a single value, itself an index, that // can be used at run-time to retrieve a reference to the original vector. // // Note that the notion recurses: if we have several vector-of-indices, we can // reduce each to an index, and then take the resulting vector-of-meta-indices // and reduce it further to an index. Doing so allows us to concisely refer // to a potentially large, deep set of indices using a single value - such as // for CPP_InitsInfo's "offset_set" member variable. class IndicesManager { public: IndicesManager() { } // Adds a new vector-of-indices to the collection we're tracking, // returning the offset that will be associated with it at run-time. int AddIndices(std::vector<int> indices) { int n = indices_set.size(); indices_set.emplace_back(std::move(indices)); return n; } // Generates the initializations used to construct the managed // vectors at run-time. void Generate(CPPCompile* c); private: // Each vector-of-indices being tracked. We could obtain some // space and time savings by recognizing duplicate vectors // (for example, empty vectors are very common), but as long // as the code compiles and executes without undue overhead, // this doesn't appear necessary. std::vector<std::vector<int>> indices_set; }; } // zeek::detail
7,052
407
#include "plugin_z3_utils.h" #include "SubgraphFunctionGenerator.h" namespace hal { extern std::unique_ptr<BasePluginInterface> create_plugin_instance() { return std::make_unique<Z3UtilsPlugin>(); } std::string Z3UtilsPlugin::get_name() const { return std::string("z3_utils"); } std::string Z3UtilsPlugin::get_version() const { return std::string("0.1"); } void Z3UtilsPlugin::initialize() { } }
203
471
<reponame>dimagilg/commcare-hq<filename>custom/openclinica/models.py from collections import defaultdict import hashlib import re from lxml import etree from corehq.apps.domain.models import Domain from corehq.apps.users.models import CouchUser from corehq.util.quickcache import quickcache from custom.openclinica.const import ( AUDIT_LOGS, CC_DOB, CC_ENROLLMENT_DATE, CC_SEX, CC_STUDY_SUBJECT_ID, CC_SUBJECT_KEY, ) from custom.openclinica.utils import ( OpenClinicaIntegrationError, get_item_measurement_unit, get_question_item, get_oc_user, get_study_event_name, is_study_event_repeating, oc_format_date, oc_format_time, originals_first, ) from dimagi.ext.couchdbkit import ( Document, DocumentSchema, StringProperty, SchemaProperty, BooleanProperty, ) from dimagi.utils.couch.cache import cache_core from suds.client import Client from suds.plugin import MessagePlugin from suds.wsse import Security, UsernameToken _reserved_keys = ('@uiVersion', '@xmlns', '@name', '#type', 'case', 'meta', '@version') class OpenClinicaAPI(object): """ We use OpenClinica's SOAP API. because their REST API is limited. CommCare subject cases are iterated, and data built up from form submissions. Subjects and their data are then compared with OpenClinica. Missing subjects are created using `StudySubject.create` and missing events are scheduled with `Event.schedule`. Data is then ready to import using `Data.import`. This automates a process that would otherwise need to be done manually. One manual aspect still remains. The OpenClinica administrator still needs to create users on OpenClinica for all CommCare mobile workers for the study, in order for AuditLog data exported from CommCare to match OpenClinica users. +============+==============================+====================+==========================================+ | Web | Method | Description | WSDL Location (Input Value) | | Service | | | | +============+==============================+====================+==========================================+ | Create | StudySubject.create | Creates a new | http://${your instance}/OpenClinica-ws/ | | Study | | Study Subject | ws/studySubject/v1/studySubjectWsdl.wsdl | | Subject | | | | +------------+------------------------------+--------------------+------------------------------------------+ | List all | StudySubject | Lists the Subjects | http://${your instance}/OpenClinica-ws/ | | Study | .listAllByStudy | in a study | ws/studySubject/v1/studySubjectWsdl.wsdl | | Subjects | | | | +------------+------------------------------+--------------------+------------------------------------------+ | Find if | StudySubject.isStudySubject | Find if Study | http://${your instance}/OpenClinica-ws/ | | Study | | Subject exists | ws/studySubject/v1/studySubjectWsdl.wsdl | | Subject | | | | | exists | | | | +------------+------------------------------+--------------------+------------------------------------------+ | Schedule | Event.schedule | Schedules an | http://${your instance}/OpenClinica-ws/ | | Event | | Event for an | ws/event/v1/eventWsdl.wsdl | | | | enrolled Study | | | | | Subject | | +------------+------------------------------+--------------------+------------------------------------------+ | Import | Data.import | Imports Data onto | http://${your instance}/OpenClinica-ws/ | | Data | | an OpenClincia | ws/data/v1/dataWsdl.wsdl | | | | CRF for an already | | | | | scheduled study | | | | | event | | +------------+------------------------------+--------------------+------------------------------------------+ | Get Study | Study.getMetadata | Returns study | http://${your instance}/OpenClinica-ws/ | | Metadata | | definition | ws/study/v1/studyWsdl.wsdl | | | | metadata in | | | | | CDISC ODM XML | | | | | format (with | | | | | OpenClinica | | | | | extensions) | | +------------+------------------------------+--------------------+------------------------------------------+ | List Study | Study.listAll | Returns a lists of | http://${your instance}/OpenClinica-ws/ | | | | studies and sites | ws/study/v1/studyWsdl.wsdl | +------------+------------------------------+--------------------+------------------------------------------+ | Study | StudyEventDefinition.listAll | Lists study event | http://${your instance}/OpenClinica-ws/ | | Event | | definitions in | ws/studyEventDefinition/v1/ | | Definition | | study | studyEventDefinitionWsdl.wsdl | +------------+------------------------------+--------------------+------------------------------------------+ """ def __init__(self, base_url, username, password, study_id, prefetch=False): """ Initialise OpenClinicaAPI :param base_url: Protocol, address (and port) of the server, e.g. "https://openclinica.example.com:8080/" :param username: Username enabled for API authentication :param password: Password :param study_id: Study identifier :param prefetch: Fetch WSDLs on init? """ self._base_url = base_url if base_url[-1] == '/' else base_url + '/' self._username = username self._password = password self._study_id = study_id self._clients = { 'data': None, 'event': None, 'study': None, 'studyEventDefinition': None, 'studySubject': None } if prefetch: for endpoint in self._clients: self.get_client(endpoint) def get_client(self, endpoint): class FixMimeMultipart(MessagePlugin): """ StudySubject.listAllByStudy replies with what looks like part of a multipart MIME message(!?) Fix this. """ def received(self, context): reply = context.reply if reply.startswith('------='): matches = re.search(r'(<SOAP-ENV:Envelope.*</SOAP-ENV:Envelope>)', reply) context.reply = matches.group(1) if endpoint not in self._clients: raise ValueError('Unknown OpenClinica API endpoint') if self._clients[endpoint] is None: client = Client( '{url}OpenClinica-ws/ws/{endpoint}/v1/{endpoint}Wsdl.wsdl'.format( url=self._base_url, endpoint=endpoint ), plugins=[FixMimeMultipart()] ) security = Security() password = hashlib.sha1(self._password).hexdigest() # SHA1, not AES as documentation says token = UsernameToken(self._username, password) security.tokens.append(token) client.set_options(wsse=security) self._clients[endpoint] = client return self._clients[endpoint] def get_study_metadata_string(self): """ Returns study metadata as an XML string """ study_client = self.get_client('study') study_client.set_options(retxml=True) # Don't parse the study metadata; just give us the raw XML resp = study_client.service.getMetadata({'identifier': self._study_id}) soap_env = etree.fromstring(resp) nsmap = { 'SOAP-ENV': "http://schemas.xmlsoap.org/soap/envelope/", 'OC': "http://openclinica.org/ws/study/v1" } odm = soap_env.xpath('./SOAP-ENV:Body/OC:createResponse/OC:odm', namespaces=nsmap)[0] return odm.text def get_subject_keys(self): subject_client = self.get_client('studySubject') resp = subject_client.service.listAllByStudy({'identifier': self._study_id}) return [s.subject.uniqueIdentifier for s in resp.studySubjects.studySubject] if resp.studySubjects else [] def create_subject(self, subject): subject_client = self.get_client('studySubject') subject_data = { 'label': subject['study_subject_id'], 'enrollmentDate': str(subject['enrollment_date']), 'subject': { 'uniqueIdentifier': subject['subject_key'][3:], # Drop the initial 'SS_' 'gender': {'1': 'm', '2': 'f'}[subject['sex']], 'dateOfBirth': str(subject['dob']), }, 'studyRef': { 'identifier': self._study_id, }, } resp = subject_client.service.create(subject_data) if resp.result != 'Success': raise OpenClinicaIntegrationError( 'Unable to register subject "{}" via OpenClinica webservice'.format(subject['subject_key']) ) def schedule_event(self, subject, event): event_client = self.get_client('event') event_data = { 'studySubjectRef': { 'label': subject['study_subject_id'], }, 'studyRef': { 'identifier': self._study_id, }, 'eventDefinitionOID': event['study_event_oid'], 'startDate': event['start_long'].split()[0], # e.g. 1999-12-31 'startTime': event['start_short'].split()[1], # e.g. 23:59 'endDate': event['end_long'].split()[0], 'endTime': event['end_short'].split()[1], } resp = event_client.service.schedule(event_data) if resp.result != 'Success': raise OpenClinicaIntegrationError( 'Unable to schedule event "{}" via OpenClinica webservice'.format(event['study_event_oid']) ) class StudySettings(DocumentSchema): is_ws_enabled = BooleanProperty() url = StringProperty() username = StringProperty() password = StringProperty() protocol_id = StringProperty() metadata = StringProperty() # Required when web service is not enabled class OpenClinicaSettings(Document): domain = StringProperty() study = SchemaProperty(StudySettings) # One study per domain prevents cases from getting mixed up @classmethod def for_domain(cls, domain): res = cache_core.cached_view( cls.get_db(), "by_domain_doc_type_date/view", key=[domain, 'OpenClinicaSettings', None], reduce=False, include_docs=True, wrapper=cls.wrap) return res[0] if len(res) > 0 else None class ItemGroup(object): """ Corresponds to a question group in CommCare. ItemGroups can repeat. To reproduce this behaviour in CommCare we use repeat groups. """ def __init__(self, domain, oid): self.oid = oid self.completed_cc_forms = set([]) self.items = defaultdict(dict) class StudyEvent(object): """ Like item groups, study events can also be repeating. """ def __init__(self, domain, oid, case_id): self.oid = oid self.case_id = case_id self.is_repeating = is_study_event_repeating(domain, oid) self.forms = defaultdict(lambda: defaultdict(list)) # a dict of forms containing a dict of item groups self.name = get_study_event_name(domain, oid) self.start_datetime = None self.end_datetime = None @property def start_short(self): """ Format the start date and time for the UI. Format the date and time so that the user to copy and paste into OpenClinica """ return self.start_datetime.strftime('%d-%b-%Y %H:%M') # e.g. 01-Jan-1970 00:00 @property def end_short(self): return self.end_datetime.strftime('%d-%b-%Y %H:%M') @property def start_long(self): """ Format the start date and time for the ODM export. OpenClinica UI doesn't allow the user to set seconds, so theirs is always "%H:%M:00.0". Make ours match: """ return self.start_datetime.strftime('%Y-%m-%d %H:%M:00.0') @property def end_long(self): return self.end_datetime.strftime('%Y-%m-%d %H:%M:00.0') class Subject(object): """ Manages data for a subject case """ def __init__(self, subject_key, study_subject_id, domain): self.subject_key = subject_key self.study_subject_id = study_subject_id self.enrollment_date = None self.sex = None self.dob = None # We need the domain to get study metadata for study events and item groups self._domain = Domain.get_by_name(domain) self._domain_name = domain # This subject's data. Stored as subject[study_event_oid][i][form_oid][item_group_oid][j][item_oid] # (Study events and item groups are lists because they can repeat.) self.data = defaultdict(list) # Tracks items in self.data by reference using form ID and question. We need this so that we can # update an item if its form has been edited on HQ, by looking it up with new_form.orig_id. self.question_items = defaultdict(dict) # The mobile workers who entered this subject's data. Used for audit logs. The number of mobile workers # entering data for any single subject should be small, even in large studies with thousands of users. # Because we are fetching the user for every question, use a dictionary for speed. self.mobile_workers = {} def get_study_event(self, item, form, case_id): """ Return the current study event. Opens a new study event if necessary. """ if len(self.data[item.study_event_oid]): study_event = self.data[item.study_event_oid][-1] if study_event.is_repeating and study_event.case_id != case_id: study_event = StudyEvent(self._domain_name, item.study_event_oid, case_id) self.data[item.study_event_oid].append(study_event) else: study_event = StudyEvent(self._domain_name, item.study_event_oid, case_id) self.data[item.study_event_oid].append(study_event) return study_event def get_item_group(self, item, form, case_id): """ Return the current item group and study event. Opens a new item group if necessary. Item groups are analogous to CommCare question groups. Like question groups, they can repeat. """ study_event = self.get_study_event(item, form, case_id) oc_form = study_event.forms[item.form_oid] if not oc_form[item.item_group_oid]: oc_form[item.item_group_oid].append(ItemGroup(self._domain_name, item.item_group_oid)) item_group = oc_form[item.item_group_oid][-1] return item_group, study_event def get_item_dict(self, item, form, case_id, question): """ Return a dict for storing item data, and current study event. Return both because both the item dict and study event may be updated by a form or question. """ item_group, study_event = self.get_item_group(item, form, case_id) item_dict = item_group.items[item.item_oid] self.question_items[form.get_id][question] = (item_dict, study_event) return item_dict, study_event @staticmethod def edit_item(item_dict, form, question, answer, audit_log_id_ref, oc_user): if AUDIT_LOGS: audit_log_id_ref['id'] += 1 item_dict['audit_logs'].append({ 'id': 'AL_{}'.format(audit_log_id_ref['id']), 'user_id': oc_user.user_id, 'username': oc_user.username, 'full_name': oc_user.full_name, 'timestamp': form.received_on, 'audit_type': 'Item data value updated', 'old_value': item_dict['value'], 'new_value': answer, 'value_type': question, }) item_dict['value'] = answer @staticmethod @quickcache(['domain', 'user_id']) def _get_cc_user(domain, user_id): return CouchUser.get_by_user_id(user_id, domain) def _get_oc_user(self, user_id): if user_id not in self.mobile_workers: cc_user = self._get_cc_user(self._domain_name, user_id) oc_user = get_oc_user(self._domain_name, cc_user) if oc_user is None: raise OpenClinicaIntegrationError( 'OpenClinica user not found for CommCare user "{}"'.format(cc_user.username)) self.mobile_workers[user_id] = oc_user return self.mobile_workers[user_id] def add_item(self, item, form, case_id, question, answer, audit_log_id_ref): answer = oc_format_date(answer) answer = oc_format_time(answer, self._domain.get_default_timezone()) oc_user = self._get_oc_user(form.auth_context['user_id']) if getattr(form, 'deprecated_form_id', None) and question in self.question_items[form.deprecated_form_id]: # This form has been edited on HQ. Fetch original item item_dict, study_event = self.question_items[form.deprecated_form_id][question] if item_dict['value'] != answer: self.edit_item(item_dict, form, question, answer, audit_log_id_ref, oc_user) else: item_dict, study_event = self.get_item_dict(item, form, case_id, question) if item_dict and item_dict['value'] != answer: # This form has been submitted more than once for a non-repeating item group. This is an edit. self.edit_item(item_dict, form, question, answer, audit_log_id_ref, oc_user) else: item_dict['value'] = answer if AUDIT_LOGS: audit_log_id_ref['id'] += 1 item_dict['audit_logs'] = [{ 'id': 'AL_{}'.format(audit_log_id_ref['id']), 'user_id': oc_user.user_id, 'username': oc_user.username, 'full_name': oc_user.full_name, 'timestamp': form.received_on, 'audit_type': 'Item data value updated', 'reason': 'initial value', 'new_value': answer, 'value_type': question, }] mu_oid = get_item_measurement_unit(self._domain_name, item) if mu_oid: item_dict['measurement_unit_oid'] = mu_oid if study_event.start_datetime is None or form.form['meta']['timeStart'] < study_event.start_datetime: study_event.start_datetime = form.form['meta']['timeStart'] if study_event.end_datetime is None or form.form['meta']['timeEnd'] > study_event.end_datetime: study_event.end_datetime = form.form['meta']['timeEnd'] def add_item_group(self, item, form): study_event = self.get_study_event(item, form) oc_form = study_event.forms[item.form_oid] item_group = ItemGroup(self._domain_name, item.item_group_oid) oc_form[item.item_group_oid].append(item_group) def add_data(self, data, form, event_case, audit_log_id_ref): def get_next_item(event_id, question_list): for question_ in question_list: item_ = get_question_item(self._domain_name, event_id, question_) if item_: return item_ return None event_id = getattr(event_case, 'event_type') # If a CommCare form is an OpenClinica repeating item group, then we would need to add a new item # group. for key, value in data.items(): if key in _reserved_keys: continue if isinstance(value, list): # Repeat group # NOTE: We need to assume that repeat groups can't be edited in later form submissions item = get_next_item(event_id, value) if item is None: # None of the questions in this group are OpenClinica items continue self.add_item_group(item, form) for v in value: if not isinstance(v, dict): raise OpenClinicaIntegrationError( 'CommCare question value is an unexpected data type. Form XMLNS: "{}"'.format( form.xmlns)) self.add_data(v, form, event_case, audit_log_id_ref) elif isinstance(value, dict): # Group self.add_data(value, form, event_case, audit_log_id_ref) else: # key is a question and value is its answer item = get_question_item(self._domain_name, event_id, key) if item is None: # This is a CommCare-only question or form continue case_id = event_case.get_id self.add_item(item, form, case_id, key, value, audit_log_id_ref) def get_report_events(self): """ The events as they appear in the report. These are useful for scheduling events in OpenClinica, which cannot be imported from ODM until they have been scheduled. """ events = [] for study_events in self.data.values(): for study_event in study_events: events.append( '"{name}" ({start} - {end})'.format( name=study_event.name, start=study_event.start_short, end=study_event.end_short)) return ', '.join(events) def get_export_data(self): """ Transform Subject.data into the structure that CdiscOdmExportWriter expects """ mkitemlist = lambda d: [dict(v, item_oid=k) for k, v in d.items()] # `dict()` updates v with item_oid def mkitemgrouplist(itemgroupdict): itemgrouplist = [] for oid, item_groups in itemgroupdict.items(): for i, item_group in enumerate(item_groups): itemgrouplist.append({ 'item_group_oid': oid, 'repeat_key': i + 1, 'items': mkitemlist(item_group.items) }) return itemgrouplist mkformslist = lambda d: [{'form_oid': k, 'item_groups': mkitemgrouplist(v)} for k, v in d.items()] def mkeventslist(eventsdict): eventslist = [] for oid, study_events in eventsdict.items(): for i, study_event in enumerate(study_events): eventslist.append({ 'study_event_oid': oid, 'repeat_key': i + 1, 'start_short': study_event.start_short, 'start_long': study_event.start_long, 'end_short': study_event.end_short, 'end_long': study_event.end_long, 'forms': mkformslist(study_event.forms) }) return eventslist return mkeventslist(self.data) @classmethod def wrap(cls, case, audit_log_id_ref): subject = cls(getattr(case, CC_SUBJECT_KEY), getattr(case, CC_STUDY_SUBJECT_ID), case.domain) subject.enrollment_date = getattr(case, CC_ENROLLMENT_DATE, None) subject.sex = getattr(case, CC_SEX, None) subject.dob = getattr(case, CC_DOB, None) for event in case.get_subcases(): for form in originals_first(event.get_forms()): # Pass audit log ID by reference to increment it for each audit log subject.add_data(form.form, form, event, audit_log_id_ref) return subject
12,353
1,968
<reponame>agramonte/corona ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #ifndef _Rtt_AppleInAppStoreApple_H__ #define _Rtt_AppleInAppStoreApple_H__ #import <Foundation/Foundation.h> #import <StoreKit/StoreKit.h> // ---------------------------------------------------------------------------- namespace Rtt { class PlatformStore; class PlatformStoreTransaction; } // ---------------------------------------------------------------------------- @interface AppleStoreManager : NSObject <SKPaymentTransactionObserver, SKProductsRequestDelegate> { Rtt::PlatformStore* fOwner; NSMutableDictionary<NSString*, SKProduct*> *fLoadedProducts; } @property(nonatomic, assign, readonly, getter=owner) Rtt::PlatformStore* fOwner; - (id)initWithOwner:(Rtt::PlatformStore*)owner; - (void)startObservingTransactions; - (void)stopObservingTransactions; - (void)loadProducts:(NSSet*)productIdentifiers; - (BOOL)canMakePurchases; - (void)purchase:(NSArray*)productIdentifiers; - (void)finishTransaction:(Rtt::PlatformStoreTransaction*)transaction; - (void)restoreCompletedTransactions; @end // ---------------------------------------------------------------------------- #endif // _Rtt_AppleInAppStoreApple_H__
398
328
<filename>lib-dmxsend/src/dmxsend.cpp /** * @file dmxsend.cpp * */ /* Copyright (C) 2018-2021 by <NAME> mailto:<EMAIL> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <cstdint> #include <climits> #include <cassert> #include "dmxsend.h" #include "dmx.h" #include "debug.h" uint8_t DmxSend::s_nStarted; static constexpr bool is_started(const uint8_t v, const uint32_t p) { return (v & (1U << p)) == (1U << p); } void DmxSend::Start(uint32_t nPortIndex) { DEBUG_ENTRY assert(nPortIndex < CHAR_BIT); DEBUG_PRINTF("nPortIndex=%d", nPortIndex); if (is_started(s_nStarted, nPortIndex)) { DEBUG_EXIT return; } s_nStarted = static_cast<uint8_t>(s_nStarted | (1U << nPortIndex)); Dmx::Get()->SetPortDirection(nPortIndex, dmx::PortDirection::OUTP, true); DEBUG_EXIT } void DmxSend::Stop(uint32_t nPortIndex) { DEBUG_ENTRY assert(nPortIndex < CHAR_BIT); DEBUG_PRINTF("nPortIndex=%d -> %u", nPortIndex, is_started(s_nStarted, static_cast<uint8_t>(nPortIndex))); if (!is_started(s_nStarted, nPortIndex)) { DEBUG_EXIT return; } s_nStarted = static_cast<uint8_t>(s_nStarted & ~(1U << nPortIndex)); Dmx::Get()->SetPortDirection(nPortIndex, dmx::PortDirection::OUTP, false); DEBUG_EXIT } void DmxSend::SetData(uint32_t nPortIndex, const uint8_t *pData, uint32_t nLength) { assert(nPortIndex < CHAR_BIT); assert(pData != nullptr); if (__builtin_expect((nLength == 0), 0)) { return; } Dmx::Get()->SetPortSendDataWithoutSC(nPortIndex, pData, nLength); } #include <cstdio> void DmxSend::Print() { printf("DMX Send\n"); printf(" Break time : %d\n", static_cast<int>(Dmx::Get()->GetDmxBreakTime())); printf(" MAB time : %d\n", static_cast<int>(Dmx::Get()->GetDmxMabTime())); printf(" Refresh rate : %d\n", static_cast<int>(1000000 / Dmx::Get()->GetDmxPeriodTime())); printf(" Slots : %d\n", static_cast<int>(Dmx::Get()->GetDmxSlots())); }
1,065
8,232
<reponame>isra-fel/STL // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // exception handling support functions #include <functional> #include <new> #include <regex> #include <stdexcept> _STD_BEGIN [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xbad_alloc() { _THROW(bad_alloc{}); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xinvalid_argument(_In_z_ const char* const _Message) { _THROW(invalid_argument(_Message)); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xlength_error(_In_z_ const char* const _Message) { _THROW(length_error(_Message)); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xout_of_range(_In_z_ const char* const _Message) { _THROW(out_of_range(_Message)); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xoverflow_error(_In_z_ const char* const _Message) { _THROW(overflow_error(_Message)); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xruntime_error(_In_z_ const char* const _Message) { _THROW(runtime_error(_Message)); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xbad_function_call() { _THROW(bad_function_call{}); } [[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Xregex_error(const regex_constants::error_type _Code) { _THROW(regex_error(_Code)); } _STD_END
643
945
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.mpp.execution.operator.process.fill.linear; import org.apache.iotdb.tsfile.read.common.block.column.Column; import org.apache.iotdb.tsfile.read.common.block.column.RunLengthEncodedColumn; import org.apache.iotdb.tsfile.read.common.block.column.TimeColumn; import static com.google.common.base.Preconditions.checkArgument; /** * The result of Linear Fill functions at timestamp "T" is calculated by performing a linear fitting * method on two time series values, one is at the closest timestamp before T, and the other is at * the closest timestamp after T. Linear Fill function calculation only supports numeric types * including int, double and float. */ public abstract class LinearFill { // whether previous value is null protected boolean previousIsNull = true; // time of next value protected long nextTime = Long.MIN_VALUE; protected long nextTimeInCurrentColumn; /** * Before we call this method, we need to make sure the nextValue has been prepared or noMoreNext * has been set to true * * @param timeColumn TimeColumn of valueColumn * @param valueColumn valueColumn that need to be filled * @return Value Column that has been filled */ public Column fill(TimeColumn timeColumn, Column valueColumn) { int size = valueColumn.getPositionCount(); // if this valueColumn is empty, just return itself; if (size == 0) { return valueColumn; } // if this valueColumn doesn't have any null value, record the last value, and then return // itself. if (!valueColumn.mayHaveNull()) { previousIsNull = false; // update the value using last non-null value updatePreviousValue(valueColumn, valueColumn.getPositionCount() - 1); return valueColumn; } // if its values are all null if (valueColumn instanceof RunLengthEncodedColumn) { // previous value is null or next value is null, we just return NULL_VALUE_BLOCK if (previousIsNull || nextTime < timeColumn.getStartTime()) { return new RunLengthEncodedColumn(createNullValueColumn(), size); } else { prepareForNextValueInCurrentColumn( timeColumn.getEndTime(), timeColumn.getPositionCount() - 1, timeColumn, valueColumn); return new RunLengthEncodedColumn(createFilledValueColumn(), size); } } else { Object array = createValueArray(size); boolean[] isNull = new boolean[size]; // have null value boolean hasNullValue = false; for (int i = 0; i < size; i++) { // current value is null, we need to fill it if (valueColumn.isNull(i)) { long currentTime = timeColumn.getLong(i); prepareForNextValueInCurrentColumn(currentTime, i + 1, timeColumn, valueColumn); // we don't fill it, if either previous value or next value is null if (previousIsNull || nextIsNull(currentTime)) { isNull[i] = true; hasNullValue = true; } else { // fill value using previous and next value fillValue(array, i); } } else { // current is not null // fill value using its own value fillValue(valueColumn, i, array); // update previous value updatePreviousValue(valueColumn, i); previousIsNull = false; } } return createFilledValueColumn(array, isNull, hasNullValue, size); } } /** * @param time end time of current valueColumn that need to be filled * @param valueColumn valueColumn that need to be filled * @return true if valueColumn can't be filled using current information, and we need to get next * TsBlock and then call prepareForNext. false if valueColumn can be filled using current * information, and we can directly call fill() function */ public boolean needPrepareForNext(long time, Column valueColumn) { return time > nextTime && valueColumn.isNull(valueColumn.getPositionCount() - 1); } /** * @param time end time of current valueColumn that need to be filled * @param nextTimeColumn TimeColumn of next TsBlock * @param nextValueColumn Value Column of next TsBlock * @return true if we get enough information to fill current column, and we can stop getting next * TsBlock and calling prepareForNext. false if we still don't get enough information to fill * current column, and still need to keep getting next TsBlock and then call prepareForNext */ public boolean prepareForNext(long time, TimeColumn nextTimeColumn, Column nextValueColumn) { checkArgument( nextTimeColumn.getPositionCount() > 0 && nextTimeColumn.getLong(0) > time, "nextColumn's time should be greater than current time"); if (time <= nextTime) { return true; } for (int i = 0; i < nextValueColumn.getPositionCount(); i++) { if (!nextValueColumn.isNull(i)) { updateNextValue(nextValueColumn, i); this.nextTime = nextTimeColumn.getLong(i); return true; } } return false; } private boolean nextIsNull(long time) { return nextTimeInCurrentColumn <= time; } private void prepareForNextValueInCurrentColumn( long time, int startIndex, TimeColumn timeColumn, Column valueColumn) { if (time <= nextTimeInCurrentColumn) { return; } for (int i = startIndex; i < valueColumn.getPositionCount(); i++) { if (!valueColumn.isNull(i)) { this.nextTimeInCurrentColumn = timeColumn.getLong(i); updateNextValueInCurrentColumn(valueColumn, i); return; } } // current column's value is not enough for filling, we should use value of next Column this.nextTimeInCurrentColumn = this.nextTime; updateNextValueInCurrentColumn(); } abstract void fillValue(Column column, int index, Object array); abstract void fillValue(Object array, int index); abstract Object createValueArray(int size); abstract Column createNullValueColumn(); abstract Column createFilledValueColumn(); abstract Column createFilledValueColumn( Object array, boolean[] isNull, boolean hasNullValue, int size); abstract void updatePreviousValue(Column column, int index); abstract void updateNextValue(Column nextValueColumn, int index); abstract void updateNextValueInCurrentColumn(Column nextValueColumn, int index); /** update nextValueInCurrentColumn using value of next Column */ abstract void updateNextValueInCurrentColumn(); }
2,305
747
/*! * \file WtExeFact.h * * \author Wesley * \date 2020/03/30 * * */ #pragma once #include "../Includes/ExecuteDefs.h" USING_NS_OTP; class WtExeFact : public IExecuterFact { public: WtExeFact(); virtual ~WtExeFact(); public: virtual const char* getName() override; virtual void enumExeUnit(FuncEnumUnitCallback cb) override; virtual ExecuteUnit* createExeUnit(const char* name) override; virtual bool deleteExeUnit(ExecuteUnit* unit) override; };
210
12,718
<reponame>aruniiird/zig #include "time32.h" #include <time.h> struct tm *__localtime32_r(time32_t *t, struct tm *tm) { return localtime_r(&(time_t){*t}, tm); }
78
3,402
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.source.hive; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hive.hcatalog.data.HCatRecord; import org.apache.hive.hcatalog.mapreduce.HCatInputFormat; import org.apache.hive.hcatalog.mapreduce.HCatSplit; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.engine.mr.IMRInput; import org.apache.kylin.job.execution.DefaultChainedExecutable; import org.apache.kylin.job.execution.ExecutableManager; import org.apache.kylin.metadata.model.IJoinedFlatTableDesc; import org.apache.kylin.metadata.model.ISegment; import org.apache.kylin.metadata.model.TableDesc; public class HiveMRInput extends HiveInputBase implements IMRInput { @Override public IBatchCubingInputSide getBatchCubingInputSide(IJoinedFlatTableDesc flatDesc) { return new HiveMRBatchCubingInputSide(flatDesc); } @Override public IBatchMergeInputSide getBatchMergeInputSide(ISegment seg) { return new IMRBatchMergeInputSide() { @Override public void addStepPhase1_MergeDictionary(DefaultChainedExecutable jobFlow) { // doing nothing } }; } @Override public IMRTableInputFormat getTableInputFormat(TableDesc table, String uuid) { return new HiveTableInputFormat(getTableNameForHCat(table, uuid)); } public static class HiveTableInputFormat implements IMRTableInputFormat { final String dbName; final String tableName; /** * Construct a HiveTableInputFormat to read hive table. * @param fullQualifiedTableName "databaseName.tableName" */ public HiveTableInputFormat(String fullQualifiedTableName) { String[] parts = HadoopUtil.parseHiveTableName(fullQualifiedTableName); dbName = parts[0]; tableName = parts[1]; } @Override public void configureJob(Job job) { try { job.getConfiguration().addResource("hive-site.xml"); HCatInputFormat.setInput(job, dbName, tableName); job.setInputFormatClass(HCatInputFormat.class); } catch (IOException e) { throw new RuntimeException(e); } } @Override public List<String[]> parseMapperInput(Object mapperInput) { return Collections.singletonList(HiveTableReader.getRowAsStringArray((HCatRecord) mapperInput)); } @Override public String getInputSplitSignature(InputSplit inputSplit) { FileSplit baseSplit = (FileSplit) ((HCatSplit) inputSplit).getBaseSplit(); //file name(for intermediate table) + start pos + length return baseSplit.getPath().getName() + "_" + baseSplit.getStart() + "_" + baseSplit.getLength(); } } public static class HiveMRBatchCubingInputSide extends BaseBatchCubingInputSide implements IMRBatchCubingInputSide { public HiveMRBatchCubingInputSide(IJoinedFlatTableDesc flatDesc) { super(flatDesc); } @Override public IMRTableInputFormat getFlatTableInputFormat() { return new HiveMRInput.HiveTableInputFormat(getIntermediateTableIdentity()); } } /** * When build job is created by kylin version 2.4.x or below, the step class name is an inner class of {@link HiveMRInput}, * to avoid the ClassNotFoundException in {@link ExecutableManager#newExecutable(java.lang.String)} , delegate the OLD class to the new one * * @since 2.5.0 * @deprecated For backwards compatibility. */ @Deprecated public static class RedistributeFlatHiveTableStep extends org.apache.kylin.source.hive.RedistributeFlatHiveTableStep { } /** * When build job is created by kylin version 2.4.x or below, the step class name is an inner class of {@link HiveMRInput}, * to avoid the ClassNotFoundException in {@link ExecutableManager#newExecutable(java.lang.String)} , delegate the OLD class to the new one * * @since 2.5.0 * @deprecated For backwards compatibility. */ @Deprecated public static class GarbageCollectionStep extends org.apache.kylin.source.hive.GarbageCollectionStep { } }
1,925
2,293
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '<EMAIL> (<NAME>)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata from gdata import test_data import gdata.base class LabelTest(unittest.TestCase): def setUp(self): self.label = gdata.base.Label() def testToAndFromString(self): self.label.text = 'test label' self.assert_(self.label.text == 'test label') new_label = gdata.base.LabelFromString(self.label.ToString()) self.assert_(self.label.text == new_label.text) class ItemTypeTest(unittest.TestCase): def setUp(self): self.item_type = gdata.base.ItemType() def testToAndFromString(self): self.item_type.text = 'product' self.item_type.type = 'text' self.assert_(self.item_type.text == 'product') self.assert_(self.item_type.type == 'text') new_item_type = gdata.base.ItemTypeFromString(self.item_type.ToString()) self.assert_(self.item_type.text == new_item_type.text) self.assert_(self.item_type.type == new_item_type.type) class GBaseItemTest(unittest.TestCase): def setUp(self): self.item = gdata.base.GBaseItem() def testToAndFromString(self): self.item.label.append(gdata.base.Label(text='my label')) self.assert_(self.item.label[0].text == 'my label') self.item.item_type = gdata.base.ItemType(text='products') self.assert_(self.item.item_type.text == 'products') self.item.item_attributes.append(gdata.base.ItemAttribute('extra', text='foo')) self.assert_(self.item.item_attributes[0].text == 'foo') self.assert_(self.item.item_attributes[0].name == 'extra') new_item = gdata.base.GBaseItemFromString(self.item.ToString()) self.assert_(self.item.label[0].text == new_item.label[0].text) self.assert_(self.item.item_type.text == new_item.item_type.text) self.assert_(self.item.item_attributes[0].text == new_item.item_attributes[0].text) def testCustomItemAttributes(self): self.item.AddItemAttribute('test_attrib', 'foo') self.assert_(self.item.FindItemAttribute('test_attrib') == 'foo') self.item.SetItemAttribute('test_attrib', 'bar') self.assert_(self.item.FindItemAttribute('test_attrib') == 'bar') self.item.RemoveItemAttribute('test_attrib') self.assert_(self.item.FindItemAttribute('test_attrib') is None) def testConvertActualData(self): feed = gdata.base.GBaseSnippetFeedFromString(test_data.GBASE_FEED) for an_entry in feed.entry: if an_entry.author[0].email.text == '<EMAIL>': for attrib in an_entry.item_attributes: if attrib.name == 'payment_notes': self.assert_(attrib.text == 'PayPal & Bill Me Later credit available online only.') if attrib.name == 'condition': self.assert_(attrib.text == 'new') # self.assert_(an_entry.item_attributes['condition'].text == 'new') def testModifyCustomItemAttributes(self): self.item.AddItemAttribute('test_attrib', 'foo', value_type='test1') self.item.AddItemAttribute('test_attrib', 'bar', value_type='test2') self.assertEquals(self.item.item_attributes[0].name, 'test_attrib') self.assertEquals(self.item.item_attributes[1].name, 'test_attrib') self.assertEquals(self.item.item_attributes[0].text, 'foo') self.assertEquals(self.item.item_attributes[1].text, 'bar') # Get one of the custom attributes from the item. attributes = self.item.GetItemAttributes('test_attrib') self.assertEquals(len(attributes), 2) self.assertEquals(attributes[0].text, 'foo') # Change the contents of the found item attribute. attributes[0].text = 'new foo' self.assertEquals(attributes[0].text, 'new foo') # Make sure that the change is reflected in the item. self.assertEquals(self.item.item_attributes[0].text, 'new foo') class GBaseItemFeedTest(unittest.TestCase): def setUp(self): self.item_feed = gdata.base.GBaseItemFeedFromString(test_data.GBASE_FEED) def testToAndFromString(self): self.assert_(len(self.item_feed.entry) == 3) for an_entry in self.item_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseItem)) new_item_feed = gdata.base.GBaseItemFeedFromString(str(self.item_feed)) for an_entry in new_item_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseItem)) #self.item_feed.label.append(gdata.base.Label(text='my label')) #self.assert_(self.item.label[0].text == 'my label') #self.item.item_type = gdata.base.ItemType(text='products') #self.assert_(self.item.item_type.text == 'products') #new_item = gdata.base.GBaseItemFromString(self.item.ToString()) #self.assert_(self.item.label[0].text == new_item.label[0].text) #self.assert_(self.item.item_type.text == new_item.item_type.text) def testLinkFinderFindsHtmlLink(self): for entry in self.item_feed.entry: # All Base entries should have a self link self.assert_(entry.GetSelfLink() is not None) # All Base items should have an HTML link self.assert_(entry.GetHtmlLink() is not None) # None of the Base items should have an edit link self.assert_(entry.GetEditLink() is None) class GBaseSnippetFeedTest(unittest.TestCase): def setUp(self): #self.item_feed = gdata.base.GBaseItemFeed() self.snippet_feed = gdata.base.GBaseSnippetFeedFromString(test_data.GBASE_FEED) def testToAndFromString(self): self.assert_(len(self.snippet_feed.entry) == 3) for an_entry in self.snippet_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseSnippet)) new_snippet_feed = gdata.base.GBaseSnippetFeedFromString(str(self.snippet_feed)) for an_entry in new_snippet_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseSnippet)) class ItemAttributeTest(unittest.TestCase): def testToAndFromStirng(self): attrib = gdata.base.ItemAttribute('price') attrib.type = 'float' self.assert_(attrib.name == 'price') self.assert_(attrib.type == 'float') new_attrib = gdata.base.ItemAttributeFromString(str(attrib)) self.assert_(new_attrib.name == attrib.name) self.assert_(new_attrib.type == attrib.type) def testClassConvertsActualData(self): attrib = gdata.base.ItemAttributeFromString(test_data.TEST_GBASE_ATTRIBUTE) self.assert_(attrib.name == 'brand') self.assert_(attrib.type == 'text') self.assert_(len(attrib.extension_elements) == 0) # Test conversion to en ElementTree element = attrib._ToElementTree() self.assert_(element.tag == gdata.base.GBASE_TEMPLATE % 'brand') class AttributeTest(unittest.TestCase): def testAttributeToAndFromString(self): attrib = gdata.base.Attribute() attrib.type = 'float' attrib.count = '44000' attrib.name = 'test attribute' attrib.value.append(gdata.base.Value(count='500', text='a value')) self.assert_(attrib.type == 'float') self.assert_(attrib.count == '44000') self.assert_(attrib.name == 'test attribute') self.assert_(attrib.value[0].count == '500') self.assert_(attrib.value[0].text == 'a value') new_attrib = gdata.base.AttributeFromString(str(attrib)) self.assert_(attrib.type == new_attrib.type) self.assert_(attrib.count == new_attrib.count) self.assert_(attrib.value[0].count == new_attrib.value[0].count) self.assert_(attrib.value[0].text == new_attrib.value[0].text) self.assert_(attrib.name == new_attrib.name) class ValueTest(unittest.TestCase): def testValueToAndFromString(self): value = gdata.base.Value() value.count = '5123' value.text = 'super great' self.assert_(value.count == '5123') self.assert_(value.text == 'super great') new_value = gdata.base.ValueFromString(str(value)) self.assert_(new_value.count == value.count) self.assert_(new_value.text == value.text) class AttributeEntryTest(unittest.TestCase): def testAttributeEntryToAndFromString(self): value = gdata.base.Value(count='500', text='happy') attribute = gdata.base.Attribute(count='600', value=[value]) a_entry = gdata.base.GBaseAttributeEntry(attribute=[attribute]) self.assert_(a_entry.attribute[0].count == '600') self.assert_(a_entry.attribute[0].value[0].count == '500') self.assert_(a_entry.attribute[0].value[0].text == 'happy') new_entry = gdata.base.GBaseAttributeEntryFromString(str(a_entry)) self.assert_(new_entry.attribute[0].count == '600') self.assert_(new_entry.attribute[0].value[0].count == '500') self.assert_(new_entry.attribute[0].value[0].text == 'happy') class GBaseAttributeEntryTest(unittest.TestCase): def testAttribteEntryFromExampleData(self): entry = gdata.base.GBaseAttributeEntryFromString( test_data.GBASE_ATTRIBUTE_ENTRY) self.assert_(len(entry.attribute) == 1) self.assert_(len(entry.attribute[0].value) == 10) self.assert_(entry.attribute[0].name == 'job industry') for val in entry.attribute[0].value: if val.text == 'it internet': self.assert_(val.count == '380772') elif val.text == 'healthcare': self.assert_(val.count == '261565') class GBaseAttributesFeedTest(unittest.TestCase): def testAttributesFeedExampleData(self): feed = gdata.base.GBaseAttributesFeedFromString(test_data.GBASE_ATTRIBUTE_FEED) self.assert_(len(feed.entry) == 1) self.assert_(isinstance(feed.entry[0], gdata.base.GBaseAttributeEntry)) def testAttributesFeedToAndFromString(self): value = gdata.base.Value(count='500', text='happy') attribute = gdata.base.Attribute(count='600', value=[value]) a_entry = gdata.base.GBaseAttributeEntry(attribute=[attribute]) feed = gdata.base.GBaseAttributesFeed(entry=[a_entry]) self.assert_(feed.entry[0].attribute[0].count == '600') self.assert_(feed.entry[0].attribute[0].value[0].count == '500') self.assert_(feed.entry[0].attribute[0].value[0].text == 'happy') new_feed = gdata.base.GBaseAttributesFeedFromString(str(feed)) self.assert_(new_feed.entry[0].attribute[0].count == '600') self.assert_(new_feed.entry[0].attribute[0].value[0].count == '500') self.assert_(new_feed.entry[0].attribute[0].value[0].text == 'happy') class GBaseLocalesFeedTest(unittest.TestCase): def testLocatesFeedWithExampleData(self): feed = gdata.base.GBaseLocalesFeedFromString(test_data.GBASE_LOCALES_FEED) self.assert_(len(feed.entry) == 3) self.assert_(feed.GetSelfLink().href == 'http://www.google.com/base/feeds/locales/') for an_entry in feed.entry: if an_entry.title.text == 'en_US': self.assert_(an_entry.category[0].term == 'en_US') self.assert_(an_entry.title.text == an_entry.category[0].term) class GBaseItemTypesFeedAndEntryTest(unittest.TestCase): def testItemTypesFeedToAndFromString(self): feed = gdata.base.GBaseItemTypesFeed() entry = gdata.base.GBaseItemTypeEntry() entry.attribute.append(gdata.base.Attribute(name='location', attribute_type='location')) entry.item_type = gdata.base.ItemType(text='jobs') feed.entry.append(entry) self.assert_(len(feed.entry) == 1) self.assert_(feed.entry[0].attribute[0].name == 'location') new_feed = gdata.base.GBaseItemTypesFeedFromString(str(feed)) self.assert_(len(new_feed.entry) == 1) self.assert_(new_feed.entry[0].attribute[0].name == 'location') class GBaseImageLinkTest(unittest.TestCase): def testImageLinkToAndFromString(self): image_link = gdata.base.ImageLink() image_link.type = 'url' image_link.text = 'example.com' thumbnail = gdata.base.Thumbnail() thumbnail.width = '60' thumbnail.height = '80' thumbnail.text = 'example text' image_link.thumbnail.append(thumbnail) xml = image_link.ToString() parsed = gdata.base.ImageLinkFromString(xml) self.assert_(parsed.type == image_link.type) self.assert_(parsed.text == image_link.text) self.assert_(len(parsed.thumbnail) == 1) self.assert_(parsed.thumbnail[0].width == thumbnail.width) self.assert_(parsed.thumbnail[0].height == thumbnail.height) self.assert_(parsed.thumbnail[0].text == thumbnail.text) class GBaseItemAttributeAccessElement(unittest.TestCase): def testItemAttributeAccessAttribute(self): item = gdata.base.GBaseItem() item.AddItemAttribute('test', '1', value_type='int', access='private') private_attribute = item.GetItemAttributes('test')[0] self.assert_(private_attribute.access == 'private') xml = item.ToString() new_item = gdata.base.GBaseItemFromString(xml) new_attributes = new_item.GetItemAttributes('test') self.assert_(len(new_attributes) == 1) #self.assert_(new_attributes[0].access == 'private') if __name__ == '__main__': unittest.main()
5,083
2,180
<reponame>Amwidtf/heritrix3 /* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.archive.crawler.selftest; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Test the max-link-hops setting. * * @author stack * @version $Id$ */ public class MaxLinkHopsSelfTest extends SelfTestBase { final private static Set<String> EXPECTED = Collections.unmodifiableSet( new HashSet<String>(Arrays.asList(new String[] { "index.html", "1.html", "2.html", "3.html", "robots.txt", "favicon.ico" }))); @Override protected void verify() throws Exception { Set<String> files = filesInArcs(); assertEquals("ARC contents not as expected",EXPECTED,files); } @Override protected String changeGlobalConfig(String config) { String replacement = "<bean class=\"org.archive.modules.deciderules.TooManyHopsDecideRule\">\n" + " <property name=\"maxHops\" value=\"3\"/>\n" + " </bean>"; String retVal = config.replaceFirst( "(?s)<bean class=\"org.archive.modules.deciderules.TooManyHopsDecideRule\".*?</bean>", replacement); return super.changeGlobalConfig(retVal); } }
736
857
<gh_stars>100-1000 # Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. # See LICENSE in the project root for license information. from ujson import dumps from ... import db def on_get(req, resp, service): """ Get list of team mapped to a service **Example request** .. sourcecode:: http GET /api/v0/services/service-foo/teams HTTP/1.1 Host: example.com **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [ "team-foo" ] """ connection = db.connect() cursor = connection.cursor() cursor.execute('''SELECT `team`.`name` FROM `service` JOIN `team_service` ON `team_service`.`service_id`=`service`.`id` JOIN `team` ON `team`.`id`=`team_service`.`team_id` WHERE `service`.`name`=%s''', service) data = [r[0] for r in cursor] cursor.close() connection.close() resp.body = dumps(data)
449
938
<reponame>URSec/Silhouette-Compiler-Legacy //===- LiveRangeShrink.cpp - Move instructions to shrink live range -------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // ///===---------------------------------------------------------------------===// /// /// \file /// This pass moves instructions close to the definition of its operands to /// shrink live range of the def instruction. The code motion is limited within /// the basic block. The moved instruction should have 1 def, and more than one /// uses, all of which are the only use of the def. /// ///===---------------------------------------------------------------------===// #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/iterator_range.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/Pass.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <iterator> #include <utility> using namespace llvm; #define DEBUG_TYPE "lrshrink" STATISTIC(NumInstrsHoistedToShrinkLiveRange, "Number of insructions hoisted to shrink live range."); namespace { class LiveRangeShrink : public MachineFunctionPass { public: static char ID; LiveRangeShrink() : MachineFunctionPass(ID) { initializeLiveRangeShrinkPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } StringRef getPassName() const override { return "Live Range Shrink"; } bool runOnMachineFunction(MachineFunction &MF) override; }; } // end anonymous namespace char LiveRangeShrink::ID = 0; char &llvm::LiveRangeShrinkID = LiveRangeShrink::ID; INITIALIZE_PASS(LiveRangeShrink, "lrshrink", "Live Range Shrink Pass", false, false) using InstOrderMap = DenseMap<MachineInstr *, unsigned>; /// Returns \p New if it's dominated by \p Old, otherwise return \p Old. /// \p M maintains a map from instruction to its dominating order that satisfies /// M[A] > M[B] guarantees that A is dominated by B. /// If \p New is not in \p M, return \p Old. Otherwise if \p Old is null, return /// \p New. static MachineInstr *FindDominatedInstruction(MachineInstr &New, MachineInstr *Old, const InstOrderMap &M) { auto NewIter = M.find(&New); if (NewIter == M.end()) return Old; if (Old == nullptr) return &New; unsigned OrderOld = M.find(Old)->second; unsigned OrderNew = NewIter->second; if (OrderOld != OrderNew) return OrderOld < OrderNew ? &New : Old; // OrderOld == OrderNew, we need to iterate down from Old to see if it // can reach New, if yes, New is dominated by Old. for (MachineInstr *I = Old->getNextNode(); M.find(I)->second == OrderNew; I = I->getNextNode()) if (I == &New) return &New; return Old; } /// Builds Instruction to its dominating order number map \p M by traversing /// from instruction \p Start. static void BuildInstOrderMap(MachineBasicBlock::iterator Start, InstOrderMap &M) { M.clear(); unsigned i = 0; for (MachineInstr &I : make_range(Start, Start->getParent()->end())) M[&I] = i++; } bool LiveRangeShrink::runOnMachineFunction(MachineFunction &MF) { if (skipFunction(MF.getFunction())) return false; MachineRegisterInfo &MRI = MF.getRegInfo(); LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n'); InstOrderMap IOM; // Map from register to instruction order (value of IOM) where the // register is used last. When moving instructions up, we need to // make sure all its defs (including dead def) will not cross its // last use when moving up. DenseMap<unsigned, std::pair<unsigned, MachineInstr *>> UseMap; for (MachineBasicBlock &MBB : MF) { if (MBB.empty()) continue; bool SawStore = false; BuildInstOrderMap(MBB.begin(), IOM); UseMap.clear(); for (MachineBasicBlock::iterator Next = MBB.begin(); Next != MBB.end();) { MachineInstr &MI = *Next; ++Next; if (MI.isPHI() || MI.isDebugInstr()) continue; if (MI.mayStore()) SawStore = true; unsigned CurrentOrder = IOM[&MI]; unsigned Barrier = 0; MachineInstr *BarrierMI = nullptr; for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg() || MO.isDebug()) continue; if (MO.isUse()) UseMap[MO.getReg()] = std::make_pair(CurrentOrder, &MI); else if (MO.isDead() && UseMap.count(MO.getReg())) // Barrier is the last instruction where MO get used. MI should not // be moved above Barrier. if (Barrier < UseMap[MO.getReg()].first) { Barrier = UseMap[MO.getReg()].first; BarrierMI = UseMap[MO.getReg()].second; } } if (!MI.isSafeToMove(nullptr, SawStore)) { // If MI has side effects, it should become a barrier for code motion. // IOM is rebuild from the next instruction to prevent later // instructions from being moved before this MI. if (MI.hasUnmodeledSideEffects() && Next != MBB.end()) { BuildInstOrderMap(Next, IOM); SawStore = false; } continue; } const MachineOperand *DefMO = nullptr; MachineInstr *Insert = nullptr; // Number of live-ranges that will be shortened. We do not count // live-ranges that are defined by a COPY as it could be coalesced later. unsigned NumEligibleUse = 0; for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg() || MO.isDead() || MO.isDebug()) continue; unsigned Reg = MO.getReg(); // Do not move the instruction if it def/uses a physical register, // unless it is a constant physical register or a noreg. if (!TargetRegisterInfo::isVirtualRegister(Reg)) { if (!Reg || MRI.isConstantPhysReg(Reg)) continue; Insert = nullptr; break; } if (MO.isDef()) { // Do not move if there is more than one def. if (DefMO) { Insert = nullptr; break; } DefMO = &MO; } else if (MRI.hasOneNonDBGUse(Reg) && MRI.hasOneDef(Reg) && DefMO && MRI.getRegClass(DefMO->getReg()) == MRI.getRegClass(MO.getReg())) { // The heuristic does not handle different register classes yet // (registers of different sizes, looser/tighter constraints). This // is because it needs more accurate model to handle register // pressure correctly. MachineInstr &DefInstr = *MRI.def_instr_begin(Reg); if (!DefInstr.isCopy()) NumEligibleUse++; Insert = FindDominatedInstruction(DefInstr, Insert, IOM); } else { Insert = nullptr; break; } } // If Barrier equals IOM[I], traverse forward to find if BarrierMI is // after Insert, if yes, then we should not hoist. for (MachineInstr *I = Insert; I && IOM[I] == Barrier; I = I->getNextNode()) if (I == BarrierMI) { Insert = nullptr; break; } // Move the instruction when # of shrunk live range > 1. if (DefMO && Insert && NumEligibleUse > 1 && Barrier <= IOM[Insert]) { MachineBasicBlock::iterator I = std::next(Insert->getIterator()); // Skip all the PHI and debug instructions. while (I != MBB.end() && (I->isPHI() || I->isDebugInstr())) I = std::next(I); if (I == MI.getIterator()) continue; // Update the dominator order to be the same as the insertion point. // We do this to maintain a non-decreasing order without need to update // all instruction orders after the insertion point. unsigned NewOrder = IOM[&*I]; IOM[&MI] = NewOrder; NumInstrsHoistedToShrinkLiveRange++; // Find MI's debug value following MI. MachineBasicBlock::iterator EndIter = std::next(MI.getIterator()); if (MI.getOperand(0).isReg()) for (; EndIter != MBB.end() && EndIter->isDebugValue() && EndIter->getOperand(0).isReg() && EndIter->getOperand(0).getReg() == MI.getOperand(0).getReg(); ++EndIter, ++Next) IOM[&*EndIter] = NewOrder; MBB.splice(I, &MBB, MI.getIterator(), EndIter); } } } return false; }
3,556
384
default_app_config = "nautobot.ipam.apps.IPAMConfig"
22
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Lhuis","circ":"5ème circonscription","dpt":"Ain","inscrits":611,"abs":285,"votants":326,"blancs":4,"nuls":1,"exp":321,"res":[{"nuance":"LR","nom":"<NAME>","voix":121},{"nuance":"REM","nom":"Mme <NAME>","voix":83},{"nuance":"FN","nom":"Mme <NAME>","voix":45},{"nuance":"FI","nom":"M. <NAME>","voix":34},{"nuance":"ECO","nom":"Mme <NAME>","voix":14},{"nuance":"DIV","nom":"<NAME>","voix":8},{"nuance":"DIV","nom":"Mme <NAME>","voix":6},{"nuance":"SOC","nom":"Mme <NAME>","voix":4},{"nuance":"DLF","nom":"M. <NAME>","voix":3},{"nuance":"COM","nom":"Mme <NAME>","voix":2},{"nuance":"EXG","nom":"M. <NAME>","voix":1},{"nuance":"DIV","nom":"<NAME>","voix":0},{"nuance":"EXG","nom":"<NAME>","voix":0}]}
307
1,160
""" summary: retrieve the strings that are selected in the "Strings" window. description: In IDA it's possible to write actions that can be applied even to core (i.e., "standard") widgets. The actions in this example use the action "context" to know what the current selection is. This example shows how you can either retrieve string literals data directly from the chooser (`ida_kernwin.get_chooser_data`), or by querying the IDB (`ida_bytes.get_strlit_contents`) keywords: actions see_also: list_strings """ import ida_kernwin import ida_strlist import ida_bytes class show_strings_base_ah_t(ida_kernwin.action_handler_t): def __init__(self, use_get_chooser_data): ida_kernwin.action_handler_t.__init__(self) self.use_get_chooser_data = use_get_chooser_data def activate(self, ctx): for idx in ctx.chooser_selection: if self.use_get_chooser_data: _, _, _, s = ida_kernwin.get_chooser_data(ctx.widget_title, idx) else: si = ida_strlist.string_info_t() if ida_strlist.get_strlist_item(si, idx): s = ida_bytes.get_strlit_contents(si.ea, si.length, si.type) print("Selected string (retrieved using %s) at index %d: \"%s\"" % ( "get_chooser_data()" if self.use_get_chooser_data else "get_strlist_item()", idx, s)) return 0 def update(self, ctx): return ida_kernwin.AST_ENABLE_FOR_WIDGET \ if ctx.widget_type == ida_kernwin.BWN_STRINGS \ else ida_kernwin.AST_DISABLE_FOR_WIDGET class show_strings_using_get_chooser_data_ah_t(show_strings_base_ah_t): ACTION_NAME = "test:show_string_using_get_chooser_data" ACTION_LABEL = "Show current string(s) using get_chooser_data()" ACTION_SHORTCUT = "Ctrl+Shift+S" def __init__(self): show_strings_base_ah_t.__init__(self, True) class show_strings_using_get_strlist_item_ah_t(show_strings_base_ah_t): ACTION_NAME = "test:show_string_using_get_strlist_item" ACTION_LABEL = "Show current string(s) using get_strlist_item() + get_strlit_contents()" ACTION_SHORTCUT = "Ctrl+Shift+K" def __init__(self): show_strings_base_ah_t.__init__(self, False) klasses = [ show_strings_using_get_chooser_data_ah_t, show_strings_using_get_strlist_item_ah_t, ] sw = ida_kernwin.find_widget("Strings") if not sw: sw = ida_kernwin.open_strings_window(ida_idaapi.BADADDR) for klass in klasses: if ida_kernwin.unregister_action(klass.ACTION_NAME): print("Unregistered previously-registered action \"%s\"" % klass.ACTION_LABEL) if ida_kernwin.register_action( ida_kernwin.action_desc_t( klass.ACTION_NAME, klass.ACTION_LABEL, klass(), klass.ACTION_SHORTCUT)): print("Registered action \"%s\"" % (klass.ACTION_LABEL,)) if sw: ida_kernwin.attach_action_to_popup(sw, None, klass.ACTION_NAME) print("Permanently added action to \"String window\"'s popup")
1,415
1,194
<reponame>MFAshby/hapi-fhir<filename>hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/r4/JpaR4Config.java<gh_stars>1000+ package ca.uhn.fhir.jpa.config.r4; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.support.IValidationSupport; import ca.uhn.fhir.jpa.api.IDaoRegistry; import ca.uhn.fhir.jpa.api.dao.IFhirSystemDao; import ca.uhn.fhir.jpa.config.GeneratedDaoAndResourceProviderConfigR4; import ca.uhn.fhir.jpa.config.JpaConfig; import ca.uhn.fhir.jpa.config.SharedConfigDstu3Plus; import ca.uhn.fhir.jpa.dao.ITransactionProcessorVersionAdapter; import ca.uhn.fhir.jpa.dao.r4.TransactionProcessorVersionAdapterR4; import ca.uhn.fhir.jpa.graphql.GraphQLProvider; import ca.uhn.fhir.jpa.graphql.GraphQLProviderWithIntrospection; import ca.uhn.fhir.jpa.term.TermLoaderSvcImpl; import ca.uhn.fhir.jpa.term.TermReadSvcR4; import ca.uhn.fhir.jpa.term.TermVersionAdapterSvcR4; import ca.uhn.fhir.jpa.term.api.ITermCodeSystemStorageSvc; import ca.uhn.fhir.jpa.term.api.ITermDeferredStorageSvc; import ca.uhn.fhir.jpa.term.api.ITermLoaderSvc; import ca.uhn.fhir.jpa.term.api.ITermReadSvcR4; import ca.uhn.fhir.jpa.term.api.ITermVersionAdapterSvc; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Meta; import org.hl7.fhir.utilities.graphql.IGraphQLStorageServices; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Lazy; import org.springframework.transaction.annotation.EnableTransactionManagement; /* * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2022 Smile CDR, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @Configuration @EnableTransactionManagement @Import({ FhirContextR4Config.class, GeneratedDaoAndResourceProviderConfigR4.class, SharedConfigDstu3Plus.class, JpaConfig.class }) public class JpaR4Config { @Bean public ITermVersionAdapterSvc terminologyVersionAdapterSvc() { return new TermVersionAdapterSvcR4(); } @Bean public ITransactionProcessorVersionAdapter transactionProcessorVersionFacade() { return new TransactionProcessorVersionAdapterR4(); } @Bean(name = JpaConfig.GRAPHQL_PROVIDER_NAME) @Lazy public GraphQLProvider graphQLProvider(FhirContext theFhirContext, IGraphQLStorageServices theGraphqlStorageServices, IValidationSupport theValidationSupport, ISearchParamRegistry theSearchParamRegistry, IDaoRegistry theDaoRegistry) { return new GraphQLProviderWithIntrospection(theFhirContext, theValidationSupport, theGraphqlStorageServices, theSearchParamRegistry, theDaoRegistry); } @Bean(name = "mySystemDaoR4") public IFhirSystemDao<Bundle, Meta> systemDaoR4() { ca.uhn.fhir.jpa.dao.r4.FhirSystemDaoR4 retVal = new ca.uhn.fhir.jpa.dao.r4.FhirSystemDaoR4(); return retVal; } @Bean(name = "mySystemProviderR4") public ca.uhn.fhir.jpa.provider.r4.JpaSystemProviderR4 systemProviderR4(FhirContext theFhirContext) { ca.uhn.fhir.jpa.provider.r4.JpaSystemProviderR4 retVal = new ca.uhn.fhir.jpa.provider.r4.JpaSystemProviderR4(); retVal.setContext(theFhirContext); retVal.setDao(systemDaoR4()); return retVal; } @Bean public ITermLoaderSvc termLoaderService(ITermDeferredStorageSvc theDeferredStorageSvc, ITermCodeSystemStorageSvc theCodeSystemStorageSvc) { return new TermLoaderSvcImpl(theDeferredStorageSvc, theCodeSystemStorageSvc); } @Bean public ITermReadSvcR4 terminologyService() { return new TermReadSvcR4(); } }
1,540
302
<reponame>supavit-siriwan/scenario_runner<filename>srunner/scenariomanager/actorcontrols/carla_autopilot.py #!/usr/bin/env python # Copyright (c) 2020 Intel Corporation # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ This module provides an example control for vehicles which use CARLA's autopilot functionality Limitations: - No direct velocity control - No lateral maneuvers can be enforced """ from srunner.scenariomanager.actorcontrols.basic_control import BasicControl class CarlaAutoPilotControl(BasicControl): """ Controller class for vehicles derived from BasicControl. The controller uses CARLA's autopilot functionality. As a result, the vehicle respects other traffic participants and traffic rules. However, no longitudinal or lateral maneuvers can be enforced. Args: actor (carla.Actor): Vehicle actor that should be controlled. args (dictionary): Dictonary of (key, value) arguments to be used by the controller. """ def __init__(self, actor, args=None): super(CarlaAutoPilotControl, self).__init__(actor) self._actor.set_autopilot(enabled=True) def reset(self): """ Reset the controller """ self._actor.set_autopilot(enabled=False) def run_step(self): """ Everything is controlled through CARLA's autopilot functionality. Nothing to do here """ pass
497
1,040
<reponame>titanomachy/flight #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <signal.h> #include <time.h> #include <sys/time.h> #include <iostream> #include <string> #include "../../LCM/lcmt_deltawing_u.h" #include "lcmtypes/mav_pose_t.h" // from pronto #include "../../externals/ConciseArgs.hpp" lcm_t * lcm; lcmt_deltawing_u_subscription_t * mav_pose_sub; const char *wingeron_u_channel; void sighandler(int dum) { printf("\nClosing... "); lcmt_deltawing_u_unsubscribe (lcm, mav_pose_sub); lcm_destroy (lcm); printf("done.\n"); exit(0); } int64_t getTimestampNow() { struct timeval thisTime; gettimeofday(&thisTime, NULL); return (thisTime.tv_sec * 1000000.0) + (float)thisTime.tv_usec + 0.5; } void pose_handler(const lcm_recv_buf_t *rbuf, const char* channel, const lcmt_deltawing_u *msg, void *user) { // publish control message lcmt_deltawing_u delta_u; delta_u.timestamp = getTimestampNow(); delta_u.throttle = 0; delta_u.elevonL = 128; delta_u.elevonR = 128; delta_u.is_autonomous = 1; delta_u.video_record = 0; lcmt_deltawing_u_publish(lcm, wingeron_u_channel, &delta_u); } int main(int argc,char** argv) { std::string pose_channel_str = "STATE_ESTIMATOR_POSE"; std::string wingeron_u_channel_str = "wingeron_u"; ConciseArgs parser(argc, argv); parser.add(pose_channel_str, "p", "pose-channel", "LCM channel for state estimate input"); parser.add(wingeron_u_channel_str, "u", "wingeron-u-channel", "LCM channel for wingeron_u output"); parser.parse(); lcm = lcm_create ("udpm://192.168.127.12:7667?ttl=1"); if (!lcm) { fprintf(stderr, "lcm_create for recieve failed. Quitting.\n"); return 1; } wingeron_u_channel = wingeron_u_channel_str.c_str(); mav_pose_sub = lcmt_deltawing_u_subscribe (lcm, pose_channel_str.c_str(), &pose_handler, NULL); signal(SIGINT,sighandler); printf("Listening to LCM:\n\t%s\n", pose_channel_str.c_str()); while (true) { // read the LCM channel lcm_handle (lcm); } return 0; }
994
992
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.recyclerview.selection; import static androidx.core.util.Preconditions.checkArgument; import static androidx.core.util.Preconditions.checkState; import static androidx.recyclerview.selection.Shared.DEBUG; import static androidx.recyclerview.selection.Shared.VERBOSE; import android.graphics.Point; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.RecyclerView; /** * Provides auto-scrolling upon request when user's interaction with the application * introduces a natural intent to scroll. Used by BandSelectionHelper and GestureSelectionHelper, * to provide auto scrolling when user is performing selection operations. */ final class ViewAutoScroller extends AutoScroller { private static final String TAG = "ViewAutoScroller"; // ratio used to calculate the top/bottom hotspot region; used with view height private static final float DEFAULT_SCROLL_THRESHOLD_RATIO = 0.125f; private static final int MAX_SCROLL_STEP = 70; private final float mScrollThresholdRatio; private final ScrollHost mHost; private final Runnable mRunner; private @Nullable Point mOrigin; private @Nullable Point mLastLocation; private boolean mPassedInitialMotionThreshold; ViewAutoScroller(@NonNull ScrollHost scrollHost) { this(scrollHost, DEFAULT_SCROLL_THRESHOLD_RATIO); } @VisibleForTesting ViewAutoScroller(@NonNull ScrollHost scrollHost, float scrollThresholdRatio) { checkArgument(scrollHost != null); mHost = scrollHost; mScrollThresholdRatio = scrollThresholdRatio; mRunner = new Runnable() { @Override public void run() { runScroll(); } }; } @Override public void reset() { mHost.removeCallback(mRunner); mOrigin = null; mLastLocation = null; mPassedInitialMotionThreshold = false; } @Override public void scroll(@NonNull Point location) { mLastLocation = location; // See #aboveMotionThreshold for details on how we track initial location. if (mOrigin == null) { mOrigin = location; if (VERBOSE) Log.v(TAG, "Origin @ " + mOrigin); } if (VERBOSE) Log.v(TAG, "Current location @ " + mLastLocation); mHost.runAtNextFrame(mRunner); } /** * Attempts to smooth-scroll the view at the given UI frame. Application should be * responsible to do any clean up (such as unsubscribing scrollListeners) after the run has * finished, and re-run this method on the next UI frame if applicable. */ private void runScroll() { if (DEBUG) checkState(mLastLocation != null); if (VERBOSE) Log.v(TAG, "Running in background using event location @ " + mLastLocation); // Compute the number of pixels the pointer's y-coordinate is past the view. // Negative values mean the pointer is at or before the top of the view, and // positive values mean that the pointer is at or after the bottom of the view. Note // that top/bottom threshold is added here so that the view still scrolls when the // pointer are in these buffer pixels. int pixelsPastView = 0; final int verticalThreshold = (int) (mHost.getViewHeight() * mScrollThresholdRatio); if (mLastLocation.y <= verticalThreshold) { pixelsPastView = mLastLocation.y - verticalThreshold; } else if (mLastLocation.y >= mHost.getViewHeight() - verticalThreshold) { pixelsPastView = mLastLocation.y - mHost.getViewHeight() + verticalThreshold; } if (pixelsPastView == 0) { // If the operation that started the scrolling is no longer inactive, or if it is active // but not at the edge of the view, no scrolling is necessary. return; } // We're in one of the endzones. Now determine if there's enough of a difference // from the orgin to take any action. Basically if a user has somehow initiated // selection, but is hovering at or near their initial contact point, we don't // scroll. This avoids a situation where the user initiates selection in an "endzone" // only to have scrolling start automatically. if (!mPassedInitialMotionThreshold && !aboveMotionThreshold(mLastLocation)) { if (VERBOSE) Log.v(TAG, "Ignoring event below motion threshold."); return; } mPassedInitialMotionThreshold = true; if (pixelsPastView > verticalThreshold) { pixelsPastView = verticalThreshold; } // Compute the number of pixels to scroll, and scroll that many pixels. final int numPixels = computeScrollDistance(pixelsPastView); mHost.scrollBy(numPixels); // Replace any existing scheduled jobs with the latest and greatest.. mHost.removeCallback(mRunner); mHost.runAtNextFrame(mRunner); } private boolean aboveMotionThreshold(@NonNull Point location) { // We reuse the scroll threshold to calculate a much smaller area // in which we ignore motion initially. int motionThreshold = (int) ((mHost.getViewHeight() * mScrollThresholdRatio) * (mScrollThresholdRatio * 2)); return Math.abs(mOrigin.y - location.y) >= motionThreshold; } /** * Computes the number of pixels to scroll based on how far the pointer is past the end * of the region. Roughly based on ItemTouchHelper's algorithm for computing the number of * pixels to scroll when an item is dragged to the end of a view. * @return */ @VisibleForTesting int computeScrollDistance(int pixelsPastView) { final int topBottomThreshold = (int) (mHost.getViewHeight() * mScrollThresholdRatio); final int direction = (int) Math.signum(pixelsPastView); final int absPastView = Math.abs(pixelsPastView); // Calculate the ratio of how far out of the view the pointer currently resides to // the top/bottom scrolling hotspot of the view. final float outOfBoundsRatio = Math.min( 1.0f, (float) absPastView / topBottomThreshold); // Interpolate this ratio and use it to compute the maximum scroll that should be // possible for this step. final int cappedScrollStep = (int) (direction * MAX_SCROLL_STEP * smoothOutOfBoundsRatio(outOfBoundsRatio)); // If the final number of pixels to scroll ends up being 0, the view should still // scroll at least one pixel. return cappedScrollStep != 0 ? cappedScrollStep : direction; } /** * Interpolates the given out of bounds ratio on a curve which starts at (0,0) and ends * at (1,1) and quickly approaches 1 near the start of that interval. This ensures that * drags that are at the edge or barely past the edge of the threshold does little to no * scrolling, while drags that are near the edge of the view does a lot of * scrolling. The equation y=x^10 is used, but this could also be tweaked if * needed. * @param ratio A ratio which is in the range [0, 1]. * @return A "smoothed" value, also in the range [0, 1]. */ private float smoothOutOfBoundsRatio(float ratio) { return (float) Math.pow(ratio, 10); } /** * Used by to calculate the proper amount of pixels to scroll given time passed * since scroll started, and to properly scroll / proper listener clean up if necessary. * * Callback used by scroller to perform UI tasks, such as scrolling and rerunning at next UI * cycle. */ abstract static class ScrollHost { /** * @return height of the view. */ abstract int getViewHeight(); /** * @param dy distance to scroll. */ abstract void scrollBy(int dy); /** * @param r schedule runnable to be run at next convenient time. */ abstract void runAtNextFrame(@NonNull Runnable r); /** * @param r remove runnable from being run. */ abstract void removeCallback(@NonNull Runnable r); } static ScrollHost createScrollHost(final RecyclerView recyclerView) { return new RuntimeHost(recyclerView); } /** * Tracks location of last surface contact as reported by RecyclerView. */ private static final class RuntimeHost extends ScrollHost { private final RecyclerView mRecyclerView; RuntimeHost(@NonNull RecyclerView recyclerView) { mRecyclerView = recyclerView; } @Override void runAtNextFrame(@NonNull Runnable r) { ViewCompat.postOnAnimation(mRecyclerView, r); } @Override void removeCallback(@NonNull Runnable r) { mRecyclerView.removeCallbacks(r); } @Override void scrollBy(int dy) { if (VERBOSE) Log.v(TAG, "Scrolling view by: " + dy); mRecyclerView.scrollBy(0, dy); } @Override int getViewHeight() { return mRecyclerView.getHeight(); } } }
3,709
460
/* * Copyright 2007-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.paoding.rose.web.impl.thread; import net.paoding.rose.web.Invocation; /** * * @author 王志亮 [<EMAIL>] * */ public interface AfterCompletion { /** * 整个流程(包括页面render流程)结束时调用,不管是否发生过异常。如果发生了异常,则将传送一个非空的Throwable对象到该方法。 * <p> * 只有之前调用before时返回true时才会调用到它的afterRender方法 * * @param inv * @param ex * @throws Exception */ void afterCompletion(Invocation inv, Throwable ex) throws Exception; }
501
1,262
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.metacat.common.server.usermetadata; import com.netflix.metacat.common.server.model.Lookup; import javax.annotation.Nullable; import java.util.Collections; import java.util.Set; /** * Lookup service API. * * @author amajumdar */ public interface LookupService { /** * Returns the lookup for the given <code>name</code>. * * @param name lookup name * @return lookup */ @Nullable default Lookup get(final String name) { return null; } /** * Returns the value of the lookup name. * * @param name lookup name * @return scalar lookup value */ default String getValue(final String name) { return null; } /** * Returns the list of values of the lookup name. * * @param name lookup name * @return list of lookup values */ default Set<String> getValues(final String name) { return Collections.emptySet(); } /** * Returns the list of values of the lookup name. * * @param lookupId lookup id * @return list of lookup values */ default Set<String> getValues(final Long lookupId) { return Collections.emptySet(); } /** * Saves the lookup value. * * @param name lookup name * @param values multiple values * @return updated lookup */ @Nullable default Lookup setValues(final String name, final Set<String> values) { return null; } /** * Saves the lookup value. * * @param name lookup name * @param values multiple values * @return updated lookup */ @Nullable default Lookup addValues(final String name, final Set<String> values) { return null; } /** * Saves the lookup value. * * @param name lookup name * @param value lookup value * @return updated lookup */ @Nullable default Lookup setValue(final String name, final String value) { return null; } }
977
7,073
def keyword_in_my_lib_file(): print('Here we go!!') def embedded(arg): print(arg) embedded.robot_name = 'Keyword with embedded ${arg} in MyLibFile'
61
1,618
// // PrismRuntimeUtil.h // DiDiPrism // // Created by hulk on 2019/6/27. // #import <Foundation/Foundation.h> #import <objc/runtime.h> NS_ASSUME_NONNULL_BEGIN @interface PrismRuntimeUtil : NSObject + (void)hookClass:(Class)cls originalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector; + (void)hookClass:(Class)cls originalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector isClassMethod:(BOOL)isClassMethod; @end NS_ASSUME_NONNULL_END
184
10,225
<filename>extensions/resteasy-reactive/quarkus-resteasy-reactive-servlet/deployment/src/test/java/io/quarkus/resteasy/reactive/server/servlet/test/ServletSimpleRestTestCase.java package io.quarkus.resteasy.reactive.server.servlet.test; import io.quarkus.resteasy.reactive.server.test.simple.SimpleQuarkusRestTestCase; public class ServletSimpleRestTestCase extends SimpleQuarkusRestTestCase { }
134
495
/* * Copyright 2014-2016 Media for Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.m4m; import org.m4m.domain.MediaFormat; import org.m4m.domain.Resolution; /** * This class is used to describe and/or setup parameters of video data. */ public abstract class VideoFormat extends MediaFormat { public static final String MIME_TYPE = "video/avc"; // H.264 Advanced Video Coding private static final java.lang.String KEY_BIT_RATE = "bitrate"; private static final java.lang.String KEY_COLOR_FORMAT = "color-format"; private static final java.lang.String KEY_FRAME_RATE = "frame-rate"; private static final java.lang.String KEY_I_FRAME_INTERVAL = "i-frame-interval"; public static final java.lang.String KEY_HEIGHT = "height"; public static final java.lang.String KEY_WIDTH = "width"; private static final String NO_INFO_AVAILABLE = "No info available."; private String mimeType; private int width; private int height; protected void setVideoCodec(String mimeType) { this.mimeType = mimeType; } /** * Returns video codec MIME type. * * @return MIME type. */ public String getVideoCodec() { return mimeType; } /** * Sets video frame size. * * @param width Frame width. * @param height Frame height. */ public void setVideoFrameSize(int width, int height) { this.width = width; this.height = height; } /** * Returns video frame size. * * @return {@link Resolution} Structure with frame width and height. */ public Resolution getVideoFrameSize() { return new Resolution(width, height); } /** * Returns video bit rate in KBytes. * * @return Video bit rate in KBytes. * @throws RuntimeException when there is no information on the parameter. */ public int getVideoBitRateInKBytes() { try { return getInteger(KEY_BIT_RATE) / 1024; } catch (NullPointerException e) { throw new RuntimeException(NO_INFO_AVAILABLE); } } /** * Sets video bit rate in KBytes. * * @param bitRate Video bit rate in KBytes. */ public void setVideoBitRateInKBytes(int bitRate) { if (width * height * 30 * 2 * 0.00007 < bitRate) { bitRate = (int) (width * height * 30 * 2 * 0.00007); } setInteger(KEY_BIT_RATE, bitRate * 1024); } /** * Returns video frame rate in frames/sec. * * @return Video frame rate in frames/sec. * @throws RuntimeException when there is no information on the parameter. */ public int getVideoFrameRate() { try { return getInteger(KEY_FRAME_RATE); } catch (NullPointerException e) { throw new RuntimeException(NO_INFO_AVAILABLE); } } /** * Sets video frame rate in frames/sec. * * @param bitRate Video frame rate in frames/sec. */ public void setVideoFrameRate(int bitRate) { setInteger(KEY_FRAME_RATE, bitRate); } /** * Sets frequency of I frames expressed in secs between I frames. * * @param iFrameIntervalInSecs Frequency of I frames expressed in secs between I frames. */ public void setVideoIFrameInterval(int iFrameIntervalInSecs) { setInteger(KEY_I_FRAME_INTERVAL, iFrameIntervalInSecs); } /** * Returns frequency of I frames expressed in secs between I frames. * * @return Frequency of I frames expressed in secs between I frames. * @throws RuntimeException when there is no information on the parameter. */ public int getVideoIFrameInterval() { try { return getInteger(KEY_I_FRAME_INTERVAL); } catch (NullPointerException e) { throw new RuntimeException(NO_INFO_AVAILABLE); } } /** * Sets the color format of the content. * See http://developer.android.com/reference/android/media/MediaCodecInfo.CodecCapabilities.html for values. * * @param colorFormat Color format. */ public void setColorFormat(int colorFormat) { setInteger(KEY_COLOR_FORMAT, colorFormat); } }
1,766
305
""" Remaining problems: 1. _testdoc.do.txt: !bc |bc pycod def f(x): return x+1 |ec !ec does not work properly. 2. """ from __future__ import absolute_import from builtins import str from builtins import range from past.builtins import basestring import re, sys from .common import default_movie, plain_exercise, bibliography, \ cite_with_multiple_args2multiple_cites, insert_code_and_tex, \ fix_ref_section_chapter from .misc import option from .doconce import errwarn def matlabnb_author(authors_and_institutions, auth2index, inst2index, index2inst, auth2email): text = '\n' for author in auth2index: email = auth2email[author] email_text = '' if email is None else '(%s)' % email text += ' '.join(['Author: ' + author, str(auth2index[author]), email_text]) + '\n' text += '\n' for index in index2inst: text += '[%d] %s\n' % (index, index2inst[index]) text += '\n' return text def matlabnb_code(filestr, code_blocks, code_block_types, tex_blocks, format): # Remove all begin-end and \[ \] in tex blocks, join to one line, # embed in $$. Write error message if anything else than a single equation. pattern = 'begin\{(.+?)\}' for i in range(len(tex_blocks)): m = re.search(pattern, tex_blocks[i]) if m: envir = m.group(1) if envir not in ('equation', 'equation*'): errwarn('*** warning: \\begin{%s}-\\end{%s} does not work in Matlab notebooks' % (envir, envir)) tex_blocks[i] = re.sub(r'\\begin{%s}\s+' % envir, '', tex_blocks[i]) tex_blocks[i] = re.sub(r'\\end{%s}\s+' % envir, '', tex_blocks[i]) tex_blocks[i] = re.sub(r'\\\[', '', tex_blocks[i]) tex_blocks[i] = re.sub(r'\\\]', '', tex_blocks[i]) tex_blocks[i] = re.sub(r'label\{(.+?)\}', '', tex_blocks[i]) tex_blocks[i] = '$$' + ' '.join(tex_blocks[i].strip().splitlines()).strip() + '$$' # Note: now the tex block ends with $$!et # Insert % in code if envir with -t name or if not Matlab code for i in range(len(code_blocks)): executable_matlab = code_block_types[i] in ('mcod', 'mpro') if not executable_matlab: # Note that monospace font requires two blanks after % code_blocks[i] = '\n'.join([ '% ' + line for line in code_blocks[i].splitlines() if not (line.startswith('!bc') or line.startswith('!ec'))]) + '\n' # Insert % at the beginning of each line from .common import _CODE_BLOCK, _MATH_BLOCK code_line = r'^\d+ ' + _CODE_BLOCK code_line_problem = r' (\d+ ' + _CODE_BLOCK + ')' math_line = r'^\d+ ' + _MATH_BLOCK math_line_problem = r' (\d+ ' + _MATH_BLOCK + ')' heading_no = 0 lines = filestr.splitlines() for i in range(len(lines)): if re.search(code_line, lines[i], flags=re.MULTILINE): if heading_no < 2: # Add %% (empty heading) before code block because # code cannot come after the first heading, only # after the second and onwards lines[i] = '%%\n' + lines[i] continue elif re.search(math_line, lines[i], flags=re.MULTILINE): continue elif re.search(code_line_problem, lines[i], flags=re.MULTILINE): # Paragraphs can move a block indicator after its heading, insert \n lines[i] = re.sub(code_line_problem, '\n\g<1>', lines[i]) elif re.search(math_line_problem, lines[i], flags=re.MULTILINE): # Paragraphs can move a block indicator after its heading, insert \n lines[i] = re.sub(math_line_problem, '\n\g<1>', lines[i]) elif lines[i].startswith('>>>H'): # Heading lines[i] = '%%' + lines[i].replace('>>>H', '') heading_no += 1 else: lines[i] = '% ' + lines[i] filestr = '\n'.join(lines) filestr = insert_code_and_tex(filestr, code_blocks, tex_blocks, 'matlabnb') filestr = re.sub(r'\$\$!et', '$$', filestr, flags=re.MULTILINE) filestr = re.sub(r'^!bt\s+\$\$', '% $$', filestr, flags=re.MULTILINE) filestr = re.sub(r'^!bc.+', '', filestr, flags=re.MULTILINE) filestr = re.sub(r'^!ec', '', filestr, flags=re.MULTILINE) # Remove all blank lines filestr = re.sub(r'^\s+', '', filestr, flags=re.MULTILINE) # Fix emphasize markup (conflicts with boldface so we do a hack) filestr = re.sub(r'\^\^\^X(.+?)X\^\^\^', '_\g<1>_', filestr, flags=re.DOTALL) # emph filestr = re.sub(r'\{\{\{X(.+?)X\}\}\}', '*\g<1>*', filestr, flags=re.DOTALL) # bold filestr = re.sub(r'<<<X(.+?)X>>>', '|\g<1>|', filestr, flags=re.DOTALL) # verb return filestr def matlabnb_ref_and_label(section_label2title, format, filestr): filestr = fix_ref_section_chapter(filestr, format) # remove label{...} from output (when only label{} on a line, remove # the newline too, leave label in figure captions, and remove all the rest) #filestr = re.sub(r'^label\{.+?\}\s*$', '', filestr, flags=re.MULTILINE) cpattern = re.compile(r'^label\{.+?\}\s*$', flags=re.MULTILINE) filestr = cpattern.sub('', filestr) #filestr = re.sub(r'^(FIGURE:.+)label\{(.+?)\}', '\g<1>{\g<2>}', filestr, flags=re.MULTILINE) cpattern = re.compile(r'^(FIGURE:.+)label\{(.+?)\}', flags=re.MULTILINE) filestr = cpattern.sub('\g<1>{\g<2>}', filestr) filestr = re.sub(r'label\{.+?\}', '', filestr) # all the remaining # replace all references to sections: for label in section_label2title: filestr = filestr.replace('ref{%s}' % label, '"%s"' % section_label2title[label]) from .common import ref2equations filestr = ref2equations(filestr) return filestr def matlabnb_index_bib(filestr, index, citations, pubfile, pubdata): if citations: filestr = cite_with_multiple_args2multiple_cites(filestr) for label in citations: filestr = filestr.replace('cite{%s}' % label, '[%d]' % citations[label]) if pubfile is not None: bibtext = bibliography(pubdata, citations, format='doconce') bibtext = re.sub(r'label\{.+?\} ', '', bibtext) # Remove boldface _author_ (typically 12. _<NAME> and <NAME>_.) bibtext = re.sub(r'(\d+)\. _(.+)_\.', '\g<2>', bibtext) filestr = re.sub(r'^BIBFILE:.+$', bibtext, filestr, flags=re.MULTILINE) # remove all index entries: filestr = re.sub(r'idx\{.+?\}\n?', '', filestr) # no index since line numbers from the .do.txt (in index dict) # never correspond to the output format file #filestr += '\n\n======= Index =======\n\n' #for word in index: # filestr + = '%s, line %s\n' % (word, ', '.join(index[word])) return filestr def matlabnb_toc(sections, filestr): # Find minimum section level tp_min = 4 for title, tp, label in sections: if tp < tp_min: tp_min = tp s = 'Table of contents:\n\n' for title, tp, label in sections: s += ' '*(2*(tp-tp_min)) + title + '\n' return s def matlabnb_box(text, title=''): """Wrap a box around the text, with a title on the upper box border.""" lines = text.splitlines() maxlen = max([len(line) for line in lines]) newlines = [] # title can be :: since equations and code must be preceeded by :: # and plaintext inserts a double colon if title == '' or title.lower() == 'none' or title == '::': newlines.append('|-' + '-'*maxlen + '-|') else: newlines.append(title + ' ' + '-'*(maxlen-len(title)) + '--|') for line in lines: newlines.append('| ' + line + ' '*(maxlen-len(line)) + ' |') newlines.append('|-' + '-'*maxlen + '-|') # Drop blank lines at the beginning drop = 0 for line in newlines[1:]: if re.search(r'[^\-| ]', line): break else: drop += 1 for i in range(drop): del newlines[1] if re.search(r'^\w', newlines[0]): # Insert a blank line newlines.insert(1, '| ' + ' '*maxlen + ' |') # Drop blank lines at the end drop = 0 for line in reversed(newlines[:-1]): if re.search(r'[^\-| ]', line): break else: drop += 1 for i in range(1, drop+1, 1): del newlines[-2] return '\n' + '\n'.join(newlines) + '\n' def matlabnb_quiz(quiz): # Simple typesetting of a quiz import string question_prefix = quiz.get('question prefix', option('quiz_question_prefix=', 'Question:')) common_choice_prefix = option('quiz_choice_prefix=', 'Choice') quiz_expl = option('quiz_explanations=', 'on') text = '\n\n' if 'new page' in quiz: text += '======= %s =======\n\n' % (quiz['new page']) # Don't write Question: ... if inside an exercise section if quiz.get('embedding', 'None') in ['exercise',]: pass else: text += '\n' if question_prefix: text += '%s ' % (question_prefix) text += quiz['question'] + '\n\n' # List choices as paragraphs for i, choice in enumerate(quiz['choices']): #choice_no = i+1 choice_no = string.ascii_uppercase[i] answer = choice[0].capitalize() + '!' choice_prefix = common_choice_prefix if 'choice prefix' in quiz: if isinstance(quiz['choice prefix'][i], basestring): choice_prefix = quiz['choice prefix'][i] if choice_prefix == '' or choice_prefix[-1] in ['.', ':', '?']: pass # don't add choice number/letter else: choice_prefix += ' %s:' % choice_no # Let choice start with a newline if pure code starts the choice # (test for different code block types so this function can work # for other formats too...) choice = choice[1].lstrip() code_starters = 'Code::', '~~~', '```', '{{{' for code_starter in code_starters: if choice.startswith(code_starter): choice = '\n' + choice # Cannot treat explanations text += '%s %s\n\n' % (choice_prefix, choice) return text def define(FILENAME_EXTENSION, BLANKLINE, INLINE_TAGS_SUBST, CODE, LIST, ARGLIST, TABLE, EXERCISE, FIGURE_EXT, CROSS_REFS, INDEX_BIB, TOC, ENVIRS, QUIZ, INTRO, OUTRO, filestr): # all arguments are dicts and accept in-place modifications (extensions) FILENAME_EXTENSION['matlabnb'] = '.m' BLANKLINE['matlabnb'] = '\n' # replacement patterns for substitutions of inline tags encoding = 'utf-8' INLINE_TAGS_SUBST['matlabnb'] = { 'math': None, 'math2': r'\g<begin>$\g<latexmath>$\g<end>', # emphasize goes to _..._ and bold subst afterwards takes it to *...* # make a different syntax and fix it in matlabnb_code 'emphasize': r'\g<begin>^^^X\g<subst>X^^^\g<end>', 'bold': r'\g<begin>*\g<subst>*\g<end>', # Need a hack to avoid |...| for verbatim to avoid conflict in tables 'verbatim': r'\g<begin><<<X\g<subst>X>>>\g<end>', 'figure': lambda m: '<<%s>>' % m.group('filename'), 'movie': default_movie, 'linkURL2': r'\g<link> <\g<url>>', 'linkURL3': r'\g<link> <\g<url>>', 'linkURL2v': r'\g<link> <\g<url>>', 'linkURL3v': r'\g<link> <\g<url>>', 'plainURL': r'<\g<url>>', 'comment': r'%% %s', 'inlinecomment': None, 'colortext': '\g<text>', 'title': r'>>>H \g<subst>\n', 'author': matlabnb_author, 'date': r'\nDate: \g<subst>\n', 'chapter': r'>>>H \g<subst>', 'section': r'>>>H \g<subst>', 'subsection': r'>>>H \g<subst>', 'subsubsection': r'>>>H \g<subst>', # Same problem with abstract/paragraph as with emphasize, use same trick 'abstract': r'\n{{{X\g<type>.X}}} \g<text>\g<rest>', 'paragraph': r'{{{X\g<subst>X}}} ', # extra blank 'linebreak': r'\g<text>', 'footnote': None, 'non-breaking-space': ' ', 'ampersand2': r' \g<1>&\g<2>', } CODE['matlabnb'] = matlabnb_code from .common import DEFAULT_ARGLIST ARGLIST['matlabnb'] = DEFAULT_ARGLIST FIGURE_EXT['matlabnb'] = { 'search': ('.png', '.gif', '.jpg', '.jpeg', '.pdf'), #.pdf? 'convert': ('.png', '.gif', '.jpg')} LIST['matlabnb'] = { 'itemize': {'begin': '', 'item': '*', 'end': '\n'}, 'enumerate': {'begin': '', 'item': '#', 'end': '\n'}, 'description': {'begin': '', 'item': '%s', 'end': '\n'}, 'separator': '\n', } CROSS_REFS['matlabnb'] = matlabnb_ref_and_label from .html import html_table TABLE['matlabnb'] = html_table #TABLE['matlabnb'] = matlabnb_table EXERCISE['matlabnb'] = plain_exercise INDEX_BIB['matlabnb'] = matlabnb_index_bib TOC['matlabnb'] = matlabnb_toc from .common import indent_lines ENVIRS['matlabnb'] = { 'warning': lambda block, format, title='Warning', text_size='normal': matlabnb_box(block, title), 'notice': lambda block, format, title='Notice', text_size='normal': matlabnb_box(block, title), 'question': lambda block, format, title='Question', text_size='normal': matlabnb_box(block, title), 'hint': lambda block, format, title='Hint', text_size='normal': matlabnb_box(block, title), 'summary': lambda block, format, title='Summary', text_size='normal': matlabnb_box(block, title), 'block': lambda block, format, title='Block', text_size='normal': matlabnb_box(block, title), 'box': lambda block, format, title='none', text_size='normal': matlabnb_box(block, title), 'quote': lambda block, format, title='none', text_size='normal': indent_lines(block, 'matlabnb'), } QUIZ['matlabnb'] = matlabnb_quiz
6,877
590
/******************************************************************************* * Copyright 2017 Bstek * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.bstek.uflo.service; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.zip.ZipInputStream; import com.bstek.uflo.model.ProcessDefinition; import com.bstek.uflo.model.ProcessInstance; import com.bstek.uflo.model.variable.Variable; import com.bstek.uflo.query.ProcessInstanceQuery; import com.bstek.uflo.query.ProcessQuery; import com.bstek.uflo.query.ProcessVariableQuery; /** * @author Jacky.gao * @since 2013年7月29日 */ public interface ProcessService { public static final String BEAN_ID="uflo.processService"; /** * 根据流程模版ID,返回流程模版对象 * @param processId 流程模版ID * @return 返回流程模版对象 */ ProcessDefinition getProcessById(long processId); /** * 根据流程模版Key,返回流程模版对象 * @param key 流程模版Key * @return 返回流程模版对象 */ ProcessDefinition getProcessByKey(String key); /** * 根据流程模版的名称,返回与该名字匹配最新发布的流程模版对象 * @param processName 流程模版名称 * @return 返回流程模版对象 */ ProcessDefinition getProcessByName(String processName); /** * 根据流程模版的名称及分类ID,返回与该名字匹配最新发布的流程模版对象 * @param processName 流程模版名称 * @param categoryId 分类ID * @return 返回流程模版对象 */ ProcessDefinition getProcessByName(String processName,String categoryId); /** * 根据流程模版的名称与版本号,返回与该名字与版本号匹配最流程模版对象 * @param processName 流程模版名称 * @param version 版本号 * @return 返回流程模版对象 */ ProcessDefinition getProcessByName(String processName,int version); /** * 根据流程模版ID,开启一个流程实例 * @param processId 流程模版ID * @param startProcessInfo 开启流程实例时所需要的各种信息的包装对象 * @return 返回开启成功的流程实例对象 */ ProcessInstance startProcessById(long processId,StartProcessInfo startProcessInfo); /** * 根据流程模版key,开启一个流程实例 * @param key 流程模版key * @param startProcessInfo 开启流程实例时所需要的各种信息的包装对象 * @return 返回开启成功的流程实例对象 */ ProcessInstance startProcessByKey(String key,StartProcessInfo startProcessInfo); /** * 根据流程模版的名称,根据该名称流程模版最新版本开启一个流程实例 * @param processName 流程模版名称 * @param startProcessInfo 开启流程实例时所需要的各种信息的包装对象 * @return 返回开启成功的流程实例对象 */ ProcessInstance startProcessByName(String processName,StartProcessInfo startProcessInfo); /** * 根据流程模版的名称与版本号,开启一个流程实例 * @param processName 流程模版名称 * @param startProcessInfo 开启流程实例时所需要的各种信息的包装对象 * @param version 版本号 * @return 返回开启成功的流程实例对象 */ ProcessInstance startProcessByName(String processName,StartProcessInfo startProcessInfo,int version); /** * 删除一个指定的流程实例对象,与这个流程实例相关的人工任务也将会被删除 * @param processInstance 流程实例对象 */ void deleteProcessInstance(ProcessInstance processInstance); /** * 删除指定流程实例ID对应的流程实例对象 * @param processInstanceId 流程实例ID */ void deleteProcessInstanceById(long processInstanceId); /** * 从一个压缩文件包中部署一个新的流程模版 * @param zipInputStream 一个压缩文件输入流 * @return 部署成功后的流程模版对象 */ ProcessDefinition deployProcess(ZipInputStream zipInputStream); /** * 从一个文件流中部署一个新的流程模版 * @param inputStream 文件流 * @return 部署成功后的流程模版对象 */ ProcessDefinition deployProcess(InputStream inputStream); /** * 更新一个流程模版,用指定InputStream中包含的流程模版对象来替换指定ID的流程模版对象 * @param inputStream 新的流程模版流对象 * @param processId 要替换的目标流程模版ID * @return 更新成功后的流程模版对象 */ ProcessDefinition deployProcess(InputStream inputStream,long processId); /** * 根据给定的流程实例ID,返回对应的流程实例对象 * @param processInstanceId 流程实例ID * @return 返回流程实例对象 */ ProcessInstance getProcessInstanceById(long processInstanceId); /** * 根据流程实例ID,返回与该流程实例相关的所有的流程变量 * @param processInsanceId 流程实例ID * @return 返回与该流程实例相关的所有的流程变量集合 */ List<Variable> getProcessVariables(long processInsanceId); /** * 根据流程实例对象,返回与该流程实例相关的所有的流程变量 * @param processInsance 流程实例对象 * @return 返回与该流程实例相关的所有的流程变量集合 */ List<Variable> getProcessVariables(ProcessInstance processInsance); /** * 获取指定流程实例上的指定key的流程变量的值 * @param key 流程变量的key * @param processInstance 流程实例对象 * @return 流程变量值 */ Object getProcessVariable(String key,ProcessInstance processInstance); /** * 获取指定流程实例ID上对应的流程实例中指定key的流程变量的值 * @param key 流程变量的key * @param processInsanceId 流程实例ID * @return 流程变量值 */ Object getProcessVariable(String key,long processInsanceId); /** * 删除指定流程实例ID中指定key的流程变量值 * @param key 流程变量的key * @param processInstanceId 流程实例ID */ void deleteProcessVariable(String key,long processInstanceId); /** * 向指定流程实例ID对应的流程实例中添加流程变量 * @param processInstanceId 流程实例ID * @param key 流程变量的key * @param value 对应的流程变量的值 */ void saveProcessVariable(long processInstanceId,String key,Object value); /** * 向指定流程实例ID对应的流程实例中批量添加流程变量 * @param processInstanceId 流程实例ID * @param variables 要添加的流程变量的Map */ void saveProcessVariables(long processInstanceId,Map<String,Object> variables); /** * @return 返回创建成功的流程实例查询对象 */ ProcessInstanceQuery createProcessInstanceQuery(); /** * @return 返回创建成功的流程变量查询对象 */ ProcessVariableQuery createProcessVariableQuery(); /** * @return 创建创建成功的流程模版查询对象 */ ProcessQuery createProcessQuery(); /** * 删除一个指定ID的流程模版对象,与该模版相关的所有实例及任务都将被删除 * @param processId 流程模版ID */ void deleteProcess(long processId); /** * 删除一个指定KEY的流程模版对象,与该模版相关的所有实例及任务都将被删除 * @param processKey 流程模版KEY */ void deleteProcess(String processKey); /** * 删除一个指定流程模版对象,与该模版相关的所有实例及任务都将被删除 * @param processDefinition 流程模版对象 */ void deleteProcess(ProcessDefinition processDefinition); /** * 根据给定的流程模版ID,更新当前内存中保存的对应的流程模版对象 * @param processId 流程模版ID */ void updateProcessForMemory(long processId); /** * 从本地内存中移除指定的流程模版ID对应的流程模版对象 * @param processId 流程模版ID */ void deleteProcessFromMemory(long processId); /** * 从本地内存中移除指定的流程模版KEY对应的流程模版对象 * @param processKey 流程模版KEY */ void deleteProcessFromMemory(String processKey); /** * 从本地内存中移除指定的流程模版对象 * @param processDefinition 流程模版对象 */ void deleteProcessFromMemory(ProcessDefinition processDefinition); }
4,325
376
<reponame>BIGWangYuDong/mmfewshot _base_ = [ '../../_base_/datasets/nway_kshot/base_coco.py', '../../_base_/schedules/schedule.py', '../fsdetview_r50_c4.py', '../../_base_/default_runtime.py' ] lr_config = dict(warmup_iters=1000, step=[80000]) runner = dict(max_iters=80000) optimizer = dict(lr=0.01) # model settings model = dict( roi_head=dict(bbox_head=dict(num_classes=60, num_meta_classes=60))) checkpoint_config = dict(interval=10000) evaluation = dict(interval=10000, metric='bbox', classwise=True)
223
859
<filename>tests/commands/completion/test_completions_command.py # -*- coding: utf-8 -*- import os import pytest from cleo.application import Application from cleo.testers.command_tester import CommandTester from .fixtures.command_with_colons import CommandWithColons from .fixtures.hello_command import HelloCommand app = Application() app.add(HelloCommand()) app.add(CommandWithColons()) def test_invalid_shell(): command = app.find("completions") tester = CommandTester(command) with pytest.raises(ValueError): tester.execute("pomodoro") def test_bash(mocker): mocker.patch( "cleo.io.inputs.string_input.StringInput.script_name", new_callable=mocker.PropertyMock, return_value="/path/to/my/script", ) mocker.patch( "cleo.commands.completions_command.CompletionsCommand._generate_function_name", return_value="_my_function", ) command = app.find("completions") tester = CommandTester(command) tester.execute("bash") with open(os.path.join(os.path.dirname(__file__), "fixtures", "bash.txt")) as f: expected = f.read() assert expected == tester.io.fetch_output().replace("\r\n", "\n") def test_zsh(mocker): mocker.patch( "cleo.io.inputs.string_input.StringInput.script_name", new_callable=mocker.PropertyMock, return_value="/path/to/my/script", ) mocker.patch( "cleo.commands.completions_command.CompletionsCommand._generate_function_name", return_value="_my_function", ) command = app.find("completions") tester = CommandTester(command) tester.execute("zsh") with open(os.path.join(os.path.dirname(__file__), "fixtures", "zsh.txt")) as f: expected = f.read() assert expected == tester.io.fetch_output().replace("\r\n", "\n") def test_fish(mocker): mocker.patch( "cleo.io.inputs.string_input.StringInput.script_name", new_callable=mocker.PropertyMock, return_value="/path/to/my/script", ) mocker.patch( "cleo.commands.completions_command.CompletionsCommand._generate_function_name", return_value="_my_function", ) command = app.find("completions") tester = CommandTester(command) tester.execute("fish") with open(os.path.join(os.path.dirname(__file__), "fixtures", "fish.txt")) as f: expected = f.read() assert expected == tester.io.fetch_output().replace("\r\n", "\n")
1,007
856
package org.lionsoul.jcseg.segmenter; import java.util.ArrayList; import org.lionsoul.jcseg.IChunk; /** * mmseg default filter class * * @author chenxin<<EMAIL>> */ public class MMSegFilter { /** * 1. the maximum match rule * this rule will return the chunks that own the largest word length */ public static ArrayList<IChunk> getMaximumMatchChunks(ArrayList<IChunk> chunks, ArrayList<IChunk> chunkArr) { int maxLength = chunks.get(0).getLength(); int j; //find the maximum word length for ( j = 1; j < chunks.size(); j++ ) { if ( chunks.get(j).getLength() > maxLength ) { maxLength = chunks.get(j).getLength(); } } //get the items that the word length equals to the largest. chunkArr.clear(); for ( j = 0; j < chunks.size(); j++ ) { if ( chunks.get(j).getLength() == maxLength) { chunkArr.add(chunks.get(j)); } } return chunkArr; } /** * 2. largest average word length * this rule will return the chunks that own the largest average word length */ public static ArrayList<IChunk> getLargestAverageWordLengthChunks(ArrayList<IChunk> chunks, ArrayList<IChunk> chunkArr) { double largetAverage = chunks.get(0).getAverageWordsLength(); int j; //find the largest average word length for ( j = 1; j < chunks.size(); j++ ) { if ( chunks.get(j).getAverageWordsLength() > largetAverage ) { largetAverage = chunks.get(j).getAverageWordsLength(); } } //get the items that the average word length equals to the largest. chunkArr.clear(); for ( j = 0; j < chunks.size(); j++ ) { if ( chunks.get(j).getAverageWordsLength() == largetAverage) { chunkArr.add(chunks.get(j)); } } return chunkArr; } /** * 2 */ /** * the smallest variance word length * this rule will the chunks that one the smallest variance word length */ public static ArrayList<IChunk> getSmallestVarianceWordLengthChunks(ArrayList<IChunk> chunks, ArrayList<IChunk> chunkArr) { double smallestVariance = chunks.get(0).getWordsVariance(); int j; //find the smallest variance word length for ( j = 1; j < chunks.size(); j++ ) { if ( chunks.get(j).getWordsVariance() < smallestVariance ) { smallestVariance = chunks.get(j).getWordsVariance(); } } //get the items that the variance word length equals to the largest chunkArr.clear(); for ( j = 0; j < chunks.size(); j++ ) { if ( chunks.get(j).getWordsVariance() == smallestVariance) { chunkArr.add(chunks.get(j)); } } return chunkArr; } /** * the largest sum of degree of morphemic freedom of one-character words * this rule will return the chunks that own the largest sum of degree of morphemic freedom * of one-character */ public static ArrayList<IChunk> getLargestSingleMorphemicFreedomChunks(ArrayList<IChunk> chunks, ArrayList<IChunk> chunkArr) { double largestFreedom = chunks.get(0).getSingleWordsMorphemicFreedom(); int j; //find the maximum sum of single morphemic freedom for ( j = 1; j < chunks.size(); j++ ) { if ( chunks.get(j).getSingleWordsMorphemicFreedom() > largestFreedom ) { largestFreedom = chunks.get(j).getSingleWordsMorphemicFreedom(); } } //get the items that the word length equals to the largest. chunkArr.clear(); for ( j = 0; j < chunks.size(); j++ ) { if ( chunks.get(j).getSingleWordsMorphemicFreedom() == largestFreedom) { chunkArr.add(chunks.get(j)); } } return chunkArr; } }
1,887
2,504
<gh_stars>1000+ //********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Animate.h" using namespace DirectX; Animate::Animate() : m_continuous(false), m_startTime(0.0f), m_duration(10.0f) { } float Animate::Start() { return m_startTime; } void Animate::Start(_In_ float start) { m_startTime = start; } float Animate::Duration() { return m_duration; } void Animate::Duration(_In_ float duration) { m_duration = duration; } bool Animate::Continuous() { return m_continuous; } void Animate::Continuous(_In_ bool continuous) { m_continuous = continuous; } AnimateLinePosition::AnimateLinePosition( _In_ XMFLOAT3 startPosition, _In_ XMFLOAT3 endPosition, _In_ float duration, _In_ bool continuous) { m_startPosition = startPosition; m_endPosition = endPosition; m_duration = duration; m_continuous = continuous; m_length = XMVectorGetX( XMVector3Length(XMLoadFloat3(&endPosition) - XMLoadFloat3(&startPosition)) ); } XMFLOAT3 AnimateLinePosition::Evaluate(_In_ float t) { if (t <= m_startTime) { return m_startPosition; } if ((t >= (m_startTime + m_duration)) && !m_continuous) { return m_endPosition; } float startTime = m_startTime; if (m_continuous) { // For continuous operation move the start time forward to // eliminate previous iterations. startTime += ((int)((t - m_startTime) / m_duration)) * m_duration; } float u = (t - startTime) / m_duration; XMFLOAT3 currentPosition; currentPosition.x = m_startPosition.x + (m_endPosition.x - m_startPosition.x) * u; currentPosition.y = m_startPosition.y + (m_endPosition.y - m_startPosition.y) * u; currentPosition.z = m_startPosition.z + (m_endPosition.z - m_startPosition.z) * u; return currentPosition; } AnimateLineListPosition::AnimateLineListPosition( _In_ unsigned int count, _In_reads_(count) XMFLOAT3 const position[], _In_ float duration, _In_ bool continuous) { m_duration = duration; m_continuous = continuous; m_count = count; m_segment = std::vector<LineSegment>(m_count); m_totalLength = 0.0f; m_segment[0].position = position[0]; for (unsigned int i = 1; i < count; i++) { m_segment[i].position = position[i]; m_segment[i - 1].length = XMVectorGetX( XMVector3Length( XMLoadFloat3(&m_segment[i].position) - XMLoadFloat3(&m_segment[i - 1].position) ) ); m_totalLength += m_segment[i - 1].length; } // Parameterize the segments to ensure uniform evaluation along the path. float u = 0.0f; for (unsigned int i = 0; i < (count - 1); i++) { m_segment[i].uStart = u; m_segment[i].uLength = (m_segment[i].length / m_totalLength); u += m_segment[i].uLength; } m_segment[count - 1].uStart = 1.0f; } XMFLOAT3 AnimateLineListPosition::Evaluate(_In_ float t) { if (t <= m_startTime) { return m_segment[0].position; } if ((t >= (m_startTime + m_duration)) && !m_continuous) { return m_segment[m_count - 1].position; } float startTime = m_startTime; if (m_continuous) { // For continuous operation move the start time forward to // eliminate previous iterations. startTime += ((int)((t - m_startTime) / m_duration)) * m_duration; } float u = (t - startTime) / m_duration; // Find the right segment. unsigned int i = 0; while (u > m_segment[i + 1].uStart) { i++; } u -= m_segment[i].uStart; u /= m_segment[i].uLength; XMFLOAT3 currentPosition; currentPosition.x = m_segment[i].position.x + (m_segment[i + 1].position.x - m_segment[i].position.x) * u; currentPosition.y = m_segment[i].position.y + (m_segment[i + 1].position.y - m_segment[i].position.y) * u; currentPosition.z = m_segment[i].position.z + (m_segment[i + 1].position.z - m_segment[i].position.z) * u; return currentPosition; } AnimateCirclePosition::AnimateCirclePosition( _In_ XMFLOAT3 center, _In_ XMFLOAT3 startPosition, _In_ XMFLOAT3 planeNormal, _In_ float duration, _In_ bool continuous, _In_ bool clockwise) { m_center = center; m_planeNormal = planeNormal; m_startPosition = startPosition; m_duration = duration; m_continuous = continuous; m_clockwise = clockwise; XMVECTOR coordX = XMLoadFloat3(&m_startPosition) - XMLoadFloat3(&m_center); m_radius = XMVectorGetX(XMVector3Length(coordX)); XMVector3Normalize(coordX); XMVECTOR coordZ = XMLoadFloat3(&m_planeNormal); XMVector3Normalize(coordZ); XMVECTOR coordY; if (m_clockwise) { coordY = XMVector3Cross(coordZ, coordX); } else { coordY = XMVector3Cross(coordX, coordZ); } XMVECTOR vectorX = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f); XMVECTOR vectorY = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f); XMMATRIX mat1 = XMMatrixIdentity(); XMMATRIX mat2 = XMMatrixIdentity(); if (!XMVector3Equal(coordX, vectorX)) { float angle; angle = XMVectorGetX( XMVector3AngleBetweenVectors(vectorX, coordX) ); if ((angle * angle) > 0.025) { XMVECTOR axis1 = XMVector3Cross(vectorX, coordX); mat1 = XMMatrixRotationAxis(axis1, angle); vectorY = XMVector3TransformCoord(vectorY, mat1); } } if (!XMVector3Equal(vectorY, coordY)) { float angle; angle = XMVectorGetX( XMVector3AngleBetweenVectors(vectorY, coordY) ); if ((angle * angle) > 0.025) { XMVECTOR axis2 = XMVector3Cross(vectorY, coordY); mat2 = XMMatrixRotationAxis(axis2, angle); } } XMStoreFloat4x4( &m_rotationMatrix, mat1 * mat2 * XMMatrixTranslation(m_center.x, m_center.y, m_center.z) ); } XMFLOAT3 AnimateCirclePosition::Evaluate(_In_ float t) { if (t <= m_startTime) { return m_startPosition; } if ((t >= (m_startTime + m_duration)) && !m_continuous) { return m_startPosition; } float startTime = m_startTime; if (m_continuous) { // For continuous operation move the start time forward to // eliminate previous iterations. startTime += ((int)((t - m_startTime) / m_duration)) * m_duration; } float u = (t - startTime) / m_duration * XM_2PI; XMFLOAT3 currentPosition; currentPosition.x = m_radius * cos(u); currentPosition.y = m_radius * sin(u); currentPosition.z = 0.0f; XMStoreFloat3( &currentPosition, XMVector3TransformCoord( XMLoadFloat3(&currentPosition), XMLoadFloat4x4(&m_rotationMatrix) ) ); return currentPosition; }
3,579
7,217
<gh_stars>1000+ package org.xutils.http.request; import android.content.Context; import android.content.pm.ApplicationInfo; import android.text.TextUtils; import org.xutils.cache.DiskCacheEntity; import org.xutils.cache.LruDiskCache; import org.xutils.common.util.IOUtil; import org.xutils.common.util.LogUtil; import org.xutils.http.RequestParams; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.Date; import java.util.List; import java.util.Map; /** * Created by wyouflf on 15/11/4. * 本地资源请求 */ public class ResRequest extends UriRequest { private static long lastModifiedTime = 0; protected long contentLength = 0; protected InputStream inputStream; public ResRequest(RequestParams params, Type loadType) throws Throwable { super(params, loadType); } @Override public void sendRequest() throws Throwable { } @Override public boolean isLoading() { return true; } @Override public String getCacheKey() { return queryUrl; } @Override public Object loadResult() throws Throwable { return this.loader.load(this); } @Override public Object loadResultFromCache() throws Throwable { DiskCacheEntity cacheEntity = LruDiskCache.getDiskCache(params.getCacheDirName()) .setMaxSize(params.getCacheSize()) .get(this.getCacheKey()); if (cacheEntity != null) { Date lastModifiedDate = cacheEntity.getLastModify(); if (lastModifiedDate == null || lastModifiedDate.getTime() < getLastModified()) { return null; } return loader.loadFromCache(cacheEntity); } else { return null; } } @Override public void clearCacheHeader() { } private int getResId() { int resId = 0; String resIdStr = queryUrl.substring("res:".length()); resIdStr = resIdStr.replace("/", ""); if (TextUtils.isDigitsOnly(resIdStr)) { resId = Integer.parseInt(resIdStr); } if (resId <= 0) { throw new IllegalArgumentException("resId not found in url:" + queryUrl); } return resId; } @Override public InputStream getInputStream() throws IOException { if (inputStream == null) { Context context = params.getContext(); inputStream = context.getResources().openRawResource(getResId()); contentLength = inputStream.available(); } return inputStream; } @Override public void close() throws IOException { IOUtil.closeQuietly(inputStream); inputStream = null; } @Override public long getContentLength() { try { getInputStream(); return contentLength; } catch (Throwable ex) { LogUtil.e(ex.getMessage(), ex); } return -1; } @Override public int getResponseCode() throws IOException { return getInputStream() != null ? 200 : 404; } @Override public String getResponseMessage() throws IOException { return null; } @Override public long getExpiration() { return Long.MAX_VALUE; } @Override public long getLastModified() { if (lastModifiedTime == 0) { try { Context context = params.getContext(); ApplicationInfo appInfo = context.getApplicationInfo(); File appFile = new File(appInfo.sourceDir); if (appFile.exists()) { lastModifiedTime = appFile.lastModified(); } } catch (Throwable ex) { LogUtil.w(ex.getMessage(), ex); lastModifiedTime = 0; } finally { if (lastModifiedTime == 0) { lastModifiedTime = System.currentTimeMillis(); } } } return lastModifiedTime; } @Override public String getETag() { return null; } @Override public String getResponseHeader(String name) { return null; } @Override public Map<String, List<String>> getResponseHeaders() { return null; } @Override public long getHeaderFieldDate(String name, long defaultValue) { return defaultValue; } }
1,923
60,067
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <assert.h> #include <arm_neon.h> #include <qnnpack/q8avgpool.h> void pytorch_q8avgpool_ukernel_up8xm__neon( size_t n, size_t ks, size_t kc, const uint8_t** input, const uint8_t* zero, uint8_t* output, size_t input_increment, size_t output_increment, const union pytorch_qnnp_avgpool_quantization_params quantization_params[restrict static 1]) { assert(n != 0); assert(ks != 0); assert(kc < 8); const int32x4_t vbias = vld1q_dup_s32(&quantization_params->neon.bias); const float32x4_t vscale = vdupq_n_f32(quantization_params->neon.scale); const int16x8_t voutput_zero_point = vld1q_dup_s16(&quantization_params->neon.output_zero_point); const uint8x8_t voutput_min = vld1_dup_u8(&quantization_params->neon.output_min); const uint8x8_t voutput_max = vld1_dup_u8(&quantization_params->neon.output_max); do { int32x4_t vacc_lo = vbias; int32x4_t vacc_hi = vbias; const uint8_t** next_input = (const uint8_t**)((uintptr_t)input + input_increment); size_t m = ks; do { const uint8_t* i = *input++; i += kc; uint8x8_t vi = vmov_n_u8(0); if (kc & 1) { i -= 1; vi = vld1_lane_u8(i, vi, 0); } if (kc & 2) { vi = vext_u8(vi, vi, 6); i -= 2; vi = vreinterpret_u8_u16(vld1_lane_u16( __builtin_assume_aligned(i, 1), vreinterpret_u16_u8(vi), 0)); } if (kc & 4) { vi = vext_u8(vi, vi, 4); i -= 4; vi = vreinterpret_u8_u32(vld1_lane_u32( __builtin_assume_aligned(i, 1), vreinterpret_u32_u8(vi), 0)); } const uint16x8_t vxi = vmovl_u8(vi); vacc_lo = vaddw_s16(vacc_lo, vreinterpret_s16_u16(vget_low_u16(vxi))); vacc_hi = vaddw_s16(vacc_hi, vreinterpret_s16_u16(vget_high_u16(vxi))); } while (--m != 0); input = next_input; float32x4_t vacc_lo_f = vcvtq_f32_s32(vacc_lo); float32x4_t vacc_hi_f = vcvtq_f32_s32(vacc_hi); vacc_lo_f = vmulq_f32(vacc_lo_f, vscale); vacc_hi_f = vmulq_f32(vacc_hi_f, vscale); #if defined(__aarch64__) vacc_lo = vcvtnq_s32_f32(vacc_lo_f); vacc_hi = vcvtnq_s32_f32(vacc_hi_f); const int16x8_t vacc = vqaddq_s16( vqmovn_high_s32(vqmovn_s32(vacc_lo), vacc_hi), voutput_zero_point); uint8x8_t vout = vqmovun_s16(vacc); vout = vmax_u8(vout, voutput_min); vout = vmin_u8(vout, voutput_max); #else const float32x4_t vfmin = vdupq_n_f32(quantization_params->neon.vfmin); const float32x4_t vfmax = vdupq_n_f32(quantization_params->neon.vfmax); const float32x4_t vfmagic = vdupq_n_f32(quantization_params->neon.vfmagic); const int32x4_t vimagic = vdupq_n_s32(quantization_params->neon.vimagic); vacc_lo_f = vminq_f32(vmaxq_f32(vacc_lo_f, vfmin), vfmax); vacc_hi_f = vminq_f32(vmaxq_f32(vacc_hi_f, vfmin), vfmax); vacc_lo = vsubq_s32( vreinterpretq_s32_f32(vaddq_f32(vacc_lo_f, vfmagic)), vimagic); vacc_hi = vsubq_s32( vreinterpretq_s32_f32(vaddq_f32(vacc_hi_f, vfmagic)), vimagic); const int16x8_t vacc = vcombine_s16(vqmovn_s32(vacc_lo), vqmovn_s32(vacc_hi)); uint8x8_t vout = vqmovun_s16(vacc); #endif if (kc & 4) { vst1_lane_u32( __builtin_assume_aligned(output, 1), vreinterpret_u32_u8(vout), 0); output += 4; vout = vext_u8(vout, vout, 4); } if (kc & 2) { vst1_lane_u16( __builtin_assume_aligned(output, 1), vreinterpret_u16_u8(vout), 0); output += 2; vout = vext_u8(vout, vout, 2); } if (kc & 1) { vst1_lane_u8(output, vout, 0); output += 1; } output = (uint8_t*)((uintptr_t)output + output_increment); } while (--n != 0); }
2,080
854
<filename>C++/1224.cpp __________________________________________________________________________________________________ sample 20 ms submission static const auto _ = [](){ ios::sync_with_stdio(false); cin.sync_with_stdio(false); cout.sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }(); class Solution { public: int maxEqualFreq(vector<int>& nums) { int cnt[100001] = {0}; int freq[100001] = {0}; int maxF = 0; int res = 0; int len = nums.size(); for(int i=0;i<len;i++) { int v = nums[i]; cnt[v]++; freq[cnt[v]]++; freq[cnt[v] - 1]--; maxF = max(maxF , cnt[v]); if(maxF == 1 || (maxF * freq[maxF]) + 1 == i + 1 || (maxF-1)*(freq[maxF-1]) + maxF == i+1) res = i+1; } return res; } }; __________________________________________________________________________________________________ sample 24 ms submission static const auto _ = [](){ ios::sync_with_stdio(false); cin.sync_with_stdio(false); cout.sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }(); class Solution { public: int maxEqualFreq(vector<int>& nums) { int cnt[100001] = {0}; int freq[100001] = {0}; int maxF = 0; int res = 0; int len = nums.size(); for(int i=0;i<len;i++) { int v = nums[i]; cnt[v]++; freq[cnt[v]]++; freq[cnt[v] - 1]--; maxF = max(maxF , cnt[v]); if(maxF == 1 || (maxF * freq[maxF]) + 1 == i + 1 || (maxF-1)*(freq[maxF-1]) + maxF == i+1) res = i+1; } return res; } }; __________________________________________________________________________________________________
888
401
<reponame>aFarkas/respimage { "name": "respimage", "version": "1.4.2", "filename": "respimage.min.js", "browser": "respimage.min.js", "scripts": { "test": "grunt test --verbose" }, "author": "<NAME> <<EMAIL>>", "repository": { "type": "git", "url": "git://github.com/aFarkas/respimage.git" }, "devDependencies": { "grunt": "~0.4.5", "grunt-bytesize": "~0.1.1", "grunt-cli": "~0.1", "grunt-contrib-jshint": "~0.10.0", "grunt-contrib-qunit": "~0.5.2", "grunt-contrib-uglify": "~0.6.0", "grunt-contrib-watch": "~0.6.1", "grunt-max-filesize": "^0.1.0" }, "npmName": "respimage", "npmFileMap": [{ "basePath": "", "files": [ "*.min.js", "plugins/**/*.min.js" ] }], "description": "The fast, lightweight and reliable polyfill for responsive images (i.e. picture element and the srcset, sizes and media attributes). With a smart resource selection algorithm, that saves bandwidth.", "keywords": [ "responsive", "image", "responsive images", "picture", "srcset", "polyfill", "respimg", "respimage", "picturefill", "performance", "bandwidth" ] }
545
763
<reponame>pranavbj-amzn/batfish package org.batfish.datamodel.acl; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.testing.EqualsTester; import org.batfish.common.util.BatfishObjectMapper; import org.batfish.datamodel.TraceElement; import org.junit.Test; /** Tests of {@link TrueExpr} */ public class TrueExprTest { @Test public void testEquals() { new EqualsTester() .addEqualityGroup(TrueExpr.INSTANCE, new TrueExpr(null)) .addEqualityGroup(new Object()) .addEqualityGroup(new TrueExpr(TraceElement.of("trace element"))) .testEquals(); } @Test public void testSerialization() { assertThat( TrueExpr.INSTANCE, equalTo(BatfishObjectMapper.clone(TrueExpr.INSTANCE, AclLineMatchExpr.class))); assertThat( new TrueExpr(TraceElement.of("foo")), equalTo( BatfishObjectMapper.clone( new TrueExpr(TraceElement.of("foo")), AclLineMatchExpr.class))); } }
428
1,042
/** * @copyright Copyright (c) 2022, Alibaba Group Holding Limited */ #ifndef _XQC_H3_REQUEST_H_INCLUDED_ #define _XQC_H3_REQUEST_H_INCLUDED_ #include "src/http3/xqc_h3_stream.h" #include "src/http3/xqc_h3_header.h" #define XQC_H3_REQUEST_INITIAL_HEADERS_CAPACITY 32 typedef struct xqc_h3_request_s { /* h3 stream handler */ xqc_h3_stream_t *h3_stream; /* user data for request callback */ void *user_data; /* request callback */ xqc_h3_request_callbacks_t *request_if; /* receive fin flag */ xqc_bool_t fin_flag; /* read flag of http3 request */ xqc_request_notify_flag_t read_flag; /* compressed header size recved */ size_t header_recvd; /* received header buf */ xqc_http_headers_t h3_header[XQC_H3_REQUEST_MAX_HEADERS_CNT]; /* total received headers frame count */ xqc_h3_header_type_t current_header; /* received body buf list and statistic information */ xqc_list_head_t body_buf; uint64_t body_buf_count; size_t body_recvd; size_t body_recvd_final_size; /* compressed header size sent */ size_t header_sent; /* send body statistic information */ size_t body_sent; size_t body_sent_final_size; /* statistic */ xqc_msec_t blocked_time; /* time of h3 stream being blocked */ xqc_msec_t unblocked_time; /* time of h3 stream being unblocked */ xqc_msec_t stream_fin_time; /* time of receiving transport fin */ xqc_msec_t h3r_begin_time; /* time of creating request */ xqc_msec_t h3r_end_time; /* time of request fin */ xqc_msec_t h3r_header_begin_time; /* time of receiving HEADERS frame */ xqc_msec_t h3r_header_end_time; /* time of finishing processing HEADERS frame */ } xqc_h3_request_t; xqc_h3_request_t *xqc_h3_request_create(xqc_engine_t *engine, const xqc_cid_t *cid, void *user_data); xqc_h3_request_t *xqc_h3_request_create_inner(xqc_h3_conn_t *h3_conn, xqc_h3_stream_t *h3_stream, void *user_data); void xqc_h3_request_destroy(xqc_h3_request_t *h3_request); /** * @brief notify events */ xqc_int_t xqc_h3_request_on_recv_header(xqc_h3_request_t *h3r); xqc_int_t xqc_h3_request_on_recv_body(xqc_h3_request_t *h3r); xqc_int_t xqc_h3_request_on_recv_empty_fin(xqc_h3_request_t *h3r); /* get headers for writing */ xqc_http_headers_t *xqc_h3_request_get_writing_headers(xqc_h3_request_t *h3r); void xqc_h3_request_blocked(xqc_h3_request_t *h3r); void xqc_h3_request_unblocked(xqc_h3_request_t *h3r); void xqc_h3_request_header_begin(xqc_h3_request_t *h3r); void xqc_h3_request_header_end(xqc_h3_request_t *h3r); void xqc_h3_request_stream_fin(xqc_h3_request_t *h3r); void xqc_h3_request_begin(xqc_h3_request_t *h3r); void xqc_h3_request_end(xqc_h3_request_t *h3r); #endif /* _XQC_H3_REQUEST_H_INCLUDED_ */
1,766
2,151
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/xml/document_xslt.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/dom/events/event_listener.h" #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/dom/processing_instruction.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/core/xml/xsl_style_sheet.h" #include "third_party/blink/renderer/core/xml/xslt_processor.h" #include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" namespace blink { class DOMContentLoadedListener final : public EventListener, public ProcessingInstruction::DetachableEventListener { USING_GARBAGE_COLLECTED_MIXIN(DOMContentLoadedListener); public: static DOMContentLoadedListener* Create(ProcessingInstruction* pi) { return new DOMContentLoadedListener(pi); } bool operator==(const EventListener& rhs) const override { return this == &rhs; } void handleEvent(ExecutionContext* execution_context, Event* event) override { DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); DCHECK_EQ(event->type(), "DOMContentLoaded"); Document& document = *ToDocument(execution_context); DCHECK(!document.Parsing()); // Processing instruction (XML documents only). // We don't support linking to embedded CSS stylesheets, // see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion. // Don't apply XSL transforms to already transformed documents. if (DocumentXSLT::HasTransformSourceDocument(document)) return; ProcessingInstruction* pi = DocumentXSLT::FindXSLStyleSheet(document); if (!pi || pi != processing_instruction_ || pi->IsLoading()) return; DocumentXSLT::ApplyXSLTransform(document, pi); } void Detach() override { processing_instruction_ = nullptr; } EventListener* ToEventListener() override { return this; } void Trace(blink::Visitor* visitor) override { visitor->Trace(processing_instruction_); EventListener::Trace(visitor); ProcessingInstruction::DetachableEventListener::Trace(visitor); } private: DOMContentLoadedListener(ProcessingInstruction* pi) : EventListener(EventListener::kCPPEventListenerType), processing_instruction_(pi) {} // If this event listener is attached to a ProcessingInstruction, keep a // weak reference back to it. That ProcessingInstruction is responsible for // detaching itself and clear out the reference. Member<ProcessingInstruction> processing_instruction_; }; DocumentXSLT::DocumentXSLT(Document& document) : Supplement<Document>(document), transform_source_document_(nullptr) {} void DocumentXSLT::ApplyXSLTransform(Document& document, ProcessingInstruction* pi) { DCHECK(!pi->IsLoading()); UseCounter::Count(document, WebFeature::kXSLProcessingInstruction); XSLTProcessor* processor = XSLTProcessor::Create(document); processor->SetXSLStyleSheet(ToXSLStyleSheet(pi->sheet())); String result_mime_type; String new_source; String result_encoding; document.SetParsingState(Document::kParsing); if (!processor->TransformToString(&document, result_mime_type, new_source, result_encoding)) { document.SetParsingState(Document::kFinishedParsing); return; } // FIXME: If the transform failed we should probably report an error (like // Mozilla does). LocalFrame* owner_frame = document.GetFrame(); processor->CreateDocumentFromSource(new_source, result_encoding, result_mime_type, &document, owner_frame); probe::frameDocumentUpdated(owner_frame); document.SetParsingState(Document::kFinishedParsing); } ProcessingInstruction* DocumentXSLT::FindXSLStyleSheet(Document& document) { for (Node* node = document.firstChild(); node; node = node->nextSibling()) { if (node->getNodeType() != Node::kProcessingInstructionNode) continue; ProcessingInstruction* pi = ToProcessingInstruction(node); if (pi->IsXSL()) return pi; } return nullptr; } bool DocumentXSLT::ProcessingInstructionInsertedIntoDocument( Document& document, ProcessingInstruction* pi) { if (!pi->IsXSL()) return false; if (!RuntimeEnabledFeatures::XSLTEnabled() || !document.GetFrame()) return true; DOMContentLoadedListener* listener = DOMContentLoadedListener::Create(pi); document.addEventListener(EventTypeNames::DOMContentLoaded, listener, false); DCHECK(!pi->EventListenerForXSLT()); pi->SetEventListenerForXSLT(listener); return true; } bool DocumentXSLT::ProcessingInstructionRemovedFromDocument( Document& document, ProcessingInstruction* pi) { if (!pi->IsXSL()) return false; if (!pi->EventListenerForXSLT()) return true; DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); document.removeEventListener(EventTypeNames::DOMContentLoaded, pi->EventListenerForXSLT(), false); pi->ClearEventListenerForXSLT(); return true; } bool DocumentXSLT::SheetLoaded(Document& document, ProcessingInstruction* pi) { if (!pi->IsXSL()) return false; if (RuntimeEnabledFeatures::XSLTEnabled() && !document.Parsing() && !pi->IsLoading() && !DocumentXSLT::HasTransformSourceDocument(document)) { if (FindXSLStyleSheet(document) == pi) ApplyXSLTransform(document, pi); } return true; } // static const char DocumentXSLT::kSupplementName[] = "DocumentXSLT"; bool DocumentXSLT::HasTransformSourceDocument(Document& document) { return Supplement<Document>::From<DocumentXSLT>(document); } DocumentXSLT& DocumentXSLT::From(Document& document) { DocumentXSLT* supplement = Supplement<Document>::From<DocumentXSLT>(document); if (!supplement) { supplement = new DocumentXSLT(document); Supplement<Document>::ProvideTo(document, supplement); } return *supplement; } void DocumentXSLT::Trace(blink::Visitor* visitor) { visitor->Trace(transform_source_document_); Supplement<Document>::Trace(visitor); } } // namespace blink
2,273
575
<reponame>sarang-apps/darshan_browser<gh_stars>100-1000 // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_LOGIN_API_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_LOGIN_API_H_ #include "components/prefs/pref_registry_simple.h" #include "extensions/browser/extension_function.h" namespace extensions { namespace login_api { void RegisterLocalStatePrefs(PrefRegistrySimple* registry); } // namespace login_api namespace login_api_errors { extern const char kAlreadyActiveSession[]; extern const char kAnotherLoginAttemptInProgress[]; extern const char kNoManagedGuestSessionAccounts[]; extern const char kNoPermissionToLock[]; extern const char kSessionIsNotActive[]; extern const char kNoPermissionToUnlock[]; extern const char kSessionIsNotLocked[]; extern const char kAnotherUnlockAttemptInProgress[]; extern const char kAuthenticationFailed[]; } // namespace login_api_errors class LoginLaunchManagedGuestSessionFunction : public ExtensionFunction { public: LoginLaunchManagedGuestSessionFunction(); LoginLaunchManagedGuestSessionFunction( const LoginLaunchManagedGuestSessionFunction&) = delete; LoginLaunchManagedGuestSessionFunction& operator=( const LoginLaunchManagedGuestSessionFunction&) = delete; DECLARE_EXTENSION_FUNCTION("login.launchManagedGuestSession", LOGIN_LAUNCHMANAGEDGUESTSESSION) protected: ~LoginLaunchManagedGuestSessionFunction() override; // ExtensionFunction: ResponseAction Run() override; }; class LoginExitCurrentSessionFunction : public ExtensionFunction { public: LoginExitCurrentSessionFunction(); LoginExitCurrentSessionFunction(const LoginExitCurrentSessionFunction&) = delete; LoginExitCurrentSessionFunction& operator=( const LoginExitCurrentSessionFunction&) = delete; DECLARE_EXTENSION_FUNCTION("login.exitCurrentSession", LOGIN_EXITCURRENTSESSION) protected: ~LoginExitCurrentSessionFunction() override; // ExtensionFunction: ResponseAction Run() override; }; class LoginFetchDataForNextLoginAttemptFunction : public ExtensionFunction { public: LoginFetchDataForNextLoginAttemptFunction(); LoginFetchDataForNextLoginAttemptFunction( const LoginFetchDataForNextLoginAttemptFunction&) = delete; LoginFetchDataForNextLoginAttemptFunction& operator=( const LoginFetchDataForNextLoginAttemptFunction&) = delete; DECLARE_EXTENSION_FUNCTION("login.fetchDataForNextLoginAttempt", LOGIN_FETCHDATAFORNEXTLOGINATTEMPT) protected: ~LoginFetchDataForNextLoginAttemptFunction() override; // ExtensionFunction: ResponseAction Run() override; }; class LoginLockManagedGuestSessionFunction : public ExtensionFunction { public: LoginLockManagedGuestSessionFunction(); LoginLockManagedGuestSessionFunction( const LoginLockManagedGuestSessionFunction&) = delete; LoginLockManagedGuestSessionFunction& operator=( const LoginLockManagedGuestSessionFunction&) = delete; DECLARE_EXTENSION_FUNCTION("login.lockManagedGuestSession", LOGIN_LOCKMANAGEDGUESTSESSION) protected: ~LoginLockManagedGuestSessionFunction() override; // ExtensionFunction: ResponseAction Run() override; }; class LoginUnlockManagedGuestSessionFunction : public ExtensionFunction { public: LoginUnlockManagedGuestSessionFunction(); LoginUnlockManagedGuestSessionFunction( const LoginUnlockManagedGuestSessionFunction&) = delete; LoginUnlockManagedGuestSessionFunction& operator=( const LoginUnlockManagedGuestSessionFunction&) = delete; DECLARE_EXTENSION_FUNCTION("login.unlockManagedGuestSession", LOGIN_UNLOCKMANAGEDGUESTSESSION) protected: ~LoginUnlockManagedGuestSessionFunction() override; // ExtensionFunction: ResponseAction Run() override; private: void OnAuthenticationComplete(bool success); }; } // namespace extensions #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_LOGIN_API_H_
1,341
3,970
// // KWStringContainsMatcher.h // Kiwi // // Created by <NAME> on 7/06/12. // Copyright (c) 2012 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "KWGenericMatcher.h" @interface KWStringContainsMatcher : NSObject <KWGenericMatching> + (id)matcherWithSubstring:(NSString *)aSubstring; - (id)initWithSubstring:(NSString *)aSubstring; - (BOOL)matches:(id)object; @end #define hasSubstring(substring) [KWStringContainsMatcher matcherWithSubstring:substring]
180
677
/* * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "CCallHelpers.h" #if ENABLE(JIT) #include "ShadowChicken.h" namespace JSC { void CCallHelpers::logShadowChickenProloguePacket(GPRReg shadowPacket, GPRReg scratch1, GPRReg scope) { storePtr(GPRInfo::callFrameRegister, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, frame))); loadPtr(Address(GPRInfo::callFrameRegister, OBJECT_OFFSETOF(CallerFrameAndPC, callerFrame)), scratch1); storePtr(scratch1, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, callerFrame))); loadPtr(addressFor(CallFrameSlot::callee), scratch1); storePtr(scratch1, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, callee))); storePtr(scope, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, scope))); } void CCallHelpers::logShadowChickenTailPacket(GPRReg shadowPacket, JSValueRegs thisRegs, GPRReg scope, CodeBlock* codeBlock, CallSiteIndex callSiteIndex) { storePtr(GPRInfo::callFrameRegister, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, frame))); storePtr(TrustedImmPtr(ShadowChicken::Packet::tailMarker()), Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, callee))); storeValue(thisRegs, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, thisValue))); storePtr(scope, Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, scope))); storePtr(TrustedImmPtr(codeBlock), Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, codeBlock))); store32(TrustedImm32(callSiteIndex.bits()), Address(shadowPacket, OBJECT_OFFSETOF(ShadowChicken::Packet, callSiteIndex))); } void CCallHelpers::ensureShadowChickenPacket(VM& vm, GPRReg shadowPacket, GPRReg scratch1NonArgGPR, GPRReg scratch2) { ASSERT(!RegisterSet::argumentGPRS().get(scratch1NonArgGPR)); move(TrustedImmPtr(vm.shadowChicken().addressOfLogCursor()), scratch1NonArgGPR); loadPtr(Address(scratch1NonArgGPR), shadowPacket); Jump ok = branchPtr(Below, shadowPacket, TrustedImmPtr(vm.shadowChicken().logEnd())); setupArgumentsExecState(); move(TrustedImmPtr(bitwise_cast<void*>(operationProcessShadowChickenLog)), scratch1NonArgGPR); call(scratch1NonArgGPR); move(TrustedImmPtr(vm.shadowChicken().addressOfLogCursor()), scratch1NonArgGPR); loadPtr(Address(scratch1NonArgGPR), shadowPacket); ok.link(this); addPtr(TrustedImm32(sizeof(ShadowChicken::Packet)), shadowPacket, scratch2); storePtr(scratch2, Address(scratch1NonArgGPR)); } } // namespace JSC #endif // ENABLE(JIT)
1,278
716
<gh_stars>100-1000 // Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "MockBatcher.h" #include "CoreMath.h" namespace orbit_gl { MockBatcher::MockBatcher(BatcherId batcher_id) : Batcher(batcher_id) { ResetElements(); } void MockBatcher::AddLine(Vec2 from, Vec2 to, float z, const Color& color, const Color& /*picking_color*/, std::unique_ptr<PickingUserData> /*user_data*/) { num_lines_by_color_[color]++; if (from[0] == to[0]) num_vertical_lines_++; if (from[1] == to[1]) num_horizontal_lines_++; AdjustDrawingBoundaries({from[0], from[1]}); AdjustDrawingBoundaries({to[0], to[1]}); z_layers_.insert(z); } void MockBatcher::AddBox(const Quad& box, float z, const std::array<Color, 4>& colors, const Color& /*picking_color*/, std::unique_ptr<PickingUserData> /*user_data*/) { num_boxes_by_color_[colors[0]]++; for (int i = 0; i < 4; i++) { AdjustDrawingBoundaries(box.vertices[i]); } z_layers_.insert(z); } void MockBatcher::AddTriangle(const Triangle& triangle, float z, const std::array<Color, 3>& colors, const Color& /*picking_color*/, std::unique_ptr<PickingUserData> /*user_data*/) { num_triangles_by_color_[colors[0]]++; for (int i = 0; i < 3; i++) { AdjustDrawingBoundaries(triangle.vertices[i]); } z_layers_.insert(z); } void MockBatcher::ResetElements() { num_lines_by_color_.clear(); num_triangles_by_color_.clear(); num_boxes_by_color_.clear(); num_horizontal_lines_ = 0; num_vertical_lines_ = 0; min_point_ = Vec2{std::numeric_limits<float>::max(), std::numeric_limits<float>::max()}; max_point_ = Vec2{std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest()}; z_layers_.clear(); } uint32_t MockBatcher::GetNumElements() const { return GetNumLines() + GetNumBoxes() + GetNumTriangles(); } int MockBatcher::GetNumLines() const { int total_lines = 0; for (auto& [unused_color, num_lines] : num_lines_by_color_) { total_lines += num_lines; } return total_lines; } int MockBatcher::GetNumTriangles() const { int total_triangles = 0; for (auto& [unused_color, num_triangles] : num_triangles_by_color_) { total_triangles += num_triangles; } return total_triangles; } int MockBatcher::GetNumBoxes() const { int total_boxes = 0; for (auto& [unused_color, num_boxes] : num_boxes_by_color_) { total_boxes += num_boxes; } return total_boxes; } // To check that everything is inside a rectangle, we just need to check the minimum and maximum // used coordinates. bool MockBatcher::IsEverythingInsideRectangle(Vec2 start, Vec2 size) const { if (GetNumElements() == 0) return true; return IsInsideRectangle(min_point_, start, size) && IsInsideRectangle(max_point_, start, size); } bool MockBatcher::IsEverythingBetweenZLayers(float z_layer_min, float z_layer_max) const { return std::find_if_not(z_layers_.begin(), z_layers_.end(), [z_layer_min, z_layer_max](float layer) { return ClosedInterval{z_layer_min, z_layer_max}.Contains(layer); }) == z_layers_.end(); } void MockBatcher::AdjustDrawingBoundaries(Vec2 point) { min_point_[0] = std::min(point[0], min_point_[0]); min_point_[1] = std::min(point[1], min_point_[1]); max_point_[0] = std::max(point[0], max_point_[0]); max_point_[1] = std::max(point[1], max_point_[1]); } } // namespace orbit_gl
1,519
5,823
<reponame>onix39/engine // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/testing/post_task_sync.h" #include "flutter/fml/synchronization/waitable_event.h" namespace flutter { namespace testing { void PostTaskSync(fml::RefPtr<fml::TaskRunner> task_runner, const std::function<void()>& function) { fml::AutoResetWaitableEvent latch; task_runner->PostTask([&] { function(); latch.Signal(); }); latch.Wait(); } } // namespace testing } // namespace flutter
219
319
<filename>ext/rinku/rinku.c /* * Copyright (c) 2016, GitHub, Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "rinku.h" #include "autolink.h" #include "buffer.h" #include "utf8.h" typedef enum { HTML_TAG_NONE = 0, HTML_TAG_OPEN, HTML_TAG_CLOSE, } html_tag; typedef enum { AUTOLINK_ACTION_NONE = 0, AUTOLINK_ACTION_WWW, AUTOLINK_ACTION_EMAIL, AUTOLINK_ACTION_URL, AUTOLINK_ACTION_SKIP_TAG } autolink_action; typedef bool (*autolink_parse_cb)( struct autolink_pos *, const uint8_t *, size_t, size_t, unsigned int); static autolink_parse_cb g_callbacks[] = { NULL, autolink__www, /* 1 */ autolink__email,/* 2 */ autolink__url, /* 3 */ }; static const char *g_hrefs[] = { NULL, "<a href=\"http://", "<a href=\"mailto:", "<a href=\"", }; /* * Rinku assumes valid HTML encoding for all input, but there's still * the case where a link can contain a double quote `"` that allows XSS. * * We need to properly escape the character we use for the `href` attribute * declaration */ static void print_link(struct buf *ob, const uint8_t *link, size_t size) { size_t i = 0, org; while (i < size) { org = i; while (i < size && link[i] != '"') i++; if (i > org) bufput(ob, link + org, i - org); if (i >= size) break; BUFPUTSL(ob, "&quot;"); i++; } } /* From sundown/html/html.c */ static int html_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname) { size_t i; int closed = 0; if (tag_size < 3 || tag_data[0] != '<') return HTML_TAG_NONE; i = 1; if (tag_data[i] == '/') { closed = 1; i++; } for (; i < tag_size; ++i, ++tagname) { if (*tagname == 0) break; if (tag_data[i] != *tagname) return HTML_TAG_NONE; } if (i == tag_size) return HTML_TAG_NONE; if (rinku_isspace(tag_data[i]) || tag_data[i] == '>') return closed ? HTML_TAG_CLOSE : HTML_TAG_OPEN; return HTML_TAG_NONE; } static size_t autolink__skip_tag( struct buf *ob, const uint8_t *text, size_t size, const char **skip_tags) { size_t i = 0; while (i < size && text[i] != '>') i++; while (*skip_tags != NULL) { if (html_is_tag(text, size, *skip_tags) == HTML_TAG_OPEN) break; skip_tags++; } if (*skip_tags != NULL) { for (;;) { while (i < size && text[i] != '<') i++; if (i == size) break; if (html_is_tag(text + i, size - i, *skip_tags) == HTML_TAG_CLOSE) break; i++; } while (i < size && text[i] != '>') i++; } return i; } int rinku_autolink( struct buf *ob, const uint8_t *text, size_t size, autolink_mode mode, unsigned int flags, const char *link_attr, const char **skip_tags, void (*link_text_cb)(struct buf *, const uint8_t *, size_t, void *), void *payload) { size_t i, end; char active_chars[256] = {0}; int link_count = 0; if (!text || size == 0) return 0; active_chars['<'] = AUTOLINK_ACTION_SKIP_TAG; if (mode & AUTOLINK_EMAILS) active_chars['@'] = AUTOLINK_ACTION_EMAIL; if (mode & AUTOLINK_URLS) { active_chars['w'] = AUTOLINK_ACTION_WWW; active_chars['W'] = AUTOLINK_ACTION_WWW; active_chars[':'] = AUTOLINK_ACTION_URL; } if (link_attr != NULL) { while (rinku_isspace(*link_attr)) link_attr++; } bufgrow(ob, size); i = end = 0; while (i < size) { struct autolink_pos link; bool link_found; char action = 0; while (end < size && (action = active_chars[text[end]]) == 0) end++; if (end == size) { if (link_count > 0) bufput(ob, text + i, end - i); break; } if (action == AUTOLINK_ACTION_SKIP_TAG) { end += autolink__skip_tag(ob, text + end, size - end, skip_tags); continue; } link_found = g_callbacks[(int)action]( &link, text, end, size, flags); if (link_found && link.start >= i) { const uint8_t *link_str = text + link.start; const size_t link_len = link.end - link.start; bufput(ob, text + i, link.start - i); bufputs(ob, g_hrefs[(int)action]); print_link(ob, link_str, link_len); if (link_attr) { BUFPUTSL(ob, "\" "); bufputs(ob, link_attr); bufputc(ob, '>'); } else { BUFPUTSL(ob, "\">"); } if (link_text_cb) { link_text_cb(ob, link_str, link_len, payload); } else { bufput(ob, link_str, link_len); } BUFPUTSL(ob, "</a>"); link_count++; end = i = link.end; } else { end = end + 1; } } return link_count; }
2,204
640
<reponame>jpoikela/z88dk /* * (c) Copyright 2015 by <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The name of its author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Modified for ZX Next + ESXDOS by z88dk.org * Program performs identically. */ // ZX SPECTRUM // // zcc +zx -vn -subtype=dot -startup=30 -clib=sdcc_iy -SO3 --max-allocs-per-node200000 --opt-code-size dzx7.c ram.asm -o dzx7 -create-app // zcc +zx -vn -subtype=dot -startup=30 -clib=new dzx7.c ram.asm -o dzx7 -create-app // ZX NEXT // // zcc +zxn -vn -subtype=dot -startup=30 -clib=sdcc_iy -SO3 --max-allocs-per-node200000 --opt-code-size dzx7.c ram.asm -o dzx7 -create-app // zcc +zxn -vn -subtype=dot -startup=30 -clib=new dzx7.c ram.asm -o dzx7 -create-app #pragma printf = "%s %u %lu" #pragma output CLIB_EXIT_STACK_SIZE = 3 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <errno.h> #include <input.h> #include <z80.h> #if __ZXNEXT #include <arch/zxn/esxdos.h> #else #include <arch/zx/esxdos.h> #endif #define BUFFER_SIZE 16384 // must be > MAX_OFFSET, must remain consistent with dzx7.asm #define MAINBANK_ADDR (65536 - BUFFER_SIZE*2) unsigned char ifp; unsigned char ofp; unsigned char *input_name; unsigned int input_name_sz; unsigned char output_name[ESXDOS_PATH_MAX + 1]; extern unsigned char input_data[BUFFER_SIZE]; extern unsigned char output_data[BUFFER_SIZE]; unsigned int input_index; unsigned int output_index; unsigned long input_size; unsigned long output_size; unsigned int partial_counter; unsigned char bit_mask; unsigned char bit_value; // custom esxdos error report #define ebuf input_data int error(char *fmt, ...) { unsigned char *p; va_list v; va_start(v, fmt); #ifdef __SCCZ80 vsnprintf(ebuf, sizeof(ebuf), va_ptr(v,char *), v); #else vsnprintf(ebuf, sizeof(ebuf), fmt, v); #endif for (p = ebuf; p = strchr(p, '\n'); ) *p = '\r'; ebuf[strlen(ebuf)-1] += 0x80; return (int)ebuf; } // dzx7 functions unsigned char read_byte(void) { if (input_index == partial_counter) { input_index = 0; partial_counter = esxdos_f_read(ifp, input_data, BUFFER_SIZE); input_size += partial_counter; if (partial_counter == 0) exit(error(input_size ? "Truncated input file %s" : "Empty input file %s", input_name)); } return input_data[input_index++]; } unsigned char read_bit(void) { bit_mask >>= 1; if (bit_mask == 0) { bit_mask = 0x80; bit_value = read_byte(); } return (bit_value & bit_mask) ? 1 : 0; } unsigned int read_elias_gamma(void) { unsigned int value; unsigned char i; for (i = 0; !read_bit(); ++i) ; if (i > 15) return -1; for (value = 1; i; --i) value = (value << 1) | read_bit(); return value; } unsigned int read_offset(void) { unsigned int value; unsigned char i; value = read_byte(); if (value < 128) return value; i = read_bit(); i = (i << 1) | read_bit(); i = (i << 1) | read_bit(); i = (i << 1) | read_bit(); return (value & 0x7f) | ((unsigned int)i << 7) + 0x80; } void save_output(void) { if (output_index) { if (esxdos_f_write(ofp, output_data, output_index) != output_index) exit(error("Can't write output file %s", output_name)); output_size += output_index; output_index = 0; printf("."); } } void write_byte(unsigned char value) { output_data[output_index++] = value; if (output_index == BUFFER_SIZE) save_output(); } void write_bytes(unsigned int offset, unsigned int length) { int i; if (offset > output_size+output_index) exit(error("Invalid data in input file %s", input_name)); while (length-- > 0) { i = output_index - offset; write_byte(output_data[(i >= 0) ? i : BUFFER_SIZE+i]); } } void decompress(void) { unsigned int length; input_size = 0; input_index = 0; partial_counter = 0; output_index = 0; output_size = 0; bit_mask = 0; write_byte(read_byte()); while (1) { if (!read_bit()) write_byte(read_byte()); else { length = read_elias_gamma() + 1; if (length == 0) { save_output(); if (input_index != partial_counter) exit(error("Input file %s too long", input_name)); return; } write_bytes(read_offset() + 1, length); } // allow user to interrupt if (in_key_pressed(IN_KEY_SCANCODE_SPACE | 0x8000)) { in_wait_nokey(); exit(error("L Break into Program")); } } } // cleanup on exit void cleanup_ifp(void) { esxdos_f_close(ifp); } void cleanup_ofp(void) { esxdos_f_close(ofp); } void cleanup_lf(void) { printf("\n\n"); } // program start int main(int argc, char **argv) { static unsigned char forced_mode; unsigned char i; printf("DZX7: LZ77/LZSS decompression\nby <NAME>\nv1.0 zx spectrum z88dk.org\n\n"); // process hidden optional parameters for (i = 1; (i < (unsigned char)argc) && (*argv[i] == '-'); ++i) { if (!stricmp(argv[i], "-f")) forced_mode = 1; else return error("Invalid parameter %s", argv[i]); } // determine output filename if (argc == i+1) { input_name = argv[i]; input_name_sz = strlen(input_name); if ((input_name_sz > 4) && (!stricmp(input_name+input_name_sz-4, ".ZX7"))) snprintf(output_name, sizeof(output_name), "%.*s", input_name_sz-4, input_name); else return error("Can't infer output filename"); } else if (argc == i+2) { input_name = argv[i]; snprintf(output_name, sizeof(output_name), "%s", argv[i+1]); } else { printf(".dzx7 [-f] inname.zx7 [outname]\n" "-f Overwrite output file\n\n"); return 0; } if (!stricmp(output_name, input_name)) return error("In and out files are same"); // check for sufficient memory in main bank if (z80_wpeek(23730) >= (unsigned int)MAINBANK_ADDR) return error("M RAMTOP no good (%u)", (unsigned int)MAINBANK_ADDR); // open input file ifp = esxdos_f_open(input_name, ESXDOS_MODE_OPEN_EXIST | ESXDOS_MODE_R); if (errno) return error("Can't open input file %s", input_name); atexit(cleanup_ifp); // check output file ofp = esxdos_f_open(output_name, forced_mode ? ESXDOS_MODE_CREAT_TRUNC | ESXDOS_MODE_W : ESXDOS_MODE_CREAT_NOEXIST | ESXDOS_MODE_W); if (errno) return error("Can't create output file %s", output_name); atexit(cleanup_ofp); // generate output file atexit(cleanup_lf); decompress(); // done! printf("\n\nFile decompressed from %lu to %lu bytes!", input_size, output_size); return 0; }
3,575
1,128
<reponame>HugoLipeng/PLDroidMediaStreaming package com.qiniu.pili.droid.streaming.demo.utils; import android.app.Activity; import android.app.Application; import android.os.Bundle; public class AppStateTracker { public static final int STATE_FOREGROUND = 0; public static final int STATE_BACKGROUND = 1; private static int currentState; public static int getCurrentState() { return currentState; } public interface AppStateChangeListener { void appTurnIntoForeground(); void appTurnIntoBackGround(); void appDestroyed(); } public static void track(Application application, final AppStateChangeListener appStateChangeListener){ application.registerActivityLifecycleCallbacks(new SimpleActivityLifecycleCallbacks(){ private int resumeActivityCount = 0; private int createActivityCount = 0; @Override public void onActivityCreated(Activity activity, Bundle bundle) { createActivityCount++; } @Override public void onActivityStarted(Activity activity) { if (resumeActivityCount==0){ currentState = STATE_FOREGROUND; appStateChangeListener.appTurnIntoForeground(); } resumeActivityCount++; } @Override public void onActivityStopped(Activity activity) { resumeActivityCount--; if (resumeActivityCount==0){ currentState = STATE_BACKGROUND; appStateChangeListener.appTurnIntoBackGround(); } } @Override public void onActivityDestroyed(Activity activity) { createActivityCount--; if (createActivityCount == 0) { appStateChangeListener.appDestroyed(); } } }); } private static class SimpleActivityLifecycleCallbacks implements Application .ActivityLifecycleCallbacks{ @Override public void onActivityCreated(Activity activity, Bundle bundle) { } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } @Override public void onActivityDestroyed(Activity activity) { } } }
1,181
2,167
# External class definitions for use in `test_polar.py` tests class Foo: def __init__(self, name=""): self.name = name def foo(self): return "Foo!" class Bar(Foo): def foo(self): return "Bar!" class Qux: pass class MyClass: def __init__(self, x="", y=""): self.x = x self.y = y def __eq__(self, other): if isinstance(other, MyClass): return self.x == other.x and self.y == other.y return False class YourClass: pass class OurClass(MyClass, YourClass): pass
256
904
<reponame>BurAndBY/pkgj #include "patchinfo.hpp" #include "sha256.hpp" namespace { constexpr uint8_t HMAC_KEY[32] = { 0xE5, 0xE2, 0x78, 0xAA, 0x1E, 0xE3, 0x40, 0x82, 0xA0, 0x88, 0x27, 0x9C, 0x83, 0xF9, 0xBB, 0xC8, 0x06, 0x82, 0x1C, 0x52, 0xF2, 0xAB, 0x5D, 0x2B, 0x4A, 0xBD, 0x99, 0x54, 0x50, 0x35, 0x51, 0x14, }; std::string get_link_for_title(const std::string& titleid) { uint8_t hmac[SHA256_MAC_LEN]; const auto uniqdata = "np_" + titleid; hmac_sha256( HMAC_KEY, sizeof(HMAC_KEY), reinterpret_cast<const uint8_t*>(uniqdata.data()), uniqdata.size(), hmac); const auto link = fmt::format( "https://gs-sec.ww.np.dl.playstation.net/pl/np/{}/{}/{}-ver.xml", titleid, pkgi_tohex(std::vector<uint8_t>(hmac, hmac + SHA256_MAC_LEN)), titleid); return link; } std::optional<std::vector<uint8_t>> download_data( Http* http, const std::string& url) { std::vector<uint8_t> data; http->start(url, 0); if (http->get_status() == 404) return std::nullopt; size_t pos = 0; while (true) { if (pos == data.size()) data.resize(pos + 4096); const auto read = http->read(data.data() + pos, data.size() - pos); if (read == 0) break; pos += read; } data.resize(pos); return data; } PatchInfo get_last_patch(const std::string& xml) { static constexpr char PackageStr[] = "<package"; static constexpr char HybridPackageStr[] = "<hybrid_package"; static constexpr char VersionStr[] = "version=\""; static constexpr char UrlStr[] = "url=\""; static constexpr char Psp2SystemVerStr[] = "psp2_system_ver=\""; const auto last_package = xml.rfind(PackageStr); const auto last_hybrid_package = xml.find(HybridPackageStr, last_package); const auto version = xml.find(VersionStr, last_package) + sizeof(VersionStr) - 1; const auto version_end = xml.find('"', version); const auto fw_version = xml.find(Psp2SystemVerStr, last_package) + sizeof(Psp2SystemVerStr) - 1; const auto fw_version_end = xml.find('"', fw_version); const auto package_of_interest = last_hybrid_package == std::string::npos ? last_package : last_hybrid_package; const auto url = xml.find(UrlStr, package_of_interest) + sizeof(UrlStr) - 1; const auto url_end = xml.find('"', url); const auto fw_version_int = std::stoi(xml.substr(fw_version, fw_version_end - fw_version)); return PatchInfo{ xml.substr(version, version_end - version), fmt::format( "{:x}.{:02x}", fw_version_int >> 24, (fw_version_int >> 16) & 0xff), xml.substr(url, url_end - url), }; } } std::optional<PatchInfo> pkgi_download_patch_info( Http* http, const std::string& titleid) { const auto info_link = get_link_for_title(titleid); const auto xml = download_data(http, info_link); if (!xml || xml->empty()) return std::nullopt; const auto patch_info = get_last_patch(std::string(xml->begin(), xml->end())); return patch_info; }
1,650
677
<reponame>InfiniteSynthesis/lynx-native<filename>Core/third_party/JavaScriptCore/heap/MachineStackMarker.h<gh_stars>100-1000 /* * Copyright (C) 1999-2000 <NAME> (<EMAIL>) * Copyright (C) 2001 <NAME> (<EMAIL>) * Copyright (C) 2003-2017 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #pragma once #include "MachineContext.h" #include "RegisterState.h" #include <wtf/DoublyLinkedList.h> #include <wtf/Lock.h> #include <wtf/Noncopyable.h> #include <wtf/ScopedLambda.h> #include <wtf/ThreadSpecific.h> namespace JSC { class CodeBlockSet; class ConservativeRoots; class Heap; class JITStubRoutineSet; struct CurrentThreadState { void* stackOrigin { nullptr }; void* stackTop { nullptr }; RegisterState* registerState { nullptr }; }; class MachineThreads { WTF_MAKE_NONCOPYABLE(MachineThreads); public: MachineThreads(); ~MachineThreads(); void gatherConservativeRoots(ConservativeRoots&, JITStubRoutineSet&, CodeBlockSet&, CurrentThreadState*); JS_EXPORT_PRIVATE void addCurrentThread(); // Only needs to be called by clients that can use the same heap from multiple threads. class MachineThread : public DoublyLinkedListNode<MachineThread> { WTF_MAKE_FAST_ALLOCATED; public: MachineThread(); struct Registers { void* stackPointer() const; #if ENABLE(SAMPLING_PROFILER) void* framePointer() const; void* instructionPointer() const; void* llintPC() const; #endif // ENABLE(SAMPLING_PROFILER) PlatformRegisters regs; }; Expected<void, Thread::PlatformSuspendError> suspend() { return m_thread->suspend(); } void resume() { m_thread->resume(); } size_t getRegisters(Registers& regs); std::pair<void*, size_t> captureStack(void* stackTop); WTF::ThreadIdentifier threadID() const { return m_thread->id(); } void* stackBase() const { return m_stackBase; } void* stackEnd() const { return m_stackEnd; } Ref<WTF::Thread> m_thread; void* m_stackBase; void* m_stackEnd; MachineThread* m_next { nullptr }; MachineThread* m_prev { nullptr }; }; Lock& getLock() { return m_registeredThreadsMutex; } const DoublyLinkedList<MachineThread>& threadsListHead(const AbstractLocker&) const { ASSERT(m_registeredThreadsMutex.isLocked()); return m_registeredThreads; } MachineThread* machineThreadForCurrentThread(); private: void gatherFromCurrentThread(ConservativeRoots&, JITStubRoutineSet&, CodeBlockSet&, CurrentThreadState&); void tryCopyOtherThreadStack(MachineThread*, void*, size_t capacity, size_t*); bool tryCopyOtherThreadStacks(const AbstractLocker&, void*, size_t capacity, size_t*); static void THREAD_SPECIFIC_CALL removeThread(void*); void removeThreadIfFound(ThreadIdentifier); Lock m_registeredThreadsMutex; DoublyLinkedList<MachineThread> m_registeredThreads; WTF::ThreadSpecificKey m_threadSpecificForMachineThreads; }; #define DECLARE_AND_COMPUTE_CURRENT_THREAD_STATE(stateName) \ CurrentThreadState stateName; \ stateName.stackTop = &stateName; \ stateName.stackOrigin = wtfThreadData().stack().origin(); \ ALLOCATE_AND_GET_REGISTER_STATE(stateName ## _registerState); \ stateName.registerState = &stateName ## _registerState // The return value is meaningless. We just use it to suppress tail call optimization. int callWithCurrentThreadState(const ScopedLambda<void(CurrentThreadState&)>&); } // namespace JSC
1,491
2,338
<gh_stars>1000+ // RUN: %clangxx_asan -xc++ -shared -fPIC -o %t.so - < %s // RUN: %clang_asan %s -o %t.out -ldl // // RUN: { env ASAN_OPTIONS=verbosity=1 %t.out %t.so || : ; } 2>&1 | FileCheck %s // // CHECK: AddressSanitizer: failed to intercept '__cxa_throw' // // This tests assumes static linking of the asan runtime. // UNSUPPORTED: asan-dynamic-runtime #ifdef __cplusplus static void foo(void) { int i = 0; throw(i); } extern "C" { int bar(void); }; int bar(void) { try { foo(); } catch (int i) { return i; } return -1; } #else #include <assert.h> #include <dlfcn.h> int main(int argc, char **argv) { int (*bar)(void); void *handle = dlopen(argv[1], RTLD_LAZY); assert(handle); bar = dlsym(handle, "bar"); assert(bar); return bar(); } #endif
347
3,428
{"id":"00157","group":"spam-1","checksum":{"type":"MD5","value":"52b0a260de7c64f539b0e5d16198b5bf"},"text":"From <EMAIL> Thu Aug 29 15:40:40 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: <EMAIL>.<EMAIL>\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.spamassassin.taint.org (Postfix) with ESMTP id 12B5643F99\n\tfor <zzzz@localhost>; Thu, 29 Aug 2002 10:40:40 -0400 (EDT)\nReceived: from mail.webnote.net [193.120.211.219]\n\tby localhost with POP3 (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Thu, 29 Aug 2002 15:40:40 +0100 (IST)\nReceived: from 2mails71.com ([217.78.76.157])\n\tby webnote.net (8.9.3/8.9.3) with SMTP id PAA10752\n\tfor <<EMAIL>>; Thu, 29 Aug 2002 15:33:45 +0100\nMessage-Id: <<EMAIL>>\nFrom: \"MR.IKE EJOH\" <<EMAIL>>\nReply-To: [email protected]\nTo: <EMAIL>\nDate: Wed, 28 Aug 2002 14:41:06 +0200\nSubject: YOUR ANTICIPATED ASSISTANT IS REQUIRED.\nX-Priority: 1\nX-Mailer: Microsoft Outlook Express 5.00.2919.6900 DM\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"us-ascii\"\nX-MIME-Autoconverted: from quoted-printable to 8bit by webnote.net id PAA10752\nContent-Transfer-Encoding: 8bit\n\nI am <NAME>. Bank Manager of Diamond Bank of Nigeria, Lagos Branch. I have urgent and very confidential business proposal for you. On June 6 1999 a FOREIGN Oil consultant/contractor with the FEDERAL MINISTRY OF AVIATIONMr. <NAME> made a numbered time (Fixed) Deposit for twelve calendar months, valued at US$25,000,000.00 (Twenty- five Million Dollars) in my branch. Upon maturity, I sent a routine notification to his forwarding address but got no reply. After a month, we sent a reminder and finally we discovered from his employers, the FEDERAL MINISTRY OF AVIATION that Mr. <NAME> died from an automobile accident. On further investigation, I found out that he died without making a WILL, and all attempts to trace his next of kin was fruitless. I therefore made further investigation and discovered that Mr. <NAME> did not declare any kin or relations in all his official documents, including his Bank Deposit paperwork in my Bank.This sum of US$25,000,000.00 is still sitting in my Bank and the interest is being rolled over with the principal sum at the end of each year. No one willever come forward to claim it.According to Nigerian Law, at the expiration of 6 (six) years, the money will revert to the ownership of the Nigerian Government if nobody applies to claim the fund. Consequently, i have just sucided in getting this fund sent to holland through a security company called GLOBAL& BASIC FINANCIAL COMPANY., I will like you to provide immediately your full names and address so that i will prepare the necessary documents and affidavits, which will put you in place as the owner of this fund in the security company. i shall employ the service of an Attorney for drafting and notarization of the changes and to obtain the necessary documents and letter of probate & administration in your favour. There is no risk at all as all the paperwork for this transaction will be done by the Attorney and my position as the Bran\nch Manager guarantees the successful execution of this transaction. If you are interested, please replyimmediately via the private email address . Upon your response, I shall then provide you with more details and relevant documents that will help you understand the transaction. Please observe utmost confidentiality, and be rest assured that this transaction would be most profitable for both of us because I shall require your assistance to invest my share in your country.\n\nAwaiting your urgent reply via my email: \n\nThanks and regards. \n\nMR.IKE EJOH\n\n\n"}
1,049
3,489
<filename>scripts/geodata/places/reverse_geocode.py import argparse import logging import os import sys import six this_dir = os.path.realpath(os.path.dirname(__file__)) sys.path.append(os.path.realpath(os.path.join(os.pardir, os.pardir))) from geodata.address_expansions.abbreviations import abbreviate from geodata.coordinates.conversion import latlon_to_decimal from geodata.math.floats import isclose from geodata.osm.extract import parse_osm from geodata.points.index import PointIndex from geodata.encoding import safe_decode class PlaceReverseGeocoder(PointIndex): GEOHASH_PRECISION = 5 include_property_patterns = set([ 'id', 'type', 'name', 'name:*', 'ISO3166-1:alpha2', 'ISO3166-1:alpha3', 'int_name', 'is_in', 'is_in:*', 'official_name', 'official_name:*', 'alt_name', 'alt_name:*', 'short_name', 'short_name:*', 'admin_level', 'place', 'population', 'designation', 'description', 'wikipedia', 'wikipedia:*', ]) @classmethod def create_from_osm_file(cls, filename, output_dir, precision=None): ''' Given an OSM file (planet or some other bounds) containing relations and their dependencies, create an R-tree index for coarse-grained reverse geocoding. Note: the input file is expected to have been created using osmfilter. Use fetch_osm_address_data.sh for planet or copy the admin borders commands if using other bounds. ''' if precision is None: precision = cls.GEOHASH_PRECISION index = cls(save_dir=output_dir, precision=precision) i = 0 for element_id, props, deps in parse_osm(filename): props = {safe_decode(k): safe_decode(v) for k, v in six.iteritems(props)} node_id = long(element_id.split(':')[-1]) lat = props.get('lat') lon = props.get('lon') if lat is None or lon is None: continue lat, lon = latlon_to_decimal(lat, lon) if lat is None or lon is None: continue if isclose(lon, 180.0): lon = 179.999 props = {k: v for k, v in six.iteritems(props) if k in ('id', 'type') or k in cls.include_property_patterns or (six.u(':') in k and six.u('{}:*').format(k.split(six.u(':'), 1)[0]) in cls.include_property_patterns)} props['type'] = 'node' props['id'] = node_id index.add_point(lat, lon, props) if i % 1000 == 0 and i > 0: print('did {} points'.format(i)) i += 1 return index if __name__ == '__main__': # Handle argument parsing here parser = argparse.ArgumentParser() parser.add_argument('-i', '--osm-places-file', help='Path to OSM places file') parser.add_argument('-p', '--precision', type=int, default=PlaceReverseGeocoder.GEOHASH_PRECISION, help='Geohash precision') parser.add_argument('-o', '--out-dir', default=os.getcwd(), help='Output directory') logging.basicConfig(level=logging.INFO) args = parser.parse_args() if args.osm_places_file: index = PlaceReverseGeocoder.create_from_osm_file(args.osm_places_file, args.out_dir, precision=args.precision) else: parser.error('Must specify places file') index.save()
1,748
764
<reponame>aboluock/ppl.nn<filename>src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/common/scatter_elements/scatter_elements_common.h // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #ifndef __ST_PPL_KERNEL_X86_COMMON_SCATTER_ELEMENTS_SCATTER_ELEMENTS_COMMON_H_ #define __ST_PPL_KERNEL_X86_COMMON_SCATTER_ELEMENTS_SCATTER_ELEMENTS_COMMON_H_ #include "ppl/kernel/x86/common/internal_include.h" #include <string.h> // memcpy namespace ppl { namespace kernel { namespace x86 { template <typename eT> ppl::common::RetCode scatter_elements_ndarray_common( const ppl::nn::TensorShape *src_shape, const ppl::nn::TensorShape *indices_shape, const eT *src, const int64_t *indices, const eT *updates, const int64_t axis, eT *dst) { memcpy(dst, src, src_shape->GetBytesExcludingPadding()); const int64_t dim_count = src_shape->GetDimCount(); const int64_t scatter_axis = axis < 0 ? axis + dim_count : axis; int64_t src_outer_dims = 1; int64_t indices_outer_dims = 1; for (int64_t i = 0; i < scatter_axis; i++) { src_outer_dims *= src_shape->GetDim(i); indices_outer_dims *= indices_shape->GetDim(i); } const int64_t src_scatter_dims = src_shape->GetDim(scatter_axis); const int64_t indices_scatter_dims = indices_shape->GetDim(scatter_axis); int64_t src_inner_dims = 1; int64_t indices_inner_dims = 1; for (int64_t i = scatter_axis + 1; i < dim_count; i++) { src_inner_dims *= src_shape->GetDim(i); indices_inner_dims *= indices_shape->GetDim(i); } for (int64_t i = 0; i < indices_outer_dims; i++) { for (int64_t j = 0; j < indices_scatter_dims; j++) { for (int64_t k = 0; k < indices_inner_dims; k++) { const int64_t index = indices[i * indices_scatter_dims * indices_inner_dims + j * indices_inner_dims + k]; const eT update_val = updates[i * indices_scatter_dims * indices_inner_dims + j * indices_inner_dims + k]; dst[i * src_scatter_dims * src_inner_dims + index * src_inner_dims + k] = update_val; } } } return ppl::common::RC_SUCCESS; } }}}; // namespace ppl::kernel::x86 #endif // __ST_PPL_KERNEL_X86_COMMON_SCATTER_ELEMENTS_SCATTER_ELEMENTS_COMMON_H_
1,223
892
{ "schema_version": "1.2.0", "id": "GHSA-2rh9-h56r-vv84", "modified": "2022-05-01T07:32:33Z", "published": "2022-05-01T07:32:33Z", "aliases": [ "CVE-2006-5862" ], "details": "Directory traversal vulnerability in the session mechanism of the web interface for Network Administration Visualized (NAV) before 3.1.1 allows attackers with filesystem write access to have an unknown impact via unknown attack vectors.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-5862" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/30174" }, { "type": "WEB", "url": "http://secunia.com/advisories/22766" }, { "type": "WEB", "url": "http://sourceforge.net/project/shownotes.php?release_id=461986" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/20995" }, { "type": "WEB", "url": "http://www.vupen.com/english/advisories/2006/4447" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
541
1,138
try: from urllib.parse import quote import html except ImportError: from urllib import quote html = None PUNCTUATION = r'''\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-''' ESCAPE_TEXT = r'\\[' + PUNCTUATION + ']' def escape(s, quote=True): s = s.replace("&", "&amp;") s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") return s def escape_url(link): safe = ( ':/?#@' # gen-delims - '[]' (rfc3986) '!$&()*+,;=' # sub-delims - "'" (rfc3986) '%' # leave already-encoded octets alone ) if html is None: return quote(link.encode('utf-8'), safe=safe) return html.escape(quote(html.unescape(link), safe=safe)) def escape_html(s): if html is not None: return html.escape(html.unescape(s)).replace('&#x27;', "'") return escape(s) def unikey(s): return ' '.join(s.split()).lower()
469
527
"""Module containing an interface to trained PyTorch model.""" from dice_ml.model_interfaces.base_model import BaseModel import torch class PyTorchModel(BaseModel): def __init__(self, model=None, model_path='', backend='PYT', func=None, kw_args=None): """Init method :param model: trained PyTorch Model. :param model_path: path to trained model. :param backend: "PYT" for PyTorch framework. :param func: function transformation required for ML model. If func is None, then func will be the identity function. :param kw_args: Dictionary of additional keyword arguments to pass to func. DiCE's data_interface is appended to the dictionary of kw_args, by default. """ super().__init__(model, model_path, backend) def load_model(self): if self.model_path != '': self.model = torch.load(self.model_path) def get_output(self, input_tensor, transform_data=False): """returns prediction probabilities :param input_tensor: test input. :param transform_data: boolean to indicate if data transformation is required. """ if transform_data: input_tensor = torch.tensor(self.transformer.transform(input_tensor)).float() return self.model(input_tensor).float() def set_eval_mode(self): self.model.eval() def get_gradient(self, input): # Future Support raise NotImplementedError("Future Support") def get_num_output_nodes(self, inp_size): temp_input = torch.rand(1, inp_size).float() return self.get_output(temp_input).data
687
1,062
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mr4c.nativec; import com.google.mr4c.algorithm.AlgorithmSchema; import com.google.mr4c.serialize.AlgorithmSerializer; import com.google.mr4c.serialize.SerializerFactory; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; public class ExternalAlgorithmSerializer { private AlgorithmSerializer m_serializer; private ExternalFactory m_factory; public ExternalAlgorithmSerializer( SerializerFactory serializerFactory, ExternalFactory factory ) { m_serializer = serializerFactory.createAlgorithmSerializer(); m_factory = factory; } public ExternalAlgorithm serializeAlgorithm(String name, AlgorithmSchema algo) throws IOException { ExternalAlgorithm extAlgorithm = m_factory.newAlgorithm(name); StringWriter writer = new StringWriter(); m_serializer.serializeAlgorithmSchema(algo,writer); extAlgorithm.setSerializedAlgorithm(writer.toString()); return extAlgorithm; } public AlgorithmSchema deserializeAlgorithm(ExternalAlgorithm extAlgorithm) throws IOException { AlgorithmSchema algo = new AlgorithmSchema(); String serializedAlgo = extAlgorithm.getSerializedAlgorithm(); StringReader reader = new StringReader(serializedAlgo); return m_serializer.deserializeAlgorithmSchema(reader); } }
567
721
package crazypants.enderio.base.config.config; import info.loenwind.autoconfig.factory.IValue; import info.loenwind.autoconfig.factory.IValueFactory; public final class FarmingConfig { public static final IValueFactory F = BaseConfig.F.section("farming"); public static final IValue<Integer> treeHarvestRadius = F.make("harvestRadius", 7, // "Radius (in addition to farm area) for harvesting logs.").setRange(1, 64).sync(); public static final IValue<Integer> treeHarvestHeight = F.make("harvestHeight", 30, // "Height (from initial block) for harvesting logs.").setRange(1, 255).sync(); public static final IValue<Integer> rubbertreeHarvestRadius = F.make("harvestRadiusRubberTree", 7, // "Radius (in addition to farm area) for harvesting rubber trees.").setRange(1, 64).sync(); public static final IValue<Integer> rubbertreeHarvestHeight = F.make("harvestHeightRubberTree", 30, // "Height (from initial block) for harvesting rubber trees.").setRange(1, 255).sync(); }
320
14,668
<reponame>zealoussnow/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_PROCESSING_NAME_PROCESSING_UTIL_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_PROCESSING_NAME_PROCESSING_UTIL_H_ #include <vector> #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_regexes.h" #include "components/autofill/core/browser/form_structure.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace autofill { #ifdef UNIT_TEST size_t FindLongestCommonAffixLength( const std::vector<base::StringPiece16>& strings, bool findCommonSuffix); bool IsValidParseableName(const base::StringPiece16 parseable_name); absl::optional<std::vector<base::StringPiece16>> RemoveCommonAffixesIfPossible( const std::vector<base::StringPiece16>& field_names); size_t FindLongestCommonPrefixLengthInStringsWithMinimalLength( const std::vector<base::StringPiece16>& strings, size_t minimal_length); absl::optional<std::vector<base::StringPiece16>> GetStrippedParseableNamesIfValid( const std::vector<base::StringPiece16>& field_names, size_t offset_left, size_t offset_right, size_t minimal_string_length_to_strip); absl::optional<std::vector<base::StringPiece16>> RemoveCommonPrefixIfPossible( const std::vector<base::StringPiece16>& field_names); absl::optional<std::vector<base::StringPiece16>> RemoveCommonPrefixForNamesWithMinimalLengthIfPossible( const std::vector<base::StringPiece16>& field_names); #endif // Determines and returns the parseable names for |field_names|. // With the |kAutofillLabelAffixRemoval| feature enabled, first it is tried to // remove a common affix from all names in |field_names|. If this is not // possible, it is attempted to remove long prefixes from a subset of names in // |field_names| which exceed a given length. If the // |kAutofillLabelAffixRemoval| is disabled, a prefix removal is attempted. In // any case, if a affix/prefix removal is not possible, the original names in // |field_names| are returned. // // Beware, this function works on string pieces and therefore, it should not be // called with temporary objects. Also, the underlying strings should not be // modified before the last usage of the result. std::vector<std::u16string> GetParseableNames( const std::vector<base::StringPiece16>& field_names); } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_PROCESSING_NAME_PROCESSING_UTIL_H_
895
3,334
from . import imports __all__ = ['__version__'] __version__ = imports.get_config().version
27
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Unreality", "definitions": [ "The quality of being imaginary, illusory, or unrealistic." ], "parts-of-speech": "Noun" }
82
1,127
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <common_test_utils/test_common.hpp> #include <ngraph_functions/utils/ngraph_helpers.hpp> #include <gtest/gtest.h> #include "ngraph/ngraph.hpp" #include "ngraph/opsets/opset4.hpp" #include "vpu/ngraph/operations/dynamic_shape_resolver.hpp" #include "vpu/ngraph/transformations/merge_subsequent_dsr_operations.hpp" namespace { TEST(MergeSubsequentDSROperations, smoke_SingleDSRFunction) { // shape // \ // dsr // / // data const auto inputType = ngraph::element::f16; const auto inputShape = ngraph::Shape{1}; const auto data = std::make_shared<ngraph::opset4::Parameter>(inputType, inputShape); const auto shape = std::make_shared<ngraph::opset4::Parameter>(ngraph::element::i64, ngraph::Shape{inputShape.size()}); const auto dsr = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(data, shape); const auto reference = std::make_shared<const ngraph::Function>( ngraph::NodeVector{dsr}, ngraph::ParameterVector{data, shape}, "SingleDSRFunction"); auto actual = ngraph::clone_function(*reference); ngraph::pass::Manager manager; manager.register_pass<vpu::MergeSubsequentDSROperations>(); manager.run_passes(actual); ASSERT_NO_THROW(ngraph::helpers::CompareFunctions(*reference, *actual)); } TEST(MergeSubsequentDSROperations, smoke_DSR_ReLU_DSR_ReLU_DSR) { // one_1 // \ // one_0 sum_1 - - - - - - - - - - dsr_2 // \ / / // shape - sum_0 - - - - - dsr_1 - relu_1 - // \ / // dsr_0 - relu_0 // / // data - // const auto inputType = ngraph::element::f16; const auto inputShape = ngraph::Shape{1}; const auto data = std::make_shared<ngraph::opset4::Parameter>(inputType, inputShape); const auto shape = std::make_shared<ngraph::opset4::Parameter>(ngraph::element::i64, ngraph::Shape{inputShape.size()}); const auto dsr_0 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(data, shape); const auto relu_0 = std::make_shared<ngraph::opset4::Relu>(dsr_0); // emulates shape subgraph for operation ReLU const auto one_0 = std::make_shared<ngraph::opset4::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<std::int64_t>{1}); const auto sum_0 = std::make_shared<ngraph::opset4::Add>(shape, one_0); const auto dsr_1 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(relu_0, sum_0); const auto relu_1 = std::make_shared<ngraph::opset4::Relu>(dsr_1); // emulates shape subgraph for operation ReLU const auto one_1 = std::make_shared<ngraph::opset4::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<std::int64_t>{1}); const auto sum_1 = std::make_shared<ngraph::opset4::Add>(sum_0, one_1); const auto dsr_2 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(relu_1, sum_1); const auto reference = std::make_shared<const ngraph::Function>( ngraph::NodeVector{dsr_2}, ngraph::ParameterVector{data, shape}, "DSR_ReLU_DSR_ReLU_DSR"); auto actual = ngraph::clone_function(*reference); ngraph::pass::Manager manager; manager.register_pass<vpu::MergeSubsequentDSROperations>(); manager.run_passes(actual); ASSERT_NO_THROW(ngraph::helpers::CompareFunctions(*reference, *actual)); } TEST(MergeSubsequentDSROperations, smoke_DSR_ReLU_DSR_DSR) { // Before: // one_1 // \ // one_0 sum_1 - - - - - - dsr_2 // \ / / // shape - sum_0 - - - - - dsr_1 - // \ / // dsr_0 - relu_0 // / // data - // // After: // one_1 // \ // one_0 sum_1 - - - - - - dsr_2 // \ / / // shape - sum_0 / // \ / // dsr_0 - relu_0 - - - - // / // data - const auto inputType = ngraph::element::f16; const auto inputShape = ngraph::Shape{1}; std::shared_ptr<ngraph::Function> actual; { const auto data = std::make_shared<ngraph::opset4::Parameter>(inputType, inputShape); const auto shape = std::make_shared<ngraph::opset4::Parameter>(ngraph::element::i64, ngraph::Shape{inputShape.size()}); const auto dsr_0 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(data, shape); const auto relu_0 = std::make_shared<ngraph::opset4::Relu>(dsr_0); // emulates shape subgraph for operation ReLU const auto one_0 = std::make_shared<ngraph::opset4::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<std::int64_t>{1}); const auto sum_0 = std::make_shared<ngraph::opset4::Add>(shape, one_0); const auto dsr_1 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(relu_0, sum_0); // emulates shape subgraph for operation ReLU const auto one_1 = std::make_shared<ngraph::opset4::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<std::int64_t>{1}); const auto sum_1 = std::make_shared<ngraph::opset4::Add>(sum_0, one_1); const auto dsr_2 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(dsr_1, sum_1); actual = std::make_shared<ngraph::Function>( ngraph::NodeVector{dsr_2}, ngraph::ParameterVector{data, shape}, "DSR_ReLU_DSR_DSR"); } std::shared_ptr<const ngraph::Function> reference; { const auto data = std::make_shared<ngraph::opset4::Parameter>(inputType, inputShape); const auto shape = std::make_shared<ngraph::opset4::Parameter>(ngraph::element::i64, ngraph::Shape{inputShape.size()}); const auto dsr_0 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(data, shape); const auto relu_0 = std::make_shared<ngraph::opset4::Relu>(dsr_0); // emulates shape subgraph for operation ReLU const auto one_0 = std::make_shared<ngraph::opset4::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<std::int64_t>{1}); const auto sum_0 = std::make_shared<ngraph::opset4::Add>(shape, one_0); // emulates shape subgraph for operation ReLU const auto one_1 = std::make_shared<ngraph::opset4::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<std::int64_t>{1}); const auto sum_1 = std::make_shared<ngraph::opset4::Add>(sum_0, one_1); const auto dsr_2 = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(relu_0, sum_1); reference = std::make_shared<const ngraph::Function>( ngraph::NodeVector{dsr_2}, ngraph::ParameterVector{data, shape}, "DSR_ReLU_DSR_DSR"); } ngraph::pass::Manager manager; manager.register_pass<vpu::MergeSubsequentDSROperations>(); manager.run_passes(actual); ASSERT_NO_THROW(ngraph::helpers::CompareFunctions(*reference, *actual)); } } //namespace
3,143
703
#pragma once #include <Core/ResourceManager/Resource.h> #include <RendererCore/Meshes/MeshBufferResource.h> #include <RendererCore/RendererCoreDLL.h> #include <RendererFoundation/RendererFoundationDLL.h> using ezDynamicMeshBufferResourceHandle = ezTypedResourceHandle<class ezDynamicMeshBufferResource>; struct ezDynamicMeshBufferResourceDescriptor { ezGALPrimitiveTopology::Enum m_Topology = ezGALPrimitiveTopology::Triangles; ezUInt32 m_uiNumPrimitives = 0; ezUInt32 m_uiNumVertices = 0; ezUInt32 m_uiNumIndices16 = 0; ezUInt32 m_uiNumIndices32 = 0; }; struct EZ_RENDERERCORE_DLL ezDynamicMeshVertex { EZ_DECLARE_POD_TYPE(); ezVec3 m_vPosition; ezVec2 m_vTexCoord; ezVec3 m_vEncodedNormal; ezVec4 m_vEncodedTangent; //ezColorLinearUB m_Color; EZ_ALWAYS_INLINE void EncodeNormal(const ezVec3& normal) { // store in [0; 1] range m_vEncodedNormal = normal * 0.5f + ezVec3(0.5f); // this is the same //ezMeshBufferUtils::EncodeNormal(normal, ezByteArrayPtr(reinterpret_cast<ezUInt8*>(&m_vEncodedNormal), sizeof(ezVec3)), ezMeshNormalPrecision::_32Bit).IgnoreResult(); } EZ_ALWAYS_INLINE void EncodeTangent(const ezVec3& tangent, float bitangentSign) { // store in [0; 1] range m_vEncodedTangent.x = tangent.x * 0.5f + 0.5f; m_vEncodedTangent.y = tangent.y * 0.5f + 0.5f; m_vEncodedTangent.z = tangent.z * 0.5f + 0.5f; m_vEncodedTangent.w = bitangentSign < 0.0f ? 0.0f : 1.0f; // this is the same //ezMeshBufferUtils::EncodeTangent(tangent, bitangentSign, ezByteArrayPtr(reinterpret_cast<ezUInt8*>(&m_vEncodedTangent), sizeof(ezVec4)), ezMeshNormalPrecision::_32Bit).IgnoreResult(); } }; class EZ_RENDERERCORE_DLL ezDynamicMeshBufferResource : public ezResource { EZ_ADD_DYNAMIC_REFLECTION(ezDynamicMeshBufferResource, ezResource); EZ_RESOURCE_DECLARE_COMMON_CODE(ezDynamicMeshBufferResource); EZ_RESOURCE_DECLARE_CREATEABLE(ezDynamicMeshBufferResource, ezDynamicMeshBufferResourceDescriptor); public: ezDynamicMeshBufferResource(); ~ezDynamicMeshBufferResource(); EZ_ALWAYS_INLINE const ezDynamicMeshBufferResourceDescriptor& GetDescriptor() const { return m_Descriptor; } EZ_ALWAYS_INLINE ezGALBufferHandle GetVertexBuffer() const { return m_hVertexBuffer; } EZ_ALWAYS_INLINE ezGALBufferHandle GetIndexBuffer() const { return m_hIndexBuffer; } ezArrayPtr<ezDynamicMeshVertex> AccessVertexData() { return m_VertexData; } ezArrayPtr<ezUInt16> AccessIndex16Data() { return m_Index16Data; } ezArrayPtr<ezUInt32> AccessIndex32Data() { return m_Index32Data; } void SetTopology(ezGALPrimitiveTopology::Enum topology) { m_Descriptor.m_Topology = topology; } ezGALPrimitiveTopology::Enum GetTopology() const { return m_Descriptor.m_Topology; } void SetPrimitiveCount(ezUInt32 numPrimitives) { m_Descriptor.m_uiNumPrimitives = numPrimitives; } ezUInt32 GetPrimitiveCount() const { return m_Descriptor.m_uiNumPrimitives; } const ezVertexDeclarationInfo& GetVertexDeclaration() const { return m_VertexDeclaration; } void UpdateGpuBuffer(ezGALCommandEncoder* pGALCommandEncoder, ezUInt32 uiFirstVertex, ezUInt32 uiNumVertices, ezUInt32 uiFirstIndex, ezUInt32 uiNumIndices, ezGALUpdateMode::Enum mode = ezGALUpdateMode::Discard); private: virtual ezResourceLoadDesc UnloadData(Unload WhatToUnload) override; virtual ezResourceLoadDesc UpdateContent(ezStreamReader* Stream) override; virtual void UpdateMemoryUsage(MemoryUsage& out_NewMemoryUsage) override; ezGALBufferHandle m_hVertexBuffer; ezGALBufferHandle m_hIndexBuffer; ezDynamicMeshBufferResourceDescriptor m_Descriptor; ezVertexDeclarationInfo m_VertexDeclaration; ezDynamicArray<ezDynamicMeshVertex, ezAlignedAllocatorWrapper> m_VertexData; ezDynamicArray<ezUInt16, ezAlignedAllocatorWrapper> m_Index16Data; ezDynamicArray<ezUInt32, ezAlignedAllocatorWrapper> m_Index32Data; };
1,486
6,989
<reponame>HeyLey/catboost<filename>catboost/libs/helpers/interrupt.h #pragma once #include <util/generic/yexception.h> extern void (* volatile INTERRUPTED_FUNC)(); class TInterruptException : public yexception { }; void SetInterruptHandler(void (*func)()); void ResetInterruptHandler(); void CheckInterrupted();
107
892
{ "schema_version": "1.2.0", "id": "GHSA-xx5w-cqxh-w2m4", "modified": "2022-05-13T01:19:12Z", "published": "2022-05-13T01:19:12Z", "aliases": [ "CVE-2018-15796" ], "details": "Cloud Foundry Bits Service Release, versions prior to 2.14.0, uses an insecure hashing algorithm to sign URLs. A remote malicious user may obtain a signed URL and extract the signing key, allowing them complete read and write access to the the Bits Service storage.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-15796" }, { "type": "WEB", "url": "https://www.cloudfoundry.org/blog/cve-2018-15796" } ], "database_specific": { "cwe_ids": [ "CWE-326" ], "severity": "HIGH", "github_reviewed": false } }
438
345
<reponame>Shadow-Devil/TeamSpeak-3-Java-API<filename>src/main/java/com/github/theholywaffle/teamspeak3/commands/FileCommands.java<gh_stars>100-1000 package com.github.theholywaffle.teamspeak3.commands; /* * #%L * TeamSpeak 3 Java API * %% * Copyright (C) 2017 <NAME>, <NAME> * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.github.theholywaffle.teamspeak3.commands.parameter.ArrayParameter; import com.github.theholywaffle.teamspeak3.commands.parameter.KeyValueParam; public final class FileCommands { private FileCommands() { throw new Error("No instances"); } public static Command ftCreateDir(String path, int channelId, String channelPassword) { CommandBuilder builder = new CommandBuilder("ftcreatedir", 3); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpw", channelPassword)); builder.add(new KeyValueParam("dirname", prefixSlash(path))); return builder.build(); } public static Command ftDeleteFile(int channelId, String channelPassword, String... filePaths) { if (filePaths == null || filePaths.length == 0) { throw new IllegalArgumentException("File array cannot be null or empty"); } CommandBuilder builder = new CommandBuilder("ftdeletefile", 3); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpw", channelPassword)); ArrayParameter files = new ArrayParameter(filePaths.length); for (String filePath : filePaths) { files.add(new KeyValueParam("name", prefixSlash(filePath))); } builder.add(files); return builder.build(); } public static Command ftGetFileInfo(int channelId, String channelPassword, String... filePaths) { if (filePaths == null || filePaths.length == 0) { throw new IllegalArgumentException("File array cannot be null or empty"); } CommandBuilder builder = new CommandBuilder("ftgetfileinfo", 1); ArrayParameter files = new ArrayParameter(filePaths.length, 3); for (String filePath : filePaths) { files.add(new KeyValueParam("cid", channelId)); files.add(new KeyValueParam("cpw", channelPassword)); files.add(new KeyValueParam("name", prefixSlash(filePath))); } builder.add(files); return builder.build(); } public static Command ftGetFileInfo(int[] channelIds, String[] channelPasswords, String[] filePaths) { if (channelIds == null || channelIds.length == 0) { throw new IllegalArgumentException("Channel ID array cannot be null or empty"); } if (filePaths == null || filePaths.length == 0) { throw new IllegalArgumentException("File array cannot be null or empty"); } if (channelIds.length != filePaths.length) { throw new IllegalArgumentException("Channel IDs length doesn't match file paths length"); } if (channelPasswords != null && filePaths.length != channelPasswords.length) { throw new IllegalArgumentException("Passwords length doesn't match file paths length"); } CommandBuilder builder = new CommandBuilder("ftgetfileinfo", 1); ArrayParameter files = new ArrayParameter(filePaths.length, 3); for (int i = 0; i < filePaths.length; ++i) { final String password = channelPasswords == null ? null : channelPasswords[i]; files.add(new KeyValueParam("cid", channelIds[i])); files.add(new KeyValueParam("cpw", password)); files.add(new KeyValueParam("name", prefixSlash(filePaths[i]))); } builder.add(files); return builder.build(); } public static Command ftGetFileList(String directoryPath, int channelId, String channelPassword) { if (directoryPath == null) throw new IllegalArgumentException("Directory path cannot be null"); CommandBuilder builder = new CommandBuilder("ftgetfilelist", 3); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpw", channelPassword)); String path = directoryPath; // Make sure path starts and ends with / if (!path.startsWith("/")) path = "/" + path; if (!path.endsWith("/")) path += "/"; builder.add(new KeyValueParam("path", path)); return builder.build(); } public static Command ftInitDownload(int transferId, String path, int channelId, String channelPassword) { CommandBuilder builder = new CommandBuilder("ftinitdownload", 6); builder.add(new KeyValueParam("clientftfid", transferId)); builder.add(new KeyValueParam("name", prefixSlash(path))); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpw", channelPassword)); builder.add(new KeyValueParam("seekpos", 0)); builder.add(new KeyValueParam("proto", 0)); // Use current (old) protocol for as long as possible return builder.build(); } public static Command ftInitUpload(int transferId, String path, int channelId, String channelPassword, long size, boolean overwrite) { CommandBuilder builder = new CommandBuilder("ftinitupload", 8); builder.add(new KeyValueParam("clientftfid", transferId)); builder.add(new KeyValueParam("name", prefixSlash(path))); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpw", channelPassword)); builder.add(new KeyValueParam("size", size)); builder.add(new KeyValueParam("overwrite", overwrite)); builder.add(new KeyValueParam("resume", 0)); builder.add(new KeyValueParam("proto", 0)); // Use current (old) protocol for as long as possible return builder.build(); } public static Command ftList() { return new CommandBuilder("ftlist").build(); } public static Command ftRenameFile(String oldPath, String newPath, int channelId, String channelPassword) { if (oldPath == null) throw new IllegalArgumentException("Old file path cannot be null"); if (newPath == null) throw new IllegalArgumentException("New file path cannot be null"); CommandBuilder builder = new CommandBuilder("ftrenamefile", 4); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpw", channelPassword)); builder.add(new KeyValueParam("oldname", prefixSlash(oldPath))); builder.add(new KeyValueParam("newname", prefixSlash(newPath))); return builder.build(); } public static Command ftRenameFile(String oldPath, String newPath, int oldChannelId, String oldChannelPassword, int newChannelId, String newChannelPassword) { if (oldPath == null) throw new IllegalArgumentException("Old file path cannot be null"); if (newPath == null) throw new IllegalArgumentException("New file path cannot be null"); CommandBuilder builder = new CommandBuilder("ftrenamefile", 6); builder.add(new KeyValueParam("cid", oldChannelId)); builder.add(new KeyValueParam("cpw", oldChannelPassword)); builder.add(new KeyValueParam("tcid", newChannelId)); builder.add(new KeyValueParam("tcpw", newChannelPassword)); builder.add(new KeyValueParam("oldname", prefixSlash(oldPath))); builder.add(new KeyValueParam("newname", prefixSlash(newPath))); return builder.build(); } private static String prefixSlash(String path) { if (path == null) throw new IllegalArgumentException("File path cannot be null"); return path.startsWith("/") ? path : "/" + path; } }
2,590
1,375
<filename>sw/device/silicon_creator/lib/sigverify_mod_exp_ibex_unittest.cc<gh_stars>1000+ // Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <unordered_set> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "sw/device/silicon_creator/lib/sigverify.h" #include "sw/device/silicon_creator/lib/sigverify_mod_exp.h" namespace sigverify_mod_exp_ibex_unittest { namespace { /** * PKCS #1 v1.5 encoded messages used in tests. */ /** * Message: "test" * SHA2-256 hash (little-endian): {0xb0f00a08, 0xd15d6c15, 0x2b0b822c, * 0xa3bf4f1b, 0xc55ad015, 0x9a2feaa0, 0x884c7d65, 0x9f86d081} * * Generated using the `openssl rsautl` command as discussed in * sw/device/silicon_creator/keys/README.md. */ constexpr sigverify_rsa_buffer_t kEncMsgTest = { 0xb0f00a08, 0xd15d6c15, 0x2b0b822c, 0xa3bf4f1b, 0xc55ad015, 0x9a2feaa0, 0x884c7d65, 0x9f86d081, 0x05000420, 0x03040201, 0x86480165, 0x0d060960, 0x00303130, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x0001ffff, }; /** * Inputs and expected values for computational tests involving signatures. */ struct SigTestCase { /** * Key to use in calculations. */ const sigverify_rsa_key_t key; /** * An RSA signature. * * Can be generated using the `openssl dgst` command as discussed in * sw/device/silicon_creator/keys/README.md. */ sigverify_rsa_buffer_t sig; /** * sig^e mod n. * * This value must match the result of `mod_exp(sig, e, n)`. */ const sigverify_rsa_buffer_t *enc_msg; }; // The keys below do not need to be kept in sync with the actual keys used in // boot stages since we have separate tests for each boot stage. However, it is // important to cover both exponents, i.e. 3 and 65537, that we support. constexpr SigTestCase kSigTestCases[2]{ // message: "test" { // sw/device/silicon_creator/mask_rom/keys/test_key_0_rsa_3072_exp_f4.public.der .key = { .n = {{ 0x5801a2bd, 0xeff64a46, 0xc8cf2251, 0xa7cd62cb, 0x634a39c2, 0x55c936d3, 0x463d61fc, 0x762ebbaa, 0x01aadfb2, 0x23da15d1, 0x8475fdc6, 0x4ec67b7b, 0xe9364570, 0xd23ec7c7, 0x98038d63, 0x5688a56b, 0x68037add, 0xb20ff289, 0x9d96c1ce, 0xbac0b8cd, 0xead33d0b, 0x195f89c8, 0xd7dc110e, 0xf5bccc12, 0x8dfa33dc, 0xedc404d2, 0x74ef8524, 0x9197c0c8, 0x79cc448e, 0x4c9c505d, 0x4a586ad7, 0xe2d0f071, 0x589f28c2, 0x2ca7fc22, 0x0354b0e2, 0xefb63b44, 0x33a75b04, 0x9e194454, 0x1b4b2cde, 0x8e3f78e0, 0x5260877c, 0x05685b72, 0x4868ad4e, 0x10303ac9, 0x05ac2411, 0x5e797381, 0xd5407668, 0xe3522348, 0xa33134f8, 0x38f7a953, 0xd926f672, 0x136f6753, 0xb186b0ab, 0x5ccab586, 0x61e5bf2e, 0x9fc0eebb, 0x788ed0bd, 0x47b5fc70, 0xf971262a, 0x3b40d99b, 0x5b9fd926, 0xce3c93bf, 0xd406005e, 0x72b9e555, 0xc9b9273e, 0xfcef747f, 0xf0a35598, 0x2761e8f6, 0xec1799df, 0x462bc52d, 0x8e47218b, 0x429ccdae, 0xe7e7d66c, 0x70c70b03, 0x0356c3d2, 0x3cb3e7d1, 0xd42d035d, 0x83c529a3, 0x8df9930e, 0xb082e1f0, 0x07509c30, 0x5c33a350, 0x4f6884b9, 0x7b9d2de0, 0x0f1d16b3, 0x38dbcf55, 0x168580ea, 0xc2f2aca4, 0x43f0ae60, 0x227dd2ed, 0xd8dc61f4, 0x9404e8bc, 0x0db76fe3, 0x3491d3b0, 0x6ca44e27, 0xcda63719, }}, .n0_inv = { 0x9c9a176b, 0x44d6fa52, 0x71a63ec4, 0xadc94595, 0x3fd9bc73, 0xa83cdc95, 0xbe1bc819, 0x2b421fae, }, .exponent = 65537, }, .sig = { 0xeb28a6d3, 0x936b42bb, 0x76d3973d, 0x6322d536, 0x253c7547, 0x1bfdda9f, 0x597b8193, 0xccac0b02, 0xb3b66a5b, 0xa7880e18, 0x04846239, 0x4e927eda, 0x37883753, 0x8bc059cd, 0xdc6102d5, 0xa702185d, 0xf963eec8, 0xfed8f779, 0xc606461b, 0xa5326e90, 0x87f4ef4b, 0xddaa7f8b, 0xcdae0535, 0x1174dbc8, 0x345db563, 0x57b9dd37, 0xd6ff9402, 0x1c8077ec, 0x02e76f6f, 0x135797fe, 0x92ca1d0c, 0x84da4abf, 0xce3f4b43, 0xe3d47def, 0x510ba10e, 0x9940e174, 0x5c0635bc, 0x8fc7b1d6, 0x9ee042d9, 0x68dc09c7, 0x30b54030, 0xf2336aa6, 0xaf6535f9, 0x7b1fc0e1, 0xeea50f7c, 0xe1d2f4b3, 0xa0405640, 0xc035d5b9, 0x34ee81ef, 0xf1460ecf, 0x943b5734, 0xae5dcd6e, 0x64373ca7, 0x968dd9e5, 0xd1916ff3, 0x0c4e1ab5, 0x5ba76542, 0x9488cc72, 0x35ef4275, 0x071eef2a, 0x64516088, 0x42a383fd, 0x477678ee, 0xd1c7c37d, 0x7f55cf49, 0x24f62205, 0x564dfc4a, 0x8b305ceb, 0x46917278, 0xab9bf3c3, 0x9a1f6739, 0x188c264e, 0x32c584e9, 0x54d0e1d6, 0x967710a1, 0x1efe8ffb, 0x299e277a, 0x0ea61f6c, 0xf7845775, 0x78386d10, 0x66245c4f, 0xfd52953a, 0x955b4b10, 0x6b7d9d30, 0x68fc106f, 0xbaaebfac, 0x653b64bd, 0x826a3baa, 0x98703747, 0x6ee930ec, 0xacbb94d8, 0xcede8d12, 0xa17b3cb0, 0xa520fe81, 0x84df2df5, 0x4f97181e, }, .enc_msg = &kEncMsgTest, }, // message: "test" { // sw/device/silicon_creator/mask_rom/keys/test_key_1_rsa_3072_exp_3.public.der .key = { .n = {{ 0xbd158913, 0xab75ea1a, 0xc04e5292, 0x68f5778a, 0xa71418c7, 0xddc4fc1c, 0xcb09302d, 0xedf3142b, 0x656d7d85, 0xf761d32a, 0x2d334d1b, 0x26c91770, 0x5b9ba5a0, 0x00ac6c05, 0xbabaf1bb, 0xa8299ecc, 0xb4223f99, 0x5b676ad3, 0xcaa786c2, 0x3e2f1785, 0x204b6991, 0x21fa118f, 0x435573ab, 0xa3353ba1, 0x1074c161, 0x2ad5e901, 0x7310247c, 0x1e21b8e9, 0x0cfc7762, 0x0a9139b1, 0xfc655b33, 0x6990faaf, 0xbb88faec, 0x7c7bd6ef, 0x261e4555, 0x6bc3d813, 0x5ce6e18b, 0xdd308629, 0x37d3d54d, 0x65acd84d, 0x97b7e0c3, 0xc0d35caa, 0xb0be177a, 0x09473af3, 0x67f43155, 0x3b2f7661, 0xf9255df2, 0x1b42c84c, 0x355cd607, 0x835e74ca, 0x1d011c4e, 0x46652555, 0x1566f96f, 0x6cffd2f9, 0x204e783e, 0xa178a2eb, 0xe7297a95, 0xd7380039, 0x1a685545, 0x76ed97c9, 0x6bc0b1b7, 0xd9b1338e, 0xa3b23005, 0x6fe7109f, 0x01c232e1, 0x851639c5, 0xe81d338c, 0x25ebe0c4, 0x5b0202cd, 0x3690cb70, 0xad13b664, 0x8bf7833e, 0x6017349c, 0xf6e90b08, 0x953ef3d8, 0x4bc11817, 0xd0f6e840, 0xfe01a954, 0x9b866209, 0xb9653ff8, 0x0d654f5c, 0xff78177c, 0x3688833c, 0x57cc0c30, 0x71965be7, 0xf61fb728, 0xaeac8ca2, 0xbdc9848b, 0x954c529f, 0x9917ac7f, 0x4ba4c007, 0xce2dbf0b, 0xfc7d8504, 0x2712580b, 0xd0293151, 0xa4dbbff3, }}, .n0_inv = { 0x079056e5, 0xe151dae1, 0xd4f9deee, 0xe18c4cab, 0x868f9abe, 0x8643ed1c, 0x58022be6, 0x8f8972c9, }, .exponent = 3, }, .sig = { 0xb13844fa, 0x9c7622d8, 0xda09bdc4, 0x79fde5c6, 0x7037a98b, 0x4d53a5cf, 0xabd7e9e4, 0x8456c575, 0x1f1fc5f6, 0x7870e2d5, 0x96a488c2, 0x7aa2263c, 0xbe5dbcf1, 0x34a6b2ff, 0x51bd23fa, 0xef582d6d, 0x52d0e2fa, 0x586c6b2f, 0x0aa1e7d0, 0x0d1f8a33, 0xf95e28bc, 0x70f13b45, 0x548740b0, 0x42be7f0d, 0x4254ac6f, 0xb7363b68, 0x48f1c461, 0x06b8f936, 0xd3274353, 0x121219e4, 0x98d8e770, 0x39e1bb17, 0x1a005ad4, 0x673985f4, 0x6f2cfd4a, 0xba537c5f, 0x1ca6bdad, 0x5e7bdb7d, 0x9b6783bd, 0xf3a1e998, 0xa5dc56f6, 0x149d6bb5, 0x9437917a, 0xfeb89880, 0x6e6ce5f9, 0x07bece66, 0xaab327ae, 0x1ff13a9e, 0x35e3b280, 0x645b636a, 0x34628104, 0xda8148ee, 0x95d22ce1, 0x78f4e1a0, 0xec9bdf2e, 0x42fc69d0, 0x4b8e5244, 0x192a0454, 0x7bfd31dc, 0x09a07d77, 0x2a3c745b, 0x8d5deeb7, 0xb539505c, 0xd5352a21, 0x22fd9774, 0x6fd4f48f, 0x60d2c5e9, 0x9292c725, 0x035797d8, 0x8bbb8d02, 0x977bdd02, 0x2da179b2, 0xa9779cc9, 0x13c5fe29, 0x607c3673, 0x8e52aeca, 0x6fd9ea3a, 0x5915a281, 0x69dc74c2, 0x162207fb, 0x1efa0497, 0x0a9e1a61, 0x3542ac58, 0x885d5d5e, 0x29623b26, 0x14cbc783, 0xa2f9511e, 0xfcb8986f, 0x6b7ca8d8, 0xde4c53b2, 0x4f8fd997, 0x2eded334, 0xe9d492dd, 0xd0751bc1, 0x9077d8cd, 0x5563ec91, }, .enc_msg = &kEncMsgTest, }, }; class ModExp : public testing::TestWithParam<SigTestCase> {}; TEST_P(ModExp, EncMsg) { sigverify_rsa_buffer_t res; EXPECT_EQ(sigverify_mod_exp_ibex(&GetParam().key, &GetParam().sig, &res), kErrorOk); EXPECT_THAT(res.data, ::testing::ElementsAreArray(GetParam().enc_msg->data)); } TEST(ModExp, BadExp) { // Exponent = 0 constexpr sigverify_rsa_key_t bad_key{}; sigverify_rsa_buffer_t empty{}; EXPECT_EQ(sigverify_mod_exp_ibex(&bad_key, &empty, &empty), kErrorSigverifyBadExponent); } INSTANTIATE_TEST_SUITE_P(AllCases, ModExp, testing::ValuesIn(kSigTestCases)); } // namespace } // namespace sigverify_mod_exp_ibex_unittest
7,045
313
<filename>titus-server-federation/src/main/java/com/netflix/titus/federation/service/CellWebClientConnectorUtil.java<gh_stars>100-1000 /* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.federation.service; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.tuple.Either; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.client.WebClientResponseException; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class CellWebClientConnectorUtil { private static final Logger logger = LoggerFactory.getLogger(CellWebClientConnectorUtil.class); /** * Run GET operation on all cells and merge the result. */ public static <T> Either<List<T>, WebApplicationException> doGetAndMerge(CellWebClientConnector cellWebClientConnector, String path, ParameterizedTypeReference<List<T>> type, long timeoutMs) { Either<List<List<T>>, Throwable> partials; try { partials = Flux .merge( cellWebClientConnector.getWebClients().values().stream() .map(c -> c.get().uri(path) .retrieve() .bodyToMono(type) ) .collect(Collectors.toList()) ) .collectList() .<Either<List<List<T>>, Throwable>>map(Either::ofValue) .onErrorResume(e -> Mono.just(Either.ofError(e))) .block(Duration.ofMillis(timeoutMs)); } catch (Exception e) { logger.error("Unexpected error: path={}, type={}", path, type, e); return Either.ofError(new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR)); } if (partials == null) { logger.error("No result from any cell: path={}, type={}", path, type); return Either.ofError(new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR)); } if (partials.hasError()) { return Either.ofError(new WebApplicationException(partials.getError(), Response.Status.INTERNAL_SERVER_ERROR)); } if (CollectionsExt.isNullOrEmpty(partials.getValue())) { return Either.ofValue(Collections.emptyList()); } List<T> result = new ArrayList<>(); partials.getValue().forEach(result::addAll); return Either.ofValue(result); } /** * Run GET operation on all cells, but only one is expected to return a result. */ public static <T> Either<T, WebApplicationException> doGetFromCell(CellWebClientConnector cellWebClientConnector, String path, ParameterizedTypeReference<T> type, long timeoutMs) { List<Either<T, Throwable>> partials; try { partials = Flux.merge( cellWebClientConnector.getWebClients().values().stream() .map(cell -> cell.get().uri(path) .retrieve() .bodyToMono(type) .map(Either::<T, Throwable>ofValue) .onErrorResume(e -> Mono.just(Either.ofError(e))) ) .collect(Collectors.toList()) ).collectList().block(Duration.ofMillis(timeoutMs)); } catch (Exception e) { logger.error("Unexpected error: path={}, type={}", path, type, e); return Either.ofError(new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR)); } if (CollectionsExt.isNullOrEmpty(partials)) { logger.error("No result from any cell: path={}, type={}", path, type); throw new WebApplicationException(Response.Status.NOT_FOUND); } Throwable systemError = null; for (Either<T, Throwable> partial : partials) { if (partial.hasValue()) { return Either.ofValue(partial.getValue()); } if (partial.getError() instanceof WebClientResponseException) { WebClientResponseException wcError = (WebClientResponseException) partial.getError(); if (!wcError.getStatusCode().equals(HttpStatus.NOT_FOUND)) { systemError = partial.getError(); } } else { systemError = partial.getError(); } } // If there is a system error, report it. Otherwise all cells returned NOT_FOUND, and we can send it back to // the client. return Either.ofError(systemError != null ? new WebApplicationException(systemError) : new WebApplicationException(Response.Status.NOT_FOUND) ); } }
3,117
552
<filename>doc/integrations/cortx-s3-slack-bot/list_bucket_contents.py from dotenv import load_dotenv from pathlib import Path import boto3 import os env_path = Path('.')/'.env' load_dotenv(dotenv_path=env_path) if __name__ == "__main__": resource = boto3.resource('s3', endpoint_url=str(os.environ.get('ENDPOINT_URL')), aws_access_key_id=str(os.environ.get('AWS_ACCESS_KEY_ID')), aws_secret_access_key=str(os.environ.get('AWS_SECRET_ACCESS_KEY')) ) bucket = resource.Bucket('testbucket') print(bucket) for my_bucket_object in bucket.objects.all(): print(my_bucket_object)
308
353
#ifndef THC_GENERIC_FILE #error "You must define THC_GENERIC_FILE before including THGenerateComplexFloatType.h" #endif #define scalar_t c10::complex<float> #define accreal c10::complex<float> #define Real ComplexFloat #define CReal CudaComplexFloat #define THC_REAL_IS_COMPLEXFLOAT #line 1 THC_GENERIC_FILE #include THC_GENERIC_FILE #undef scalar_t #undef accreal #undef Real #undef CReal #undef THC_REAL_IS_COMPLEXFLOAT #ifndef THCGenerateAllTypes #ifndef THCGenerateComplexTypes #undef THC_GENERIC_FILE #endif #endif
230
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dfareporting.model; /** * Placement Assignment. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Campaign Manager 360 API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class PlacementAssignment extends com.google.api.client.json.GenericJson { /** * Whether this placement assignment is active. When true, the placement will be included in the * ad's rotation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean active; /** * ID of the placement to be assigned. This is a required field. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long placementId; /** * Dimension value for the ID of the placement. This is a read-only, auto-generated field. * The value may be {@code null}. */ @com.google.api.client.util.Key private DimensionValue placementIdDimensionValue; /** * Whether the placement to be assigned requires SSL. This is a read-only field that is auto- * generated when the ad is inserted or updated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean sslRequired; /** * Whether this placement assignment is active. When true, the placement will be included in the * ad's rotation. * @return value or {@code null} for none */ public java.lang.Boolean getActive() { return active; } /** * Whether this placement assignment is active. When true, the placement will be included in the * ad's rotation. * @param active active or {@code null} for none */ public PlacementAssignment setActive(java.lang.Boolean active) { this.active = active; return this; } /** * ID of the placement to be assigned. This is a required field. * @return value or {@code null} for none */ public java.lang.Long getPlacementId() { return placementId; } /** * ID of the placement to be assigned. This is a required field. * @param placementId placementId or {@code null} for none */ public PlacementAssignment setPlacementId(java.lang.Long placementId) { this.placementId = placementId; return this; } /** * Dimension value for the ID of the placement. This is a read-only, auto-generated field. * @return value or {@code null} for none */ public DimensionValue getPlacementIdDimensionValue() { return placementIdDimensionValue; } /** * Dimension value for the ID of the placement. This is a read-only, auto-generated field. * @param placementIdDimensionValue placementIdDimensionValue or {@code null} for none */ public PlacementAssignment setPlacementIdDimensionValue(DimensionValue placementIdDimensionValue) { this.placementIdDimensionValue = placementIdDimensionValue; return this; } /** * Whether the placement to be assigned requires SSL. This is a read-only field that is auto- * generated when the ad is inserted or updated. * @return value or {@code null} for none */ public java.lang.Boolean getSslRequired() { return sslRequired; } /** * Whether the placement to be assigned requires SSL. This is a read-only field that is auto- * generated when the ad is inserted or updated. * @param sslRequired sslRequired or {@code null} for none */ public PlacementAssignment setSslRequired(java.lang.Boolean sslRequired) { this.sslRequired = sslRequired; return this; } @Override public PlacementAssignment set(String fieldName, Object value) { return (PlacementAssignment) super.set(fieldName, value); } @Override public PlacementAssignment clone() { return (PlacementAssignment) super.clone(); } }
1,448
2,023
#! /usr/bin/env python3 """ markdowndoc.py Written by <NAME> and <NAME> Licensed under GPLv3 Released 28 April 2009 This module contains a simple class to output Markdown-style pydocs. """ import pydoc, inspect, re, builtins class MarkdownDoc(pydoc.TextDoc): underline = "*" * 40 def process_docstring(self, obj): """Get the docstring and turn it into a list.""" docstring = pydoc.getdoc(obj) if docstring: return docstring + "\n\n" return "" def process_class_name(self, name, bases, module): """Format the class's name and bases.""" title = "## class " + self.bold(name) if bases: # get the names of each of the bases base_titles = [pydoc.classname(base, module) for base in bases] # if its not just object if len(base_titles) > 1: # append the list to the title title += "(%s)" % ", ".join(base_titles) return title def process_subsection(self, name): """format the subsection as a header""" return "### " + name def docclass(self, cls, name=None, mod=None): """Produce text documentation for the class object cls.""" # the overall document, as a line-delimited list document = [] # get the object's actual name, defaulting to the passed in name name = name or cls.__name__ # get the object's bases bases = cls.__bases__ # get the object's module mod = cls.__module__ # get the object's MRO mro = [pydoc.classname(base, mod) for base in inspect.getmro(cls)] # get the object's classname, which should be printed classtitle = self.process_class_name(name, bases, mod) document.append(classtitle) document.append(self.underline) # get the object's docstring, which should be printed docstring = self.process_docstring(cls) document.append(docstring) # get all the attributes of the class attrs = [] for name, kind, classname, value in pydoc.classify_class_attrs(cls): if pydoc.visiblename(name): attrs.append((name, kind, classname, value)) # sort them into categories data, descriptors, methods = [], [], [] for attr in attrs: if attr[1] == "data" and not attr[0].startswith("_"): data.append(attr) elif attr[1] == "data descriptor" and not attr[0].startswith("_"): descriptors.append(attr) elif "method" in attr[1] and not attr[2] is builtins.object: methods.append(attr) if data: # start the data section document.append(self.process_subsection(self.bold("data"))) document.append(self.underline) # process your attributes for name, kind, classname, value in data: if hasattr(value, '__call__') or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None document.append(self.docother(getattr(cls, name), name, mod, maxlen=70, doc=doc) + '\n') if descriptors: # start the descriptors section document.append(self.process_subsection(self.bold("descriptors"))) document.append(self.underline) # process your descriptors for name, kind, classname, value in descriptors: document.append(self._docdescriptor(name, value, mod)) if methods: # start the methods section document.append(self.process_subsection(self.bold("methods"))) document.append(self.underline) # process your methods for name, kind, classname, value in methods: document.append(self.document(getattr(cls, name), name, mod, cls)) return "\n".join(document) def bold(self, text): """ Formats text as bold in markdown. """ if text.startswith('_') and text.endswith('_'): return "__\%s\__" %text elif text.startswith('_'): return "__\%s__" %text elif text.endswith('_'): return "__%s\__" %text else: return "__%s__" %text def indent(self, text, prefix=''): """Indent text by prepending a given prefix to each line.""" return text def section(self, title, contents): """Format a section with a given heading.""" clean_contents = self.indent(contents).rstrip() return "# " + self.bold(title) + '\n\n' + clean_contents + '\n\n' def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): object = object.__func__ if name == realname: title = self.bold(realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = inspect.getfullargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann, formatvalue=self.formatvalue, formatannotation=inspect.formatannotationrelativeto(object)) if realname == '<lambda>': title = self.bold(name) + ' lambda ' # XXX lambda's won't usually have func_annotations['return'] # since the syntax doesn't support but it is possible. # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = "#### " + "def " + title + argspec + ':' + '\n' + note if skipdocs: return decl + '\n' else: doc = pydoc.getdoc(object) or '' return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n') def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" line = "#### " + object.__name__ + "\n" line += super().docother(object, name, mod, parent, maxlen, doc) return line + "\n" def _docdescriptor(self, name, value, mod): results = "" if name: results += "#### " + self.bold(name) + "\n" doc = pydoc.getdoc(value) or "" if doc: results += doc + "\n" return results
2,191
9,106
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "IReactDispatcher.h" #include "ReactDispatcherHelper.g.cpp" #include <glog/logging.h> using namespace winrt; using namespace Windows::Foundation; namespace winrt::Microsoft::ReactNative::implementation { // Implements IDispatchQueue2 on top of a custom IReactDispatcher provided by the application struct WrappedReactDispatcher : public Mso::UnknownObject<Mso::React::IDispatchQueue2> { WrappedReactDispatcher(const winrt::Microsoft::ReactNative::IReactDispatcher &dispatcher) noexcept : m_dispatcher(dispatcher) {} void Post(Mso::DispatchTask &&task) const noexcept override { m_dispatcher.Post(task); } void InvokeElsePost(Mso::DispatchTask &&task) const noexcept override { if (m_dispatcher.HasThreadAccess()) { task(); } else { Post(std::move(task)); } } private: winrt::Microsoft::ReactNative::IReactDispatcher m_dispatcher; }; ReactDispatcher::ReactDispatcher(Mso::DispatchQueue &&queue) noexcept : m_queue{std::move(queue)} {} bool ReactDispatcher::HasThreadAccess() noexcept { return m_queue.HasThreadAccess(); } ReactDispatcherCallback CreateLoggingCallback(ReactDispatcherCallback const &callback) { return [callback]() { try { callback(); } catch (winrt::hresult_error const &error) { std::stringstream errorCode; errorCode << "0x" << std::hex << error.code(); LOG(ERROR) << "HRESULT " << errorCode.str() << ": " << winrt::to_string(error.message()); throw; } }; } void ReactDispatcher::Post(ReactDispatcherCallback const &callback) noexcept { return m_queue.Post([callback = CreateLoggingCallback(callback)]() noexcept { callback(); }); } void ReactDispatcher::Post(Mso::DispatchTask &&task) const noexcept { m_queue.Post(std::move(task)); } void ReactDispatcher::InvokeElsePost(Mso::DispatchTask &&task) const noexcept { m_queue.InvokeElsePost(std::move(task)); } /*static*/ IReactDispatcher ReactDispatcher::CreateSerialDispatcher() noexcept { return make<ReactDispatcher>(Mso::DispatchQueue{}); } /*static*/ Mso::CntPtr<Mso::React::IDispatchQueue2> ReactDispatcher::GetUIDispatchQueue2( IReactPropertyBag const &properties) noexcept { auto iReactDispatcher = GetUIDispatcher(properties); if (!iReactDispatcher) return nullptr; if (auto simpleDispatcher = iReactDispatcher.try_as<IDispatchQueue2>()) return simpleDispatcher.get(); return Mso::Make<WrappedReactDispatcher>(iReactDispatcher); } /*static*/ IReactDispatcher ReactDispatcher::UIThreadDispatcher() noexcept { static thread_local weak_ref<IReactDispatcher> *tlsWeakDispatcher{nullptr}; IReactDispatcher dispatcher{nullptr}; auto queue = Mso::DispatchQueue::GetCurrentUIThreadQueue(); if (queue && queue.HasThreadAccess()) { queue.InvokeElsePost([&queue, &dispatcher]() noexcept { // This code runs synchronously, but we want it to be run the queue context to // access the queue local value where we store the weak_ref to the dispatcher. // The queue local values are destroyed along with the queue. // To access queue local value we temporary swap it with the thread local value. // It must be a TLS value to ensure proper indexing of the queue local value entry. auto tlsGuard{queue.LockLocalValue(&tlsWeakDispatcher)}; dispatcher = tlsWeakDispatcher->get(); if (!dispatcher) { dispatcher = winrt::make<ReactDispatcher>(std::move(queue)); *tlsWeakDispatcher = dispatcher; } }); } return dispatcher; } /*static*/ IReactPropertyName ReactDispatcher::UIDispatcherProperty() noexcept { static IReactPropertyName uiThreadDispatcherProperty{ReactPropertyBagHelper::GetName( ReactPropertyBagHelper::GetNamespace(L"ReactNative.Dispatcher"), L"UIDispatcher")}; return uiThreadDispatcherProperty; } /*static*/ IReactDispatcher ReactDispatcher::GetUIDispatcher(IReactPropertyBag const &properties) noexcept { return properties.Get(UIDispatcherProperty()).try_as<IReactDispatcher>(); } /*static*/ void ReactDispatcher::SetUIThreadDispatcher(IReactPropertyBag const &properties) noexcept { properties.Set(UIDispatcherProperty(), UIThreadDispatcher()); } /*static*/ IReactPropertyName ReactDispatcher::JSDispatcherProperty() noexcept { static IReactPropertyName jsThreadDispatcherProperty{ReactPropertyBagHelper::GetName( ReactPropertyBagHelper::GetNamespace(L"ReactNative.Dispatcher"), L"JSDispatcher")}; return jsThreadDispatcherProperty; } } // namespace winrt::Microsoft::ReactNative::implementation
1,705
321
<gh_stars>100-1000 // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by // base/android/jni_generator/jni_generator.py // For // org/chromium/base/LocaleUtils #ifndef org_chromium_base_LocaleUtils_JNI #define org_chromium_base_LocaleUtils_JNI #include <jni.h> #include "base/android/jni_generator/jni_generator_helper.h" // Step 1: forward declarations. namespace { const char kLocaleUtilsClassPath[] = "org/chromium/base/LocaleUtils"; // Leaking this jclass as we cannot use LazyInstance from some threads. jclass g_LocaleUtils_clazz = NULL; } // namespace // Step 2: method stubs. static base::subtle::AtomicWord g_LocaleUtils_getDefaultLocale = 0; static base::android::ScopedJavaLocalRef<jstring> Java_LocaleUtils_getDefaultLocale(JNIEnv* env) { /* Must call RegisterNativesImpl() */ CHECK_CLAZZ(env, g_LocaleUtils_clazz, g_LocaleUtils_clazz, NULL); jmethodID method_id = base::android::MethodID::LazyGet< base::android::MethodID::TYPE_STATIC>( env, g_LocaleUtils_clazz, "getDefaultLocale", "(" ")" "Ljava/lang/String;", &g_LocaleUtils_getDefaultLocale); jstring ret = static_cast<jstring>(env->CallStaticObjectMethod(g_LocaleUtils_clazz, method_id)); jni_generator::CheckException(env); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } // Step 3: RegisterNatives. static bool RegisterNativesImpl(JNIEnv* env) { g_LocaleUtils_clazz = reinterpret_cast<jclass>(env->NewGlobalRef( base::android::GetClass(env, kLocaleUtilsClassPath).obj())); return true; } #endif // org_chromium_base_LocaleUtils_JNI
680
1,801
#ifndef UPSAMPLE_LAYER_H #define UPSAMPLE_LAYER_H #include "dark_cuda.h" #include "layer.h" #include "network.h" #ifdef __cplusplus extern "C" { #endif layer make_upsample_layer(int batch, int w, int h, int c, int stride); void forward_upsample_layer(const layer l, network_state state); void backward_upsample_layer(const layer l, network_state state); void resize_upsample_layer(layer *l, int w, int h); #ifdef GPU void forward_upsample_layer_gpu(const layer l, network_state state); void backward_upsample_layer_gpu(const layer l, network_state state); #endif #ifdef __cplusplus } #endif #endif
217
4,085
<reponame>m-mead/pip-tools<filename>piptools/subprocess_utils.py<gh_stars>1000+ # WARNING! BE CAREFUL UPDATING THIS FILE # Consider possible security implications associated with subprocess module. import subprocess # nosec def run_python_snippet(python_executable: str, code_to_run: str) -> str: """ Executes python code by calling python_executable with '-c' option. """ py_exec_cmd = python_executable, "-c", code_to_run # subprocess module should never be used with untrusted input return subprocess.check_output( # nosec py_exec_cmd, shell=False, universal_newlines=True, )
229
454
package io.vertx.up.uca.yaml; import io.vertx.core.json.JsonObject; import io.vertx.up.fn.Fn; public class ZeroInfix implements Node<JsonObject> { private transient final String key; ZeroInfix(final String key) { this.key = key; } @Override public JsonObject read() { // Not null because execNil final JsonObject config = ZeroTool.read(key, true); return Fn.getJvm(new JsonObject(), () -> config, config); } }
189
6,835
<filename>bench/jinja/jinja.py import time from jinja2 import Template, Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('.')) print env.get_template('index.html').render() # src = open('index.html').read() # print(env._generate(env._parse(src, 'poop', 'hello.html'), # 'poop', # 'hello.html')) # print([x for x in env._tokenize(src, 'poop', 'hello.html')]) # env = Environment(loader=FileSystemLoader('.')) # times = [] # arr = [5]*1000 # for i in range(100): # env = Environment(loader=FileSystemLoader('.')) # t1 = time.time() # tmpl = env.get_template('index.html') # tmpl.render({'username': 'james', # 'arr': arr}) # t2 = time.time() # times.append(t2-t1) # print( reduce(lambda x, y: x+y, times) / len(times))
363
711
package com.java110.user.api; import com.alibaba.fastjson.JSONObject; import com.java110.dto.owner.OwnerDto; import com.java110.po.owner.OwnerPo; import com.java110.user.bmo.owner.*; import com.java110.utils.util.Assert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value = "/ownerApi") public class OwnerApi { @Autowired private IQueryTenants queryTenantsImpl; @Autowired private IVisitorRecord visitorRecordImpl; @Autowired private IChangeOwnerPhone changeOwnerPhoneImpl; @Autowired private IComprehensiveQuery comprehensiveQueryImpl; @Autowired private IQueryShopsHireLog queryShopsHireLogImpl; @RequestMapping(value = "/tenants") public ResponseEntity<String> tenants(@RequestBody JSONObject reqJson) { Assert.hasKeyAndValue(reqJson, "code", "小区编码不能为空"); return queryTenantsImpl.query(reqJson); } @RequestMapping(value = "/visitorRecord") public ResponseEntity<String> visitorRecord(@RequestBody JSONObject reqJson) { Assert.hasKeyAndValue(reqJson, "code", "小区编码不能为空"); return visitorRecordImpl.query(reqJson); } /** * 变更 业主手机号 * * @param reqJson * @return * @service /ownerApi/changeOwnerPhone * @path /app/ownerApi/changeOwnerPhoto */ @RequestMapping(value = "/changeOwnerPhone", method = RequestMethod.POST) public ResponseEntity<String> changeOwnerPhone(@RequestBody JSONObject reqJson) { Assert.hasKeyAndValue(reqJson, "link", "请求报文中未包含手机号"); Assert.hasKeyAndValue(reqJson, "userId", "请求报文中未包含用户ID"); Assert.hasKeyAndValue(reqJson, "memberId", "请求报文中未包含业主信息"); Assert.hasKeyAndValue(reqJson, "communityId", "请求报文中未包含小区信息"); OwnerPo ownerPo = new OwnerPo(); ownerPo.setLink(reqJson.getString("link")); ownerPo.setMemberId(reqJson.getString("memberId")); ownerPo.setCommunityId(reqJson.getString("communityId")); ownerPo.setUserId(reqJson.getString("userId")); return changeOwnerPhoneImpl.change(ownerPo); } /** * 综合查询 * * @param communityId 小区ID * @return * @service /ownerApi/comprehensiveQuery * @path /app/ownerApi/comprehensiveQuery */ @RequestMapping(value = "/comprehensiveQuery", method = RequestMethod.GET) public ResponseEntity<String> comprehensiveQuery(@RequestParam(value = "communityId") String communityId, @RequestParam(value = "searchValue") String searchValue, @RequestParam(value = "searchType") String searchType, @RequestHeader(value = "user-id") String userId) { return comprehensiveQueryImpl.query(communityId, searchValue, searchType, userId); } /** * 微信删除消息模板 * * @param communityId 小区ID * @return * @serviceCode /ownerApi/queryShopsHireLog * @path /app/ownerApi/queryShopsHireLog */ @RequestMapping(value = "/queryShopsHireLog", method = RequestMethod.GET) public ResponseEntity<String> queryShopsHireLog(@RequestParam(value = "communityId") String communityId, @RequestParam(value = "roomId") String roomId, @RequestParam(value = "page") int page, @RequestParam(value = "row") int row) { OwnerDto ownerDto = new OwnerDto(); ownerDto.setPage(page); ownerDto.setRow(row); ownerDto.setCommunityId(communityId); ownerDto.setRoomId(roomId); return queryShopsHireLogImpl.query(ownerDto); } }
1,829
713
<filename>core/src/test/java/org/infinispan/util/NotifierLatch.java package org.infinispan.util; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A latch that can be open and close. It allows the notification when the some thread is blocking in it. * * @author <NAME> * @since 6.0 */ public class NotifierLatch { private static final Log log = LogFactory.getLog(NotifierLatch.class); private final String name; private boolean enabled = false; private boolean blocked = false; private int disableOnUnblock = 0; public NotifierLatch(String name) { this.name = name; } public final synchronized void startBlocking() { log.tracef("Start blocking %s", name); this.enabled = true; } public final synchronized void stopBlocking() { log.tracef("Stop blocking %s", name); this.enabled = false; this.disableOnUnblock = 0; notifyAll(); } public final synchronized void blockIfNeeded() { log.tracef("Blocking on %s", name); blocked = true; notifyAll(); try { while (enabled) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } } finally { blocked = false; if (disableOnUnblock > 0 && --disableOnUnblock == 0) { enabled = true; } log.tracef("Resuming on %s", name); } } public final synchronized void waitToBlock() throws InterruptedException { log.tracef("Waiting for another thread to block on %s", name); while (!blocked) { wait(); } } public synchronized void unblockOnce() { log.tracef("Unblocking once %s", name); enabled = false; disableOnUnblock++; notifyAll(); } public void waitToBlockAndUnblockOnce() throws InterruptedException { waitToBlock(); unblockOnce(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("NotifierLatch{"); sb.append("enabled=").append(enabled); sb.append(", blocked=").append(blocked); sb.append(", disableOnUnblock=").append(disableOnUnblock); sb.append('}'); return sb.toString(); } }
933
1,645
/* * Seldon -- open source prediction engine * ======================================= * * Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/) * * ******************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ******************************************************************************************** */ package io.seldon.api.controller; import javax.servlet.http.HttpServletRequest; import io.seldon.api.APIException; import io.seldon.api.resource.ConsumerBean; import io.seldon.api.resource.ErrorBean; import io.seldon.api.resource.ResourceBean; import io.seldon.api.resource.VersionBean; import io.seldon.api.resource.service.VersionService; import io.seldon.api.service.ApiLoggerServer; import io.seldon.api.service.ResourceServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Determine the current API version; query a client for its declared version. * <p/> * Created by: marc on 10/08/2011 at 13:43 */ @Controller public class VersionController { @Autowired private ResourceServer resourceServer; private static final Logger logger = LoggerFactory.getLogger(VersionController.class); @Autowired private VersionBean apiVersion; @RequestMapping("/version") public @ResponseBody VersionBean getVersion() { return apiVersion; } @RequestMapping("/version/me") public @ResponseBody ResourceBean clientVersion(HttpServletRequest req) { ResourceBean requestBean = resourceServer.validateResourceRequest(req); return getClientVersionBean(requestBean); } private ResourceBean getClientVersionBean(ResourceBean requestBean) { ResourceBean responseBean = requestBean; if (requestBean instanceof ConsumerBean) { try { responseBean = VersionService.getVersion((ConsumerBean) requestBean); } catch (APIException e) { ApiLoggerServer.log(this, e); responseBean = new ErrorBean(e); } catch (Exception e) { ApiLoggerServer.log(this, e); APIException apiEx = new APIException(APIException.GENERIC_ERROR); responseBean = new ErrorBean(apiEx); } } return responseBean; } }
1,036
315
<filename>gactions-sample/src/main/java/com/frogermcs/gactions/sample/AppEngineResponseHandler.java package com.frogermcs.gactions.sample; import com.fasterxml.jackson.databind.ObjectMapper; import com.frogermcs.gactions.ResponseHandler; import com.frogermcs.gactions.api.response.RootResponse; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; /** * Created by froger_mcs on 19/01/2017. */ public class AppEngineResponseHandler implements ResponseHandler { private final HttpServletResponse httpServletResponse; private final ObjectMapper objectMapper; public AppEngineResponseHandler(HttpServletResponse httpServletResponse) { this(httpServletResponse, new ObjectMapper()); } public AppEngineResponseHandler(HttpServletResponse httpServletResponse, ObjectMapper objectMapper) { this.httpServletResponse = httpServletResponse; this.objectMapper = objectMapper; } @Override public void onPrepareContentType(String contentType) { httpServletResponse.setContentType(contentType); } @Override public void onPrepareResponseHeaders(Map<String, String> headers) { for (String headerName : headers.keySet()) { httpServletResponse.addHeader(headerName, headers.get(headerName)); } } @Override public void onResponse(RootResponse rootResponse) { try { objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.writeValue(httpServletResponse.getWriter(), rootResponse); } catch (IOException e) { e.printStackTrace(); } } }
602
474
package org.javacord.api.interaction; import org.javacord.api.interaction.internal.SlashCommandOptionBuilderDelegate; import org.javacord.api.util.internal.DelegateFactory; import java.util.List; public class SlashCommandOptionBuilder { private final SlashCommandOptionBuilderDelegate delegate = DelegateFactory.createSlashCommandOptionBuilderDelegate(); /** * Creates a new slash command option builder. */ public SlashCommandOptionBuilder() { } /** * Sets the type of the slash command option. * * @param type The type. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder setType(SlashCommandOptionType type) { delegate.setType(type); return this; } /** * Sets the name of the slash command option. * * @param name The name. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder setName(String name) { delegate.setName(name); return this; } /** * Sets the description of the slash command option. * * @param description The description. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder setDescription(String description) { delegate.setDescription(description); return this; } /** * Sets if the slash command option is required. * * @param required Whether or not the option is required. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder setRequired(boolean required) { delegate.setRequired(required); return this; } /** * Adds an choice for the slash command option. * * @param choice The choice. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder addChoice(SlashCommandOptionChoice choice) { delegate.addChoice(choice); return this; } /** * Adds an string choice for the slash command option. * * @param name The name of the choice. * @param value The value of the choice. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder addChoice(String name, String value) { delegate.addChoice(new SlashCommandOptionChoiceBuilder().setName(name).setValue(value).build()); return this; } /** * Adds an int choice for the slash command option. * * @param name The name of the choice. * @param value The value of the choice. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder addChoice(String name, int value) { delegate.addChoice(new SlashCommandOptionChoiceBuilder().setName(name).setValue(value).build()); return this; } /** * Sets the choices of the slash command option. * * @param choices The choices. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder setChoices(List<SlashCommandOptionChoice> choices) { delegate.setChoices(choices); return this; } /** * Adds an slash command option to the slash command option. * * @param option The option. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder addOption(SlashCommandOption option) { delegate.addOption(option); return this; } /** * Sets the slash commands for the slash command option. * * @param options The options. * @return The current instance in order to chain call methods. */ public SlashCommandOptionBuilder setOptions(List<SlashCommandOption> options) { delegate.setOptions(options); return this; } /** * Builds the slash command option. * * @return The built option. */ public SlashCommandOption build() { return delegate.build(); } }
1,430
759
<filename>rome/src/test/java/com/rometools/rome/unittest/TestSyndFeedAtom10prefix.java /* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.rometools.rome.unittest; import com.rometools.rome.feed.atom.Feed; public class TestSyndFeedAtom10prefix extends FeedTest { public TestSyndFeedAtom10prefix() { super("atom_1.0_prefix.xml"); } public void testTitle() throws Exception { final Feed feed = (Feed) getWireFeed(); assertEquals("1", feed.getId()); assertEquals("xxx1", feed.getOtherLinks().get(0).getRel()); assertEquals("xxx2", feed.getOtherLinks().get(1).getRel()); assertEquals("xxx11", feed.getOtherLinks().get(0).getType()); assertEquals("xxx22", feed.getOtherLinks().get(1).getType()); assertEquals("http://foo.com/1", feed.getOtherLinks().get(0).getHref()); assertEquals("http://foo.com/2", feed.getOtherLinks().get(1).getHref()); } }
507