text stringlengths 2 99k | meta dict |
|---|---|
<StyleCopSettings Version="105">
<GlobalSettings>
<StringProperty Name="MergeSettingsFiles">NoMerge</StringProperty>
</GlobalSettings>
<Analyzers>
<Analyzer AnalyzerId="StyleCop.CSharp.DocumentationRules">
<Rules>
<Rule Name="PartialElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="EnumerationItemsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementDocumentationMustHaveSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustNotHaveDefaultSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParametersMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustMatchElementParameters">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementReturnValueMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementReturnValueDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="VoidReturnValueMustNotBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParametersMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParametersMustBeDocumentedPartialClass">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustMatchTypeParameters">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustDeclareParameterName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustNotBeCopiedAndPasted">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="SingleLineCommentsMustNotUseDocumentationStyleSlashes">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustNotBeEmpty">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustContainWhitespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationMustMeetCharacterPercentage">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ConstructorSummaryDocumentationMustBeginWithStandardText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DestructorSummaryDocumentationMustBeginWithStandardText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationHeadersMustNotContainBlankLines">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="IncludedDocumentationXPathDoesNotExist">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="IncludeNodeDoesNotContainValidFileAndPath">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="InheritDocMustBeUsedWithInheritingClass">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustBeSpelledCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileMustHaveHeader">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustShowCopyright">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustHaveCopyrightText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustContainFileName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderFileNameDocumentationMustMatchFileName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustHaveValidCompanyText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderFileNameDocumentationMustMatchTypeName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationMustContainValidXml">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustHaveSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustHaveSummaryText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementDocumentationMustHaveSummaryText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustDeclareParameterName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PropertySummaryDocumentationMustMatchAccessors">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PropertySummaryDocumentationMustOmitSetAccessorWithRestrictedAccess">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings>
<BooleanProperty Name="IncludeFields">False</BooleanProperty>
</AnalyzerSettings>
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.NamingRules">
<Rules>
<Rule Name="FieldNamesMustNotBeginWithUnderscore">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FieldNamesMustBeginWithLowerCaseLetter">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings>
<CollectionProperty Name="Hungarian">
<Value>x</Value>
<Value>y</Value>
<Value>z</Value>
</CollectionProperty>
</AnalyzerSettings>
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.MaintainabilityRules">
<Rules>
<Rule Name="AccessModifierMustBeDeclared">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FieldsMustBePrivate">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileMayOnlyContainASingleClass">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileMayOnlyContainASingleNamespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ArithmeticExpressionsMustDeclarePrecedence">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.ReadabilityRules">
<Rules>
<Rule Name="PrefixLocalCallsWithThis">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PrefixCallsCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.OrderingRules">
<Rules>
<Rule Name="UsingDirectivesMustBePlacedWithinNamespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ConstantsMustAppearBeforeFields">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="StaticElementsMustAppearBeforeInstanceElements">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="StaticReadonlyElementsMustAppearBeforeStaticNonReadonlyElements">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="InstanceReadonlyElementsMustAppearBeforeInstanceNonReadonlyElements">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="UsingAliasDirectivesMustBePlacedAfterOtherUsingDirectives">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementsMustAppearInTheCorrectOrder">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementsMustBeOrderedByAccess">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.SpacingRules">
<Rules>
<Rule Name="SymbolsMustBeSpacedCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ClosingParenthesisMustBeSpacedCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="KeywordsMustBeSpacedCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="OpeningParenthesisMustBeSpacedCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ClosingSquareBracketsMustBeSpacedCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.LayoutRules">
<Rules>
<Rule Name="AllAccessorsMustBeMultiLineOrSingleLine">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
</Analyzers>
</StyleCopSettings> | {
"pile_set_name": "Github"
} |
package org.yyx.netty.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* 对象序列化工具
* <p>
* create by 叶云轩 at 2018/3/3-下午1:43
* contact by tdg_yyx@foxmail.com
*/
public class ObjectSerializerUtils {
/**
* ObjectSerializerUtils 日志控制器
* Create by 叶云轩 at 2018/3/3 下午1:43
* Concat at tdg_yyx@foxmail.com
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectSerializerUtils.class);
/**
* 反序列化
*
* @param data
* @return
*/
public static Object deSerilizer(byte[] data) {
if (data != null && data.length > 0) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
} catch (Exception e) {
LOGGER.info("[异常信息] {}", e.getMessage());
e.printStackTrace();
}
return null;
} else {
LOGGER.info("[反序列化] 入参为空");
return null;
}
}
/**
* 序列化对象
*
* @param obj
* @return
*/
public static byte[] serilizer(Object obj) {
if (obj != null) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} else {
return null;
}
}
}
| {
"pile_set_name": "Github"
} |
require File.dirname(__FILE__) + "/../sample-app/sample_app"
class AjaxTestEnvironment
def run
Thread.abort_on_exception = true
@example_app = Thread.new { SampleApp.start("127.0.0.1", 4567) }
poller = Selenium::WebDriver::SocketPoller.new("127.0.0.1", 4567, 60)
unless poller.connected?
raise "timed out waiting for SampleApp to launch"
end
self
end
def stop
@example_app.kill
end
end
@server = AjaxTestEnvironment.new
@server.run
at_exit do
@server.stop
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2013 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 com.mohamadamin.persianmaterialdatetimepicker.time;
import android.animation.ObjectAnimator;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mohamadamin.persianmaterialdatetimepicker.HapticFeedbackController;
import com.mohamadamin.persianmaterialdatetimepicker.R;
import com.mohamadamin.persianmaterialdatetimepicker.TypefaceHelper;
import com.mohamadamin.persianmaterialdatetimepicker.Utils;
import com.mohamadamin.persianmaterialdatetimepicker.time.RadialPickerLayout.OnValueSelectedListener;
import com.mohamadamin.persianmaterialdatetimepicker.utils.LanguageUtils;
import java.util.ArrayList;
import java.util.Locale;
/**
* Dialog to set a time.
*/
public class TimePickerDialog extends DialogFragment implements OnValueSelectedListener {
private static final String TAG = "TimePickerDialog";
private static final String KEY_HOUR_OF_DAY = "hour_of_day";
private static final String KEY_MINUTE = "minute";
private static final String KEY_IS_24_HOUR_VIEW = "is_24_hour_view";
private static final String KEY_TITLE = "dialog_title";
private static final String KEY_CURRENT_ITEM_SHOWING = "current_item_showing";
private static final String KEY_IN_KB_MODE = "in_kb_mode";
private static final String KEY_TYPED_TIMES = "typed_times";
private static final String KEY_DARK_THEME = "dark_theme";
public static final int HOUR_INDEX = 0;
public static final int MINUTE_INDEX = 1;
// NOT a real index for the purpose of what's showing.
public static final int AMPM_INDEX = 2;
// Also NOT a real index, just used for keyboard mode.
public static final int ENABLE_PICKER_INDEX = 3;
public static final int AM = 0;
public static final int PM = 1;
// Delay before starting the pulse animation, in ms.
private static final int PULSE_ANIMATOR_DELAY = 300;
private OnTimeSetListener mCallback;
private DialogInterface.OnCancelListener mOnCancelListener;
private DialogInterface.OnDismissListener mOnDismissListener;
private HapticFeedbackController mHapticFeedbackController;
private Button mOkButton;
private TextView mHourView;
private TextView mHourSpaceView;
private TextView mMinuteView;
private TextView mMinuteSpaceView;
private TextView mAmPmTextView;
private View mAmPmHitspace;
private RadialPickerLayout mTimePicker;
private int mSelectedColor;
private int mUnselectedColor;
private String mAmText;
private String mPmText;
private boolean mAllowAutoAdvance;
private int mInitialHourOfDay;
private int mInitialMinute;
private boolean mIs24HourMode;
private String mTitle;
private boolean mThemeDark;
// For hardware IME input.
private char mPlaceholderText;
private String mDoublePlaceholderText;
private String mDeletedKeyFormat;
private boolean mInKbMode;
private ArrayList<Integer> mTypedTimes;
private Node mLegalTimesTree;
private int mAmKeyCode;
private int mPmKeyCode;
// Accessibility strings.
private String mHourPickerDescription;
private String mSelectHours;
private String mMinutePickerDescription;
private String mSelectMinutes;
private String fontName="DroidNaskh-Regular";
/**
* The callback interface used to indicate the user is done filling in
* the time (they clicked on the 'Set' button).
*/
public interface OnTimeSetListener {
/**
* @param view The view associated with this listener.
* @param hourOfDay The hour that was set.
* @param minute The minute that was set.
*/
void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute);
}
public TimePickerDialog() {
// Empty constructor required for dialog fragment.
}
/**
* public TimePickerDialog(Context context, int theme, OnTimeSetListener callback,
* int hourOfDay, int minute, boolean is24HourMode) {
* // Empty constructor required for dialog fragment.
* }
**/
public static TimePickerDialog newInstance(OnTimeSetListener callback,
int hourOfDay, int minute, boolean is24HourMode) {
TimePickerDialog ret = new TimePickerDialog();
ret.initialize(callback, hourOfDay, minute, is24HourMode);
return ret;
}
public void initialize(OnTimeSetListener callback,
int hourOfDay, int minute, boolean is24HourMode) {
mCallback = callback;
mInitialHourOfDay = hourOfDay;
mInitialMinute = minute;
mIs24HourMode = is24HourMode;
mInKbMode = false;
mTitle = "";
mThemeDark = false;
}
/**
* Set a title. NOTE: this will only take effect with the next onCreateView
*/
public void setTitle(String title) {
mTitle = title;
}
public String getTitle() {
return mTitle;
}
/**
* Set a dark or light theme. NOTE: this will only take effect for the next onCreateView.
*/
public void setThemeDark(boolean dark) {
mThemeDark = dark;
}
public boolean isThemeDark() {
return mThemeDark;
}
public void setOnTimeSetListener(OnTimeSetListener callback) {
mCallback = callback;
}
public void setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) {
mOnCancelListener = onCancelListener;
}
public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
mOnDismissListener = onDismissListener;
}
public void setStartTime(int hourOfDay, int minute) {
mInitialHourOfDay = hourOfDay;
mInitialMinute = minute;
mInKbMode = false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_HOUR_OF_DAY)
&& savedInstanceState.containsKey(KEY_MINUTE)
&& savedInstanceState.containsKey(KEY_IS_24_HOUR_VIEW)) {
mInitialHourOfDay = savedInstanceState.getInt(KEY_HOUR_OF_DAY);
mInitialMinute = savedInstanceState.getInt(KEY_MINUTE);
mIs24HourMode = savedInstanceState.getBoolean(KEY_IS_24_HOUR_VIEW);
mInKbMode = savedInstanceState.getBoolean(KEY_IN_KB_MODE);
mTitle = savedInstanceState.getString(KEY_TITLE);
mThemeDark = savedInstanceState.getBoolean(KEY_DARK_THEME);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
View view = inflater.inflate(R.layout.mdtp_time_picker_dialog, null);
final Activity activity = getActivity();
KeyboardListener keyboardListener = new KeyboardListener();
view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener);
Resources res = getResources();
mHourPickerDescription = res.getString(R.string.mdtp_hour_picker_description);
mSelectHours = res.getString(R.string.mdtp_select_hours);
mMinutePickerDescription = res.getString(R.string.mdtp_minute_picker_description);
mSelectMinutes = res.getString(R.string.mdtp_select_minutes);
mSelectedColor = res.getColor(R.color.mdtp_white);
mUnselectedColor = res.getColor(R.color.mdtp_accent_color_focused);
mHourView = view.findViewById(R.id.hours);
mHourView.setOnKeyListener(keyboardListener);
mHourSpaceView = view.findViewById(R.id.hour_space);
mMinuteSpaceView = view.findViewById(R.id.minutes_space);
mMinuteView = view.findViewById(R.id.minutes);
mMinuteView.setOnKeyListener(keyboardListener);
mAmPmTextView = view.findViewById(R.id.ampm_label);
mOkButton = view.findViewById(R.id.ok);
Button mCancelButton = view.findViewById(R.id.cancel);
mOkButton.setTypeface(TypefaceHelper.get(activity, fontName));
mCancelButton.setTypeface(TypefaceHelper.get(activity, fontName));
mHourView.setTypeface(TypefaceHelper.get(activity, fontName));
mMinuteView.setTypeface(TypefaceHelper.get(activity, fontName));
mAmPmTextView.setTypeface(TypefaceHelper.get(activity, fontName));
mAmPmTextView.setOnKeyListener(keyboardListener);
mAmText = "قبلازظهر";
mPmText = "بعدازظهر";
mHapticFeedbackController = new HapticFeedbackController(getActivity());
mTimePicker = view.findViewById(R.id.time_picker);
mTimePicker.setOnValueSelectedListener(this);
mTimePicker.setOnKeyListener(keyboardListener);
mTimePicker.initialize(getActivity(), mHapticFeedbackController, mInitialHourOfDay,
mInitialMinute, mIs24HourMode,fontName);
int currentItemShowing = HOUR_INDEX;
if (savedInstanceState != null &&
savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) {
currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING);
}
setCurrentItemShowing(currentItemShowing, false, true, true);
mTimePicker.invalidate();
mHourView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setCurrentItemShowing(HOUR_INDEX, true, false, true);
tryVibrate();
}
});
mMinuteView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setCurrentItemShowing(MINUTE_INDEX, true, false, true);
tryVibrate();
}
});
mOkButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mInKbMode && isTypedTimeFullyLegal()) {
finishKbMode(false);
} else {
tryVibrate();
}
if (mCallback != null) {
mCallback.onTimeSet(mTimePicker,
mTimePicker.getHours(), mTimePicker.getMinutes());
}
dismiss();
}
});
mOkButton.setOnKeyListener(keyboardListener);
mCancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tryVibrate();
getDialog().cancel();
}
});
mCancelButton.setVisibility(isCancelable() ? View.VISIBLE : View.GONE);
// Enable or disable the AM/PM view.
mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
if (mIs24HourMode) {
mAmPmTextView.setVisibility(View.GONE);
RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
TextView separatorView = view.findViewById(R.id.separator);
separatorView.setLayoutParams(paramsSeparator);
} else {
mAmPmTextView.setVisibility(View.VISIBLE);
updateAmPmDisplay(mInitialHourOfDay < 12 ? AM : PM);
mAmPmHitspace.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tryVibrate();
int amOrPm = mTimePicker.getIsCurrentlyAmOrPm();
if (amOrPm == AM) {
amOrPm = PM;
} else if (amOrPm == PM) {
amOrPm = AM;
}
updateAmPmDisplay(amOrPm);
mTimePicker.setAmOrPm(amOrPm);
}
});
}
mAllowAutoAdvance = true;
setHour(mInitialHourOfDay, true);
setMinute(mInitialMinute);
// Set up for keyboard mode.
mDoublePlaceholderText = res.getString(R.string.mdtp_time_placeholder);
mDeletedKeyFormat = res.getString(R.string.mdtp_deleted_key);
mPlaceholderText = mDoublePlaceholderText.charAt(0);
mAmKeyCode = mPmKeyCode = -1;
generateLegalTimesTree();
if (mInKbMode) {
mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES);
tryStartingKbMode(-1);
mHourView.invalidate();
} else if (mTypedTimes == null) {
mTypedTimes = new ArrayList<>();
}
// Set the title (if any)
TextView timePickerHeader = view.findViewById(R.id.time_picker_header);
if (!mTitle.isEmpty()) {
timePickerHeader.setVisibility(TextView.VISIBLE);
timePickerHeader.setText(mTitle); // TODO
}
// Set the theme at the end so that the initialize()s above don't counteract the theme.
mTimePicker.setTheme(getActivity().getApplicationContext(), mThemeDark);
// Prepare some colors to use.
int white = res.getColor(R.color.mdtp_white);
int accent = res.getColor(R.color.mdtp_accent_color);
int circleBackground = res.getColor(R.color.mdtp_circle_background);
int line = res.getColor(R.color.mdtp_line_background);
int timeDisplay = res.getColor(R.color.mdtp_numbers_text_color);
ColorStateList doneTextColor = res.getColorStateList(R.color.mdtp_done_text_color);
int doneBackground = R.drawable.mdtp_done_background_color;
int backgroundColor = res.getColor(R.color.mdtp_background_color);
int darkBackgroundColor = res.getColor(R.color.mdtp_light_gray);
int darkGray = res.getColor(R.color.mdtp_dark_gray);
int lightGray = res.getColor(R.color.mdtp_light_gray);
int darkLine = res.getColor(R.color.mdtp_line_dark);
ColorStateList darkDoneTextColor = res.getColorStateList(R.color.mdtp_done_text_color_dark);
int darkDoneBackground = R.drawable.mdtp_done_background_color_dark;
// Set the colors for each view based on the theme.
//view.findViewById(R.id.time_display_background).setBackgroundColor(mThemeDark? darkGray : accent);
//view.findViewById(R.id.time_display).setBackgroundColor(mThemeDark? darkGray : white);
//((TextView) view.findViewById(R.id.separator)).setTextColor(mThemeDark? white : timeDisplay);
//((TextView) view.findViewById(R.id.ampm_label)).setTextColor(mThemeDark? white : timeDisplay);
//view.findViewById(R.id.line).setBackgroundColor(mThemeDark? darkLine : line);
//mOkButton.setTextColor(mThemeDark? darkDoneTextColor : doneTextColor);
mTimePicker.setBackgroundColor(mThemeDark ? lightGray : circleBackground);
view.findViewById(R.id.time_picker_dialog).setBackgroundColor(mThemeDark ? darkBackgroundColor : backgroundColor);
//mOkButton.setBackgroundResource(mThemeDark? darkDoneBackground : doneBackground);
return view;
}
@Override
public void onResume() {
super.onResume();
mHapticFeedbackController.start();
}
@Override
public void onPause() {
super.onPause();
mHapticFeedbackController.stop();
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
if (mOnCancelListener != null) {
mOnCancelListener.onCancel(dialog);
}
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss(dialog);
}
}
public void tryVibrate() {
mHapticFeedbackController.tryVibrate();
}
private void updateAmPmDisplay(int amOrPm) {
if (amOrPm == AM) {
mAmPmTextView.setText(mAmText);
Utils.tryAccessibilityAnnounce(mTimePicker, mAmText);
mAmPmHitspace.setContentDescription(mAmText);
} else if (amOrPm == PM) {
mAmPmTextView.setText(mPmText);
Utils.tryAccessibilityAnnounce(mTimePicker, mPmText);
mAmPmHitspace.setContentDescription(mPmText);
} else {
mAmPmTextView.setText(mDoublePlaceholderText);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
if (mTimePicker != null) {
outState.putInt(KEY_HOUR_OF_DAY, mTimePicker.getHours());
outState.putInt(KEY_MINUTE, mTimePicker.getMinutes());
outState.putBoolean(KEY_IS_24_HOUR_VIEW, mIs24HourMode);
outState.putInt(KEY_CURRENT_ITEM_SHOWING, mTimePicker.getCurrentItemShowing());
outState.putBoolean(KEY_IN_KB_MODE, mInKbMode);
if (mInKbMode) {
outState.putIntegerArrayList(KEY_TYPED_TIMES, mTypedTimes);
}
outState.putString(KEY_TITLE, mTitle);
outState.putBoolean(KEY_DARK_THEME, mThemeDark);
}
}
/**
* Called by the picker for updating the header display.
*/
@Override
public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
if (pickerIndex == HOUR_INDEX) {
setHour(newValue, false);
String announcement = String.format(Locale.getDefault(),"%d", newValue);
if (mAllowAutoAdvance && autoAdvance) {
setCurrentItemShowing(MINUTE_INDEX, true, true, false);
announcement += ". " + mSelectMinutes;
} else {
mTimePicker.setContentDescription(mHourPickerDescription + ": " + newValue);
}
Utils.tryAccessibilityAnnounce(mTimePicker, announcement);
} else if (pickerIndex == MINUTE_INDEX) {
setMinute(newValue);
mTimePicker.setContentDescription(mMinutePickerDescription + ": " + newValue);
} else if (pickerIndex == AMPM_INDEX) {
updateAmPmDisplay(newValue);
} else if (pickerIndex == ENABLE_PICKER_INDEX) {
if (!isTypedTimeFullyLegal()) {
mTypedTimes.clear();
}
finishKbMode(true);
}
}
@Override
public void setTypeface(String fontName) {
this.fontName = fontName;
}
@Override
public String getTypeface() {
return fontName;
}
private void setHour(int value, boolean announce) {
String format;
if (mIs24HourMode) {
format = "%02d";
} else {
format = "%d";
value = value % 12;
if (value == 0) {
value = 12;
}
}
String text = LanguageUtils.getPersianNumbers(String.format(Locale.getDefault(),format, value));
mHourView.setText(text);
mHourSpaceView.setText(text);
if (announce) {
Utils.tryAccessibilityAnnounce(mTimePicker, text);
}
}
private void setMinute(int value) {
if (value == 60) {
value = 0;
}
CharSequence text = LanguageUtils.getPersianNumbers(String.format(Locale.getDefault(), "%02d", value));
Utils.tryAccessibilityAnnounce(mTimePicker, text);
mMinuteView.setText(text);
mMinuteSpaceView.setText(text);
}
// Show either Hours or Minutes.
private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate,
boolean announce) {
mTimePicker.setCurrentItemShowing(index, animateCircle);
TextView labelToAnimate;
if (index == HOUR_INDEX) {
int hours = mTimePicker.getHours();
if (!mIs24HourMode) {
hours = hours % 12;
}
mTimePicker.setContentDescription(mHourPickerDescription + ": " + hours);
if (announce) {
Utils.tryAccessibilityAnnounce(mTimePicker, mSelectHours);
}
labelToAnimate = mHourView;
} else {
int minutes = mTimePicker.getMinutes();
mTimePicker.setContentDescription(mMinutePickerDescription + ": " + minutes);
if (announce) {
Utils.tryAccessibilityAnnounce(mTimePicker, mSelectMinutes);
}
labelToAnimate = mMinuteView;
}
int hourColor = (index == HOUR_INDEX) ? mSelectedColor : mUnselectedColor;
int minuteColor = (index == MINUTE_INDEX) ? mSelectedColor : mUnselectedColor;
mHourView.setTextColor(hourColor);
mMinuteView.setTextColor(minuteColor);
ObjectAnimator pulseAnimator = Utils.getPulseAnimator(labelToAnimate, 0.85f, 1.1f);
if (delayLabelAnimate) {
pulseAnimator.setStartDelay(PULSE_ANIMATOR_DELAY);
}
pulseAnimator.start();
}
/**
* For keyboard mode, processes key events.
*
* @param keyCode the pressed key.
* @return true if the key was successfully processed, false otherwise.
*/
private boolean processKeyUp(int keyCode) {
if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
if (isCancelable()) {
dismiss();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_TAB) {
if (mInKbMode) {
if (isTypedTimeFullyLegal()) {
finishKbMode(true);
}
return true;
}
} else if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mInKbMode) {
if (!isTypedTimeFullyLegal()) {
return true;
}
finishKbMode(false);
}
if (mCallback != null) {
mCallback.onTimeSet(mTimePicker,
mTimePicker.getHours(), mTimePicker.getMinutes());
}
dismiss();
return true;
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
if (mInKbMode) {
if (!mTypedTimes.isEmpty()) {
int deleted = deleteLastTypedKey();
String deletedKeyStr;
if (deleted == getAmOrPmKeyCode(AM)) {
deletedKeyStr = mAmText;
} else if (deleted == getAmOrPmKeyCode(PM)) {
deletedKeyStr = mPmText;
} else {
deletedKeyStr = String.format(Locale.getDefault(),"%d", getValFromKeyCode(deleted)); //TODO
}
Utils.tryAccessibilityAnnounce(mTimePicker,
String.format(mDeletedKeyFormat, deletedKeyStr));
updateDisplay(true);
}
}
} else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1
|| keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3
|| keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
|| keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7
|| keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9
|| (!mIs24HourMode &&
(keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
if (!mInKbMode) {
if (mTimePicker == null) {
// Something's wrong, because time picker should definitely not be null.
Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
return true;
}
mTypedTimes.clear();
tryStartingKbMode(keyCode);
return true;
}
// We're already in keyboard mode.
if (addKeyIfLegal(keyCode)) {
updateDisplay(false);
}
return true;
}
return false;
}
/**
* Try to start keyboard mode with the specified key, as long as the timepicker is not in the
* middle of a touch-event.
*
* @param keyCode The key to use as the first press. Keyboard mode will not be started if the
* key is not legal to start with. Or, pass in -1 to get into keyboard mode without a starting
* key.
*/
private void tryStartingKbMode(int keyCode) {
if (mTimePicker.trySettingInputEnabled(false) &&
(keyCode == -1 || addKeyIfLegal(keyCode))) {
mInKbMode = true;
mOkButton.setEnabled(false);
updateDisplay(false);
}
}
private boolean addKeyIfLegal(int keyCode) {
// If we're in 24hour mode, we'll need to check if the input is full. If in AM/PM mode,
// we'll need to see if AM/PM have been typed.
if ((mIs24HourMode && mTypedTimes.size() == 4) ||
(!mIs24HourMode && isTypedTimeFullyLegal())) {
return false;
}
mTypedTimes.add(keyCode); //TODO
if (!isTypedTimeLegalSoFar()) {
deleteLastTypedKey();
return false;
}
int val = getValFromKeyCode(keyCode);
Utils.tryAccessibilityAnnounce(mTimePicker, String.format(Locale.getDefault(),"%d", val));
// Automatically fill in 0's if AM or PM was legally entered.
if (isTypedTimeFullyLegal()) {
if (!mIs24HourMode && mTypedTimes.size() <= 3) {
mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
}
mOkButton.setEnabled(true);
}
return true;
}
/**
* Traverse the tree to see if the keys that have been typed so far are legal as is,
* or may become legal as more keys are typed (excluding backspace).
*/
private boolean isTypedTimeLegalSoFar() {
Node node = mLegalTimesTree;
for (int keyCode : mTypedTimes) {
node = node.canReach(keyCode);
if (node == null) {
return false;
}
}
return true;
}
/**
* Check if the time that has been typed so far is completely legal, as is.
*/
private boolean isTypedTimeFullyLegal() {
if (mIs24HourMode) {
// For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
// getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
int[] values = getEnteredTime(null);
return (values[0] >= 0 && values[1] >= 0 && values[1] < 60);
} else {
// For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
// legally added at specific times based on the tree's algorithm.
return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
mTypedTimes.contains(getAmOrPmKeyCode(PM)));
}
}
private int deleteLastTypedKey() {
int deleted = mTypedTimes.remove(mTypedTimes.size() - 1);
if (!isTypedTimeFullyLegal()) {
mOkButton.setEnabled(false);
}
return deleted;
}
/**
* Get out of keyboard mode. If there is nothing in typedTimes, revert to TimePicker's time.
*
* @param updateDisplays If true, update the displays with the relevant time.
*/
private void finishKbMode(boolean updateDisplays) {
mInKbMode = false;
if (!mTypedTimes.isEmpty()) {
int values[] = getEnteredTime(null);
mTimePicker.setTime(values[0], values[1]);
if (!mIs24HourMode) {
mTimePicker.setAmOrPm(values[2]);
}
mTypedTimes.clear();
}
if (updateDisplays) {
updateDisplay(false);
mTimePicker.trySettingInputEnabled(true);
}
}
/**
* Update the hours, minutes, and AM/PM displays with the typed times. If the typedTimes is
* empty, either show an empty display (filled with the placeholder text), or update from the
* timepicker's values.
*
* @param allowEmptyDisplay if true, then if the typedTimes is empty, use the placeholder text.
* Otherwise, revert to the timepicker's values.
*/
private void updateDisplay(boolean allowEmptyDisplay) {
if (!allowEmptyDisplay && mTypedTimes.isEmpty()) {
int hour = mTimePicker.getHours();
int minute = mTimePicker.getMinutes();
setHour(hour, true);
setMinute(minute);
if (!mIs24HourMode) {
updateAmPmDisplay(hour < 12 ? AM : PM);
}
setCurrentItemShowing(mTimePicker.getCurrentItemShowing(), true, true, true);
mOkButton.setEnabled(true);
} else {
Boolean[] enteredZeros = {false, false};
int[] values = getEnteredTime(enteredZeros);
String hourFormat = enteredZeros[0] ? "%02d" : "%2d";
String minuteFormat = (enteredZeros[1]) ? "%02d" : "%2d";
String hourStr = (values[0] == -1) ? mDoublePlaceholderText :
String.format(hourFormat, values[0]).replace(' ', mPlaceholderText);
String minuteStr = (values[1] == -1) ? mDoublePlaceholderText :
String.format(minuteFormat, values[1]).replace(' ', mPlaceholderText);
mHourView.setText(LanguageUtils.getPersianNumbers(hourStr));
mHourSpaceView.setText(LanguageUtils.getPersianNumbers(hourStr));
mHourView.setTextColor(mUnselectedColor);
mMinuteView.setText(LanguageUtils.getPersianNumbers(minuteStr));
mMinuteSpaceView.setText(LanguageUtils.getPersianNumbers(minuteStr));
mMinuteView.setTextColor(mUnselectedColor);
if (!mIs24HourMode) {
updateAmPmDisplay(values[2]);
}
}
}
private static int getValFromKeyCode(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_0:
return 0;
case KeyEvent.KEYCODE_1:
return 1;
case KeyEvent.KEYCODE_2:
return 2;
case KeyEvent.KEYCODE_3:
return 3;
case KeyEvent.KEYCODE_4:
return 4;
case KeyEvent.KEYCODE_5:
return 5;
case KeyEvent.KEYCODE_6:
return 6;
case KeyEvent.KEYCODE_7:
return 7;
case KeyEvent.KEYCODE_8:
return 8;
case KeyEvent.KEYCODE_9:
return 9;
default:
return -1;
}
}
/**
* Get the currently-entered time, as integer values of the hours and minutes typed.
*
* @param enteredZeros A size-2 boolean array, which the caller should initialize, and which
* may then be used for the caller to know whether zeros had been explicitly entered as either
* hours of minutes. This is helpful for deciding whether to show the dashes, or actual 0's.
* @return A size-3 int array. The first value will be the hours, the second value will be the
* minutes, and the third will be either TimePickerDialog.AM or TimePickerDialog.PM.
*/
private int[] getEnteredTime(Boolean[] enteredZeros) {
int amOrPm = -1;
int startIndex = 1;
if (!mIs24HourMode && isTypedTimeFullyLegal()) {
int keyCode = mTypedTimes.get(mTypedTimes.size() - 1);
if (keyCode == getAmOrPmKeyCode(AM)) {
amOrPm = AM;
} else if (keyCode == getAmOrPmKeyCode(PM)) {
amOrPm = PM;
}
startIndex = 2;
}
int minute = -1;
int hour = -1;
for (int i = startIndex; i <= mTypedTimes.size(); i++) {
int val = getValFromKeyCode(mTypedTimes.get(mTypedTimes.size() - i));
if (i == startIndex) {
minute = val;
} else if (i == startIndex + 1) {
minute += 10 * val;
if (enteredZeros != null && val == 0) {
enteredZeros[1] = true;
}
} else if (i == startIndex + 2) {
hour = val;
} else if (i == startIndex + 3) {
hour += 10 * val;
if (enteredZeros != null && val == 0) {
enteredZeros[0] = true;
}
}
}
return new int[] {hour, minute, amOrPm};
}
/**
* Get the keycode value for AM and PM in the current language.
*/
private int getAmOrPmKeyCode(int amOrPm) {
// Cache the codes.
if (mAmKeyCode == -1 || mPmKeyCode == -1) {
// Find the first character in the AM/PM text that is unique.
KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
char amChar;
char pmChar;
for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) {
amChar = "AM".toLowerCase(Locale.getDefault()).charAt(i);
pmChar = "PM".toLowerCase(Locale.getDefault()).charAt(i);
if (amChar != pmChar) {
KeyEvent[] events = kcm.getEvents(new char[] {amChar, pmChar});
// There should be 4 events: a down and up for both AM and PM.
if (events != null && events.length == 4) {
mAmKeyCode = events[0].getKeyCode();
mPmKeyCode = events[2].getKeyCode();
} else {
Log.e(TAG, "Unable to find keycodes for AM and PM.");
}
break;
}
}
}
if (amOrPm == AM) {
return mAmKeyCode;
} else if (amOrPm == PM) {
return mPmKeyCode;
}
return -1;
}
/**
* Create a tree for deciding what keys can legally be typed.
*/
private void generateLegalTimesTree() {
// Create a quick cache of numbers to their keycodes.
int k0 = KeyEvent.KEYCODE_0;
int k1 = KeyEvent.KEYCODE_1;
int k2 = KeyEvent.KEYCODE_2;
int k3 = KeyEvent.KEYCODE_3;
int k4 = KeyEvent.KEYCODE_4;
int k5 = KeyEvent.KEYCODE_5;
int k6 = KeyEvent.KEYCODE_6;
int k7 = KeyEvent.KEYCODE_7;
int k8 = KeyEvent.KEYCODE_8;
int k9 = KeyEvent.KEYCODE_9;
// The root of the tree doesn't contain any numbers.
mLegalTimesTree = new Node();
if (mIs24HourMode) {
// We'll be re-using these nodes, so we'll save them.
Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
// The first digit must be followed by the second digit.
minuteFirstDigit.addChild(minuteSecondDigit);
// The first digit may be 0-1.
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit);
// When the first digit is 0-1, the second digit may be 0-5.
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
// We may now be followed by the first minute digit. E.g. 00:09, 15:58.
secondDigit.addChild(minuteFirstDigit);
// When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
Node thirdDigit = new Node(k6, k7, k8, k9);
// The time must now be finished. E.g. 0:55, 1:08.
secondDigit.addChild(thirdDigit);
// When the first digit is 0-1, the second digit may be 6-9.
secondDigit = new Node(k6, k7, k8, k9);
firstDigit.addChild(secondDigit);
// We must now be followed by the first minute digit. E.g. 06:50, 18:20.
secondDigit.addChild(minuteFirstDigit);
// The first digit may be 2.
firstDigit = new Node(k2);
mLegalTimesTree.addChild(firstDigit);
// When the first digit is 2, the second digit may be 0-3.
secondDigit = new Node(k0, k1, k2, k3);
firstDigit.addChild(secondDigit);
// We must now be followed by the first minute digit. E.g. 20:50, 23:09.
secondDigit.addChild(minuteFirstDigit);
// When the first digit is 2, the second digit may be 4-5.
secondDigit = new Node(k4, k5);
firstDigit.addChild(secondDigit);
// We must now be followd by the last minute digit. E.g. 2:40, 2:53.
secondDigit.addChild(minuteSecondDigit);
// The first digit may be 3-9.
firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
// We must now be followed by the first minute digit. E.g. 3:57, 8:12.
firstDigit.addChild(minuteFirstDigit);
} else {
// We'll need to use the AM/PM node a lot.
// Set up AM and PM to respond to "a" and "p".
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
// The first hour digit may be 1.
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit);
// We'll allow quick input of on-the-hour times. E.g. 1pm.
firstDigit.addChild(ampm);
// When the first digit is 1, the second digit may be 0-2.
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit);
// Also for quick input of on-the-hour times. E.g. 10pm, 12am.
secondDigit.addChild(ampm);
// When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
secondDigit.addChild(thirdDigit);
// The time may be finished now. E.g. 1:02pm, 1:25am.
thirdDigit.addChild(ampm);
// When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
// the fourth digit may be 0-9.
Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
thirdDigit.addChild(fourthDigit);
// The time must be finished now. E.g. 10:49am, 12:40pm.
fourthDigit.addChild(ampm);
// When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
thirdDigit = new Node(k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
// The time must be finished now. E.g. 1:08am, 1:26pm.
thirdDigit.addChild(ampm);
// When the first digit is 1, the second digit may be 3-5.
secondDigit = new Node(k3, k4, k5);
firstDigit.addChild(secondDigit);
// When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
// The time must be finished now. E.g. 1:39am, 1:50pm.
thirdDigit.addChild(ampm);
// The hour digit may be 2-9.
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
// We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
firstDigit.addChild(ampm);
// When the first digit is 2-9, the second digit may be 0-5.
secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
// When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
// The time must be finished now. E.g. 2:57am, 9:30pm.
thirdDigit.addChild(ampm);
}
}
/**
* Simple node class to be used for traversal to check for legal times.
* mLegalKeys represents the keys that can be typed to get to the node.
* mChildren are the children that can be reached from this node.
*/
private static class Node {
private int[] mLegalKeys;
private ArrayList<Node> mChildren;
public Node(int... legalKeys) {
mLegalKeys = legalKeys;
mChildren = new ArrayList<>();
}
public void addChild(Node child) {
mChildren.add(child);
}
public boolean containsKey(int key) {
for (int i = 0; i < mLegalKeys.length; i++) {
if (mLegalKeys[i] == key) {
return true;
}
}
return false;
}
public Node canReach(int key) {
if (mChildren == null) {
return null;
}
for (Node child : mChildren) {
if (child.containsKey(key)) {
return child;
}
}
return null;
}
}
private class KeyboardListener implements OnKeyListener {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
return processKeyUp(keyCode);
}
return false;
}
}
}
| {
"pile_set_name": "Github"
} |
Type doesn't match prototype for parameter:2 on line 4 of input038.c
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_ALGORITHM_AUXILIARY_02192011_0907)
#define FUSION_ALGORITHM_AUXILIARY_02192011_0907
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/algorithm/auxiliary/copy.hpp>
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
#include <boost/fusion/algorithm/auxiliary/move.hpp>
#endif
#endif
| {
"pile_set_name": "Github"
} |
.TH SCITE 1 "2001 February 26"
.SH NAME
SciTE \- a programmers text editor
.SH SYNOPSIS
.br
.B SciTE
[file ..]
.SH DESCRIPTION
.B SciTE
is a graphical GTK+ based editor. It has support
for indenting, highlighting, and shortcuts in a myriad
of languages and can be extended by editing object-oriented
configuration files.
.PP
Support is included for Java, C, C++, C#, Shell, Apache.
.SH ON-LINE HELP
Type Alt-H or Click the Help Pulldown menu.
.SH AUTHOR
Most of
.B SciTE
was made by Neil Hodgson, with a lot of help from others.
See Help
.br
.SH BUGS
Probably.
| {
"pile_set_name": "Github"
} |
/*
* Point-to-Point Tunneling Protocol for Linux
*
* Authors: Dmitry Kozlov <xeb@mail.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/string.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/vmalloc.h>
#include <linux/init.h>
#include <linux/ppp_channel.h>
#include <linux/ppp_defs.h>
#include <linux/if_pppox.h>
#include <linux/ppp-ioctl.h>
#include <linux/notifier.h>
#include <linux/file.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/rcupdate.h>
#include <linux/spinlock.h>
#include <net/sock.h>
#include <net/protocol.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/route.h>
#include <net/gre.h>
#include <linux/uaccess.h>
#define PPTP_DRIVER_VERSION "0.8.5"
#define MAX_CALLID 65535
static DECLARE_BITMAP(callid_bitmap, MAX_CALLID + 1);
static struct pppox_sock __rcu **callid_sock;
static DEFINE_SPINLOCK(chan_lock);
static struct proto pptp_sk_proto __read_mostly;
static const struct ppp_channel_ops pptp_chan_ops;
static const struct proto_ops pptp_ops;
#define PPP_LCP_ECHOREQ 0x09
#define PPP_LCP_ECHOREP 0x0A
#define SC_RCV_BITS (SC_RCV_B7_1|SC_RCV_B7_0|SC_RCV_ODDP|SC_RCV_EVNP)
#define MISSING_WINDOW 20
#define WRAPPED(curseq, lastseq)\
((((curseq) & 0xffffff00) == 0) &&\
(((lastseq) & 0xffffff00) == 0xffffff00))
#define PPTP_GRE_PROTO 0x880B
#define PPTP_GRE_VER 0x1
#define PPTP_GRE_FLAG_C 0x80
#define PPTP_GRE_FLAG_R 0x40
#define PPTP_GRE_FLAG_K 0x20
#define PPTP_GRE_FLAG_S 0x10
#define PPTP_GRE_FLAG_A 0x80
#define PPTP_GRE_IS_C(f) ((f)&PPTP_GRE_FLAG_C)
#define PPTP_GRE_IS_R(f) ((f)&PPTP_GRE_FLAG_R)
#define PPTP_GRE_IS_K(f) ((f)&PPTP_GRE_FLAG_K)
#define PPTP_GRE_IS_S(f) ((f)&PPTP_GRE_FLAG_S)
#define PPTP_GRE_IS_A(f) ((f)&PPTP_GRE_FLAG_A)
#define PPTP_HEADER_OVERHEAD (2+sizeof(struct pptp_gre_header))
struct pptp_gre_header {
u8 flags;
u8 ver;
__be16 protocol;
__be16 payload_len;
__be16 call_id;
__be32 seq;
__be32 ack;
} __packed;
static struct pppox_sock *lookup_chan(u16 call_id, __be32 s_addr)
{
struct pppox_sock *sock;
struct pptp_opt *opt;
rcu_read_lock();
sock = rcu_dereference(callid_sock[call_id]);
if (sock) {
opt = &sock->proto.pptp;
if (opt->dst_addr.sin_addr.s_addr != s_addr)
sock = NULL;
else
sock_hold(sk_pppox(sock));
}
rcu_read_unlock();
return sock;
}
static int lookup_chan_dst(u16 call_id, __be32 d_addr)
{
struct pppox_sock *sock;
struct pptp_opt *opt;
int i;
rcu_read_lock();
i = 1;
for_each_set_bit_from(i, callid_bitmap, MAX_CALLID) {
sock = rcu_dereference(callid_sock[i]);
if (!sock)
continue;
opt = &sock->proto.pptp;
if (opt->dst_addr.call_id == call_id &&
opt->dst_addr.sin_addr.s_addr == d_addr)
break;
}
rcu_read_unlock();
return i < MAX_CALLID;
}
static int add_chan(struct pppox_sock *sock,
struct pptp_addr *sa)
{
static int call_id;
spin_lock(&chan_lock);
if (!sa->call_id) {
call_id = find_next_zero_bit(callid_bitmap, MAX_CALLID, call_id + 1);
if (call_id == MAX_CALLID) {
call_id = find_next_zero_bit(callid_bitmap, MAX_CALLID, 1);
if (call_id == MAX_CALLID)
goto out_err;
}
sa->call_id = call_id;
} else if (test_bit(sa->call_id, callid_bitmap)) {
goto out_err;
}
sock->proto.pptp.src_addr = *sa;
set_bit(sa->call_id, callid_bitmap);
rcu_assign_pointer(callid_sock[sa->call_id], sock);
spin_unlock(&chan_lock);
return 0;
out_err:
spin_unlock(&chan_lock);
return -1;
}
static void del_chan(struct pppox_sock *sock)
{
spin_lock(&chan_lock);
clear_bit(sock->proto.pptp.src_addr.call_id, callid_bitmap);
RCU_INIT_POINTER(callid_sock[sock->proto.pptp.src_addr.call_id], NULL);
spin_unlock(&chan_lock);
synchronize_rcu();
}
static int pptp_xmit(struct ppp_channel *chan, struct sk_buff *skb)
{
struct sock *sk = (struct sock *) chan->private;
struct pppox_sock *po = pppox_sk(sk);
struct net *net = sock_net(sk);
struct pptp_opt *opt = &po->proto.pptp;
struct pptp_gre_header *hdr;
unsigned int header_len = sizeof(*hdr);
struct flowi4 fl4;
int islcp;
int len;
unsigned char *data;
__u32 seq_recv;
struct rtable *rt;
struct net_device *tdev;
struct iphdr *iph;
int max_headroom;
if (sk_pppox(po)->sk_state & PPPOX_DEAD)
goto tx_error;
rt = ip_route_output_ports(net, &fl4, NULL,
opt->dst_addr.sin_addr.s_addr,
opt->src_addr.sin_addr.s_addr,
0, 0, IPPROTO_GRE,
RT_TOS(0), 0);
if (IS_ERR(rt))
goto tx_error;
tdev = rt->dst.dev;
max_headroom = LL_RESERVED_SPACE(tdev) + sizeof(*iph) + sizeof(*hdr) + 2;
if (skb_headroom(skb) < max_headroom || skb_cloned(skb) || skb_shared(skb)) {
struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom);
if (!new_skb) {
ip_rt_put(rt);
goto tx_error;
}
if (skb->sk)
skb_set_owner_w(new_skb, skb->sk);
consume_skb(skb);
skb = new_skb;
}
data = skb->data;
islcp = ((data[0] << 8) + data[1]) == PPP_LCP && 1 <= data[2] && data[2] <= 7;
/* compress protocol field */
if ((opt->ppp_flags & SC_COMP_PROT) && data[0] == 0 && !islcp)
skb_pull(skb, 1);
/* Put in the address/control bytes if necessary */
if ((opt->ppp_flags & SC_COMP_AC) == 0 || islcp) {
data = skb_push(skb, 2);
data[0] = PPP_ALLSTATIONS;
data[1] = PPP_UI;
}
len = skb->len;
seq_recv = opt->seq_recv;
if (opt->ack_sent == seq_recv)
header_len -= sizeof(hdr->ack);
/* Push down and install GRE header */
skb_push(skb, header_len);
hdr = (struct pptp_gre_header *)(skb->data);
hdr->flags = PPTP_GRE_FLAG_K;
hdr->ver = PPTP_GRE_VER;
hdr->protocol = htons(PPTP_GRE_PROTO);
hdr->call_id = htons(opt->dst_addr.call_id);
hdr->flags |= PPTP_GRE_FLAG_S;
hdr->seq = htonl(++opt->seq_sent);
if (opt->ack_sent != seq_recv) {
/* send ack with this message */
hdr->ver |= PPTP_GRE_FLAG_A;
hdr->ack = htonl(seq_recv);
opt->ack_sent = seq_recv;
}
hdr->payload_len = htons(len);
/* Push down and install the IP header. */
skb_reset_transport_header(skb);
skb_push(skb, sizeof(*iph));
skb_reset_network_header(skb);
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED | IPSKB_REROUTED);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = sizeof(struct iphdr) >> 2;
if (ip_dont_fragment(sk, &rt->dst))
iph->frag_off = htons(IP_DF);
else
iph->frag_off = 0;
iph->protocol = IPPROTO_GRE;
iph->tos = 0;
iph->daddr = fl4.daddr;
iph->saddr = fl4.saddr;
iph->ttl = ip4_dst_hoplimit(&rt->dst);
iph->tot_len = htons(skb->len);
skb_dst_drop(skb);
skb_dst_set(skb, &rt->dst);
nf_reset(skb);
skb->ip_summed = CHECKSUM_NONE;
ip_select_ident(net, skb, NULL);
ip_send_check(iph);
ip_local_out(net, skb->sk, skb);
return 1;
tx_error:
kfree_skb(skb);
return 1;
}
static int pptp_rcv_core(struct sock *sk, struct sk_buff *skb)
{
struct pppox_sock *po = pppox_sk(sk);
struct pptp_opt *opt = &po->proto.pptp;
int headersize, payload_len, seq;
__u8 *payload;
struct pptp_gre_header *header;
if (!(sk->sk_state & PPPOX_CONNECTED)) {
if (sock_queue_rcv_skb(sk, skb))
goto drop;
return NET_RX_SUCCESS;
}
header = (struct pptp_gre_header *)(skb->data);
headersize = sizeof(*header);
/* test if acknowledgement present */
if (PPTP_GRE_IS_A(header->ver)) {
__u32 ack;
if (!pskb_may_pull(skb, headersize))
goto drop;
header = (struct pptp_gre_header *)(skb->data);
/* ack in different place if S = 0 */
ack = PPTP_GRE_IS_S(header->flags) ? header->ack : header->seq;
ack = ntohl(ack);
if (ack > opt->ack_recv)
opt->ack_recv = ack;
/* also handle sequence number wrap-around */
if (WRAPPED(ack, opt->ack_recv))
opt->ack_recv = ack;
} else {
headersize -= sizeof(header->ack);
}
/* test if payload present */
if (!PPTP_GRE_IS_S(header->flags))
goto drop;
payload_len = ntohs(header->payload_len);
seq = ntohl(header->seq);
/* check for incomplete packet (length smaller than expected) */
if (!pskb_may_pull(skb, headersize + payload_len))
goto drop;
payload = skb->data + headersize;
/* check for expected sequence number */
if (seq < opt->seq_recv + 1 || WRAPPED(opt->seq_recv, seq)) {
if ((payload[0] == PPP_ALLSTATIONS) && (payload[1] == PPP_UI) &&
(PPP_PROTOCOL(payload) == PPP_LCP) &&
((payload[4] == PPP_LCP_ECHOREQ) || (payload[4] == PPP_LCP_ECHOREP)))
goto allow_packet;
} else {
opt->seq_recv = seq;
allow_packet:
skb_pull(skb, headersize);
if (payload[0] == PPP_ALLSTATIONS && payload[1] == PPP_UI) {
/* chop off address/control */
if (skb->len < 3)
goto drop;
skb_pull(skb, 2);
}
if ((*skb->data) & 1) {
/* protocol is compressed */
skb_push(skb, 1)[0] = 0;
}
skb->ip_summed = CHECKSUM_NONE;
skb_set_network_header(skb, skb->head-skb->data);
ppp_input(&po->chan, skb);
return NET_RX_SUCCESS;
}
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
static int pptp_rcv(struct sk_buff *skb)
{
struct pppox_sock *po;
struct pptp_gre_header *header;
struct iphdr *iph;
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (!pskb_may_pull(skb, 12))
goto drop;
iph = ip_hdr(skb);
header = (struct pptp_gre_header *)skb->data;
if (ntohs(header->protocol) != PPTP_GRE_PROTO || /* PPTP-GRE protocol for PPTP */
PPTP_GRE_IS_C(header->flags) || /* flag C should be clear */
PPTP_GRE_IS_R(header->flags) || /* flag R should be clear */
!PPTP_GRE_IS_K(header->flags) || /* flag K should be set */
(header->flags&0xF) != 0) /* routing and recursion ctrl = 0 */
/* if invalid, discard this packet */
goto drop;
po = lookup_chan(htons(header->call_id), iph->saddr);
if (po) {
skb_dst_drop(skb);
nf_reset(skb);
return sk_receive_skb(sk_pppox(po), skb, 0);
}
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len)
{
struct sock *sk = sock->sk;
struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
int error = 0;
if (sockaddr_len < sizeof(struct sockaddr_pppox))
return -EINVAL;
lock_sock(sk);
if (sk->sk_state & PPPOX_DEAD) {
error = -EALREADY;
goto out;
}
if (sk->sk_state & PPPOX_BOUND) {
error = -EBUSY;
goto out;
}
if (add_chan(po, &sp->sa_addr.pptp))
error = -EBUSY;
else
sk->sk_state |= PPPOX_BOUND;
out:
release_sock(sk);
return error;
}
static int pptp_connect(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct pptp_opt *opt = &po->proto.pptp;
struct rtable *rt;
struct flowi4 fl4;
int error = 0;
if (sockaddr_len < sizeof(struct sockaddr_pppox))
return -EINVAL;
if (sp->sa_protocol != PX_PROTO_PPTP)
return -EINVAL;
if (lookup_chan_dst(sp->sa_addr.pptp.call_id, sp->sa_addr.pptp.sin_addr.s_addr))
return -EALREADY;
lock_sock(sk);
/* Check for already bound sockets */
if (sk->sk_state & PPPOX_CONNECTED) {
error = -EBUSY;
goto end;
}
/* Check for already disconnected sockets, on attempts to disconnect */
if (sk->sk_state & PPPOX_DEAD) {
error = -EALREADY;
goto end;
}
if (!opt->src_addr.sin_addr.s_addr || !sp->sa_addr.pptp.sin_addr.s_addr) {
error = -EINVAL;
goto end;
}
po->chan.private = sk;
po->chan.ops = &pptp_chan_ops;
rt = ip_route_output_ports(sock_net(sk), &fl4, sk,
opt->dst_addr.sin_addr.s_addr,
opt->src_addr.sin_addr.s_addr,
0, 0,
IPPROTO_GRE, RT_CONN_FLAGS(sk), 0);
if (IS_ERR(rt)) {
error = -EHOSTUNREACH;
goto end;
}
sk_setup_caps(sk, &rt->dst);
po->chan.mtu = dst_mtu(&rt->dst);
if (!po->chan.mtu)
po->chan.mtu = PPP_MRU;
po->chan.mtu -= PPTP_HEADER_OVERHEAD;
po->chan.hdrlen = 2 + sizeof(struct pptp_gre_header);
error = ppp_register_channel(&po->chan);
if (error) {
pr_err("PPTP: failed to register PPP channel (%d)\n", error);
goto end;
}
opt->dst_addr = sp->sa_addr.pptp;
sk->sk_state |= PPPOX_CONNECTED;
end:
release_sock(sk);
return error;
}
static int pptp_getname(struct socket *sock, struct sockaddr *uaddr,
int *usockaddr_len, int peer)
{
int len = sizeof(struct sockaddr_pppox);
struct sockaddr_pppox sp;
memset(&sp.sa_addr, 0, sizeof(sp.sa_addr));
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_PPTP;
sp.sa_addr.pptp = pppox_sk(sock->sk)->proto.pptp.src_addr;
memcpy(uaddr, &sp, len);
*usockaddr_len = len;
return 0;
}
static int pptp_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct pppox_sock *po;
struct pptp_opt *opt;
int error = 0;
if (!sk)
return 0;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD)) {
release_sock(sk);
return -EBADF;
}
po = pppox_sk(sk);
opt = &po->proto.pptp;
del_chan(po);
pppox_unbind_sock(sk);
sk->sk_state = PPPOX_DEAD;
sock_orphan(sk);
sock->sk = NULL;
release_sock(sk);
sock_put(sk);
return error;
}
static void pptp_sock_destruct(struct sock *sk)
{
if (!(sk->sk_state & PPPOX_DEAD)) {
del_chan(pppox_sk(sk));
pppox_unbind_sock(sk);
}
skb_queue_purge(&sk->sk_receive_queue);
dst_release(rcu_dereference_protected(sk->sk_dst_cache, 1));
}
static int pptp_create(struct net *net, struct socket *sock, int kern)
{
int error = -ENOMEM;
struct sock *sk;
struct pppox_sock *po;
struct pptp_opt *opt;
sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pptp_sk_proto, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
sock->state = SS_UNCONNECTED;
sock->ops = &pptp_ops;
sk->sk_backlog_rcv = pptp_rcv_core;
sk->sk_state = PPPOX_NONE;
sk->sk_type = SOCK_STREAM;
sk->sk_family = PF_PPPOX;
sk->sk_protocol = PX_PROTO_PPTP;
sk->sk_destruct = pptp_sock_destruct;
po = pppox_sk(sk);
opt = &po->proto.pptp;
opt->seq_sent = 0; opt->seq_recv = 0xffffffff;
opt->ack_recv = 0; opt->ack_sent = 0xffffffff;
error = 0;
out:
return error;
}
static int pptp_ppp_ioctl(struct ppp_channel *chan, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = (struct sock *) chan->private;
struct pppox_sock *po = pppox_sk(sk);
struct pptp_opt *opt = &po->proto.pptp;
void __user *argp = (void __user *)arg;
int __user *p = argp;
int err, val;
err = -EFAULT;
switch (cmd) {
case PPPIOCGFLAGS:
val = opt->ppp_flags;
if (put_user(val, p))
break;
err = 0;
break;
case PPPIOCSFLAGS:
if (get_user(val, p))
break;
opt->ppp_flags = val & ~SC_RCV_BITS;
err = 0;
break;
default:
err = -ENOTTY;
}
return err;
}
static const struct ppp_channel_ops pptp_chan_ops = {
.start_xmit = pptp_xmit,
.ioctl = pptp_ppp_ioctl,
};
static struct proto pptp_sk_proto __read_mostly = {
.name = "PPTP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pppox_sock),
};
static const struct proto_ops pptp_ops = {
.family = AF_PPPOX,
.owner = THIS_MODULE,
.release = pptp_release,
.bind = pptp_bind,
.connect = pptp_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pptp_getname,
.poll = sock_no_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.mmap = sock_no_mmap,
.ioctl = pppox_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = pppox_compat_ioctl,
#endif
};
static const struct pppox_proto pppox_pptp_proto = {
.create = pptp_create,
.owner = THIS_MODULE,
};
static const struct gre_protocol gre_pptp_protocol = {
.handler = pptp_rcv,
};
static int __init pptp_init_module(void)
{
int err = 0;
pr_info("PPTP driver version " PPTP_DRIVER_VERSION "\n");
callid_sock = vzalloc((MAX_CALLID + 1) * sizeof(void *));
if (!callid_sock)
return -ENOMEM;
err = gre_add_protocol(&gre_pptp_protocol, GREPROTO_PPTP);
if (err) {
pr_err("PPTP: can't add gre protocol\n");
goto out_mem_free;
}
err = proto_register(&pptp_sk_proto, 0);
if (err) {
pr_err("PPTP: can't register sk_proto\n");
goto out_gre_del_protocol;
}
err = register_pppox_proto(PX_PROTO_PPTP, &pppox_pptp_proto);
if (err) {
pr_err("PPTP: can't register pppox_proto\n");
goto out_unregister_sk_proto;
}
return 0;
out_unregister_sk_proto:
proto_unregister(&pptp_sk_proto);
out_gre_del_protocol:
gre_del_protocol(&gre_pptp_protocol, GREPROTO_PPTP);
out_mem_free:
vfree(callid_sock);
return err;
}
static void __exit pptp_exit_module(void)
{
unregister_pppox_proto(PX_PROTO_PPTP);
proto_unregister(&pptp_sk_proto);
gre_del_protocol(&gre_pptp_protocol, GREPROTO_PPTP);
vfree(callid_sock);
}
module_init(pptp_init_module);
module_exit(pptp_exit_module);
MODULE_DESCRIPTION("Point-to-Point Tunneling Protocol");
MODULE_AUTHOR("D. Kozlov (xeb@mail.ru)");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2009 Christopher Schmidt
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_FUSION_VIEW_JOINT_VIEW_DETAIL_KEY_OF_IMPL_HPP
#define BOOST_FUSION_VIEW_JOINT_VIEW_DETAIL_KEY_OF_IMPL_HPP
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/iterator/key_of.hpp>
namespace boost { namespace fusion { namespace extension
{
template <typename>
struct key_of_impl;
template <>
struct key_of_impl<joint_view_iterator_tag>
{
template <typename It>
struct apply
: result_of::key_of<typename It::first_type>
{};
};
}}}
#endif
| {
"pile_set_name": "Github"
} |
package com.bioxx.tfc.Blocks.Terrain;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;
import com.bioxx.tfc.api.Constant.Global;
public class BlockIgInCobble extends BlockCobble
{
public BlockIgInCobble(Material material)
{
super(material);
names = Global.STONE_IGIN;
icons = new IIcon[names.length];
looseStart = Global.STONE_IGIN_START;
}
}
| {
"pile_set_name": "Github"
} |
const PriceCheckEntry = require("./pricecheck-entry.js");
const CurrencyIcons = require("../../resource/icons/currencyIcons");
const BaseTypeIcons = require("../../resource/icons/baseTypeIcons");
const querystring = require("querystring");
const https = require("https");
class RareItemEntry extends PriceCheckEntry {
/**
* Creates a new RareItemEntry object
*
* @constructor
* @param {Object} poePrices poeprices.info result, including item text in base 64
* @param {Parser} parser Parser object
*/
constructor(poePrices, parser) {
super();
this.poePrices = poePrices;
this.parser = parser;
this.selectedFeedback = "";
}
add() {
var template = templates.get("rare.html");
var replacements = this._buildReplacements();
// Set template, replacements and add
super.setTemplate(template);
super.setReplacements(replacements);
super.add();
// Set buttons, links, prediction explanation and feedback elements
super.setCloseable(true);
super.enableToggle("expand");
super.enableExternalLinks();
this._addExplanationTable();
this._enableFeedbackElements();
// Enable autoclose if configured
if(config.get("autoclose.enabled") && config.get("autoclose.timeouts.rare.enabled")) {
if(!(config.get("autoclose.threshold.enabled")
&& (this.poePrices.price.min > config.get("autoclose.threshold.value") || this.poePrices.price.currency === "exalt"))) {
super.enableAutoClose(config.get("autoclose.timeouts.rare.value"));
}
}
}
_buildReplacements() {
var baseType = this.parser.getBaseType();
var url = "https://www.poeprices.info/api?l=" + config.get("league") + "&i=" + this.poePrices.encodedItemText + "&w=1";
var currencyIcon = "", currencyName = "";
if(this.poePrices.price.currency === "chaos") {
currencyName = "Chaos Orb";
} else {
currencyName = "Exalted Orb";
}
currencyIcon = CurrencyIcons[currencyName];
var replacements = [
{ find: "item-name", replace: this.parser.getName() },
{ find: "item-baseType", replace: baseType },
{ find: "item-value-min", replace: this.poePrices.price.min },
{ find: "item-value-max", replace: this.poePrices.price.max },
{ find: "currency-name", replace: currencyName },
{ find: "currency-icon", replace: currencyIcon },
{ find: "link", replace: url}
];
if(BaseTypeIcons.hasOwnProperty(baseType)) {
replacements.push({ find: "item-icon", replace: BaseTypeIcons[baseType] });
}
return replacements;
}
_addExplanationTable() {
for(var modIndex in this.poePrices.price.pred_explanation) {
var mod = this.poePrices.price.pred_explanation[modIndex];
var percentage = (mod[1] * 100).toFixed(2);
$(".entry[data-id='" + this.id + "']").find("tbody:last-child").append(
"<tr><td class='percentage grey'>" + percentage + "%</td><td class='mod'>" + mod[0] + "</td></tr>"
);
}
}
_enableFeedbackElements() {
var self = this;
var textarea = $(".entry[data-id='" + this.id + "']").find("[data-comment]").find("textarea");
textarea.focusout(function() {
GUI.onFocus();
});
// Send feedback button
$(".entry[data-id='" + this.id + "']").find("[data-feedback-send]").click(function() {
self._sendFeedback();
});
// Feedback buttons (fair, high, low)
$(".entry[data-id='" + this.id + "']").find("[data-feedback]").each(function() {
$(this).click(function() {
self._feedbackButtonClick($(this));
});
});
}
_removeFeedbackButtons() {
$(".entry[data-id='" + this.id + "']").find("[data-feedback]").each(function() {
$(this).remove();
});
}
_feedbackButtonClick(selector) {
var feedback = selector.attr("data-feedback")
// Cancel auto-close if feedback button is pressed
if(this.timeout != null) {
this.cancelAutoClose();
}
if(feedback !== this.selectedFeedback) {
$(".entry[data-id='" + this.id + "']").find("[data-feedback]").each(function() {
$(this).removeClass("active");
});
selector.addClass("active");
this._toggleCommentBox(true);
this.selectedFeedback = feedback;
} else {
selector.removeClass("active");
this._toggleCommentBox(false);
this.selectedFeedback = "";
}
}
_toggleCommentBox(toggle) {
var selector = $(".entry[data-id='" + this.id + "']").find("[data-comment]");
selector.toggle(toggle);
GUI.updateWindowHeight();
}
_sendFeedback() {
if(["fair", "low", "high"].includes(this.selectedFeedback)) {
var text = $(".entry[data-id='" + this.id + "']").find("[data-comment]").find("textarea").val();
this._toggleCommentBox(false);
this._removeFeedbackButtons();
var postData = querystring.stringify({
selector: this.selectedFeedback,
feedbacktxt: text,
qitem_txt: this.poePrices.encodedItemText,
source: "xenontrade",
min: this.poePrices.price.min,
max: this.poePrices.price.max,
currency: this.poePrices.price.currency,
debug: 0
});
var options = {
hostname: "poeprices.info",
port: 443,
path: "/send_feedback",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": postData.length
}
};
var infoText = $(".entry[data-id='" + this.id + "']").find("[data-feedback-info]");
infoText.html("Sending feedback...");
var req = https.request(options, (res) => {
res.on("data", (d) => {
infoText.html("Thank you for your feedback!");
});
});
req.on("error", (e) => {
infoText.html("An error occured while sending your feedback.");
});
req.write(postData);
req.end();
}
}
}
module.exports = RareItemEntry;
| {
"pile_set_name": "Github"
} |
# 0.4.17 / 2017-04-22
* Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn)
# 0.4.16 / 2017-04-22
* Added support for React Native (#150)
* Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex)
* Fixed typo in Readme (#138 by @jiangzhuo)
* Fixed build for Node v6.10+ by making correct version comparison
* Added a warning if iconv-lite is loaded not as utf-8 (see #142)
# 0.4.15 / 2016-11-21
* Fixed typescript type definition (#137)
# 0.4.14 / 2016-11-20
* Preparation for v1.0
* Added Node v6 and latest Node versions to Travis CI test rig
* Deprecated Node v0.8 support
* Typescript typings (@larssn)
* Fix encoding of Euro character in GB 18030 (inspired by @lygstate)
* Add ms prefix to dbcs windows encodings (@rokoroku)
# 0.4.13 / 2015-10-01
* Fix silly mistake in deprecation notice.
# 0.4.12 / 2015-09-26
* Node v4 support:
* Added CESU-8 decoding (#106)
* Added deprecation notice for `extendNodeEncodings`
* Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol)
# 0.4.11 / 2015-07-03
* Added CESU-8 encoding.
# 0.4.10 / 2015-05-26
* Changed UTF-16 endianness heuristic to take into account any ASCII chars, not
just spaces. This should minimize the importance of "default" endianness.
# 0.4.9 / 2015-05-24
* Streamlined BOM handling: strip BOM by default, add BOM when encoding if
addBOM: true. Added docs to Readme.
* UTF16 now uses UTF16-LE by default.
* Fixed minor issue with big5 encoding.
* Added io.js testing on Travis; updated node-iconv version to test against.
Now we just skip testing SBCS encodings that node-iconv doesn't support.
* (internal refactoring) Updated codec interface to use classes.
* Use strict mode in all files.
# 0.4.8 / 2015-04-14
* added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94)
# 0.4.7 / 2015-02-05
* stop official support of Node.js v0.8. Should still work, but no guarantees.
reason: Packages needed for testing are hard to get on Travis CI.
* work in environment where Object.prototype is monkey patched with enumerable
props (#89).
# 0.4.6 / 2015-01-12
* fix rare aliases of single-byte encodings (thanks @mscdex)
* double the timeout for dbcs tests to make them less flaky on travis
# 0.4.5 / 2014-11-20
* fix windows-31j and x-sjis encoding support (@nleush)
* minor fix: undefined variable reference when internal error happens
# 0.4.4 / 2014-07-16
* added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3)
* fixed streaming base64 encoding
# 0.4.3 / 2014-06-14
* added encodings UTF-16BE and UTF-16 with BOM
# 0.4.2 / 2014-06-12
* don't throw exception if `extendNodeEncodings()` is called more than once
# 0.4.1 / 2014-06-11
* codepage 808 added
# 0.4.0 / 2014-06-10
* code is rewritten from scratch
* all widespread encodings are supported
* streaming interface added
* browserify compatibility added
* (optional) extend core primitive encodings to make usage even simpler
* moved from vows to mocha as the testing framework
| {
"pile_set_name": "Github"
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MoveUsings.cs" company="http://stylecop.codeplex.com">
// MS-PL
// </copyright>
// <license>
// This source code is subject to terms and conditions of the Microsoft
// Public License. A copy of the license can be found in the License.html
// file at the root of this distribution. If you cannot locate the
// Microsoft Public License, please send an email to dlr@microsoft.com.
// By using this source code in any fashion, you are agreeing to be bound
// by the terms of the Microsoft Public License. You must not remove this
// notice, or any other, from this software.
// </license>
// <summary>
// BulbItem - MoveUsings : Moves Using statements inside the closest namespace.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace StyleCop.ReSharper.BulbItems.Ordering
{
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.TextControl;
using StyleCop.ReSharper.BulbItems.Framework;
using StyleCop.ReSharper.Core;
/// <summary>
/// BulbItem - MoveUsings : Moves Using statements inside the closest namespace.
/// </summary>
internal class MoveUsings : V5BulbItemImpl
{
/// <summary>
/// The execute transaction inner.
/// </summary>
/// <param name="solution">
/// The solution.
/// </param>
/// <param name="textControl">
/// The text control.
/// </param>
public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
{
ITreeNode element = Utils.GetElementAtCaret(solution, textControl);
if (element == null)
{
return;
}
IUsingList usingList = element.GetContainingNode(typeof(IUsingList), false) as IUsingList;
if (usingList == null)
{
return;
}
ICSharpFile file = Utils.GetCSharpFile(solution, textControl);
// This violation will only run if there are some using statements and definately at least 1 namespace
// so [0] index will always be OK.
ICSharpNamespaceDeclaration firstNamespace = file.NamespaceDeclarations[0];
foreach (IUsingDirective usingDirectiveNode in usingList.Imports)
{
firstNamespace.AddImportBefore(usingDirectiveNode, null);
file.RemoveImport(usingDirectiveNode);
}
// Now sort the Usings into order.
OrderUsingsBulbItem orderUsingsBulbItem = new OrderUsingsBulbItem();
orderUsingsBulbItem.ExecuteTransactionInner(solution, textControl);
}
}
} | {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#ifndef genericFvPatchFields_H
#define genericFvPatchFields_H
#include "genericFvPatchField.H"
#include "fieldTypes.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
makePatchTypeFieldTypedefs(generic);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes 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.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/coordination/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// LeaseLister helps list Leases.
type LeaseLister interface {
// List lists all Leases in the indexer.
List(selector labels.Selector) (ret []*v1beta1.Lease, err error)
// Leases returns an object that can list and get Leases.
Leases(namespace string) LeaseNamespaceLister
LeaseListerExpansion
}
// leaseLister implements the LeaseLister interface.
type leaseLister struct {
indexer cache.Indexer
}
// NewLeaseLister returns a new LeaseLister.
func NewLeaseLister(indexer cache.Indexer) LeaseLister {
return &leaseLister{indexer: indexer}
}
// List lists all Leases in the indexer.
func (s *leaseLister) List(selector labels.Selector) (ret []*v1beta1.Lease, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.Lease))
})
return ret, err
}
// Leases returns an object that can list and get Leases.
func (s *leaseLister) Leases(namespace string) LeaseNamespaceLister {
return leaseNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// LeaseNamespaceLister helps list and get Leases.
type LeaseNamespaceLister interface {
// List lists all Leases in the indexer for a given namespace.
List(selector labels.Selector) (ret []*v1beta1.Lease, err error)
// Get retrieves the Lease from the indexer for a given namespace and name.
Get(name string) (*v1beta1.Lease, error)
LeaseNamespaceListerExpansion
}
// leaseNamespaceLister implements the LeaseNamespaceLister
// interface.
type leaseNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all Leases in the indexer for a given namespace.
func (s leaseNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Lease, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.Lease))
})
return ret, err
}
// Get retrieves the Lease from the indexer for a given namespace and name.
func (s leaseNamespaceLister) Get(name string) (*v1beta1.Lease, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("lease"), name)
}
return obj.(*v1beta1.Lease), nil
}
| {
"pile_set_name": "Github"
} |
if (!Array.prototype.flat) {
Object.defineProperty(Array.prototype, 'flat', {
configurable: true,
value: function flat () {
var depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);
return depth ? Array.prototype.reduce.call(this, function (acc, cur) {
if (Array.isArray(cur)) {
acc.push.apply(acc, flat.call(cur, depth - 1));
} else {
acc.push(cur);
}
return acc;
}, []) : Array.prototype.slice.call(this);
},
writable: true
});
}
| {
"pile_set_name": "Github"
} |
version: build-{build}.{branch}
clone_folder: C:\gopath\src\github.com\pkg\errors
shallow_clone: true # for startup speed
environment:
GOPATH: C:\gopath
platform:
- x64
# http://www.appveyor.com/docs/installed-software
install:
# some helpful output for debugging builds
- go version
- go env
# pre-installed MinGW at C:\MinGW is 32bit only
# but MSYS2 at C:\msys64 has mingw64
- set PATH=C:\msys64\mingw64\bin;%PATH%
- gcc --version
- g++ --version
build_script:
- go install -v ./...
test_script:
- set PATH=C:\gopath\bin;%PATH%
- go test -v ./...
#artifacts:
# - path: '%GOPATH%\bin\*.exe'
deploy: off
| {
"pile_set_name": "Github"
} |
//
// TAAbstractDotView.h
// TAPageControl
//
// Created by Tanguy Aladenise on 2015-01-22.
// Copyright (c) 2015 Tanguy Aladenise. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TAAbstractDotView : UIView
/**
* A method call let view know which state appearance it should take. Active meaning it's current page. Inactive not the current page.
*
* @param active BOOL to tell if view is active or not
*/
- (void)changeActivityState:(BOOL)active;
@end
| {
"pile_set_name": "Github"
} |
%TITLE%
KGLS 031118/0300
LEVEL HGHT TEMP DWPT WDIR WSPD
-------------------------------------------------------------------
%RAW%
1007.00, 0.00, 23.13, 23.13, 165.83, 20.64
1004.50, 21.90, 24.24, 22.99, 166.97, 24.13
999.40, 66.60, 24.04, 22.83, 167.47, 26.86
991.80, 133.70, 23.84, 22.62, 168.06, 30.97
981.70, 223.60, 23.64, 21.75, 168.87, 37.22
966.50, 360.20, 22.44, 20.61, 171.80, 43.57
951.30, 498.50, 21.74, 19.68, 178.81, 46.63
936.10, 638.70, 21.24, 18.93, 187.24, 47.78
920.90, 780.90, 20.84, 18.34, 194.61, 46.97
905.70, 925.30, 20.54, 17.66, 200.17, 46.77
890.50, 1071.90, 20.14, 16.63, 201.54, 47.62
875.30, 1220.70, 19.24, 15.72, 201.55, 48.66
860.10, 1371.40, 17.84, 14.88, 203.82, 49.05
844.90, 1524.00, 16.44, 14.09, 206.16, 49.34
829.70, 1678.70, 15.34, 13.20, 206.57, 49.95
814.50, 1835.60, 14.24, 12.27, 207.36, 49.87
799.40, 1993.80, 13.14, 11.36, 207.99, 48.84
784.20, 2155.40, 12.34, 10.54, 208.96, 47.74
769.00, 2319.60, 10.84, 9.70, 209.92, 47.51
753.80, 2486.30, 10.34, 8.22, 210.92, 46.87
738.60, 2656.10, 9.74, 6.59, 212.81, 45.53
723.40, 2828.70, 8.44, 4.68, 214.81, 44.24
708.20, 3004.20, 7.54, 2.28, 215.48, 43.18
693.00, 3182.70, 6.54, -0.43, 216.92, 43.01
677.80, 3364.60, 5.84, -3.47, 217.28, 43.94
662.60, 3549.90, 4.74, -6.69, 215.54, 45.12
626.20, 4007.40, 1.04, -9.15, 218.27, 44.54
566.10, 4809.70, -5.26, -5.97, 228.15, 42.51
539.00, 5193.90, -7.06, -12.02, 231.34, 44.78
520.60, 5464.30, -8.06, -13.50, 230.74, 46.66
504.80, 5703.60, -8.66, -14.35, 229.87, 48.52
487.60, 5972.30, -8.86, -15.37, 228.81, 51.62
462.00, 6388.80, -10.46, -16.64, 229.46, 58.28
419.50, 7125.00, -15.26, -19.70, 232.92, 63.79
374.50, 7972.80, -21.06, -25.66, 239.99, 67.97
347.50, 8521.90, -24.16, -30.30, 240.54, 73.85
308.80, 9372.40, -30.16, -37.39, 240.71, 84.19
255.20, 10698.50, -40.96, -49.20, 239.82, 92.36
204.40, 12167.00, -53.36, -62.82, 237.77, 97.60
171.60, 13269.50, -62.26, -73.93, 238.39, 100.82
150.30, 14075.80, -68.36, -74.78, 238.93, 102.74
134.90, 14716.70, -72.86, -75.46, 238.00, 102.62
125.50, 15138.20, -74.76, -75.92, 239.25, 96.51
120.10, 15394.10, -73.96, -76.20, 242.68, 92.27
115.10, 15642.90, -72.56, -76.47, 246.31, 86.55
106.00, 16129.10, -70.36, -76.99, 249.65, 62.57
95.00, 16781.70, -68.96, -77.69, 256.30, 47.59
80.90, 17745.80, -67.36, -78.71, 220.24, 19.85
64.40, 19119.10, -67.56, -80.16, 234.37, 28.68
46.30, 21115.50, -65.36, -82.26, 294.88, 14.77
%END%
----- Parcel Information-----
*** MU PARCEL IN LOWEST 300mb ***
LPL: P=992 T=75F Td=73F
CAPE: 1829 J/kg
CINH: -13 J/kg
LI: -6 C
LI(300mb): -3 C
3km Cape: 144 J/kg
NCAPE: 0.14 m/s2
LCL: 974mb 291m
LFC: 860mb 1371m
EL: 150mb 14076m
MPL: 91mb 17040m
All heights AGL
----- Moisture -----
Precip Water: 1.90 in
Mean W: 16.4 g/Kg
----- Lapse Rates -----
700-500mb 16 C 6.1 C/km
850-500mb 27 C 6.4 C/km
| {
"pile_set_name": "Github"
} |
/*
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 client
import (
"encoding/json"
"fmt"
"github.com/apache/trafficcontrol/lib/go-tc"
"net/http"
"net/url"
)
const (
API_SNAPSHOT = apiBase + "/snapshot"
)
type OuterResponse struct {
Response json.RawMessage `json:"response"`
}
// GetCRConfig returns the raw JSON bytes of the CRConfig from Traffic Ops, and whether the bytes were from the client's internal cache.
func (to *Session) GetCRConfig(cdn string) ([]byte, ReqInf, error) {
uri := apiBase + `/cdns/` + cdn + `/snapshot`
bts, reqInf, err := to.getBytesWithTTL(uri, tmPollingInterval)
if err != nil {
return nil, reqInf, err
}
resp := OuterResponse{}
if err := json.Unmarshal(bts, &resp); err != nil {
return nil, reqInf, err
}
return []byte(resp.Response), reqInf, nil
}
// GetCRConfigNew returns the raw JSON bytes of the latest CRConfig from Traffic Ops, and whether the bytes were from the client's internal cache.
func (to *Session) GetCRConfigNew(cdn string) ([]byte, ReqInf, error) {
uri := apiBase + `/cdns/` + cdn + `/snapshot/new`
bts, reqInf, err := to.getBytesWithTTL(uri, tmPollingInterval)
if err != nil {
return nil, reqInf, err
}
resp := OuterResponse{}
if err := json.Unmarshal(bts, &resp); err != nil {
return nil, reqInf, err
}
return []byte(resp.Response), reqInf, nil
}
// SnapshotCRConfig snapshots a CDN by name.
func (to *Session) SnapshotCRConfig(cdn string) (ReqInf, error) {
uri := fmt.Sprintf("%s?cdn=%s", API_SNAPSHOT, url.QueryEscape(cdn))
_, remoteAddr, err := to.request(http.MethodPut, uri, nil)
reqInf := ReqInf{RemoteAddr: remoteAddr, CacheHitStatus: CacheHitStatusMiss}
return reqInf, err
}
// SnapshotCDNByID snapshots a CDN by ID.
func (to *Session) SnapshotCRConfigByID(id int) (tc.Alerts, ReqInf, error) {
url := fmt.Sprintf("%s?cdnID=%d", API_SNAPSHOT, id)
resp, remoteAddr, err := to.request(http.MethodPut, url, nil)
reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
if err != nil {
return tc.Alerts{}, reqInf, err
}
defer resp.Body.Close()
var alerts tc.Alerts
err = json.NewDecoder(resp.Body).Decode(&alerts)
return alerts, reqInf, nil
}
| {
"pile_set_name": "Github"
} |
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=7
if [[ ${PV} == 9999* ]]; then
EGIT_REPO_URI="https://github.com/mooltipass/moolticute.git"
inherit git-r3
else
SRC_URI="https://github.com/mooltipass/moolticute/archive/v${PV/_/-}.tar.gz -> ${P}.tar.gz"
KEYWORDS="~amd64 ~arm"
fi
inherit xdg-utils qmake-utils udev
DESCRIPTION="Mooltipass crossplatform daemon/tools"
HOMEPAGE="https://github.com/mooltipass/moolticute"
LICENSE="GPL-3"
SLOT="0"
IUSE=""
RDEPEND="
>=dev-libs/libusb-1.0.20
dev-qt/qtdbus:5
dev-qt/qtcore:5
dev-qt/qtgui:5
dev-qt/qtnetwork:5
dev-qt/qttest:5
dev-qt/qtwebsockets:5
dev-qt/qtwidgets:5
"
BDEPEND="${RDEPEND}
dev-qt/linguist-tools:5
"
S="${WORKDIR}/${P/_/-}"
src_prepare() {
default
# Fill version.h with package version
if [[ ${PV} != 9999* ]]; then
sed -i "s/\"git\"/\"v${PV/_/-}\"/" src/version.h || die
fi
}
src_configure() {
eqmake5 PREFIX="/usr" Moolticute.pro
}
src_install() {
emake install INSTALL_ROOT="${D}"
udev_dorules "${FILESDIR}/50-mooltipass.rule"
newinitd "${FILESDIR}/moolticuted.init" moolticuted
}
pkg_postinst() {
udev_reload
xdg_icon_cache_update
}
pkg_postrm() {
xdg_icon_cache_update
}
| {
"pile_set_name": "Github"
} |
[gd_resource type="AtlasTexture" load_steps=2 format=2]
[ext_resource path="res://addons/Rakugo/emojis/atlas/16x16.png" type="Texture" id=1]
[resource]
flags = 7
atlas = ExtResource( 1 )
region = Rect2( 19, 343, 16, 16 )
| {
"pile_set_name": "Github"
} |
---
blog: 'https://jetpack.com/blog'
facebook: 'https://facebook.com/WordPresscom'
logohandle: jetpack
sort: jetpack
title: Jetpack
website: 'https://jetpack.com/'
---
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 35405fc9d817249958711883902db606
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
---
layout: api
title: "v3.3.0 JavaScript Library: L.Class"
categories: api
version: v3.3.0
permalink: /api/v3.3.0/l-class/
---
<h2 id="class">Class</h2>
<p><code>L.Class</code> powers the OOP facilities of Leaflet and is used to create almost all of the Leaflet classes documented here.</p>
<p>In addition to implementing a simple classical inheritance model, it introduces several special properties for convenient code organization — <code>options</code>, <code>includes</code> and <code>statics</code>.</p>
<pre><code>var MyClass = L.Class.extend({
initialize: function (greeter) {
this.greeter = greeter;
// class constructor
},
greet: function (name) {
alert(this.greeter + ', ' + name)
}
});
// create instance of MyClass, passing "Hello" to the constructor
var a = new MyClass("Hello");
// call greet method, alerting "Hello, World"
a.greet("World");
</code></pre>
<h3>Class Factories</h3>
<p>You may have noticed that Leaflet objects are created without using the <code>new</code> keyword. This is achieved by complementing each class with a lowercase factory method:</p>
<pre><code>new L.Map('map'); // becomes:
L.map('map');</code></pre>
<p>The factories are implemented very easily, and you can do this for your own classes:</p>
<pre><code>L.map = function (id, options) {
return new L.Map(id, options);
};</code></pre>
<h3>Inheritance</h3>
<p>You use <code>L.Class.extend</code> to define new classes, but you can use the same method on any class to inherit from it:</p>
<pre><code>var MyChildClass = MyClass.extend({
// ... new properties and methods
});</code></pre>
<p>This will create a class that inherits all methods and properties of the parent class (through a proper prototype chain), adding or overriding the ones you pass to <code>extend</code>. It will also properly react to <code>instanceof</code>:</p>
<pre><code>var a = new MyChildClass();
a instanceof MyChildClass; // true
a instanceof MyClass; // true
</code></pre>
<p>You can call parent methods (including constructor) from corresponding child ones (as you do with <code>super</code> calls in other languages) by accessing parent class prototype and using JavaScript's <code>call</code> or <code>apply</code>:</p>
<pre><code>var MyChildClass = MyClass.extend({
initialize: function () {
MyClass.prototype.initialize.call(this, "Yo");
},
greet: function (name) {
MyClass.prototype.greet.call(this, 'bro ' + name + '!');
}
});
var a = new MyChildClass();
a.greet('Jason'); // alerts "Yo, bro Jason!"</code></pre>
<h3 id="class-options">Options</h3>
<p><code>options</code> is a special property that unlike other objects that you pass to <code>extend</code> will be merged with the parent one instead of overriding it completely, which makes managing configuration of objects and default values convenient:</p>
<pre><code>var MyClass = L.Class.extend({
options: {
myOption1: 'foo',
myOption2: 'bar'
}
});
var MyChildClass = MyClass.extend({
options: {
myOption1: 'baz',
myOption3: 5
}
});
var a = new MyChildClass();
a.options.myOption1; // 'baz'
a.options.myOption2; // 'bar'
a.options.myOption3; // 5</code></pre>
<p>There's also <code>L.Util.setOptions</code>, a method for conveniently merging options passed to constructor with the defauls defines in the class:</p>
<pre><code>var MyClass = L.Class.extend({
options: {
foo: 'bar',
bla: 5
},
initialize: function (options) {
L.Util.setOptions(this, options);
...
}
});
var a = new MyClass({bla: 10});
a.options; // {foo: 'bar', bla: 10}</code></pre>
<h3>Includes</h3>
<p><code>includes</code> is a special class property that merges all specified objects into the class (such objects are called mixins). A good example of this is <code>L.Mixin.Events</code> that <a href="/mapbox.js/api/v3.3.0/l-events">event-related methods</a> like <code>on</code>, <code>off</code> and <code>fire</code> to the class.</p>
<pre><code> var MyMixin = {
foo: function () { ... },
bar: 5
};
var MyClass = L.Class.extend({
includes: MyMixin
});
var a = new MyClass();
a.foo();</code></pre>
<p>You can also do such includes in runtime with the <code>include</code> method:</p>
<pre><code><b>MyClass.include</b>(MyMixin);</code></pre>
<h3>Statics</h3>
<p><code>statics</code> is just a convenience property that injects specified object properties as the static properties of the class, useful for defining constants:</p>
<pre><code>var MyClass = L.Class.extend({
statics: {
FOO: 'bar',
BLA: 5
}
});
MyClass.FOO; // 'bar'</code></pre>
<h3>Constructor Hooks</h3>
<p>If you're a plugin developer, you often need to add additional initialization code to existing classes (e.g. editing hooks for <code>L.Polyline</code>). Leaflet comes with a way to do it easily using the <code>addInitHook</code> method:</p>
<pre><code>MyClass.addInitHook(function () {
// ... do something in constructor additionally
// e.g. add event listeners, set custom properties etc.
});</code></pre>
<p>You can also use the following shortcut when you just need to make one additional method call:</p>
<pre><code>MyClass.addInitHook('methodName', arg1, arg2, …);</code></pre>
| {
"pile_set_name": "Github"
} |
package ceui.lisa.http;
public class RequestMap {
}
| {
"pile_set_name": "Github"
} |
/*
* JBox2D - A Java Port of Erin Catto's Box2D
*
* JBox2D homepage: http://jbox2d.sourceforge.net/
* Box2D homepage: http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package org.jbox2d.dynamics.joints;
import org.jbox2d.dynamics.Body;
public class JointDef {
public JointType type;
public Body body1;
public Body body2;
public Object userData;
public boolean collideConnected;
public JointDef() {
type = JointType.UNKNOWN_JOINT;
body1 = null;
body2 = null;
userData = null;
collideConnected = false;
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2018, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef _IPA3_ODL_H_
#define _IPA3_ODL_H_
#define IPA_ODL_AGGR_BYTE_LIMIT (15 * 1024)
#define IPA_ODL_RX_RING_SIZE 192
#define MAX_QUEUE_TO_ODL 1024
#define CONFIG_SUCCESS 1
#define ODL_EP_TYPE_HSUSB 2
#define ODL_EP_PERIPHERAL_IFACE_ID 3
struct ipa3_odlstats {
u32 odl_rx_pkt;
u32 odl_tx_diag_pkt;
u32 odl_drop_pkt;
atomic_t numer_in_queue;
};
struct odl_state_bit_mask {
u32 odl_init:1;
u32 odl_open:1;
u32 adpl_open:1;
u32 aggr_byte_limit_sent:1;
u32 odl_ep_setup:1;
u32 odl_setup_done_sent:1;
u32 odl_ep_info_sent:1;
u32 odl_connected:1;
u32 odl_disconnected:1;
u32:0;
};
/**
* struct ipa3_odl_char_device_context - IPA ODL character device
* @class: pointer to the struct class
* @dev_num: device number
* @dev: the dev_t of the device
* @cdev: cdev of the device
*/
struct ipa3_odl_char_device_context {
struct class *class;
dev_t dev_num;
struct device *dev;
struct cdev cdev;
};
struct ipa_odl_context {
struct ipa3_odl_char_device_context odl_cdev[2];
struct list_head adpl_msg_list;
struct mutex adpl_msg_lock;
struct ipa_sys_connect_params odl_sys_param;
u32 odl_client_hdl;
struct odl_state_bit_mask odl_state;
bool odl_ctl_msg_wq_flag;
struct ipa3_odlstats stats;
};
struct ipa3_push_msg_odl {
void *buff;
int len;
struct list_head link;
};
extern struct ipa_odl_context *ipa3_odl_ctx;
int ipa_odl_init(void);
void ipa3_odl_pipe_cleanup(bool is_ssr);
int ipa3_odl_pipe_open(void);
#endif /* _IPA3_ODL_H_ */
| {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.DotNet.Configurer
{
public interface IFirstTimeUseNoticeSentinel : IDisposable
{
bool Exists();
void CreateIfNotExists();
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright The containerd 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 metadata
import bolt "go.etcd.io/bbolt"
type migration struct {
schema string
version int
migrate func(*bolt.Tx) error
}
// migrations stores the list of database migrations
// for each update to the database schema. The migrations
// array MUST be ordered by version from least to greatest.
// The last entry in the array should correspond to the
// schemaVersion and dbVersion constants.
// A migration test MUST be added for each migration in
// the array.
// The migrate function can safely assume the version
// of the data it is migrating from is the previous version
// of the database.
var migrations = []migration{
{
schema: "v1",
version: 1,
migrate: addChildLinks,
},
{
schema: "v1",
version: 2,
migrate: migrateIngests,
},
{
schema: "v1",
version: 3,
migrate: noOpMigration,
},
}
// addChildLinks Adds children key to the snapshotters to enforce snapshot
// entries cannot be removed which have children
func addChildLinks(tx *bolt.Tx) error {
v1bkt := tx.Bucket(bucketKeyVersion)
if v1bkt == nil {
return nil
}
// iterate through each namespace
v1c := v1bkt.Cursor()
for k, v := v1c.First(); k != nil; k, v = v1c.Next() {
if v != nil {
continue
}
nbkt := v1bkt.Bucket(k)
sbkt := nbkt.Bucket(bucketKeyObjectSnapshots)
if sbkt != nil {
// Iterate through each snapshotter
if err := sbkt.ForEach(func(sk, sv []byte) error {
if sv != nil {
return nil
}
snbkt := sbkt.Bucket(sk)
// Iterate through each snapshot
return snbkt.ForEach(func(k, v []byte) error {
if v != nil {
return nil
}
parent := snbkt.Bucket(k).Get(bucketKeyParent)
if len(parent) > 0 {
pbkt := snbkt.Bucket(parent)
if pbkt == nil {
// Not enforcing consistency during migration, skip
return nil
}
cbkt, err := pbkt.CreateBucketIfNotExists(bucketKeyChildren)
if err != nil {
return err
}
if err := cbkt.Put(k, nil); err != nil {
return err
}
}
return nil
})
}); err != nil {
return err
}
}
}
return nil
}
// migrateIngests moves ingests from the key/value ingest bucket
// to a structured ingest bucket for storing additional state about
// an ingest.
func migrateIngests(tx *bolt.Tx) error {
v1bkt := tx.Bucket(bucketKeyVersion)
if v1bkt == nil {
return nil
}
// iterate through each namespace
v1c := v1bkt.Cursor()
for k, v := v1c.First(); k != nil; k, v = v1c.Next() {
if v != nil {
continue
}
bkt := v1bkt.Bucket(k).Bucket(bucketKeyObjectContent)
if bkt == nil {
continue
}
dbkt := bkt.Bucket(deprecatedBucketKeyObjectIngest)
if dbkt == nil {
continue
}
// Create new ingests bucket
nbkt, err := bkt.CreateBucketIfNotExists(bucketKeyObjectIngests)
if err != nil {
return err
}
if err := dbkt.ForEach(func(ref, bref []byte) error {
ibkt, err := nbkt.CreateBucketIfNotExists(ref)
if err != nil {
return err
}
return ibkt.Put(bucketKeyRef, bref)
}); err != nil {
return err
}
if err := bkt.DeleteBucket(deprecatedBucketKeyObjectIngest); err != nil {
return err
}
}
return nil
}
// noOpMigration was for a database change from boltdb/bolt which is no
// longer being supported, to go.etcd.io/bbolt which is the currently
// maintained repo for boltdb.
func noOpMigration(tx *bolt.Tx) error {
return nil
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2016 GeometryFactory SARL (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : Andreas Fabri
//
// Warning: this file is generated, see include/CGAL/licence/README.md
#ifndef CGAL_LICENSE_HEAT_METHOD_3_H
#define CGAL_LICENSE_HEAT_METHOD_3_H
#include <CGAL/config.h>
#include <CGAL/license.h>
#ifdef CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE
# if CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE < CGAL_RELEASE_DATE
# if defined(CGAL_LICENSE_WARNING)
CGAL_pragma_warning("Your commercial license for CGAL does not cover "
"this release of the 3D Heat Method package.")
# endif
# ifdef CGAL_LICENSE_ERROR
# error "Your commercial license for CGAL does not cover this release \
of the 3D Heat Method package. \
You get this error, as you defined CGAL_LICENSE_ERROR."
# endif // CGAL_LICENSE_ERROR
# endif // CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE < CGAL_RELEASE_DATE
#else // no CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE
# if defined(CGAL_LICENSE_WARNING)
CGAL_pragma_warning("\nThe macro CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE is not defined."
"\nYou use the CGAL 3D Heat Method package under "
"the terms of the GPLv3+.")
# endif // CGAL_LICENSE_WARNING
# ifdef CGAL_LICENSE_ERROR
# error "The macro CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE is not defined.\
You use the CGAL 3D Heat Method package under the terms of \
the GPLv3+. You get this error, as you defined CGAL_LICENSE_ERROR."
# endif // CGAL_LICENSE_ERROR
#endif // no CGAL_HEAT_METHOD_3_COMMERCIAL_LICENSE
#endif // CGAL_LICENSE_CHECK_HEAT_METHOD_3_H
| {
"pile_set_name": "Github"
} |
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "video_core/regs_texturing.h"
namespace Pica {
/// Initialize Pica state
void Init();
/// Shutdown Pica state
void Shutdown();
} // namespace Pica
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2008 Joel de Guzman
Copyright (c) 2001-2008 Hartmut Kaiser
http://spirit.sourceforge.net/
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_FILE_ITERATOR
#define BOOST_SPIRIT_INCLUDE_CLASSIC_FILE_ITERATOR
#include <boost/spirit/home/classic/iterator/file_iterator.hpp>
#endif
| {
"pile_set_name": "Github"
} |
//
// server.hpp
// fibio
//
// Created by Chen Xu on 14-3-13.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#ifndef fibio_http_server_server_hpp
#define fibio_http_server_server_hpp
#include <memory>
#include <string>
#include <functional>
#include <system_error>
#include <fibio/stream/iostream.hpp>
#include <fibio/stream/ssl.hpp>
#include <fibio/http/server/request.hpp>
#include <fibio/http/server/response.hpp>
namespace fibio {
namespace http {
constexpr unsigned DEFAULT_MAX_KEEP_ALIVE = 100;
#if defined(_WIN32)
// NOTE: std::chrono::seconds constructor is not constexpr in VC
static const timeout_type DEFAULT_TIMEOUT = std::chrono::seconds(60);
static const timeout_type NO_TIMEOUT = std::chrono::seconds(0);
#else
constexpr timeout_type DEFAULT_TIMEOUT = std::chrono::seconds(60);
constexpr timeout_type NO_TIMEOUT = std::chrono::seconds(0);
#endif
struct server_error : std::runtime_error
{
server_error(http_status_code c) : std::runtime_error(""), code(c) {}
server_error(http_status_code c, const std::string& msg) : std::runtime_error(msg), code(c) {}
server_error(http_status_code c, const char* msg) : std::runtime_error(msg), code(c) {}
server_error(http_status_code c, const std::string& msg, const common::header_map& hdrs)
: std::runtime_error(msg), code(c), additional_headers(hdrs)
{
}
http_status_code code;
common::header_map additional_headers;
};
struct server
{
typedef fibio::http::server_request request;
typedef fibio::http::server_response response;
typedef std::function<bool(request& req, response& resp)> request_handler;
struct settings
{
std::string address_ = "0.0.0.0";
unsigned short port_ = 80;
request_handler default_request_handler_
= [](request&, response&) -> bool { return false; };
timeout_type read_timeout_ = DEFAULT_TIMEOUT;
timeout_type write_timeout_ = DEFAULT_TIMEOUT;
unsigned max_keep_alive_ = DEFAULT_MAX_KEEP_ALIVE;
ssl::context* ctx_ = nullptr;
};
server() = default;
server(unsigned short p) { port(p); }
server(const std::string& a, unsigned short p) { address(a).port(p); }
~server();
server& address(const std::string& a)
{
s_.address_ = a;
return *this;
}
server& port(unsigned short p)
{
s_.port_ = p;
return *this;
}
server& ssl(ssl::context& c)
{
s_.ctx_ = &c;
return *this;
}
server& timeout(timeout_type t)
{
s_.read_timeout_ = s_.write_timeout_ = t;
return *this;
}
server& max_keepalive(unsigned m)
{
s_.max_keep_alive_ = m;
return *this;
}
server& handler(request_handler h)
{
s_.default_request_handler_ = h;
return *this;
}
server& start();
void stop();
boost::system::error_code join();
boost::system::error_code run() { return start().join(); }
struct impl;
private:
void init_engine();
bool ssl() const { return s_.ctx_; }
settings s_;
impl* engine_ = nullptr;
std::unique_ptr<fiber> servant_;
};
} // End of namespace http
} // End of namespace fibio
#endif
| {
"pile_set_name": "Github"
} |
/**
* jQuery EasyUI 1.5
*
* Copyright (c) 2009-2016 www.jeasyui.com. All rights reserved.
*
* Licensed under the freeware license: http://www.jeasyui.com/license_freeware.php
* To use it on other terms please contact us: info@jeasyui.com
*
*/
(function($){
function _1(_2){
var _3=$.data(_2,"datetimebox");
var _4=_3.options;
$(_2).datebox($.extend({},_4,{onShowPanel:function(){
var _5=$(this).datetimebox("getValue");
_d(this,_5,true);
_4.onShowPanel.call(this);
},formatter:$.fn.datebox.defaults.formatter,parser:$.fn.datebox.defaults.parser}));
$(_2).removeClass("datebox-f").addClass("datetimebox-f");
$(_2).datebox("calendar").calendar({onSelect:function(_6){
_4.onSelect.call(this.target,_6);
}});
if(!_3.spinner){
var _7=$(_2).datebox("panel");
var p=$("<div style=\"padding:2px\"><input></div>").insertAfter(_7.children("div.datebox-calendar-inner"));
_3.spinner=p.children("input");
}
_3.spinner.timespinner({width:_4.spinnerWidth,showSeconds:_4.showSeconds,separator:_4.timeSeparator});
$(_2).datetimebox("initValue",_4.value);
};
function _8(_9){
var c=$(_9).datetimebox("calendar");
var t=$(_9).datetimebox("spinner");
var _a=c.calendar("options").current;
return new Date(_a.getFullYear(),_a.getMonth(),_a.getDate(),t.timespinner("getHours"),t.timespinner("getMinutes"),t.timespinner("getSeconds"));
};
function _b(_c,q){
_d(_c,q,true);
};
function _e(_f){
var _10=$.data(_f,"datetimebox").options;
var _11=_8(_f);
_d(_f,_10.formatter.call(_f,_11));
$(_f).combo("hidePanel");
};
function _d(_12,_13,_14){
var _15=$.data(_12,"datetimebox").options;
$(_12).combo("setValue",_13);
if(!_14){
if(_13){
var _16=_15.parser.call(_12,_13);
$(_12).combo("setText",_15.formatter.call(_12,_16));
$(_12).combo("setValue",_15.formatter.call(_12,_16));
}else{
$(_12).combo("setText",_13);
}
}
var _16=_15.parser.call(_12,_13);
$(_12).datetimebox("calendar").calendar("moveTo",_16);
$(_12).datetimebox("spinner").timespinner("setValue",_17(_16));
function _17(_18){
function _19(_1a){
return (_1a<10?"0":"")+_1a;
};
var tt=[_19(_18.getHours()),_19(_18.getMinutes())];
if(_15.showSeconds){
tt.push(_19(_18.getSeconds()));
}
return tt.join($(_12).datetimebox("spinner").timespinner("options").separator);
};
};
$.fn.datetimebox=function(_1b,_1c){
if(typeof _1b=="string"){
var _1d=$.fn.datetimebox.methods[_1b];
if(_1d){
return _1d(this,_1c);
}else{
return this.datebox(_1b,_1c);
}
}
_1b=_1b||{};
return this.each(function(){
var _1e=$.data(this,"datetimebox");
if(_1e){
$.extend(_1e.options,_1b);
}else{
$.data(this,"datetimebox",{options:$.extend({},$.fn.datetimebox.defaults,$.fn.datetimebox.parseOptions(this),_1b)});
}
_1(this);
});
};
$.fn.datetimebox.methods={options:function(jq){
var _1f=jq.datebox("options");
return $.extend($.data(jq[0],"datetimebox").options,{originalValue:_1f.originalValue,disabled:_1f.disabled,readonly:_1f.readonly});
},cloneFrom:function(jq,_20){
return jq.each(function(){
$(this).datebox("cloneFrom",_20);
$.data(this,"datetimebox",{options:$.extend(true,{},$(_20).datetimebox("options")),spinner:$(_20).datetimebox("spinner")});
$(this).removeClass("datebox-f").addClass("datetimebox-f");
});
},spinner:function(jq){
return $.data(jq[0],"datetimebox").spinner;
},initValue:function(jq,_21){
return jq.each(function(){
var _22=$(this).datetimebox("options");
var _23=_22.value;
if(_23){
_23=_22.formatter.call(this,_22.parser.call(this,_23));
}
$(this).combo("initValue",_23).combo("setText",_23);
});
},setValue:function(jq,_24){
return jq.each(function(){
_d(this,_24);
});
},reset:function(jq){
return jq.each(function(){
var _25=$(this).datetimebox("options");
$(this).datetimebox("setValue",_25.originalValue);
});
}};
$.fn.datetimebox.parseOptions=function(_26){
var t=$(_26);
return $.extend({},$.fn.datebox.parseOptions(_26),$.parser.parseOptions(_26,["timeSeparator","spinnerWidth",{showSeconds:"boolean"}]));
};
$.fn.datetimebox.defaults=$.extend({},$.fn.datebox.defaults,{spinnerWidth:"100%",showSeconds:true,timeSeparator:":",keyHandler:{up:function(e){
},down:function(e){
},left:function(e){
},right:function(e){
},enter:function(e){
_e(this);
},query:function(q,e){
_b(this,q);
}},buttons:[{text:function(_27){
return $(_27).datetimebox("options").currentText;
},handler:function(_28){
var _29=$(_28).datetimebox("options");
_d(_28,_29.formatter.call(_28,new Date()));
$(_28).datetimebox("hidePanel");
}},{text:function(_2a){
return $(_2a).datetimebox("options").okText;
},handler:function(_2b){
_e(_2b);
}},{text:function(_2c){
return $(_2c).datetimebox("options").closeText;
},handler:function(_2d){
$(_2d).datetimebox("hidePanel");
}}],formatter:function(_2e){
var h=_2e.getHours();
var M=_2e.getMinutes();
var s=_2e.getSeconds();
function _2f(_30){
return (_30<10?"0":"")+_30;
};
var _31=$(this).datetimebox("spinner").timespinner("options").separator;
var r=$.fn.datebox.defaults.formatter(_2e)+" "+_2f(h)+_31+_2f(M);
if($(this).datetimebox("options").showSeconds){
r+=_31+_2f(s);
}
return r;
},parser:function(s){
if($.trim(s)==""){
return new Date();
}
var dt=s.split(" ");
var d=$.fn.datebox.defaults.parser(dt[0]);
if(dt.length<2){
return d;
}
var _32=$(this).datetimebox("spinner").timespinner("options").separator;
var tt=dt[1].split(_32);
var _33=parseInt(tt[0],10)||0;
var _34=parseInt(tt[1],10)||0;
var _35=parseInt(tt[2],10)||0;
return new Date(d.getFullYear(),d.getMonth(),d.getDate(),_33,_34,_35);
}});
})(jQuery);
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
// RUN: %clang_cc1 -std=c++11 -fcxx-exceptions -DCXX_EXCEPTIONS -fsyntax-only -verify %s
template <class _Tp> struct is_nothrow_move_constructible {
static const bool value = false;
};
template <class _Tp>
class allocator;
template <>
class allocator<char> {};
template <class _Allocator>
class basic_string {
typedef _Allocator allocator_type;
basic_string(basic_string &&__str)
noexcept(is_nothrow_move_constructible<allocator_type>::value);
};
class Foo {
Foo(Foo &&) noexcept = default;
#ifdef CXX_EXCEPTIONS
// expected-error@-2 {{does not match the calculated}}
#else
// expected-no-diagnostics
#endif
Foo &operator=(Foo &&) noexcept = default;
basic_string<allocator<char> > vectorFoo_;
};
| {
"pile_set_name": "Github"
} |
<Application x:Class="MVVMBasicApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMBasicApp"
Startup="Application_Startup">
<Application.Resources>
</Application.Resources>
</Application>
| {
"pile_set_name": "Github"
} |
def exo1():
"""
Implement the Newton algorithm.
Display the evolution of $f(x^{(\ell)})$ and $\norm{x^{(\ell)}-x^{(+\infty)}}$
during the iterations.
isplay
"""
niter = 10
x = [-1.5; 2.5]
x = [1.7; 2.7]
E = []; X = []
for i in 1: niter:
X(: , end + 1) = x
x = x - pinv(Hessf(x))*Gradf(x)
E(i) = f(x(1), x(2))
myplot = lambda E: plot(log10(E(E >eps)))
Xs = [1; 1]
e = sqrt(sum((X-repmat(Xs, [1 niter])).^2))
subplot(2, 1, 1)
myplot(E); axis tight
title('log_{10}|E(x_k)-E^*|')
subplot(2, 1, 2)
myplot(e); axis tight
title('log_{10}|x_k-x^*|')
def exo2():
"""
Display the evolution of $x^{(\ell)}$, from several starting points.
"""
cols = {'r' 'g' 'b' 'c' 'm' 'y'}
Xinit = {[-1.5; 2.5] [1.7; 2.7] [-.3; .85]}
niter = 10
clf; hold on
imagesc(x2, x1, perform_hist_eq(F, 'linear'))
colormap jet(256)
for k in 1: length(Xinit):
x = Xinit{k}; % [4*rand-2; 3.5*rand-.5]
X = []
for i in 1: niter:
X(: , end + 1) = x
x = x - pinv(Hessf(x))*Gradf(x)
plot(X(2, : ), X(1, : ), [cols{k} '.-'], 'MarkerSize', 20, 'LineWidth', 2)
axis([-.5 3 -2 2])
def exo3():
"""
Implement the Newton descent algorithm.
d = Hinv(Gradf(x), A(x), d);
"""
niter = 12; % 300
x = y
E = []
d = zeros(n)
for i in 1: niter:
E(end + 1) = f(x)
[d, ~] = Hinv(Gradf(x), A(x), d)
d = flatI(d)
x = x - d
h = plot(E)
title('f(x^{l})')
set(h, 'LineWidth', 2)
axis tight
def exo4():
"""
Compare the Newton descent with the gradient descent with a fixed step
size, in term of decay of the energy.
"""
tau = 1.8/ (1 + lambda*8/ epsilon)
tau = tau*4
x = y
E1 = []
for i in 1: niter:
E1(end + 1) = f(x)
x = x - tau*Gradf(x)
h = plot([E; E1]')
title('f(x^{l})')
legend('Newton', 'Gradient')
set(h, 'LineWidth', 2)
axis tight
def exo5():
"""
The direct comparison between gradient method and Newton is not fair in
term of iteration count. Indeed, and iteration of Newton requires
several steps of conjugate gradient, which takes some time.
Try to set-up a fair comparison benchmark that takes into account the
runing time of the methods. Pay a particular attention to the number of
steps (or the tolerance criterion) that parameterize |cgs|.
"""
| {
"pile_set_name": "Github"
} |
<div class="form-group {{ $errors->has('created_at') ? 'has-error' : ''}}">
{!! Form::label('created_at', 'Created At', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('created_at', null, ('' == 'required') ? ['class' => 'form-control', 'required' => 'required'] : ['class' => 'form-control']) !!}
{!! $errors->first('created_at', '<p class="help-block">:message</p>') !!}
</div>
</div><div class="form-group {{ $errors->has('number') ? 'has-error' : ''}}">
{!! Form::label('number', 'Number', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('number', null, ('' == 'required') ? ['class' => 'form-control', 'required' => 'required'] : ['class' => 'form-control']) !!}
{!! $errors->first('number', '<p class="help-block">:message</p>') !!}
</div>
</div><div class="form-group {{ $errors->has('points') ? 'has-error' : ''}}">
{!! Form::label('points', 'Points', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('points', null, ('' == 'required') ? ['class' => 'form-control', 'required' => 'required'] : ['class' => 'form-control']) !!}
{!! $errors->first('points', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-4">
{!! Form::submit(isset($submitButtonText) ? $submitButtonText : 'Create', ['class' => 'btn btn-primary']) !!}
</div>
</div>
| {
"pile_set_name": "Github"
} |
// PROJECT: Micro-Manager
// SUBSYSTEM: MMCore
//
// COPYRIGHT: University of California, San Francisco, 2014,
// All Rights reserved
//
// LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Mark Tsuchida
// Note: This code must reside in the same binary image as the rest of the
// Core.
#ifdef WIN32 // whole file
#include "LibraryPaths.h"
#include "../CoreUtils.h"
#include "../Error.h"
#include <boost/scoped_array.hpp>
#include <Psapi.h>
static HMODULE GetHandleOfThisModule()
{
// This function is located in this module (obviously), so get the module
// containing the address of this function.
HMODULE hModule;
BOOL ok = GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCSTR>(&GetHandleOfThisModule),
&hModule);
if (!ok) {
DWORD err = GetLastError();
// TODO FormatMessage()
throw CMMError("Cannot get handle to DLL or executable "
"(Windows system error code " + ToString(err) + ")");
}
return hModule;
}
static std::string GetPathOfModule(HMODULE hModule)
{
for (size_t bufsize = 1024, len = bufsize; ; bufsize += 1024)
{
boost::scoped_array<char> filename(new char[bufsize]);
len = GetModuleFileNameA(hModule, filename.get(),
static_cast<DWORD>(bufsize));
if (!len)
{
DWORD err = GetLastError();
// TODO FormatMessage()
throw CMMError("Cannot get filename of DLL or executable "
"(Windows system error code " + ToString(err) + ")");
}
if (len == bufsize) // Filename may not have fit in buffer
continue;
return filename.get();
}
}
namespace MMCorePrivate {
std::string GetPathOfThisModule()
{
return GetPathOfModule(GetHandleOfThisModule());
}
} // namespace MMCorePrivate
#endif // WIN32
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Copyright 2016 Víctor Albertos
*
* 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 rx_activity_result2;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import androidx.annotation.Nullable;
public class RequestIntentSender extends Request {
private final IntentSender intentSender;
private final Intent fillInIntent;
private final int flagsMask, flagsValues, extraFlags;
private final Bundle options;
public RequestIntentSender(IntentSender intentSender, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options) {
super(null);
this.intentSender = intentSender;
this.fillInIntent = fillInIntent;
this.flagsMask = flagsMask;
this.flagsValues = flagsValues;
this.extraFlags = extraFlags;
this.options = options;
}
public IntentSender getIntentSender() {
return intentSender;
}
public Intent getFillInIntent() {
return fillInIntent;
}
public int getFlagsMask() {
return flagsMask;
}
public int getFlagsValues() {
return flagsValues;
}
public int getExtraFlags() {
return extraFlags;
}
public Bundle getOptions() {
return options;
}
}
| {
"pile_set_name": "Github"
} |
#main-text p.note {
font-style: italic;
}
/*
a,
label,
input {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
a {
color: rgb(0, 102, 204);
text-decoration: none;
border-bottom: 1px solid rgba(0, 102, 204, .2);
}
a:visited {
color: rgb(102, 102, 102);
border-bottom: 1px solid rgba(102, 102, 102, .2);
}
*/
a.add-code-popup {
color: rgb(150, 90, 40);
font-weight: 600;
text-decoration: none;
border-bottom: 1px solid rgba(150, 90, 40, .2);
background: inherit !important;
padding-right: inherit !important;
}
a.add-code-popup:hover {
color: rgb(120, 60, 30);
border-bottom-color: rgba(150, 90, 40, .4);
}
a.add-code-popup.showing {
color: black;
border-bottom-color: rgba(0, 0, 0, .2);
}
/*
a:active {
position: relative;
top: 1px;
}*/
a.important {
font-weight: 600;
}
#main-text abbr {
font-size: 85%;
font-weight: 600;
letter-spacing: 1px;
}
#main-text em {
letter-spacing: 1px;
}
span.title {
font-style: italic;
}
span.url {
font-style: italic;
}
span.foreign {
font-style: italic;
}
#main-text label,
#main-text label * {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
/* Lists */
#main-text ul,
#main-text ol {
margin: 12px 0;
padding: 0;
list-style: none;
}
#main-text li {
margin: 0;
padding: 0;
list-style: none;
position: relative;
counter-increment: number;
}
#main-text ul > li::before {
content: '·';
position: absolute;
left: -1em;
width: 1em;
display: inline-block;
}
#main-text ol > li::before {
content: counter(number) '.';
position: absolute;
left: -3.5em;
width: 3em;
display: inline-block;
text-align: right;
}
#main-text figure > img {
max-width: 100%;
display: block;
margin: 24px auto;
}
#main-text img.black {
background: black;
}
#main-text img.padded {
padding: 12px 18px;
-moz-box-sizing: border-box;
-o-sizing: border-box;
box-sizing: border-box;
}
#main-text figure iframe {
display: block;
border: 0;
margin: 0 auto;
}
#main-text figcaption a {
color: rgb(60, 60, 60);
border-bottom-color: rgba(60, 60, 60, .3);
}
#main-text figure table {
max-width: 42em;
margin: 0 auto;
border-collapse: collapse;
}
#main-text figure td {
text-align: center;
padding: 12px 24px;
}
#main-text figure table.compact td {
padding: 0;
text-align: left;
}
#main-text figure th {
font-weight: 400;
text-align: left;
line-height: 18px;
font-size: 14px;
padding: 12px 24px;
}
#main-text figure table.text td {
text-align: left;
padding: 6px 12px;
}
#main-text figure table.text th {
text-align: left;
padding: 6px 12px;
}
/* Code pop-up */
.code-popup {
position: absolute;
overflow: hidden;
outline: none;
-webkit-transition: opacity 150ms, margin 350ms, height 250ms;
-moz-transition: opacity 150ms, margin 350ms, height 250ms;
-o-transition: opacity 150ms, margin 350ms, height 250ms;
transition: opacity 150ms, margin 350ms, height 250ms;
opacity: 1;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.code-popup.below .triangle {
position: absolute;
background: rgb(220, 180, 140);
box-shadow: -2px -2px 1px rgba(0, 0, 0, .1);
width: 14px;
height: 14px;
left: 49px;
top: 7px;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
.code-popup.above .triangle {
position: absolute;
z-index: 5000;
background: rgb(248, 248, 248);
box-shadow: 2px 2px 3px rgba(0, 0, 0, .2);
width: 14px;
height: 14px;
left: 49px;
bottom: 7px;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
.code-popup.aside .triangle {
position: absolute;
z-index: 5000;
background: rgb(248, 248, 248);
box-shadow: -2px 2px 1px rgba(0, 0, 0, .2);
width: 14px;
height: 14px;
left: 6px;
top: 38px;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
.code-popup .content {
border-radius: 5px;
padding: 0;
position: absolute;
left: 12px;
top: 12px;
right: 12px;
bottom: 12px;
box-shadow: 0 2px 5px rgba(0, 0, 0, .35);
overflow: hidden;
}
.code-popup.showing {
-webkit-transition: none, width 250ms, height 250ms;
-moz-transition: none, width 250ms, height 250ms;
-o-transition: none, width 250ms, height 250ms;
transition: none, width 250ms, height 250ms;
opacity: 0;
height: 0;
overflow-y: hidden;
}
.code-popup.showing.below {
margin-top: 10px;
}
.code-popup.showing.above {
margin-top: -10px;
}
.code-popup.showing.aside {
margin-left: 10px;
}
.code-popup.ready {
-webkit-transition: none;
-moz-transition: none;
-o-transition: none;
transition: none;
}
.code-popup.hiding {
-webkit-transition: opacity 150ms;
-moz-transition: opacity 150ms;
-o-transition: opacity 150ms;
transition: opacity 150ms;
opacity: 0;
}
.code-popup .content h1 {
font-family: Arial, sans-serif;
font-size: 12px;
letter-spacing: 0;
padding: 0;
margin: 0;
padding-left: 9px;
padding-right: 9px;
-moz-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
padding-top: 2px;
line-height: 22px;
background: rgb(240, 200, 160);
color: black;
}
.code-popup .content h1 a {
display: inline-block;
line-height: 14px;
}
.code-popup .content pre {
margin: 0;
padding: 0;
font-size: 14px;
line-height: 18px !important;
padding: 6px;
padding-left: 50px;
background: -webkit-linear-gradient(rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), white, rgb(230, 230, 230), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248));
background: -moz-linear-gradient(rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), white, rgb(230, 230, 230), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248));
background: -o-linear-gradient(rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), white, rgb(230, 230, 230), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248));
background: linear-gradient(rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), white, rgb(230, 230, 230), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248), rgb(248, 248, 248));
background-repeat: repeat-y;
background-size: 100% 18px;
position: absolute;
left: 0;
top: 24px !important;
right: 0;
bottom: 0;
border: 0;
border-radius: 0;
overflow-x: auto;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.code-popup .content pre .line-numbers {
width: 44px;
line-height: 18px;
padding-top: 9px;
}
#main-text pre {
position: relative;
padding-left: 50px;
line-height: 17px;
}
pre .line-numbers {
font-family: Arial, sans-serif;
font-size: 12px;
letter-spacing: 0;
position: absolute;
left: 0;
top: 0;
width: 43px;
-moz-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
padding-top: 11px;
padding-right: 8px;
padding-bottom: 9px;
text-align: right;
color: rgb(160, 160, 160);
line-height: 17px;
border-right: 1px solid rgba(0, 0, 0, .1);
}
.code-popup .content h1 button {
position: absolute;
-webkit-appearance: none;
border: none;
background: none;
padding: 6px 10px;
right: -3px;
top: -3px;
cursor: pointer;
}
.code-popup .content h1 button:active {
top: -2px;
}
.button-download {
display: block;
position: relative;
padding: 10px 20px 10px 40px;
margin: 10px 0;
background: #1f1f1f;
background: -webkit-gradient(linear, left top, left bottom, from(#3d3d3d), to(#1f1f1f));
background: -webkit-linear-gradient(top, #3d3d3d, #1f1f1f);
background: -moz-linear-gradient(top, #3d3d3d, #1f1f1f);
background: -ms-linear-gradient(top, #3d3d3d, #1f1f1f);
background: -o-linear-gradient(top, #3d3d3d, #1f1f1f);
border-top: 1px solid #c7c7c7;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: rgba(0,0,0,1) 0 1px 0;
-moz-box-shadow: rgba(0,0,0,1) 0 1px 0;
box-shadow: rgba(0,0,0,1) 0 1px 0;
text-shadow: rgba(0,0,0,.4) 0 1px 0;
color: #aaa;
font-size: 16px;
line-height: 20px;
font-family: 'Lucida Grande', Helvetica, Arial, Sans-Serif;
text-decoration: none;
vertical-align: middle;
}
.button-download:hover, .button-download:focus {
border-top-color: #141414;
background: #141414;
cursor: pointer;
color: white;
}
.button-download::before {
content: url('../assets/images/download-gem.png');
position: absolute;
top: 8px;
left: 10px;
}
.button-download::after {
content: ".zip";
float: right;
position: relative;
top: -1px;
color: #666;
}
.button-download:hover::after {
color: #34bbce;
}
.button-download.pdf::after {
content: ".pdf";
}
.button-download:active {
border-top-color: #8f8f8f;
background: #8f8f8f;
}
.button-download em {
position: absolute;
text-transform: uppercase;
font-size: 10px;
color: #666;
top: 2px;
right: 60px;
}
.button-download:hover em {
color: #ccc;
}
.button-download em::before {
content: "*";
position: relative;
top: 12px;
font-size: 30px;
}
.button-download:hover em::before {
color: #34bbce;
}
@media screen and (max-width: 480px) {
.hidden-narrow {
display: none;
}/*
#main-text ul > li {
margin-left: 1em;
}
#main-text ol > li {
margin-left: 2.5em;
}
#main-text ol > li::before {
left: -2.5em;
text-align: left;
}
#main-text figcaption {
margin: 24px 0;
line-height: 36px;
font-size: 28px;
}
#main-text code {
padding: 0 8px;
margin: 0 4px;
line-height: 36px;
}
#main-text code,
#main-text pre {
font-size: 28px;
}
#main-text pre {
font-size: 28px;
line-height: 36px;
padding-top: 12px;
padding-bottom: 12px;
margin-left: -100px;
padding-left: 200px;
background-position: 0 12px;
background-size: 100% 36px;
-webkit-overflow-scrolling: touch;
}
.code-popup .content h1 {
font-size: 24px;
padding-top: 4px;
line-height: 44px;
padding-left: 18px;
padding-right: 18px;
}
.code-popup .content h1 a {
line-height: 28px;
}
.code-popup .content pre {
font-size: 28px;
line-height: 36px;
padding: 12px;
padding-left: 100px;
top: 48px;
background-size: 100% 36px;
background-position: 0 18px;
}
.code-popup .content pre .line-numbers {
width: 88px;
}
#main-text pre .line-numbers {
font-size: 24px;
width: 188px;
padding-top: 14px;
padding-right: 16px;
padding-bottom: 8px;
}
.code-popup .content h1 button {
font-size: 100%;
padding: 12px 20px;
right: -6px;
top: -6px;
}
.code-popup .content h1 button:active {
top: -5px;
}*/
} | {
"pile_set_name": "Github"
} |
/**
******************************************************************************
* @file stm32f4xx_ll_dma2d.c
* @author MCD Application Team
* @brief DMA2D LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* 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.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may 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 THE COPYRIGHT HOLDER 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.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_ll_dma2d.h"
#include "stm32f4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F4xx_LL_Driver
* @{
*/
#if defined (DMA2D)
/** @addtogroup DMA2D_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup DMA2D_LL_Private_Constants DMA2D Private Constants
* @{
*/
#define LL_DMA2D_COLOR 0xFFU /*!< Maximum output color setting */
#define LL_DMA2D_NUMBEROFLINES DMA2D_NLR_NL /*!< Maximum number of lines */
#define LL_DMA2D_NUMBEROFPIXELS (DMA2D_NLR_PL >> DMA2D_NLR_PL_Pos) /*!< Maximum number of pixels per lines */
#define LL_DMA2D_OFFSET_MAX 0x3FFFU /*!< Maximum output line offset expressed in pixels */
#define LL_DMA2D_CLUTSIZE_MAX 0xFFU /*!< Maximum CLUT size */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DMA2D_LL_Private_Macros
* @{
*/
#define IS_LL_DMA2D_MODE(MODE) (((MODE) == LL_DMA2D_MODE_M2M) || \
((MODE) == LL_DMA2D_MODE_M2M_PFC) || \
((MODE) == LL_DMA2D_MODE_M2M_BLEND) || \
((MODE) == LL_DMA2D_MODE_R2M))
#define IS_LL_DMA2D_OCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB8888) || \
((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB888) || \
((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB565) || \
((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB1555) || \
((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB4444))
#define IS_LL_DMA2D_GREEN(GREEN) ((GREEN) <= LL_DMA2D_COLOR)
#define IS_LL_DMA2D_RED(RED) ((RED) <= LL_DMA2D_COLOR)
#define IS_LL_DMA2D_BLUE(BLUE) ((BLUE) <= LL_DMA2D_COLOR)
#define IS_LL_DMA2D_ALPHA(ALPHA) ((ALPHA) <= LL_DMA2D_COLOR)
#define IS_LL_DMA2D_OFFSET(OFFSET) ((OFFSET) <= LL_DMA2D_OFFSET_MAX)
#define IS_LL_DMA2D_LINE(LINES) ((LINES) <= LL_DMA2D_NUMBEROFLINES)
#define IS_LL_DMA2D_PIXEL(PIXELS) ((PIXELS) <= LL_DMA2D_NUMBEROFPIXELS)
#define IS_LL_DMA2D_LCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB8888) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB888) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB565) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB1555) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB4444) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L8) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL44) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL88) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L4) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A8) || \
((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A4))
#define IS_LL_DMA2D_CLUTCMODE(CLUTCMODE) (((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_ARGB8888) || \
((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_RGB888))
#define IS_LL_DMA2D_CLUTSIZE(SIZE) ((SIZE) <= LL_DMA2D_CLUTSIZE_MAX)
#define IS_LL_DMA2D_ALPHAMODE(MODE) (((MODE) == LL_DMA2D_ALPHA_MODE_NO_MODIF) || \
((MODE) == LL_DMA2D_ALPHA_MODE_REPLACE) || \
((MODE) == LL_DMA2D_ALPHA_MODE_COMBINE))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DMA2D_LL_Exported_Functions
* @{
*/
/** @addtogroup DMA2D_LL_EF_Init_Functions Initialization and De-initialization Functions
* @{
*/
/**
* @brief De-initialize DMA2D registers (registers restored to their default values).
* @param DMA2Dx DMA2D Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DMA2D registers are de-initialized
* - ERROR: DMA2D registers are not de-initialized
*/
ErrorStatus LL_DMA2D_DeInit(DMA2D_TypeDef *DMA2Dx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
if (DMA2Dx == DMA2D)
{
/* Force reset of DMA2D clock */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA2D);
/* Release reset of DMA2D clock */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA2D);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize DMA2D registers according to the specified parameters in DMA2D_InitStruct.
* @note DMA2D transfers must be disabled to set initialization bits in configuration registers,
* otherwise ERROR result is returned.
* @param DMA2Dx DMA2D Instance
* @param DMA2D_InitStruct pointer to a LL_DMA2D_InitTypeDef structure
* that contains the configuration information for the specified DMA2D peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DMA2D registers are initialized according to DMA2D_InitStruct content
* - ERROR: Issue occurred during DMA2D registers initialization
*/
ErrorStatus LL_DMA2D_Init(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_InitTypeDef *DMA2D_InitStruct)
{
ErrorStatus status = ERROR;
LL_DMA2D_ColorTypeDef DMA2D_ColorStruct;
uint32_t tmp = 0U, tmp1 = 0U, tmp2 = 0U;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
assert_param(IS_LL_DMA2D_MODE(DMA2D_InitStruct->Mode));
assert_param(IS_LL_DMA2D_OCMODE(DMA2D_InitStruct->ColorMode));
assert_param(IS_LL_DMA2D_LINE(DMA2D_InitStruct->NbrOfLines));
assert_param(IS_LL_DMA2D_PIXEL(DMA2D_InitStruct->NbrOfPixelsPerLines));
assert_param(IS_LL_DMA2D_GREEN(DMA2D_InitStruct->OutputGreen));
assert_param(IS_LL_DMA2D_RED(DMA2D_InitStruct->OutputRed));
assert_param(IS_LL_DMA2D_BLUE(DMA2D_InitStruct->OutputBlue));
assert_param(IS_LL_DMA2D_ALPHA(DMA2D_InitStruct->OutputAlpha));
assert_param(IS_LL_DMA2D_OFFSET(DMA2D_InitStruct->LineOffset));
/* DMA2D transfers must be disabled to configure bits in initialization registers */
tmp = LL_DMA2D_IsTransferOngoing(DMA2Dx);
tmp1 = LL_DMA2D_FGND_IsEnabledCLUTLoad(DMA2Dx);
tmp2 = LL_DMA2D_BGND_IsEnabledCLUTLoad(DMA2Dx);
if ((tmp == 0U) && (tmp1 == 0U) && (tmp2 == 0U))
{
/* DMA2D CR register configuration -------------------------------------------*/
LL_DMA2D_SetMode(DMA2Dx, DMA2D_InitStruct->Mode);
/* DMA2D OPFCCR register configuration ---------------------------------------*/
MODIFY_REG(DMA2Dx->OPFCCR, DMA2D_OPFCCR_CM, DMA2D_InitStruct->ColorMode);
/* DMA2D OOR register configuration ------------------------------------------*/
LL_DMA2D_SetLineOffset(DMA2Dx, DMA2D_InitStruct->LineOffset);
/* DMA2D NLR register configuration ------------------------------------------*/
LL_DMA2D_ConfigSize(DMA2Dx, DMA2D_InitStruct->NbrOfLines, DMA2D_InitStruct->NbrOfPixelsPerLines);
/* DMA2D OMAR register configuration ------------------------------------------*/
LL_DMA2D_SetOutputMemAddr(DMA2Dx, DMA2D_InitStruct->OutputMemoryAddress);
/* DMA2D OCOLR register configuration ------------------------------------------*/
DMA2D_ColorStruct.ColorMode = DMA2D_InitStruct->ColorMode;
DMA2D_ColorStruct.OutputBlue = DMA2D_InitStruct->OutputBlue;
DMA2D_ColorStruct.OutputGreen = DMA2D_InitStruct->OutputGreen;
DMA2D_ColorStruct.OutputRed = DMA2D_InitStruct->OutputRed;
DMA2D_ColorStruct.OutputAlpha = DMA2D_InitStruct->OutputAlpha;
LL_DMA2D_ConfigOutputColor(DMA2Dx, &DMA2D_ColorStruct);
status = SUCCESS;
}
/* If DMA2D transfers are not disabled, return ERROR */
return (status);
}
/**
* @brief Set each @ref LL_DMA2D_InitTypeDef field to default value.
* @param DMA2D_InitStruct pointer to a @ref LL_DMA2D_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_DMA2D_StructInit(LL_DMA2D_InitTypeDef *DMA2D_InitStruct)
{
/* Set DMA2D_InitStruct fields to default values */
DMA2D_InitStruct->Mode = LL_DMA2D_MODE_M2M;
DMA2D_InitStruct->ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB8888;
DMA2D_InitStruct->NbrOfLines = 0x0U;
DMA2D_InitStruct->NbrOfPixelsPerLines = 0x0U;
DMA2D_InitStruct->LineOffset = 0x0U;
DMA2D_InitStruct->OutputBlue = 0x0U;
DMA2D_InitStruct->OutputGreen = 0x0U;
DMA2D_InitStruct->OutputRed = 0x0U;
DMA2D_InitStruct->OutputAlpha = 0x0U;
DMA2D_InitStruct->OutputMemoryAddress = 0x0U;
}
/**
* @brief Configure the foreground or background according to the specified parameters
* in the LL_DMA2D_LayerCfgTypeDef structure.
* @param DMA2Dx DMA2D Instance
* @param DMA2D_LayerCfg pointer to a LL_DMA2D_LayerCfgTypeDef structure that contains
* the configuration information for the specified layer.
* @param LayerIdx DMA2D Layer index.
* This parameter can be one of the following values:
* 0(background) / 1(foreground)
* @retval None
*/
void LL_DMA2D_ConfigLayer(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg, uint32_t LayerIdx)
{
/* Check the parameters */
assert_param(IS_LL_DMA2D_OFFSET(DMA2D_LayerCfg->LineOffset));
assert_param(IS_LL_DMA2D_LCMODE(DMA2D_LayerCfg->ColorMode));
assert_param(IS_LL_DMA2D_CLUTCMODE(DMA2D_LayerCfg->CLUTColorMode));
assert_param(IS_LL_DMA2D_CLUTSIZE(DMA2D_LayerCfg->CLUTSize));
assert_param(IS_LL_DMA2D_ALPHAMODE(DMA2D_LayerCfg->AlphaMode));
assert_param(IS_LL_DMA2D_GREEN(DMA2D_LayerCfg->Green));
assert_param(IS_LL_DMA2D_RED(DMA2D_LayerCfg->Red));
assert_param(IS_LL_DMA2D_BLUE(DMA2D_LayerCfg->Blue));
assert_param(IS_LL_DMA2D_ALPHA(DMA2D_LayerCfg->Alpha));
if (LayerIdx == 0U)
{
/* Configure the background memory address */
LL_DMA2D_BGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress);
/* Configure the background line offset */
LL_DMA2D_BGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset);
/* Configure the background Alpha value, Alpha mode, CLUT size, CLUT Color mode and Color mode */
MODIFY_REG(DMA2Dx->BGPFCCR, \
(DMA2D_BGPFCCR_ALPHA | DMA2D_BGPFCCR_AM | DMA2D_BGPFCCR_CS | DMA2D_BGPFCCR_CCM | DMA2D_BGPFCCR_CM), \
((DMA2D_LayerCfg->Alpha << DMA2D_BGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->AlphaMode | \
(DMA2D_LayerCfg->CLUTSize << DMA2D_BGPFCCR_CS_Pos) | DMA2D_LayerCfg->CLUTColorMode | \
DMA2D_LayerCfg->ColorMode));
/* Configure the background color */
LL_DMA2D_BGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue);
/* Configure the background CLUT memory address */
LL_DMA2D_BGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress);
}
else
{
/* Configure the foreground memory address */
LL_DMA2D_FGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress);
/* Configure the foreground line offset */
LL_DMA2D_FGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset);
/* Configure the foreground Alpha value, Alpha mode, CLUT size, CLUT Color mode and Color mode */
MODIFY_REG(DMA2Dx->FGPFCCR, \
(DMA2D_FGPFCCR_ALPHA | DMA2D_FGPFCCR_AM | DMA2D_FGPFCCR_CS | DMA2D_FGPFCCR_CCM | DMA2D_FGPFCCR_CM), \
((DMA2D_LayerCfg->Alpha << DMA2D_FGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->AlphaMode | \
(DMA2D_LayerCfg->CLUTSize << DMA2D_FGPFCCR_CS_Pos) | DMA2D_LayerCfg->CLUTColorMode | \
DMA2D_LayerCfg->ColorMode));
/* Configure the foreground color */
LL_DMA2D_FGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue);
/* Configure the foreground CLUT memory address */
LL_DMA2D_FGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress);
}
}
/**
* @brief Set each @ref LL_DMA2D_LayerCfgTypeDef field to default value.
* @param DMA2D_LayerCfg pointer to a @ref LL_DMA2D_LayerCfgTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_DMA2D_LayerCfgStructInit(LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg)
{
/* Set DMA2D_LayerCfg fields to default values */
DMA2D_LayerCfg->MemoryAddress = 0x0U;
DMA2D_LayerCfg->ColorMode = LL_DMA2D_INPUT_MODE_ARGB8888;
DMA2D_LayerCfg->LineOffset = 0x0U;
DMA2D_LayerCfg->CLUTColorMode = LL_DMA2D_CLUT_COLOR_MODE_ARGB8888;
DMA2D_LayerCfg->CLUTSize = 0x0U;
DMA2D_LayerCfg->AlphaMode = LL_DMA2D_ALPHA_MODE_NO_MODIF;
DMA2D_LayerCfg->Alpha = 0x0U;
DMA2D_LayerCfg->Blue = 0x0U;
DMA2D_LayerCfg->Green = 0x0U;
DMA2D_LayerCfg->Red = 0x0U;
DMA2D_LayerCfg->CLUTMemoryAddress = 0x0U;
}
/**
* @brief Initialize DMA2D output color register according to the specified parameters
* in DMA2D_ColorStruct.
* @param DMA2Dx DMA2D Instance
* @param DMA2D_ColorStruct pointer to a LL_DMA2D_ColorTypeDef structure that contains
* the color configuration information for the specified DMA2D peripheral.
* @retval None
*/
void LL_DMA2D_ConfigOutputColor(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_ColorTypeDef *DMA2D_ColorStruct)
{
uint32_t outgreen = 0U;
uint32_t outred = 0U;
uint32_t outalpha = 0U;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
assert_param(IS_LL_DMA2D_OCMODE(DMA2D_ColorStruct->ColorMode));
assert_param(IS_LL_DMA2D_GREEN(DMA2D_ColorStruct->OutputGreen));
assert_param(IS_LL_DMA2D_RED(DMA2D_ColorStruct->OutputRed));
assert_param(IS_LL_DMA2D_BLUE(DMA2D_ColorStruct->OutputBlue));
assert_param(IS_LL_DMA2D_ALPHA(DMA2D_ColorStruct->OutputAlpha));
/* DMA2D OCOLR register configuration ------------------------------------------*/
if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888)
{
outgreen = DMA2D_ColorStruct->OutputGreen << 8U;
outred = DMA2D_ColorStruct->OutputRed << 16U;
outalpha = DMA2D_ColorStruct->OutputAlpha << 24U;
}
else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888)
{
outgreen = DMA2D_ColorStruct->OutputGreen << 8U;
outred = DMA2D_ColorStruct->OutputRed << 16U;
outalpha = 0x00000000U;
}
else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)
{
outgreen = DMA2D_ColorStruct->OutputGreen << 5U;
outred = DMA2D_ColorStruct->OutputRed << 11U;
outalpha = 0x00000000U;
}
else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555)
{
outgreen = DMA2D_ColorStruct->OutputGreen << 5U;
outred = DMA2D_ColorStruct->OutputRed << 10U;
outalpha = DMA2D_ColorStruct->OutputAlpha << 15U;
}
else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */
{
outgreen = DMA2D_ColorStruct->OutputGreen << 4U;
outred = DMA2D_ColorStruct->OutputRed << 8U;
outalpha = DMA2D_ColorStruct->OutputAlpha << 12U;
}
LL_DMA2D_SetOutputColor(DMA2Dx, (outgreen | outred | DMA2D_ColorStruct->OutputBlue | outalpha));
}
/**
* @brief Return DMA2D output Blue color.
* @param DMA2Dx DMA2D Instance.
* @param ColorMode This parameter can be one of the following values:
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444
* @retval Output Blue color value between Min_Data=0 and Max_Data=0xFF
*/
uint32_t LL_DMA2D_GetOutputBlueColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode)
{
uint32_t color = 0U;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
assert_param(IS_LL_DMA2D_OCMODE(ColorMode));
/* DMA2D OCOLR register reading ------------------------------------------*/
if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU));
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU));
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU));
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU));
}
else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFU));
}
return color;
}
/**
* @brief Return DMA2D output Green color.
* @param DMA2Dx DMA2D Instance.
* @param ColorMode This parameter can be one of the following values:
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444
* @retval Output Green color value between Min_Data=0 and Max_Data=0xFF
*/
uint32_t LL_DMA2D_GetOutputGreenColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode)
{
uint32_t color = 0U;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
assert_param(IS_LL_DMA2D_OCMODE(ColorMode));
/* DMA2D OCOLR register reading ------------------------------------------*/
if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U);
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U);
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7E0U) >> 5U);
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x3E0U) >> 5U);
}
else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF0U) >> 4U);
}
return color;
}
/**
* @brief Return DMA2D output Red color.
* @param DMA2Dx DMA2D Instance.
* @param ColorMode This parameter can be one of the following values:
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444
* @retval Output Red color value between Min_Data=0 and Max_Data=0xFF
*/
uint32_t LL_DMA2D_GetOutputRedColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode)
{
uint32_t color = 0U;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
assert_param(IS_LL_DMA2D_OCMODE(ColorMode));
/* DMA2D OCOLR register reading ------------------------------------------*/
if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U);
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U);
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF800U) >> 11U);
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7C00U) >> 10U);
}
else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF00U) >> 8U);
}
return color;
}
/**
* @brief Return DMA2D output Alpha color.
* @param DMA2Dx DMA2D Instance.
* @param ColorMode This parameter can be one of the following values:
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888
* @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555
* @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444
* @retval Output Alpha color value between Min_Data=0 and Max_Data=0xFF
*/
uint32_t LL_DMA2D_GetOutputAlphaColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode)
{
uint32_t color = 0U;
/* Check the parameters */
assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx));
assert_param(IS_LL_DMA2D_OCMODE(ColorMode));
/* DMA2D OCOLR register reading ------------------------------------------*/
if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF000000U) >> 24U);
}
else if ((ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) || (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565))
{
color = 0x0U;
}
else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555)
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x8000U) >> 15U);
}
else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */
{
color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF000U) >> 12U);
}
return color;
}
/**
* @brief Configure DMA2D transfer size.
* @param DMA2Dx DMA2D Instance
* @param NbrOfLines Value between Min_Data=0 and Max_Data=0xFFFF
* @param NbrOfPixelsPerLines Value between Min_Data=0 and Max_Data=0x3FFF
* @retval None
*/
void LL_DMA2D_ConfigSize(DMA2D_TypeDef *DMA2Dx, uint32_t NbrOfLines, uint32_t NbrOfPixelsPerLines)
{
MODIFY_REG(DMA2Dx->NLR, (DMA2D_NLR_PL | DMA2D_NLR_NL), \
((NbrOfPixelsPerLines << DMA2D_NLR_PL_Pos) | NbrOfLines));
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (DMA2D) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"pile_set_name": "Github"
} |
/*
* linux/drivers/video/clps711xfb.c
*
* Copyright (C) 2000-2001 Deep Blue Solutions Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Framebuffer driver for the CLPS7111 and EP7212 processors.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <linux/uaccess.h>
#include <asm/hardware/clps7111.h>
#include <mach/syspld.h>
struct fb_info *cfb;
#define CMAP_MAX_SIZE 16
/* The /proc entry for the backlight. */
static struct proc_dir_entry *clps7111fb_backlight_proc_entry = NULL;
static int clps7111fb_proc_backlight_read(char *page, char **start, off_t off,
int count, int *eof, void *data);
static int clps7111fb_proc_backlight_write(struct file *file,
const char *buffer, unsigned long count, void *data);
/*
* LCD AC Prescale. This comes from the LCD panel manufacturers specifications.
* This determines how many clocks + 1 of CL1 before the M signal toggles.
* The number of lines on the display must not be divisible by this number.
*/
static unsigned int lcd_ac_prescale = 13;
/*
* Set a single color register. Return != 0 for invalid regno.
*/
static int
clps7111fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
unsigned int level, mask, shift, pal;
if (regno >= (1 << info->var.bits_per_pixel))
return 1;
/* gray = 0.30*R + 0.58*G + 0.11*B */
level = (red * 77 + green * 151 + blue * 28) >> 20;
/*
* On an LCD, a high value is dark, while a low value is light.
* So we invert the level.
*
* This isn't true on all machines, so we only do it on EDB7211.
* --rmk
*/
if (machine_is_edb7211()) {
level = 15 - level;
}
shift = 4 * (regno & 7);
level <<= shift;
mask = 15 << shift;
level &= mask;
regno = regno < 8 ? PALLSW : PALMSW;
pal = clps_readl(regno);
pal = (pal & ~mask) | level;
clps_writel(pal, regno);
return 0;
}
/*
* Validate the purposed mode.
*/
static int
clps7111fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
var->transp.msb_right = 0;
var->transp.offset = 0;
var->transp.length = 0;
var->red.msb_right = 0;
var->red.offset = 0;
var->red.length = var->bits_per_pixel;
var->green = var->red;
var->blue = var->red;
if (var->bits_per_pixel > 4)
return -EINVAL;
return 0;
}
/*
* Set the hardware state.
*/
static int
clps7111fb_set_par(struct fb_info *info)
{
unsigned int lcdcon, syscon, pixclock;
switch (info->var.bits_per_pixel) {
case 1:
info->fix.visual = FB_VISUAL_MONO01;
break;
case 2:
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
case 4:
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
}
info->fix.line_length = info->var.xres_virtual * info->var.bits_per_pixel / 8;
lcdcon = (info->var.xres_virtual * info->var.yres_virtual * info->var.bits_per_pixel) / 128 - 1;
lcdcon |= ((info->var.xres_virtual / 16) - 1) << 13;
lcdcon |= lcd_ac_prescale << 25;
/*
* Calculate pixel prescale value from the pixclock. This is:
* 36.864MHz / pixclock_mhz - 1.
* However, pixclock is in picoseconds, so this ends up being:
* 36864000 * pixclock_ps / 10^12 - 1
* and this will overflow the 32-bit math. We perform this as
* (9 * 4096000 == 36864000):
* pixclock_ps * 9 * (4096000 / 10^12) - 1
*/
pixclock = 9 * info->var.pixclock / 244140 - 1;
lcdcon |= pixclock << 19;
if (info->var.bits_per_pixel == 4)
lcdcon |= LCDCON_GSMD;
if (info->var.bits_per_pixel >= 2)
lcdcon |= LCDCON_GSEN;
/*
* LCDCON must only be changed while the LCD is disabled
*/
syscon = clps_readl(SYSCON1);
clps_writel(syscon & ~SYSCON1_LCDEN, SYSCON1);
clps_writel(lcdcon, LCDCON);
clps_writel(syscon | SYSCON1_LCDEN, SYSCON1);
return 0;
}
static int clps7111fb_blank(int blank, struct fb_info *info)
{
if (blank) {
if (machine_is_edb7211()) {
/* Turn off the LCD backlight. */
clps_writeb(clps_readb(PDDR) & ~EDB_PD3_LCDBL, PDDR);
/* Power off the LCD DC-DC converter. */
clps_writeb(clps_readb(PDDR) & ~EDB_PD1_LCD_DC_DC_EN, PDDR);
/* Delay for a little while (half a second). */
udelay(100);
/* Power off the LCD panel. */
clps_writeb(clps_readb(PDDR) & ~EDB_PD2_LCDEN, PDDR);
/* Power off the LCD controller. */
clps_writel(clps_readl(SYSCON1) & ~SYSCON1_LCDEN,
SYSCON1);
}
} else {
if (machine_is_edb7211()) {
/* Power up the LCD controller. */
clps_writel(clps_readl(SYSCON1) | SYSCON1_LCDEN,
SYSCON1);
/* Power up the LCD panel. */
clps_writeb(clps_readb(PDDR) | EDB_PD2_LCDEN, PDDR);
/* Delay for a little while. */
udelay(100);
/* Power up the LCD DC-DC converter. */
clps_writeb(clps_readb(PDDR) | EDB_PD1_LCD_DC_DC_EN,
PDDR);
/* Turn on the LCD backlight. */
clps_writeb(clps_readb(PDDR) | EDB_PD3_LCDBL, PDDR);
}
}
return 0;
}
static struct fb_ops clps7111fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = clps7111fb_check_var,
.fb_set_par = clps7111fb_set_par,
.fb_setcolreg = clps7111fb_setcolreg,
.fb_blank = clps7111fb_blank,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static int
clps7111fb_proc_backlight_read(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
/* We need at least two characters, one for the digit, and one for
* the terminating NULL. */
if (count < 2)
return -EINVAL;
if (machine_is_edb7211()) {
return sprintf(page, "%d\n",
(clps_readb(PDDR) & EDB_PD3_LCDBL) ? 1 : 0);
}
return 0;
}
static int
clps7111fb_proc_backlight_write(struct file *file, const char *buffer,
unsigned long count, void *data)
{
unsigned char char_value;
int value;
if (count < 1) {
return -EINVAL;
}
if (copy_from_user(&char_value, buffer, 1))
return -EFAULT;
value = char_value - '0';
if (machine_is_edb7211()) {
unsigned char port_d;
port_d = clps_readb(PDDR);
if (value) {
port_d |= EDB_PD3_LCDBL;
} else {
port_d &= ~EDB_PD3_LCDBL;
}
clps_writeb(port_d, PDDR);
}
return count;
}
static void __init clps711x_guess_lcd_params(struct fb_info *info)
{
unsigned int lcdcon, syscon, size;
unsigned long phys_base = PAGE_OFFSET;
void *virt_base = (void *)PAGE_OFFSET;
info->var.xres_virtual = 640;
info->var.yres_virtual = 240;
info->var.bits_per_pixel = 4;
info->var.activate = FB_ACTIVATE_NOW;
info->var.height = -1;
info->var.width = -1;
info->var.pixclock = 93006; /* 10.752MHz pixel clock */
/*
* If the LCD controller is already running, decode the values
* in LCDCON to xres/yres/bpp/pixclock/acprescale
*/
syscon = clps_readl(SYSCON1);
if (syscon & SYSCON1_LCDEN) {
lcdcon = clps_readl(LCDCON);
/*
* Decode GSMD and GSEN bits to bits per pixel
*/
switch (lcdcon & (LCDCON_GSMD | LCDCON_GSEN)) {
case LCDCON_GSMD | LCDCON_GSEN:
info->var.bits_per_pixel = 4;
break;
case LCDCON_GSEN:
info->var.bits_per_pixel = 2;
break;
default:
info->var.bits_per_pixel = 1;
break;
}
/*
* Decode xres/yres
*/
info->var.xres_virtual = (((lcdcon >> 13) & 0x3f) + 1) * 16;
info->var.yres_virtual = (((lcdcon & 0x1fff) + 1) * 128) /
(info->var.xres_virtual *
info->var.bits_per_pixel);
/*
* Calculate pixclock
*/
info->var.pixclock = (((lcdcon >> 19) & 0x3f) + 1) * 244140 / 9;
/*
* Grab AC prescale
*/
lcd_ac_prescale = (lcdcon >> 25) & 0x1f;
}
info->var.xres = info->var.xres_virtual;
info->var.yres = info->var.yres_virtual;
info->var.grayscale = info->var.bits_per_pixel > 1;
size = info->var.xres * info->var.yres * info->var.bits_per_pixel / 8;
/*
* Might be worth checking to see if we can use the on-board
* RAM if size here...
* CLPS7110 - no on-board SRAM
* EP7212 - 38400 bytes
*/
if (size <= 38400) {
printk(KERN_INFO "CLPS711xFB: could use on-board SRAM?\n");
}
if ((syscon & SYSCON1_LCDEN) == 0) {
/*
* The display isn't running. Ensure that
* the display memory is empty.
*/
memset(virt_base, 0, size);
}
info->screen_base = virt_base;
info->fix.smem_start = phys_base;
info->fix.smem_len = PAGE_ALIGN(size);
info->fix.type = FB_TYPE_PACKED_PIXELS;
}
int __init clps711xfb_init(void)
{
int err = -ENOMEM;
if (fb_get_options("clps711xfb", NULL))
return -ENODEV;
cfb = kzalloc(sizeof(*cfb), GFP_KERNEL);
if (!cfb)
goto out;
strcpy(cfb->fix.id, "clps711x");
cfb->fbops = &clps7111fb_ops;
cfb->flags = FBINFO_DEFAULT;
clps711x_guess_lcd_params(cfb);
fb_alloc_cmap(&cfb->cmap, CMAP_MAX_SIZE, 0);
/* Register the /proc entries. */
clps7111fb_backlight_proc_entry = create_proc_entry("backlight", 0444,
NULL);
if (clps7111fb_backlight_proc_entry == NULL) {
printk("Couldn't create the /proc entry for the backlight.\n");
return -EINVAL;
}
clps7111fb_backlight_proc_entry->read_proc =
&clps7111fb_proc_backlight_read;
clps7111fb_backlight_proc_entry->write_proc =
&clps7111fb_proc_backlight_write;
/*
* Power up the LCD
*/
if (machine_is_p720t()) {
PLD_LCDEN = PLD_LCDEN_EN;
PLD_PWR |= (PLD_S4_ON|PLD_S3_ON|PLD_S2_ON|PLD_S1_ON);
}
if (machine_is_edb7211()) {
/* Power up the LCD panel. */
clps_writeb(clps_readb(PDDR) | EDB_PD2_LCDEN, PDDR);
/* Delay for a little while. */
udelay(100);
/* Power up the LCD DC-DC converter. */
clps_writeb(clps_readb(PDDR) | EDB_PD1_LCD_DC_DC_EN, PDDR);
/* Turn on the LCD backlight. */
clps_writeb(clps_readb(PDDR) | EDB_PD3_LCDBL, PDDR);
}
err = register_framebuffer(cfb);
out: return err;
}
static void __exit clps711xfb_exit(void)
{
unregister_framebuffer(cfb);
kfree(cfb);
/*
* Power down the LCD
*/
if (machine_is_p720t()) {
PLD_LCDEN = 0;
PLD_PWR &= ~(PLD_S4_ON|PLD_S3_ON|PLD_S2_ON|PLD_S1_ON);
}
}
module_init(clps711xfb_init);
module_exit(clps711xfb_exit);
MODULE_AUTHOR("Russell King <rmk@arm.linux.org.uk>");
MODULE_DESCRIPTION("CLPS711x framebuffer driver");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
#ifndef TESTS_HPP_
#define TESTS_HPP_
void runAllTests();
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) Internet Systems Consortium, Inc. ("ISC")
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
*
* See the COPYRIGHT file distributed with this work for additional
* information regarding copyright ownership.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <isc/errno.h>
#include <isc/glob.h>
#include <isc/print.h>
#include <isc/result.h>
#include <isc/types.h>
#include <isc/util.h>
#if HAVE_GLOB_H
#include <glob.h>
#elif defined(_WIN32)
#include <stdlib.h>
#include <windows.h>
#include <isc/list.h>
#define GLOB_ERR 0x0004 /* Return on error. */
#define GLOB_NOSPACE (-1)
#define GLOB_NOMATCH (-3)
/* custom glob implementation for windows */
static int
glob(const char *pattern, int flags, void *unused, glob_t *pglob);
static void
globfree(glob_t *pglob);
#else
#error "Required header missing: glob.h"
#endif
isc_result_t
isc_glob(const char *pattern, glob_t *pglob) {
REQUIRE(pattern != NULL);
REQUIRE(*pattern != '\0');
REQUIRE(pglob != NULL);
int rc = glob(pattern, GLOB_ERR, NULL, pglob);
switch (rc) {
case 0:
return (ISC_R_SUCCESS);
case GLOB_NOMATCH:
return (ISC_R_FILENOTFOUND);
case GLOB_NOSPACE:
return (ISC_R_NOMEMORY);
default:
return (errno != 0 ? isc_errno_toresult(errno) : ISC_R_IOERROR);
}
}
void
isc_globfree(glob_t *pglob) {
REQUIRE(pglob != NULL);
globfree(pglob);
}
#if defined(_WIN32)
typedef struct file_path file_path_t;
struct file_path {
char *path;
ISC_LINK(file_path_t) link;
};
typedef ISC_LIST(file_path_t) file_list_t;
/* map a winapi error to a convenient errno code */
static int
map_error(DWORD win_err_code) {
switch (win_err_code) {
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
return (GLOB_NOMATCH);
case ERROR_ACCESS_DENIED:
return (EACCES);
case ERROR_NOT_ENOUGH_MEMORY:
return (GLOB_NOSPACE);
default:
return (EIO);
}
}
/* add file in directory dir, that matches glob expression
* provided in function glob(), to the linked list fl */
static void
append_file(isc_mem_t *mctx, file_list_t *fl, const char *dir, const char *file,
size_t full_path_len) {
file_path_t *fp = isc_mem_get(mctx, sizeof(file_path_t));
fp->path = isc_mem_get(mctx, full_path_len + 1);
_snprintf(fp->path, full_path_len + 1, "%s%s", dir, file);
ISC_LINK_INIT(fp, link);
ISC_LIST_PREPEND(*fl, fp, link);
}
/* sort files alphabetically case insensitive on windows */
static int
path_cmp(const void *path1, const void *path2) {
return _stricmp((const char *)path1, (const char *)path2);
}
static int
glob(const char *pattern, int flags, void *unused, glob_t *pglob) {
char path[MAX_PATH];
WIN32_FIND_DATAA find_data;
int ec;
HANDLE hnd;
REQUIRE(pattern != NULL);
REQUIRE(pglob != NULL);
UNUSED(flags);
UNUSED(unused);
pglob->mctx = NULL;
pglob->gl_pathc = 0;
pglob->gl_pathv = NULL;
hnd = FindFirstFileA(pattern, &find_data);
if (hnd == INVALID_HANDLE_VALUE) {
return (map_error(GetLastError()));
}
path[MAX_PATH - 1] = 0;
strncpy(path, pattern, MAX_PATH);
if (path[MAX_PATH - 1] != 0) {
errno = ENAMETOOLONG;
goto fail;
}
// strip filename from path.
size_t dir_len = strlen(path);
while (dir_len > 0 && path[dir_len - 1] != '/' &&
path[dir_len - 1] != '\\') {
dir_len--;
}
path[dir_len] = '\0';
isc_mem_create(&pglob->mctx);
pglob->reserved = isc_mem_get(pglob->mctx, sizeof(file_list_t));
ISC_LIST_INIT(*(file_list_t *)pglob->reserved);
size_t entries = 0;
do {
size_t file_len = strlen(find_data.cFileName);
size_t full_path_len = dir_len + file_len;
if (full_path_len > MAX_PATH) {
errno = ENAMETOOLONG;
goto fail;
}
append_file(pglob->mctx, (file_list_t *)pglob->reserved, path,
find_data.cFileName, full_path_len);
entries++;
} while (FindNextFileA(hnd, &find_data));
FindClose(hnd);
pglob->gl_pathv = isc_mem_get(pglob->mctx,
(entries + 1) * sizeof(char *));
pglob->gl_pathv[entries] = NULL;
pglob->gl_pathc = entries;
file_list_t *fl = (file_list_t *)pglob->reserved;
size_t e = 0;
file_path_t *fp;
for (fp = ISC_LIST_HEAD(*fl); fp != NULL; fp = ISC_LIST_NEXT(fp, link))
{
pglob->gl_pathv[e++] = fp->path;
}
qsort(pglob->gl_pathv, pglob->gl_pathc, sizeof(char *), path_cmp);
return (0);
fail:
ec = errno;
FindClose(hnd);
if (pglob->mctx) {
globfree(pglob);
}
return ec;
}
void
globfree(glob_t *pglob) {
REQUIRE(pglob != NULL);
REQUIRE(pglob->mctx != NULL);
/* first free memory used by char ** gl_pathv */
if (pglob->gl_pathv) {
isc_mem_put(pglob->mctx, pglob->gl_pathv,
(pglob->gl_pathc + 1) * sizeof(char *));
pglob->gl_pathv = NULL;
}
file_list_t *fl = (file_list_t *)pglob->reserved;
file_path_t *p, *next;
/* next free each individual file path string + nodes in list */
for (p = ISC_LIST_HEAD(*fl); p != NULL; p = next) {
next = ISC_LIST_NEXT(p, link);
isc_mem_put(pglob->mctx, p->path, strlen(p->path) + 1);
isc_mem_put(pglob->mctx, p, sizeof(file_path_t));
}
/* free linked list of files */
isc_mem_put(pglob->mctx, pglob->reserved, sizeof(file_list_t));
pglob->reserved = NULL;
pglob->gl_pathc = 0;
pglob->gl_pathv = NULL;
isc_mem_destroy(&pglob->mctx);
pglob->mctx = NULL;
}
#endif /* defined(_WIN32) */
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="@string/sync_account_type"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:smallIcon="@mipmap/ic_launcher" /> | {
"pile_set_name": "Github"
} |
[crowdin.project]
projectid = "ext-SpecialDiscussions"
product_person = "cristina"
format = "mediawiki"
source.file = "SpecialDiscussions.i18n.php"
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Web.Http.Controllers;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using Abp.Collections.Extensions;
using Abp.Reflection;
using Abp.Web;
using Abp.WebApi.Configuration;
using Abp.Extensions;
namespace Abp.WebApi.Controllers.Dynamic.Selectors
{
internal static class DynamicApiDescriptorHelper
{
internal static ReadOnlyCollection<T> FilterType<T>(object[] objects) where T : class
{
int max = objects.Length;
List<T> list = new List<T>(max);
int idx = 0;
for (int i = 0; i < max; i++)
{
T attr = objects[i] as T;
if (attr != null)
{
list.Add(attr);
idx++;
}
}
list.Capacity = idx;
return new ReadOnlyCollection<T>(list);
}
}
public class DynamicHttpActionDescriptor : ReflectedHttpActionDescriptor
{
public override Collection<HttpMethod> SupportedHttpMethods { get; }
private readonly DynamicApiActionInfo _actionInfo;
private readonly Lazy<Collection<IFilter>> _filters;
private readonly Lazy<Collection<HttpParameterDescriptor>> _parameters;
private readonly object[] _attributes;
private readonly object[] _declaredOnlyAttributes;
public DynamicHttpActionDescriptor(
IAbpWebApiConfiguration configuration,
HttpControllerDescriptor controllerDescriptor,
DynamicApiActionInfo actionInfo)
: base(
controllerDescriptor,
actionInfo.Method)
{
_actionInfo = actionInfo;
SupportedHttpMethods = new Collection<HttpMethod> { actionInfo.Verb.ToHttpMethod() };
Properties["__AbpDynamicApiActionInfo"] = actionInfo;
Properties["__AbpDynamicApiDontWrapResultAttribute"] =
ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
actionInfo.Method,
configuration.DefaultDynamicApiWrapResultAttribute
);
_filters = new Lazy<Collection<IFilter>>(GetFiltersInternal, true);
_parameters = new Lazy<Collection<HttpParameterDescriptor>>(GetParametersInternal, true);
_declaredOnlyAttributes = _actionInfo.Method.GetCustomAttributes(inherit: false);
_attributes = _actionInfo.Method.GetCustomAttributes(inherit: true);
}
/// <summary>
/// Overrides the GetFilters for the action and adds the Dynamic Action filters.
/// </summary>
/// <returns> The Collection of filters.</returns>
public override Collection<IFilter> GetFilters()
{
return _filters.Value;
}
public override Collection<T> GetCustomAttributes<T>(bool inherit)
{
object[] attributes = inherit ? _attributes : _declaredOnlyAttributes;
return new Collection<T>(DynamicApiDescriptorHelper.FilterType<T>(attributes));
}
public override Collection<HttpParameterDescriptor> GetParameters()
{
return _parameters.Value;
}
private Collection<IFilter> GetFiltersInternal()
{
if (_actionInfo.Filters.IsNullOrEmpty())
{
return base.GetFilters();
}
var actionFilters = new Collection<IFilter>();
foreach (var filter in _actionInfo.Filters)
{
actionFilters.Add(filter);
}
foreach (var baseFilter in base.GetFilters())
{
actionFilters.Add(baseFilter);
}
return actionFilters;
}
private Collection<HttpParameterDescriptor> GetParametersInternal()
{
var parameters = base.GetParameters();
if (_actionInfo.Verb.IsIn(HttpVerb.Get, HttpVerb.Head))
{
foreach (var parameter in parameters)
{
if (parameter.ParameterBinderAttribute == null)
{
parameter.ParameterBinderAttribute = new FromUriAttribute();
}
}
}
return parameters;
}
}
} | {
"pile_set_name": "Github"
} |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal class EXPRUSERLOGOP : EXPR
{
public EXPR TrueFalseCall;
public EXPRCALL OperatorCall;
public EXPR FirstOperandToExamine;
}
}
| {
"pile_set_name": "Github"
} |
// Vigil
//
// Microservices Status Page
// Copyright: 2018, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)
use std::iter::FromIterator;
use std::thread;
use std::time::{Duration, SystemTime};
use time;
use crate::notifier::generic::Notification;
use crate::prober::manager::STORE as PROBER_STORE;
use crate::prober::mode::Mode;
use crate::prober::status::Status;
use crate::APP_CONF;
#[cfg(feature = "notifier-email")]
use crate::notifier::email::EmailNotifier;
#[cfg(feature = "notifier-twilio")]
use crate::notifier::twilio::TwilioNotifier;
#[cfg(feature = "notifier-slack")]
use crate::notifier::slack::SlackNotifier;
#[cfg(feature = "notifier-telegram")]
use crate::notifier::telegram::TelegramNotifier;
#[cfg(feature = "notifier-pushover")]
use crate::notifier::pushover::PushoverNotifier;
#[cfg(feature = "notifier-xmpp")]
use crate::notifier::xmpp::XMPPNotifier;
#[cfg(feature = "notifier-webhook")]
use crate::notifier::webhook::WebHookNotifier;
const AGGREGATE_INTERVAL_SECONDS: u64 = 10;
struct BumpedStates {
status: Status,
replicas: Vec<String>,
changed: bool,
startup: bool,
}
fn check_child_status(parent_status: &Status, child_status: &Status) -> Option<Status> {
if child_status == &Status::Dead {
Some(Status::Dead)
} else if child_status == &Status::Sick && parent_status != &Status::Dead {
Some(Status::Sick)
} else {
None
}
}
fn scan_and_bump_states() -> Option<BumpedStates> {
let mut bumped_replicas = Vec::new();
let mut store = PROBER_STORE.write().unwrap();
let mut general_status = Status::Healthy;
for (probe_id, probe) in store.states.probes.iter_mut() {
debug!("aggregate probe: {}", probe_id);
let mut probe_status = Status::Healthy;
for (node_id, node) in probe.nodes.iter_mut() {
debug!("aggregate node: {}:{}", probe_id, node_id);
let mut node_status = Status::Healthy;
for (replica_id, replica) in node.replicas.iter_mut() {
let mut replica_status = Status::Healthy;
// Process metrics
match node.mode {
Mode::Push => {
// Compare delays and compute a new status?
if let Some(ref replica_report) = replica.report {
if let Ok(duration_since_report) =
SystemTime::now().duration_since(replica_report.time)
{
if duration_since_report
>= (replica_report.interval
+ Duration::from_secs(APP_CONF.metrics.push_delay_dead))
{
debug!(
"replica: {}:{}:{} is dead because it didnt report in a while",
probe_id, node_id, replica_id
);
replica_status = Status::Dead;
}
}
}
// Compare system load indices and compute a new status?
if replica_status == Status::Healthy {
if let Some(ref replica_load) = replica.load {
if (replica_load.cpu > APP_CONF.metrics.push_system_cpu_sick_above)
|| (replica_load.ram
> APP_CONF.metrics.push_system_ram_sick_above)
{
debug!(
"replica: {}:{}:{} is sick because it is overloaded",
probe_id, node_id, replica_id
);
replica_status = Status::Sick;
}
}
}
// Check RabbitMQ queue full marker?
if replica_status == Status::Healthy {
if let Some(ref replica_load) = replica.load {
if replica_load.queue.stalled == true {
replica_status = Status::Dead;
} else if replica_load.queue.loaded == true {
replica_status = Status::Sick;
}
}
}
}
Mode::Local => {
// Assign stored status by default ('local' nodes report their status \
// themselves)
replica_status = replica.status.to_owned();
// Compare delays and compute a new status?
if let Some(ref replica_report) = replica.report {
if let Ok(duration_since_report) =
SystemTime::now().duration_since(replica_report.time)
{
if duration_since_report
>= (replica_report.interval
+ Duration::from_secs(APP_CONF.metrics.local_delay_dead))
{
debug!(
"replica: {}:{}:{} is dead because it didnt report in a while",
probe_id, node_id, replica_id
);
replica_status = Status::Dead;
}
}
}
}
_ => {
// Forward stored status (eg. 'poll' or 'script' nodes)
replica_status = replica.status.to_owned();
}
}
// Bump node status with worst replica status?
if let Some(worst_status) = check_child_status(&node_status, &replica_status) {
node_status = worst_status;
}
debug!(
"aggregated status for replica: {}:{}:{} => {:?}",
probe_id, node_id, replica_id, replica_status
);
// Append bumped replica path?
if replica_status == Status::Dead {
bumped_replicas.push(format!("{}:{}:{}", probe_id, node_id, replica_id));
}
replica.status = replica_status;
}
// Bump probe status with worst node status?
if let Some(worst_status) = check_child_status(&probe_status, &node_status) {
probe_status = worst_status;
}
debug!(
"aggregated status for node: {}:{} => {:?}",
probe_id, node_id, node_status
);
node.status = node_status;
}
// Bump general status with worst node status?
if let Some(worst_status) = check_child_status(&general_status, &probe_status) {
general_status = worst_status;
}
debug!(
"aggregated status for probe: {} => {:?}",
probe_id, probe_status
);
probe.status = probe_status;
}
// Check if general status has changed
let has_changed = store.states.status != general_status;
// Check if should dispatch notification later (only if critical)
// Allow for cases:
// - healthy >> dead
// - sick >> dead
// - dead >> sick
// - dead >> healthy
let mut should_notify = (store.states.status != Status::Dead && general_status == Status::Dead)
|| (store.states.status == Status::Dead && general_status != Status::Dead);
// Check if should re-notify? (in case status did not change; only if dead)
// Notice: this is used to send periodic reminders of downtime (ie. 'still down' messages)
if has_changed == false && should_notify == false && general_status == Status::Dead {
debug!("status unchanged, but may need to re-notify; checking");
if let Some(ref notify) = APP_CONF.notify {
match (store.notified, notify.reminder_interval) {
(Some(last_notified), Some(reminder_interval)) => {
if let Ok(duration_since_notified) =
SystemTime::now().duration_since(last_notified)
{
// Duration since last notified exceeds reminder interval, should re-notify
if duration_since_notified >= Duration::from_secs(reminder_interval) {
info!("should re-notify about unchanged status");
should_notify = true
} else {
debug!(
"should not re-notify about unchanged status (interval: {})",
reminder_interval
);
}
}
}
_ => {}
}
}
}
// Bump stored values
store.states.status = general_status.to_owned();
if let Ok(time_string) = time_now_as_string() {
store.states.date = Some(time_string);
}
if should_notify == true {
store.notified = Some(SystemTime::now());
Some(BumpedStates {
status: general_status,
replicas: bumped_replicas,
changed: has_changed,
startup: false,
})
} else {
None
}
}
fn time_now_as_string() -> Result<String, ()> {
time::strftime("%H:%M:%S UTC%z", &time::now()).or(Err(()))
}
fn dispatch_startup_notification() {
if let Some(ref conf_notify) = APP_CONF.notify {
if conf_notify.startup_notification == true {
debug!("sending aggregate startup notification...");
notify(&BumpedStates {
status: Status::Healthy,
replicas: Vec::new(),
changed: true,
startup: true,
});
}
}
}
fn notify(bumped_states: &BumpedStates) {
let notification = Notification {
status: &bumped_states.status,
time: time_now_as_string().unwrap_or("".to_string()),
replicas: Vec::from_iter(bumped_states.replicas.iter().map(String::as_str)),
changed: bumped_states.changed,
startup: bumped_states.startup,
};
if let Some(ref notify) = APP_CONF.notify {
#[cfg(feature = "notifier-email")]
Notification::dispatch::<EmailNotifier>(notify, ¬ification).ok();
#[cfg(feature = "notifier-twilio")]
Notification::dispatch::<TwilioNotifier>(notify, ¬ification).ok();
#[cfg(feature = "notifier-slack")]
Notification::dispatch::<SlackNotifier>(notify, ¬ification).ok();
#[cfg(feature = "notifier-telegram")]
Notification::dispatch::<TelegramNotifier>(notify, ¬ification).ok();
#[cfg(feature = "notifier-pushover")]
Notification::dispatch::<PushoverNotifier>(notify, ¬ification).ok();
#[cfg(feature = "notifier-xmpp")]
Notification::dispatch::<XMPPNotifier>(notify, ¬ification).ok();
#[cfg(feature = "notifier-webhook")]
Notification::dispatch::<WebHookNotifier>(notify, ¬ification).ok();
}
}
pub fn run() {
// Notify that systems are healthy (when booting up aggregator)
dispatch_startup_notification();
// Start aggregate loop
loop {
debug!("running an aggregate operation...");
// Should notify after bump?
let bumped_states = scan_and_bump_states();
if let Some(ref bumped_states_inner) = bumped_states {
notify(bumped_states_inner);
}
info!(
"ran aggregate operation (notified: {})",
bumped_states.is_some()
);
// Hold for next aggregate run
thread::sleep(Duration::from_secs(AGGREGATE_INTERVAL_SECONDS));
}
}
| {
"pile_set_name": "Github"
} |
CREATE TABLE subjectId (
id int not null,
feature int not null,
PRIMARY KEY(id)
);
| {
"pile_set_name": "Github"
} |
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).
package nl.bzk.brp.model.data.lev;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import nl.bzk.brp.model.data.lev.Lev;
import org.springframework.transaction.annotation.Transactional;
privileged aspect Lev_Roo_Jpa_ActiveRecord {
@PersistenceContext
transient EntityManager Lev.entityManager;
public static final EntityManager Lev.entityManager() {
EntityManager em = new Lev().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long Lev.countLevs() {
return entityManager().createQuery("SELECT COUNT(o) FROM Lev o", Long.class).getSingleResult();
}
public static List<Lev> Lev.findAllLevs() {
return entityManager().createQuery("SELECT o FROM Lev o", Lev.class).getResultList();
}
public static Lev Lev.findLev(Long id) {
if (id == null) return null;
return entityManager().find(Lev.class, id);
}
public static List<Lev> Lev.findLevEntries(int firstResult, int maxResults) {
return entityManager().createQuery("SELECT o FROM Lev o", Lev.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
@Transactional
public void Lev.persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public void Lev.remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Lev attached = Lev.findLev(this.id);
this.entityManager.remove(attached);
}
}
@Transactional
public void Lev.flush() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.flush();
}
@Transactional
public void Lev.clear() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.clear();
}
@Transactional
public Lev Lev.merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Lev merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
}
| {
"pile_set_name": "Github"
} |
fun main() {
SOLAR_MASS = 4.0 * PI * PI;
let n = argv(0).toInt32().unwrap();
let bodies = NBodySystem();
var i = 0;
println(bodies.energy().toString());
while i < n {
bodies.advance(0.01);
i = i + 1;
}
println(bodies.energy().toString());
}
class NBodySystem {
let bodies: Array[Body] = Array::ofSizeUnsafe[Body](5L);
{
self.bodies(0L) = Body::sun();
self.bodies(1L) = Body::jupiter();
self.bodies(2L) = Body::saturn();
self.bodies(3L) = Body::uranus();
self.bodies(4L) = Body::neptune();
var px = 0.0;
var py = 0.0;
var pz = 0.0;
var i = 0L;
while i < self.bodies.size() {
px = px + self.bodies.get(i).vx * self.bodies.get(i).mass;
py = py + self.bodies.get(i).vy * self.bodies.get(i).mass;
pz = pz + self.bodies.get(i).vz * self.bodies.get(i).mass;
i = i + 1L;
}
self.bodies.get(0L).offsetMomentum(px, py, pz);
}
fun advance(dt: Float64) {
var i = 0L;
while i < self.bodies.size() {
let iBody = self.bodies.get(i);
var j = i + 1L;
while j < self.bodies.size() {
let dx = iBody.x - self.bodies.get(j).x;
let dy = iBody.y - self.bodies.get(j).y;
let dz = iBody.z - self.bodies.get(j).z;
let dSquared = dx * dx + dy * dy + dz * dz;
let distance = dSquared.sqrt();
let mag = dt / (dSquared * distance);
iBody.vx = iBody.vx - dx * self.bodies.get(j).mass * mag;
iBody.vy = iBody.vy - dy * self.bodies.get(j).mass * mag;
iBody.vz = iBody.vz - dz * self.bodies.get(j).mass * mag;
self.bodies.get(j).vx = self.bodies.get(j).vx + dx * iBody.mass * mag;
self.bodies.get(j).vy = self.bodies.get(j).vy + dy * iBody.mass * mag;
self.bodies.get(j).vz = self.bodies.get(j).vz + dz * iBody.mass * mag;
j = j + 1L;
}
i = i + 1L;
}
var i = 0L;
while i < self.bodies.size() {
let body = self.bodies.get(i);
body.x = body.x + dt * body.vx;
body.y = body.y + dt * body.vy;
body.z = body.z + dt * body.vz;
i = i + 1L;
}
}
fun energy(): Float64 {
var dx = 0.0;
var dy = 0.0;
var dz = 0.0;
var distance = 0.0;
var e = 0.0;
var i = 0L;
while i < self.bodies.size() {
let iBody = self.bodies.get(i);
e = e + 0.5 * iBody.mass *
( iBody.vx * iBody.vx
+ iBody.vy * iBody.vy
+ iBody.vz * iBody.vz );
var j = i+1L;
while j < self.bodies.size() {
let jBody = self.bodies.get(j);
dx = iBody.x - jBody.x;
dy = iBody.y - jBody.y;
dz = iBody.z - jBody.z;
distance = (dx*dx + dy*dy + dz*dz).sqrt();
e = e - (iBody.mass * jBody.mass) / distance;
j = j + 1L;
}
i = i + 1L;
}
return e;
}
}
const PI: Float64 = 3.141592653589793;
var SOLAR_MASS: Float64;
const DAYS_PER_YEAR: Float64 = 365.24;
class Body {
var x: Float64;
var y: Float64;
var z: Float64;
var vx: Float64;
var vy: Float64;
var vz: Float64;
var mass: Float64;
fun offsetMomentum(px: Float64, py: Float64, pz: Float64): Body {
self.vx = -px / SOLAR_MASS;
self.vy = -py / SOLAR_MASS;
self.vz = -pz / SOLAR_MASS;
return self;
}
}
module Body {
fun jupiter(): Body {
let p = Body();
p.x = 4.84143144246472090e+00;
p.y = -1.16032004402742839e+00;
p.z = -1.03622044471123109e-01;
p.vx = 1.66007664274403694e-03 * DAYS_PER_YEAR;
p.vy = 7.69901118419740425e-03 * DAYS_PER_YEAR;
p.vz = -6.90460016972063023e-05 * DAYS_PER_YEAR;
p.mass = 9.54791938424326609e-04 * SOLAR_MASS;
return p;
}
fun saturn(): Body {
let p = Body();
p.x = 8.34336671824457987e+00;
p.y = 4.12479856412430479e+00;
p.z = -4.03523417114321381e-01;
p.vx = -2.76742510726862411e-03 * DAYS_PER_YEAR;
p.vy = 4.99852801234917238e-03 * DAYS_PER_YEAR;
p.vz = 2.30417297573763929e-05 * DAYS_PER_YEAR;
p.mass = 2.85885980666130812e-04 * SOLAR_MASS;
return p;
}
fun uranus(): Body {
let p = Body();
p.x = 1.28943695621391310e+01;
p.y = -1.51111514016986312e+01;
p.z = -2.23307578892655734e-01;
p.vx = 2.96460137564761618e-03 * DAYS_PER_YEAR;
p.vy = 2.37847173959480950e-03 * DAYS_PER_YEAR;
p.vz = -2.96589568540237556e-05 * DAYS_PER_YEAR;
p.mass = 4.36624404335156298e-05 * SOLAR_MASS;
return p;
}
fun neptune(): Body {
let p = Body();
p.x = 1.53796971148509165e+01;
p.y = -2.59193146099879641e+01;
p.z = 1.79258772950371181e-01;
p.vx = 2.68067772490389322e-03 * DAYS_PER_YEAR;
p.vy = 1.62824170038242295e-03 * DAYS_PER_YEAR;
p.vz = -9.51592254519715870e-05 * DAYS_PER_YEAR;
p.mass = 5.15138902046611451e-05 * SOLAR_MASS;
return p;
}
fun sun(): Body {
let p = Body();
p.mass = SOLAR_MASS;
return p;
}
}
| {
"pile_set_name": "Github"
} |
//
// ofxGrtSettings.h
//
// Created by luca lolli on 11/08/2016.
// Updated: nickgillian: 26/09/2016
//
#include "ofxGrtSettings.h"
//We need to declare our static non-const variable after being definid in the header
std::shared_ptr<ofxGrtSettings::variables> ofxGrtSettings::mVariables;
ofTrueTypeFont ofxGrtSettings::variables::fontSmall;
ofTrueTypeFont ofxGrtSettings::variables::fontNormal;
ofTrueTypeFont ofxGrtSettings::variables::fontLarge;
std::string ofxGrtSettings::variables::fontFile = "verdana.ttf";
ofColor ofxGrtSettings::variables::activeTextColor = {255,255,255};
ofColor ofxGrtSettings::variables::gridColor = {64,64,64};
ofColor ofxGrtSettings::variables::axisColor = {192,192,192};
ofColor ofxGrtSettings::variables::backgroundColor = {0,0,0};
ofColor ofxGrtSettings::variables::disabledTextColor = {128,128,128};
int ofxGrtSettings::variables::titleTextSpacer = -12;
int ofxGrtSettings::variables::axisTicksSize = 5;
int ofxGrtSettings::variables::info_margin = 15;
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ampligraph documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 17 14:10:15 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
# sys.path.insert(0, os.path.abspath('.'))
from recommonmark.parser import CommonMarkParser
import sphinx_rtd_theme
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import ampligraph
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinxcontrib.bibtex',
'sphinx.ext.napoleon',
'sphinx.ext.autosummary'
]
autodoc_mock_imports = ["tensorflow"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
source_parsers = {'.md': CommonMarkParser}
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'AmpliGraph'
copyright = 'AmpliGraph is licensed under the Apache 2.0 License'
author = 'Accenture Labs Dublin'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ampligraph.__version__
# The full version, including alpha/beta/rc tags.
release = ampligraph.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['ampligraph.']
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_logo = 'img/ampligraph_logo_transparent_white.png'
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
'donate.html',
]
}
html_show_sourcelink = False
html_show_sphinx = False
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'xai_lpdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'ampligraph.tex', 'AmpliGraph',
'Luca Costabello - Accenture Labs Dublin', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'ampligraph', 'AmpliGraph Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'ampligraph', 'ampligraph Documentation',
author, 'Accenture Dublin Labs', 'Open source Python library that predicts links between concepts in a knowledge graph.',
''),
]
| {
"pile_set_name": "Github"
} |
@import './citation';
| {
"pile_set_name": "Github"
} |
# Advanced F2PY usages
## Adding self-written functions to F2PY generated modules
Self-written Python C/API functions can be defined inside
signature files using ``usercode`` and ``pymethoddef`` statements
(they must be used inside the ``python module`` block). For
example, the following signature file ``spam.pyf``
``` python
! -*- f90 -*-
python module spam
usercode '''
static char doc_spam_system[] = "Execute a shell command.";
static PyObject *spam_system(PyObject *self, PyObject *args)
{
char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
}
'''
pymethoddef '''
{"system", spam_system, METH_VARARGS, doc_spam_system},
'''
end python module spam
```
wraps the C library function ``system()``:
``` python
f2py -c spam.pyf
```
In Python:
``` python
>>> import spam
>>> status = spam.system('whoami')
pearu
>> status = spam.system('blah')
sh: line 1: blah: command not found
```
## Modifying the dictionary of a F2PY generated module
The following example illustrates how to add a user-defined
variables to a F2PY generated extension module. Given the following
signature file
``` python
! -*- f90 -*-
python module var
usercode '''
int BAR = 5;
'''
interface
usercode '''
PyDict_SetItemString(d,"BAR",PyInt_FromLong(BAR));
'''
end interface
end python module
```
compile it as ``f2py -c var.pyf``.
Notice that the second ``usercode`` statement must be defined inside
an ``interface`` block and where the module dictionary is available through
the variable ``d`` (see ``f2py var.pyf``-generated ``varmodule.c`` for
additional details).
In Python:
``` python
>>> import var
>>> var.BAR
5
``` | {
"pile_set_name": "Github"
} |
items
{
0 1 3 1 1 string3 NO 0
1 2 5 1 2 string6 NO 0
}
| {
"pile_set_name": "Github"
} |
import sys
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Text, Tuple
class Event(NamedTuple):
time: float
priority: Any
action: Callable[..., Any]
argument: Tuple[Any, ...]
kwargs: Dict[Text, Any]
class scheduler:
if sys.version_info >= (3, 3):
def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], None] = ...) -> None: ...
def enterabs(
self,
time: float,
priority: Any,
action: Callable[..., Any],
argument: Tuple[Any, ...] = ...,
kwargs: Dict[str, Any] = ...,
) -> Event: ...
def enter(
self,
delay: float,
priority: Any,
action: Callable[..., Any],
argument: Tuple[Any, ...] = ...,
kwargs: Dict[str, Any] = ...,
) -> Event: ...
def run(self, blocking: bool = ...) -> Optional[float]: ...
else:
def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ...
def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ...
def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ...
def run(self) -> None: ...
def cancel(self, event: Event) -> None: ...
def empty(self) -> bool: ...
@property
def queue(self) -> List[Event]: ...
| {
"pile_set_name": "Github"
} |
# Super Grub Disk - enablelvm.cfg
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015 Adrian Gibanel Lopez.
#
# Super Grub Disk is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Super Grub Disk is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Super Grub Disk. If not, see <http://www.gnu.org/licenses/>.
set option_title=$"Enable GRUB2's LVM support"
function run_option {
insmod lvm
} | {
"pile_set_name": "Github"
} |
// Targeted by JavaCPP version 1.5.4: DO NOT EDIT THIS FILE
package org.bytedeco.cpython;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.cpython.global.python.*;
@Properties(inherit = org.bytedeco.cpython.presets.python.class)
public class objobjargproc extends FunctionPointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public objobjargproc(Pointer p) { super(p); }
protected objobjargproc() { allocate(); }
private native void allocate();
public native int call(PyObject arg0, PyObject arg1, PyObject arg2);
}
| {
"pile_set_name": "Github"
} |
editArea.add_lang("de",{
charmap_but: "Sonderzeichen",
charmap_title: "Sonderzeichen",
charmap_choose_block: "Bereich auswählen",
charmap_insert: "dieses Zeichen einfügen"
});
| {
"pile_set_name": "Github"
} |
(* This file is part of the ocaml-vdom package, released under the terms of an MIT-like license. *)
(* See the attached LICENSE file. *)
(* Copyright 2016 by LexiFi. *)
module Cmd = struct
type 'msg t = ..
type 'msg t +=
| Echo of 'msg
| Batch of 'msg t list
| Map: ('a -> 'msg) * 'a t -> 'msg t
let echo msg = Echo msg
let batch l = Batch l
let map f x = Map (f, x)
end
module Custom = struct
type t = ..
type event = ..
end
type mouse_event = {x: int; y: int; page_x: float; page_y: float; buttons: int; alt_key: bool; ctrl_key: bool; shift_key: bool}
type key_event = {which: int; alt_key: bool; ctrl_key: bool; shift_key: bool}
type 'msg event_handler =
| MouseDown of (mouse_event -> 'msg)
| Click of (mouse_event -> 'msg)
| DblClick of (mouse_event -> 'msg)
| Focus of 'msg
| Blur of 'msg
| Input of (string -> 'msg)
| Change of (string -> 'msg)
| ChangeIndex of (int -> 'msg)
| ChangeChecked of (bool -> 'msg)
| MouseMove of (mouse_event -> 'msg)
| KeyDown of (key_event -> 'msg)
| KeyDownCancel of (key_event -> 'msg option)
| ContextMenu of (mouse_event -> 'msg)
| CustomEvent of (Custom.event -> 'msg option)
type prop_val =
| String of string
| Int of int
| Float of float
| Bool of bool
type 'msg attribute =
| Property of string * prop_val
| Style of string * string
| Handler of 'msg event_handler
| Attribute of string * string
let onmousedown msg = Handler (MouseDown msg)
let onclick msg = Handler (Click msg)
let ondblclick msg = Handler (DblClick msg)
let oncontextmenu msg = Handler (ContextMenu msg)
let onfocus msg = Handler (Focus msg)
let oninput msg = Handler (Input msg)
let onchange msg = Handler (Change msg)
let onchange_index msg = Handler (ChangeIndex msg)
let onchange_checked msg = Handler (ChangeChecked msg)
let onblur msg = Handler (Blur msg)
let onmousemove msg = Handler (MouseMove msg)
let onkeydown msg = Handler (KeyDown msg)
let onkeydown_cancel msg = Handler (KeyDownCancel msg)
let oncustomevent msg = Handler (CustomEvent msg)
let str_prop k v = Property (k, String v)
let int_prop k v = Property (k, Int v)
let bool_prop k v = Property (k, Bool v)
let float_prop k v = Property (k, Float v)
let style k v = Style (k, v)
let attr k v = Attribute (k, v)
let int_attr k v = Attribute (k, string_of_int v)
let float_attr k v = Attribute (k, string_of_float v)
let scroll_to_show = bool_prop "scroll-to-show" true
let autofocus = bool_prop "autofocus" true
let autofocus_counter x = int_prop "autofocus" x
let relative_dropdown x = int_prop "relative-dropdown" x
let class_ x = Property ("className", String x)
let type_ x = Property ("type", String x)
let type_button = type_ "button"
let value x = Property ("value", String x)
let disabled x = Property ("disabled", Bool x)
let add_class x attrs =
let has_className =
List.exists (function Property ("className", _) -> true | _ -> false) attrs
in
if has_className then
List.map (function
| Property ("className", String s) ->
Property ("className", String (Printf.sprintf "%s %s" s x))
| a ->
a
) attrs
else
class_ x :: attrs
type +'msg vdom =
| Text of
{
key: string;
txt: string;
}
| Element of
{
key: string;
ns: string;
tag: string;
attributes: 'msg attribute list;
children: 'msg vdom list;
}
| Map:
{
key: string;
f: ('submsg -> 'msg);
child: 'submsg vdom;
} -> 'msg vdom
| Memo:
{
key: string;
f: ('a -> 'msg vdom);
arg: 'a;
} -> 'msg vdom
| Custom of
{
key: string;
elt: Custom.t;
attributes: 'msg attribute list;
}
let text ?(key ="_txt") txt = Text {key; txt}
type ('msg, 'res) elt_gen =
?key:string ->
?a:'msg attribute list ->
'res
let elt ?(ns = "") tag ?key ?(a = []) l =
Element
{
key = (match key with None -> tag | Some k -> k);
ns;
tag;
children = l;
attributes = a;
}
let svg_ns = "http://www.w3.org/2000/svg"
let svg_elt tag ?key ?a l = elt ~ns:svg_ns tag ?key ?a l
let div ?key ?a l = elt "div" ?key ?a l
let input ?key ?a l = elt "input" ?key ?a l
let txt_span ?key ?a s = elt "span" ?key ?a [text s]
let map_attr f = function
| Custom ({ attributes; _ } as x) ->
Custom { x with attributes = f attributes }
| Element ({ attributes; _ } as x) ->
Element { x with attributes = f attributes }
| x -> x
let map ?(key = "_map") f child = Map {key; f; child}
let memo ?(key = "_memo") f arg = Memo {key; f; arg}
let custom ?(key ="_custom") ?(a = []) elt = Custom {key; elt; attributes = a}
let return ?(c = []) model = model, Cmd.batch c
type ('model, 'msg) app =
{
init: ('model * 'msg Cmd.t);
update: ('model -> 'msg -> 'model * 'msg Cmd.t);
view: ('model -> 'msg vdom);
}
let app ~init ~update ~view () =
{init; update; view}
let simple_app ~init ~update ~view () =
app
~init:(return init)
~update:(fun model msg -> return (update model msg))
~view
()
type event = {ev: 'msg. ('msg event_handler -> 'msg option)}
let blur_event = {ev = function Blur msg -> Some msg | _ -> None}
let input_event s = {ev = function Input f -> Some (f s) | _ -> None}
let checked_event b = {ev = function ChangeChecked f -> Some (f b) | _ -> None}
let change_event s = {ev = function Change f -> Some (f s) | _ -> None}
let change_index_event i = {ev = function ChangeIndex f -> Some (f i) | _ -> None}
let custom_event e = {ev = function CustomEvent f -> f e | _ -> None}
| {
"pile_set_name": "Github"
} |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: SI (Slovenian)
*/
(function ($) {
$.extend($.validator.messages, {
required: "To polje je obvezno.",
remote: "Vpis v tem polju ni v pravi obliki.",
email: "Prosimo, vnesite pravi email naslov.",
url: "Prosimo, vnesite pravi URL.",
date: "Prosimo, vnesite pravi datum.",
dateISO: "Prosimo, vnesite pravi datum (ISO).",
number: "Prosimo, vnesite pravo številko.",
digits: "Prosimo, vnesite samo številke.",
creditcard: "Prosimo, vnesite pravo številko kreditne kartice.",
equalTo: "Prosimo, ponovno vnesite enako vsebino.",
accept: "Prosimo, vnesite vsebino z pravo končnico.",
maxlength: $.validator.format("Prosimo, da ne vnašate več kot {0} znakov."),
minlength: $.validator.format("Prosimo, vnesite vsaj {0} znakov."),
rangelength: $.validator.format("Prosimo, vnesite od {0} do {1} znakov."),
range: $.validator.format("Prosimo, vnesite vrednost med {0} in {1}."),
max: $.validator.format("Prosimo, vnesite vrednost manjšo ali enako {0}."),
min: $.validator.format("Prosimo, vnesite vrednost večjo ali enako {0}.")
});
}(jQuery));
| {
"pile_set_name": "Github"
} |
StartChar: m.sc
Encoding: 1114680 -1 1679
GlifName: m.sc
Width: 707
VWidth: 0
Flags: HMW
AnchorPoint: "cedilla" 561 8 basechar 0
AnchorPoint: "below_accent" 342 -99 basechar 0
AnchorPoint: "top_accent" 345 615 basechar 0
LayerCount: 3
Fore
SplineSet
578 388 m 0
578 267 580 187 586 73 c 0
588 42 608 32 643 25 c 0
654 23 667 19 667 9 c 0
667 1 654 -3 647 -3 c 0
608 -3 592 3 556 3 c 24
517 3 495 -3 456 -3 c 0
449 -3 436 1 436 9 c 0
436 19 449 23 460 25 c 0
495 32 507 42 507 70 c 0
507 163 507 229 504 323 c 0
503 339 496 336 490 323 c 2
348 -1 l 2
343 -12 337 -17 331 -17 c 0
323 -17 316 -10 311 1 c 0
262 104 227 201 171 328 c 16
167 337 163 338 162 328 c 0
157 272 150 173 145 79 c 0
145 61 146 32 181 25 c 0
192 23 205 19 205 9 c 0
205 1 192 -3 185 -3 c 0
146 -3 144 3 118 3 c 24
89 3 84 -3 45 -3 c 0
38 -3 25 1 25 9 c 0
25 19 38 23 49 25 c 0
84 32 97 57 101 79 c 0
117 173 140 357 140 387 c 0
140 408 122 415 80 422 c 0
68 424 56 431 56 441 c 0
56 449 69 453 76 453 c 0
115 453 109 450 145 450 c 0
175 450 174 452 188 452 c 0
195 452 199 452 200 450 c 2
348 106 l 2
354 93 358 91 364 104 c 0
404 195 438 275 484 389 c 0
493 412 504 447 509 447 c 2
547 448 l 0
582 448 617 453 640 453 c 0
647 453 660 449 660 441 c 0
660 431 648 424 636 422 c 0
594 415 578 414 578 388 c 0
EndSplineSet
Validated: 1
Comment: "."
EndChar
| {
"pile_set_name": "Github"
} |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"fmt"
"go/scanner"
"go/token"
"go/types"
"regexp"
"strconv"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/packages"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/analysisinternal"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/event"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/debug/tag"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/protocol"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/source"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/span"
errors "golang.org/x/xerrors"
)
func sourceError(ctx context.Context, snapshot *snapshot, pkg *pkg, e interface{}) (*source.Error, error) {
fset := snapshot.view.session.cache.fset
var (
spn span.Span
err error
msg, category string
kind source.ErrorKind
fixes []source.SuggestedFix
related []source.RelatedInformation
)
switch e := e.(type) {
case packages.Error:
kind = toSourceErrorKind(e.Kind)
var ok bool
if msg, spn, ok = parseGoListImportCycleError(ctx, snapshot, e, pkg); ok {
kind = source.TypeError
break
}
if e.Pos == "" {
spn = parseGoListError(e.Msg)
// We may not have been able to parse a valid span.
if _, err := spanToRange(snapshot, pkg, spn); err != nil {
return &source.Error{
URI: spn.URI(),
Message: msg,
Kind: kind,
}, nil
}
} else {
spn = span.Parse(e.Pos)
}
case *scanner.Error:
msg = e.Msg
kind = source.ParseError
spn, err = scannerErrorRange(snapshot, pkg, e.Pos)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
event.Error(ctx, "no span for scanner.Error pos", err, tag.Package.Of(pkg.ID()))
spn = span.Parse(e.Pos.String())
}
case scanner.ErrorList:
// The first parser error is likely the root cause of the problem.
if e.Len() <= 0 {
return nil, errors.Errorf("no errors in %v", e)
}
msg = e[0].Msg
kind = source.ParseError
spn, err = scannerErrorRange(snapshot, pkg, e[0].Pos)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
event.Error(ctx, "no span for scanner.Error pos", err, tag.Package.Of(pkg.ID()))
spn = span.Parse(e[0].Pos.String())
}
case types.Error:
msg = e.Msg
kind = source.TypeError
if !e.Pos.IsValid() {
return nil, fmt.Errorf("invalid position for type error %v", e)
}
spn, err = typeErrorRange(snapshot, fset, pkg, e.Pos)
if err != nil {
return nil, err
}
case extendedError:
perr := e.primary
msg = perr.Msg
kind = source.TypeError
if !perr.Pos.IsValid() {
return nil, fmt.Errorf("invalid position for type error %v", e)
}
spn, err = typeErrorRange(snapshot, fset, pkg, perr.Pos)
if err != nil {
return nil, err
}
for _, s := range e.secondaries {
var x source.RelatedInformation
x.Message = s.Msg
xspn, err := typeErrorRange(snapshot, fset, pkg, s.Pos)
if err != nil {
return nil, fmt.Errorf("invalid position for type error %v", s)
}
x.URI = xspn.URI()
rng, err := spanToRange(snapshot, pkg, xspn)
if err != nil {
return nil, err
}
x.Range = rng
related = append(related, x)
}
case *analysis.Diagnostic:
spn, err = span.NewRange(fset, e.Pos, e.End).Span()
if err != nil {
return nil, err
}
msg = e.Message
kind = source.Analysis
category = e.Category
fixes, err = suggestedFixes(snapshot, pkg, e)
if err != nil {
return nil, err
}
related, err = relatedInformation(snapshot, pkg, e)
if err != nil {
return nil, err
}
default:
panic(fmt.Sprintf("%T unexpected", e))
}
rng, err := spanToRange(snapshot, pkg, spn)
if err != nil {
return nil, err
}
return &source.Error{
URI: spn.URI(),
Range: rng,
Message: msg,
Kind: kind,
Category: category,
SuggestedFixes: fixes,
Related: related,
}, nil
}
func suggestedFixes(snapshot *snapshot, pkg *pkg, diag *analysis.Diagnostic) ([]source.SuggestedFix, error) {
var fixes []source.SuggestedFix
for _, fix := range diag.SuggestedFixes {
edits := make(map[span.URI][]protocol.TextEdit)
for _, e := range fix.TextEdits {
spn, err := span.NewRange(snapshot.view.session.cache.fset, e.Pos, e.End).Span()
if err != nil {
return nil, err
}
rng, err := spanToRange(snapshot, pkg, spn)
if err != nil {
return nil, err
}
edits[spn.URI()] = append(edits[spn.URI()], protocol.TextEdit{
Range: rng,
NewText: string(e.NewText),
})
}
fixes = append(fixes, source.SuggestedFix{
Title: fix.Message,
Edits: edits,
})
}
return fixes, nil
}
func relatedInformation(snapshot *snapshot, pkg *pkg, diag *analysis.Diagnostic) ([]source.RelatedInformation, error) {
var out []source.RelatedInformation
for _, related := range diag.Related {
spn, err := span.NewRange(snapshot.view.session.cache.fset, related.Pos, related.End).Span()
if err != nil {
return nil, err
}
rng, err := spanToRange(snapshot, pkg, spn)
if err != nil {
return nil, err
}
out = append(out, source.RelatedInformation{
URI: spn.URI(),
Range: rng,
Message: related.Message,
})
}
return out, nil
}
func toSourceErrorKind(kind packages.ErrorKind) source.ErrorKind {
switch kind {
case packages.ListError:
return source.ListError
case packages.ParseError:
return source.ParseError
case packages.TypeError:
return source.TypeError
default:
return source.UnknownError
}
}
func typeErrorRange(snapshot *snapshot, fset *token.FileSet, pkg *pkg, pos token.Pos) (span.Span, error) {
posn := fset.Position(pos)
pgf, err := pkg.File(span.URIFromPath(posn.Filename))
if err != nil {
return span.Span{}, err
}
return span.Range{
FileSet: fset,
Start: pos,
End: analysisinternal.TypeErrorEndPos(fset, pgf.Src, pos),
Converter: pgf.Mapper.Converter,
}.Span()
}
func scannerErrorRange(snapshot *snapshot, pkg *pkg, posn token.Position) (span.Span, error) {
fset := snapshot.view.session.cache.fset
pgf, err := pkg.File(span.URIFromPath(posn.Filename))
if err != nil {
return span.Span{}, err
}
pos := pgf.Tok.Pos(posn.Offset)
return span.NewRange(fset, pos, pos).Span()
}
// spanToRange converts a span.Span to a protocol.Range,
// assuming that the span belongs to the package whose diagnostics are being computed.
func spanToRange(snapshot *snapshot, pkg *pkg, spn span.Span) (protocol.Range, error) {
pgf, err := pkg.File(spn.URI())
if err != nil {
return protocol.Range{}, err
}
return pgf.Mapper.Range(spn)
}
// parseGoListError attempts to parse a standard `go list` error message
// by stripping off the trailing error message.
//
// It works only on errors whose message is prefixed by colon,
// followed by a space (": "). For example:
//
// attributes.go:13:1: expected 'package', found 'type'
//
func parseGoListError(input string) span.Span {
input = strings.TrimSpace(input)
msgIndex := strings.Index(input, ": ")
if msgIndex < 0 {
return span.Parse(input)
}
return span.Parse(input[:msgIndex])
}
func parseGoListImportCycleError(ctx context.Context, snapshot *snapshot, e packages.Error, pkg *pkg) (string, span.Span, bool) {
re := regexp.MustCompile(`(.*): import stack: \[(.+)\]`)
matches := re.FindStringSubmatch(strings.TrimSpace(e.Msg))
if len(matches) < 3 {
return e.Msg, span.Span{}, false
}
msg := matches[1]
importList := strings.Split(matches[2], " ")
// Since the error is relative to the current package. The import that is causing
// the import cycle error is the second one in the list.
if len(importList) < 2 {
return msg, span.Span{}, false
}
// Imports have quotation marks around them.
circImp := strconv.Quote(importList[1])
for _, cgf := range pkg.compiledGoFiles {
// Search file imports for the import that is causing the import cycle.
for _, imp := range cgf.File.Imports {
if imp.Path.Value == circImp {
spn, err := span.NewRange(snapshot.view.session.cache.fset, imp.Pos(), imp.End()).Span()
if err != nil {
return msg, span.Span{}, false
}
return msg, spn, true
}
}
}
return msg, span.Span{}, false
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2014 - 2020 Michael Rapp
*
* 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 de.mrapp.android.dialog.decorator;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import androidx.annotation.ArrayRes;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import de.mrapp.android.dialog.R;
import de.mrapp.android.dialog.ScrollableArea.Area;
import de.mrapp.android.dialog.adapter.ArrayRecyclerViewAdapter;
import de.mrapp.android.dialog.adapter.RecyclerViewAdapterWrapper;
import de.mrapp.android.dialog.adapter.RecyclerViewAdapterWrapper.ChoiceMode;
import de.mrapp.android.dialog.adapter.RecyclerViewAdapterWrapper.MultipleChoiceMode;
import de.mrapp.android.dialog.adapter.RecyclerViewAdapterWrapper.NoChoiceMode;
import de.mrapp.android.dialog.adapter.RecyclerViewAdapterWrapper.SingleChoiceMode;
import de.mrapp.android.dialog.listener.OnItemClickListenerWrapper;
import de.mrapp.android.dialog.listener.OnMultiChoiceClickListenerWrapper;
import de.mrapp.android.dialog.model.ButtonBarDialog;
import de.mrapp.android.dialog.model.ListDialog;
import de.mrapp.android.dialog.view.DialogRootView.AreaViewType;
import de.mrapp.android.dialog.view.DialogRootView.DividerLocation;
import de.mrapp.android.dialog.view.DialogRootView.DividerViewType;
import de.mrapp.android.dialog.view.DialogRootView.ViewType;
import de.mrapp.android.dialog.view.Divider;
import de.mrapp.util.Condition;
/**
* A decorator, which allows to modify the view hierarchy of a dialog, which is designed according
* to Android 5's Material Design guidelines even on pre-Lollipop devices and may contain list
* items.
*
* @author Michael Rapp
* @since 3.2.0
*/
public class ListDialogDecorator extends AbstractDialogDecorator<ButtonBarDialog>
implements de.mrapp.android.dialog.model.ListDialogDecorator {
/**
* The name of the extra, which is used to store the color of the list items of the dialog
* within a bundle.
*/
private static final String ITEM_COLOR_EXTRA =
ListDialogDecorator.class.getSimpleName() + "::itemColor";
/**
* The name of the extra, which is used to store the dialog's items within a bundle.
*/
private static final String ITEMS_EXTRA = ListDialogDecorator.class.getSimpleName() + "::items";
/**
* The name of the extra, which is used to store the resource ids of the iconds of the dialog's
* items within a bundle.
*/
private static final String ICON_RESOURCE_IDS_EXTRA =
ListDialogDecorator.class.getSimpleName() + "::iconResourceIds";
/**
* The name of the extra, which is used to store the dialog's single choice items within a
* bundle.
*/
private static final String SINGLE_CHOICE_ITEMS_EXTRA =
ListDialogDecorator.class.getSimpleName() + "::singleChoiceItems";
/**
* The name of the extra, which is used to store the dialog's mnultiple choice items within a
* bundle.
*/
private static final String MULTI_CHOICE_ITEMS_EXTRA =
ListDialogDecorator.class.getSimpleName() + "::multiChoiceItems";
/**
* The name of the extra, which is used to store the checked items within a bundle.
*/
private static final String CHECKED_ITEMS_EXTRA =
ListDialogDecorator.class.getSimpleName() + "::checkedItems";
/**
* The name of the extra, which is used to store the enabled items within a bundle.
*/
private static final String ENABLED_ITEMS_EXTRA =
ListDialogDecorator.class.getSimpleName() + "::enabledItems";
/**
* The list view, which is used to show the dialog's list items.
*/
private RecyclerView listView;
/**
* The divider, which is shown above the list view.
*/
private Divider listDivider;
/**
* True, if the custom view of the dialog has been inflated by the decorator itself, false
* otherwise.
*/
private boolean inflatedCustomView;
/**
* The text color of the dialog's list items.
*/
private ColorStateList itemColor;
/**
* The typeface of the dialog's list items.
*/
private Typeface itemTypeface;
/**
* The color state list, which is used to tint the icons of the dialog's list items.
*/
private ColorStateList itemIconTintList;
/**
* The mode, which is used to tint the icons of the dialog's list items.
*/
private PorterDuff.Mode itemIconTintMode = PorterDuff.Mode.SRC_ATOP;
/**
* The adapter, which is used to manage the list items of the dialog.
*/
private RecyclerViewAdapterWrapper<?> adapter;
/**
* The layout manager, which is used to layout the list items of the dialog.
*/
private RecyclerView.LayoutManager layoutManager;
/**
* The listener, which is notified, when the selection of a list item of the dialog changes and
* the list view's choice mode is <code>ListView.CHOICE_MODE_SINGLE</code>.
*/
private DialogInterface.OnClickListener singleChoiceListener;
/**
* The listener, which is notified, when the selection of a list item of the dialog changes and
* the list view's choice mode is <code>ListView.CHOICE_MODE_MULTIPLE</code>.
*/
private DialogInterface.OnMultiChoiceClickListener multiChoiceListener;
/**
* The listener, which is notified, when a list item of the dialog becomes selected or
* unselected, irrespective of the list view's choice mode.
*/
private ListDialog.OnItemSelectedListener listViewItemSelectedListener;
/**
* The listener, which is notified, when a list item of the dialog becomes enabled or disabled.
*/
private ListDialog.OnItemEnabledListener listViewItemEnabledListener;
/**
* The dialog's items.
*/
private CharSequence[] items;
/**
* The resource ids of the icons of the dialog's items.
*/
private int[] iconResourceIds;
/**
* The dialog's single choice items.
*/
private CharSequence[] singleChoiceItems;
/**
* The dialog's multiple choice items.
*/
private CharSequence[] multiChoiceItems;
/**
* Inflates the list view, which is used to show the dialog's list items.
*
* @param contentContainer The view group, which contains the dialog's content, as an instance of the class
* {@link ViewGroup}. The view group may not be null
*/
private void inflateListView(@NonNull final ViewGroup contentContainer) {
View listView = contentContainer.findViewById(android.R.id.list);
this.listView = listView instanceof RecyclerView ? (RecyclerView) listView : null;
if (this.listView == null && !getDialog().isCustomViewUsed()) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater
.inflate(R.layout.material_dialog_list_view, contentContainer, false);
this.listView = view.findViewById(android.R.id.list);
getDialog().setView(view);
this.inflatedCustomView = true;
} else {
this.inflatedCustomView = false;
}
View divider = contentContainer.findViewById(R.id.list_divider);
this.listDivider = divider instanceof Divider ? (Divider) divider : null;
}
/**
* Attaches the adapter to the dialog's list view.
*/
private void attachAdapter() {
if (listView != null) {
if (adapter != null) {
listView.setHasFixedSize(false);
listView.setLayoutManager(layoutManager);
listView.setAdapter(adapter);
listView.setVisibility(adapter != null ? View.VISIBLE : View.GONE);
adapter.setOnItemSelectedListener(listViewItemSelectedListener);
adapter.setOnItemEnabledListener(listViewItemEnabledListener);
initializeSelectionListener();
adaptItemColor();
adaptItemTypeface();
adaptItemIconTintList();
adaptItemIconTintMode();
} else {
if (inflatedCustomView) {
getDialog().setView(null);
}
listView = null;
}
}
}
/**
* Returns an array, which identifies the currently checked list items.
*
* @return An array, which identifies the currently checked list items, as {@link Boolean} array
*/
@Nullable
private boolean[] getCheckedItems() {
if (adapter != null) {
boolean[] result = new boolean[adapter.getItemCount()];
for (int i = 0; i < result.length; i++) {
result[i] = adapter.isItemChecked(i);
}
return result;
}
return null;
}
/**
* Returns an array, which identifies the currently enabled list items.
*
* @return An array, which identifies the currently enabled list items, as a {@link Boolean}
* array
*/
@Nullable
private boolean[] getEnabledItems() {
if (adapter != null) {
boolean[] result = new boolean[adapter.getItemCount()];
for (int i = 0; i < result.length; i++) {
result[i] = adapter.isItemEnabled(i);
}
return result;
}
return null;
}
/**
* Returns the index of the first checked item.
*
* @param checkedItems A boolean array that specifies, whether the item at an individual
* position is checked, or not
* @return The index of the first checked item or -1, if no item is checked
*/
private int indexOfCheckedItem(final boolean[] checkedItems) {
for (int i = 0; i < checkedItems.length; i++) {
if (checkedItems[i]) {
return i;
}
}
return -1;
}
/**
* Initializes the listener, which should be notified, when the selection of a list item of the
* dialog has been changed.
*/
private void initializeSelectionListener() {
ChoiceMode choiceMode = adapter.getChoiceMode();
if (choiceMode instanceof MultipleChoiceMode) {
adapter.setOnItemClickListener(
new OnMultiChoiceClickListenerWrapper(multiChoiceListener, getDialog(), 0));
} else if (choiceMode instanceof SingleChoiceMode) {
adapter.setOnItemClickListener(
new OnItemClickListenerWrapper(singleChoiceListener, getDialog(), 0));
} else {
adapter.setOnItemClickListener(
new OnItemClickListenerWrapper(singleChoiceListener, getDialog(),
DialogInterface.BUTTON_POSITIVE));
}
}
/**
* Adapts the color of the dialog's list items.
*/
private void adaptItemColor() {
if (adapter != null) {
RecyclerView.Adapter<?> wrappedAdapter = adapter.getWrappedAdapter();
if (wrappedAdapter instanceof ArrayRecyclerViewAdapter) {
((ArrayRecyclerViewAdapter) wrappedAdapter).setItemColor(itemColor);
}
}
}
/**
* Adapts the typeface of the dialog's list items.
*/
private void adaptItemTypeface() {
if (adapter != null && itemTypeface != null) {
RecyclerView.Adapter<?> wrappedAdapter = adapter.getWrappedAdapter();
if (wrappedAdapter instanceof ArrayRecyclerViewAdapter) {
((ArrayRecyclerViewAdapter) wrappedAdapter).setItemTypeface(itemTypeface);
}
}
}
/**
* Adapts the color state list, which is used to tint the icons of the dialog's list items.
*/
private void adaptItemIconTintList() {
if (adapter != null) {
RecyclerView.Adapter<?> wrappedAdapter = adapter.getWrappedAdapter();
if (wrappedAdapter instanceof ArrayRecyclerViewAdapter) {
((ArrayRecyclerViewAdapter) wrappedAdapter).setItemIconTintList(itemIconTintList);
}
}
}
/**
* Adapts the mode, which is used to tint the icons of the dialog's list items.
*/
private void adaptItemIconTintMode() {
if (adapter != null) {
RecyclerView.Adapter<?> wrappedAdapter = adapter.getWrappedAdapter();
if (wrappedAdapter instanceof ArrayRecyclerViewAdapter) {
((ArrayRecyclerViewAdapter) wrappedAdapter).setItemIconTintMode(itemIconTintMode);
}
}
}
/**
* Adapts the enabled items.
*
* @param enabledItems An array, which indicates the enabled items, as a {@link Boolean} array
*/
private void adaptEnabledItems(@Nullable final boolean[] enabledItems) {
if (enabledItems != null && adapter != null) {
for (int i = 0; i < enabledItems.length; i++) {
adapter.setItemEnabled(i, enabledItems[i]);
}
}
}
/**
* Creates a new decorator, which allows to modify the view hierarchy of a dialog, which is
* designed according to Android 5's Material Design guidelines even on pre-Lollipop devices and
* may contain list items.
*
* @param dialog The dialog, whose view hierarchy should be modified by the dialog, as an instance of
* the type {@link ButtonBarDialog}. The dialog may not be null
*/
public ListDialogDecorator(@NonNull final ButtonBarDialog dialog) {
super(dialog);
}
@Override
public final RecyclerView getListView() {
return listView != null && listView.getVisibility() == View.VISIBLE ? listView : null;
}
@Override
public final RecyclerView.Adapter<?> getListAdapter() {
return adapter;
}
@Nullable
@Override
public final ColorStateList getItemColor() {
return itemColor;
}
@Override
public final void setItemColor(@ColorInt final int color) {
setItemColor(ColorStateList.valueOf(color));
}
@Override
public final void setItemColor(@NonNull final ColorStateList colorStateList) {
Condition.INSTANCE.ensureNotNull(colorStateList, "The color state list may not be null");
this.itemColor = colorStateList;
adaptItemColor();
}
@Override
public final void setItemTypeface(@NonNull final Typeface typeface) {
Condition.INSTANCE.ensureNotNull(typeface, "The typeface may not be null");
itemTypeface = typeface;
adaptItemTypeface();
}
@Nullable
@Override
public final Typeface getItemTypeface() {
return itemTypeface;
}
@Nullable
@Override
public final ColorStateList getItemIconTintList() {
return itemIconTintList;
}
@Override
public final void setItemIconTint(@ColorInt final int color) {
setItemIconTintList(ColorStateList.valueOf(color));
}
@Override
public final void setItemIconTintList(@Nullable final ColorStateList tintList) {
this.itemIconTintList = tintList;
adaptItemIconTintList();
}
@NonNull
@Override
public final PorterDuff.Mode getItemIconTintMode() {
return itemIconTintMode;
}
@Override
public final void setItemIconTintMode(@NonNull final PorterDuff.Mode mode) {
Condition.INSTANCE.ensureNotNull(mode, "The tint mode may not be null");
this.itemIconTintMode = mode;
adaptItemIconTintMode();
}
@Override
public final int getItemCount() {
return adapter != null ? adapter.getItemCount() : 0;
}
@Override
public final boolean isItemChecked(final int position) {
Condition.INSTANCE.ensureNotNull(adapter, "No list items are shown by the dialog",
IndexOutOfBoundsException.class);
return adapter.isItemChecked(position);
}
@Override
public final void setItemChecked(final int position, final boolean checked) {
Condition.INSTANCE.ensureNotNull(adapter, "No list items are shown by the dialog",
IndexOutOfBoundsException.class);
adapter.setItemChecked(position, checked);
}
@Override
public final boolean isItemEnabled(final int position) {
Condition.INSTANCE.ensureNotNull(adapter, "No list items are shown by the dialog",
IndexOutOfBoundsException.class);
return adapter.isItemEnabled(position);
}
@Override
public final void setItemEnabled(final int position, final boolean enabled) {
Condition.INSTANCE.ensureNotNull(adapter, "No list items are shown by the dialog",
IndexOutOfBoundsException.class);
adapter.setItemEnabled(position, enabled);
}
@Override
public final void setItems(@Nullable final CharSequence[] items,
@Nullable final DialogInterface.OnClickListener listener) {
setItems(items, null, listener);
}
@Override
public final void setItems(@Nullable final CharSequence[] items,
@Nullable final int[] iconResourceIds,
@Nullable final DialogInterface.OnClickListener listener) {
this.items = items;
this.iconResourceIds = iconResourceIds;
this.singleChoiceItems = null;
this.multiChoiceItems = null;
this.adapter = items != null ? new RecyclerViewAdapterWrapper<>(getContext(),
new ArrayRecyclerViewAdapter(android.R.layout.simple_list_item_1, items,
iconResourceIds), new NoChoiceMode()) : null;
this.layoutManager = new LinearLayoutManager(getContext());
this.singleChoiceListener = items != null ? listener : null;
this.multiChoiceListener = null;
attachAdapter();
}
@Override
public final void setItems(@ArrayRes final int resourceId,
@Nullable final DialogInterface.OnClickListener listener) {
setItems(resourceId, null, listener);
}
@Override
public final void setItems(final int resourceId, @Nullable final int[] iconResourceIds,
@Nullable final DialogInterface.OnClickListener listener) {
setItems(getContext().getResources().getTextArray(resourceId), iconResourceIds, listener);
}
@Override
public final <VH extends RecyclerView.ViewHolder> void setAdapter(
@Nullable final RecyclerView.Adapter<VH> adapter,
@Nullable final RecyclerView.LayoutManager layoutManager,
@Nullable final DialogInterface.OnClickListener listener) {
this.items = null;
this.iconResourceIds = null;
this.singleChoiceItems = null;
this.multiChoiceItems = null;
this.adapter = adapter != null ?
new RecyclerViewAdapterWrapper<>(getContext(), adapter, new NoChoiceMode()) : null;
this.layoutManager = adapter != null ?
(layoutManager != null ? layoutManager : new LinearLayoutManager(getContext())) :
null;
this.singleChoiceListener = adapter != null ? listener : null;
this.multiChoiceListener = null;
attachAdapter();
}
@Override
public final void setSingleChoiceItems(@Nullable final CharSequence[] items,
final int checkedItem,
@Nullable final DialogInterface.OnClickListener listener) {
setSingleChoiceItems(items, null, checkedItem, listener);
}
@Override
public final void setSingleChoiceItems(@Nullable final CharSequence[] items,
@Nullable final int[] iconResourceIds,
final int checkedItem,
@Nullable final DialogInterface.OnClickListener listener) {
this.items = null;
this.iconResourceIds = iconResourceIds;
this.singleChoiceItems = items;
this.multiChoiceItems = null;
this.adapter = items != null ? new RecyclerViewAdapterWrapper<>(getContext(),
new ArrayRecyclerViewAdapter(android.R.layout.simple_list_item_single_choice,
items, iconResourceIds), new SingleChoiceMode()) : null;
this.layoutManager = new LinearLayoutManager(getContext());
this.singleChoiceListener = items != null ? listener : null;
this.multiChoiceListener = null;
if (checkedItem != -1 && this.adapter != null) {
this.adapter.setItemChecked(checkedItem, true);
}
attachAdapter();
}
@Override
public final void setSingleChoiceItems(@ArrayRes final int resourceId, final int checkedItem,
@Nullable final DialogInterface.OnClickListener listener) {
setSingleChoiceItems(resourceId, null, checkedItem, listener);
}
@Override
public final void setSingleChoiceItems(final int resourceId,
@Nullable final int[] iconResourceIds,
final int checkedItem,
@Nullable final DialogInterface.OnClickListener listener) {
setSingleChoiceItems(getContext().getResources().getTextArray(resourceId), iconResourceIds,
checkedItem, listener);
}
@Override
public final <VH extends RecyclerView.ViewHolder> void setSingleChoiceItems(
@Nullable final RecyclerView.Adapter<VH> adapter,
@Nullable final RecyclerView.LayoutManager layoutManager, final int checkedItem,
@Nullable final DialogInterface.OnClickListener listener) {
this.items = null;
this.iconResourceIds = null;
this.singleChoiceItems = null;
this.multiChoiceItems = null;
this.adapter = adapter != null ?
new RecyclerViewAdapterWrapper<>(getContext(), adapter, new SingleChoiceMode()) :
null;
this.layoutManager = adapter != null ?
(layoutManager != null ? layoutManager : new LinearLayoutManager(getContext())) :
null;
this.singleChoiceListener = adapter != null ? listener : null;
this.multiChoiceListener = null;
if (checkedItem != -1 && this.adapter != null) {
this.adapter.setItemChecked(checkedItem, true);
}
attachAdapter();
}
@Override
public final void setMultiChoiceItems(@Nullable final CharSequence[] items,
@Nullable final boolean[] checkedItems,
@Nullable final DialogInterface.OnMultiChoiceClickListener listener) {
setMultiChoiceItems(items, null, checkedItems, listener);
}
@Override
public final void setMultiChoiceItems(@Nullable final CharSequence[] items,
@Nullable final int[] iconResourceIds,
@Nullable final boolean[] checkedItems,
@Nullable final DialogInterface.OnMultiChoiceClickListener listener) {
Condition.INSTANCE.ensureTrue(checkedItems == null || items == null ||
checkedItems.length == items.length, "Invalid number of checked items given");
this.items = null;
this.iconResourceIds = iconResourceIds;
this.singleChoiceItems = null;
this.multiChoiceItems = items;
this.adapter = items != null ? new RecyclerViewAdapterWrapper<>(getContext(),
new ArrayRecyclerViewAdapter(android.R.layout.simple_list_item_multiple_choice,
items, iconResourceIds), new MultipleChoiceMode()) : null;
this.layoutManager = new LinearLayoutManager(getContext());
this.singleChoiceListener = null;
this.multiChoiceListener = items != null ? listener : null;
if (this.adapter != null && checkedItems != null) {
for (int i = 0; i < checkedItems.length; i++) {
this.adapter.setItemChecked(i, checkedItems[i]);
}
}
attachAdapter();
}
@Override
public final void setMultiChoiceItems(@ArrayRes final int resourceId,
@Nullable final boolean[] checkedItems,
@Nullable final DialogInterface.OnMultiChoiceClickListener listener) {
setMultiChoiceItems(resourceId, null, checkedItems, listener);
}
@Override
public final void setMultiChoiceItems(final int resourceId,
@Nullable final int[] iconResourceIds,
@Nullable final boolean[] checkedItems,
@Nullable final DialogInterface.OnMultiChoiceClickListener listener) {
setMultiChoiceItems(getContext().getResources().getTextArray(resourceId), iconResourceIds,
checkedItems, listener);
}
@Override
public final <VH extends RecyclerView.ViewHolder> void setMultiChoiceItems(
@Nullable final RecyclerView.Adapter<VH> adapter,
@Nullable final RecyclerView.LayoutManager layoutManager,
@Nullable final boolean[] checkedItems,
@Nullable final DialogInterface.OnMultiChoiceClickListener listener) {
Condition.INSTANCE.ensureTrue(checkedItems == null || adapter == null ||
adapter.getItemCount() == checkedItems.length,
"Invalid number of checked items given");
this.items = null;
this.iconResourceIds = null;
this.singleChoiceItems = null;
this.multiChoiceItems = null;
this.adapter = adapter != null ?
new RecyclerViewAdapterWrapper<>(getContext(), adapter, new MultipleChoiceMode()) :
null;
this.layoutManager = adapter != null ?
(layoutManager != null ? layoutManager : new LinearLayoutManager(getContext())) :
null;
this.singleChoiceListener = null;
this.multiChoiceListener = adapter != null ? listener : null;
if (this.adapter != null && checkedItems != null) {
for (int i = 0; i < checkedItems.length; i++) {
this.adapter.setItemChecked(i, checkedItems[i]);
}
}
attachAdapter();
}
@Override
public final void setOnItemSelectedListener(
@Nullable final ListDialog.OnItemSelectedListener listener) {
listViewItemSelectedListener = listener;
if (adapter != null) {
adapter.setOnItemSelectedListener(listViewItemSelectedListener);
}
}
@Override
public final void setOnItemEnabledListener(
@Nullable final ListDialog.OnItemEnabledListener listener) {
listViewItemEnabledListener = listener;
if (adapter != null) {
adapter.setOnItemEnabledListener(listViewItemEnabledListener);
}
}
@Override
public final void onSaveInstanceState(@NonNull final Bundle outState) {
outState.putParcelable(ITEM_COLOR_EXTRA, getItemColor());
outState.putIntArray(ICON_RESOURCE_IDS_EXTRA, iconResourceIds);
if (items != null) {
outState.putCharSequenceArray(ITEMS_EXTRA, items);
outState.putBooleanArray(ENABLED_ITEMS_EXTRA, getEnabledItems());
} else if (singleChoiceItems != null) {
outState.putCharSequenceArray(SINGLE_CHOICE_ITEMS_EXTRA, singleChoiceItems);
outState.putBooleanArray(CHECKED_ITEMS_EXTRA, getCheckedItems());
outState.putBooleanArray(ENABLED_ITEMS_EXTRA, getEnabledItems());
} else if (multiChoiceItems != null) {
outState.putCharSequenceArray(MULTI_CHOICE_ITEMS_EXTRA, multiChoiceItems);
outState.putBooleanArray(CHECKED_ITEMS_EXTRA, getCheckedItems());
outState.putBooleanArray(ENABLED_ITEMS_EXTRA, getEnabledItems());
}
}
@Override
public final void onRestoreInstanceState(@NonNull final Bundle savedInstanceState) {
ColorStateList itemColor = savedInstanceState.getParcelable(ITEM_COLOR_EXTRA);
if (itemColor != null) {
setItemColor(itemColor);
}
CharSequence[] items = savedInstanceState.getCharSequenceArray(ITEMS_EXTRA);
int[] iconResourceIds = savedInstanceState.getIntArray(ICON_RESOURCE_IDS_EXTRA);
if (items != null) {
boolean[] enabledItems = savedInstanceState.getBooleanArray(ENABLED_ITEMS_EXTRA);
setItems(items, iconResourceIds, this.singleChoiceListener);
adaptEnabledItems(enabledItems);
} else {
boolean[] checkedItems = savedInstanceState.getBooleanArray(CHECKED_ITEMS_EXTRA);
boolean[] enabledItems = savedInstanceState.getBooleanArray(ENABLED_ITEMS_EXTRA);
CharSequence[] singleChoiceItems =
savedInstanceState.getCharSequenceArray(SINGLE_CHOICE_ITEMS_EXTRA);
if (singleChoiceItems != null) {
int checkedItem = checkedItems != null ? indexOfCheckedItem(checkedItems) : -1;
setSingleChoiceItems(singleChoiceItems, iconResourceIds, checkedItem,
this.singleChoiceListener);
adaptEnabledItems(enabledItems);
} else {
CharSequence[] multiChoiceItems =
savedInstanceState.getCharSequenceArray(MULTI_CHOICE_ITEMS_EXTRA);
if (multiChoiceItems != null) {
setMultiChoiceItems(multiChoiceItems, iconResourceIds, checkedItems,
this.multiChoiceListener);
adaptEnabledItems(enabledItems);
}
}
}
}
@NonNull
@Override
protected final Map<ViewType, View> onAttach(@NonNull final Window window,
@NonNull final View view,
@NonNull final Map<ViewType, View> areas,
final Void param) {
View contentView = areas.get(new AreaViewType(Area.CONTENT));
if (contentView instanceof ViewGroup) {
inflateListView((ViewGroup) contentView);
attachAdapter();
}
if (listDivider != null) {
Map<ViewType, View> result = new HashMap<>();
result.put(new DividerViewType(DividerLocation.TOP), listDivider);
return result;
}
return Collections.emptyMap();
}
@Override
protected final void onDetach() {
this.listView = null;
}
} | {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::multivariateSurfaceInterpolationScheme
Description
Abstract base class for multi-variate surface interpolation schemes.
SourceFiles
multivariateSurfaceInterpolationScheme.C
\*---------------------------------------------------------------------------*/
#ifndef multivariateSurfaceInterpolationScheme_H
#define multivariateSurfaceInterpolationScheme_H
#include "surfaceInterpolationScheme.H"
#include "HashTable.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class multivariateSurfaceInterpolationScheme Declaration
\*---------------------------------------------------------------------------*/
template<class Type>
class multivariateSurfaceInterpolationScheme
:
public refCount
{
public:
//- fieldTable
class fieldTable
:
public HashTable<const GeometricField<Type, fvPatchField, volMesh>*>
{
public:
fieldTable()
{}
void add(const GeometricField<Type, fvPatchField, volMesh>& f)
{
this->insert(f.name(), &f);
}
};
private:
// Private data
//- Hold reference to mesh
const fvMesh& mesh_;
//- HashTable of pointers to the field set
const fieldTable& fields_;
// Private Member Functions
//- Disallow default bitwise copy construct
multivariateSurfaceInterpolationScheme
(
const multivariateSurfaceInterpolationScheme&
);
//- Disallow default bitwise assignment
void operator=(const multivariateSurfaceInterpolationScheme&);
public:
//- Runtime type information
virtual const word& type() const = 0;
// Declare run-time constructor selection tables
declareRunTimeSelectionTable
(
tmp,
multivariateSurfaceInterpolationScheme,
Istream,
(
const fvMesh& mesh,
const fieldTable& fields,
const surfaceScalarField& faceFlux,
Istream& is
),
(mesh, fields, faceFlux, is)
);
// Constructors
//- Construct for interpolating given field
multivariateSurfaceInterpolationScheme
(
const fvMesh& mesh,
const fieldTable& fields,
const surfaceScalarField& faceFlux,
Istream& schemeData
);
// Selectors
//- Return a pointer to a new gradScheme created on freestore
static tmp<multivariateSurfaceInterpolationScheme<Type> > New
(
const fvMesh& mesh,
const fieldTable& fields,
const surfaceScalarField& faceFlux,
Istream& schemeData
);
//- Destructor
virtual ~multivariateSurfaceInterpolationScheme();
// Member Functions
//- Return mesh reference
const fvMesh& mesh() const
{
return mesh_;
}
//- Return fields to be interpolated
const fieldTable& fields() const
{
return fields_;
}
// Member Operators
//- surfaceInterpolationScheme sub-class returned by operator(field)
// which is used as the interpolation scheme for the field
class fieldScheme
:
public surfaceInterpolationScheme<Type>
{
public:
// Constructors
fieldScheme
(
const GeometricField<Type, fvPatchField, volMesh>& field
)
:
surfaceInterpolationScheme<Type>(field.mesh())
{}
// Member Functions
//- Return the interpolation weighting factors
virtual tmp<surfaceScalarField> weights
(
const GeometricField<Type, fvPatchField, volMesh>& field
) const = 0;
};
virtual tmp<surfaceInterpolationScheme<Type> > operator()
(
const GeometricField<Type, fvPatchField, volMesh>& field
) const = 0;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Add the patch constructor functions to the hash tables
#define makeMultivariateSurfaceInterpolationTypeScheme(SS, Type) \
\
defineNamedTemplateTypeNameAndDebug(SS<Type>, 0); \
\
multivariateSurfaceInterpolationScheme<Type>:: \
addIstreamConstructorToTable<SS<Type> > \
add##SS##Type##ConstructorToTable_;
#define makeMultivariateSurfaceInterpolationScheme(SS) \
\
makeMultivariateSurfaceInterpolationTypeScheme(SS, scalar) \
makeMultivariateSurfaceInterpolationTypeScheme(SS, vector) \
makeMultivariateSurfaceInterpolationTypeScheme(SS, sphericalTensor) \
makeMultivariateSurfaceInterpolationTypeScheme(SS, symmTensor) \
makeMultivariateSurfaceInterpolationTypeScheme(SS, tensor)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
# include "multivariateSurfaceInterpolationScheme.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
#
# Required Modules
# - beautifulsoup4
# - html5lib
# - requests
#
import sys
import os
import re
import logging
import multiprocessing
import requests
from bs4 import BeautifulSoup
import unicodedata
from debug import Debug
from apkhelper import ApkVersionInfo
from reporthelper import ReportHelper
###################
# DEBUG VARS #
###################
# Debug.DEBUG = True
# Debug.READFROMFILE = True # Read from file for debugging
# Debug.SAVELASTFILE = True # Write to file upon each request
###################
# END: DEBUG VARS #
###################
###################
# Globals #
###################
# logging
logFile = '{0}.log'.format(os.path.basename(__file__))
logLevel = (logging.DEBUG if Debug.DEBUG else logging.INFO)
logFormat = '%(asctime)s %(levelname)s/%(funcName)s(%(process)-5d): %(message)s'
class ApkdlCrawler(object):
def __init__(self, report, dlFiles=[], dlFilesBeta=[]):
self.report = report
self.dlFiles = dlFiles
self.dlFilesBeta = dlFilesBeta
def getUrlFromRedirect(self, apkname, url):
"""
getUrlFromRedirect(url):
"""
link = ''
session = requests.Session()
logging.debug('Requesting2: ' + url)
resp = session.get(url)
html = unicodedata.normalize('NFKD', resp.text).encode('ascii', 'ignore')
try:
dom = BeautifulSoup(html, 'html5lib')
link = dom.find('span', {'class': 'glyphicon glyphicon-cloud-download'}).parent['href']
except:
logging.exception('!!! Error parsing html from: "{0}"'.format(url))
return link
# END: def getUrlFromRedirect:
def downloadApk(self, apkInfo, isBeta=False):
"""
downloadApk(apkInfo): Download the specified URL to APK file name
"""
apkname = ('beta.' if isBeta else '') + avi.getFilename()
url = self.getUrlFromRedirect(apkname, apkInfo.download_src)
if url == '':
logging.error('Unable to determine redirect url for ' + apkname)
return
logging.info('Downloading "{0}" from: {1}'.format(apkname, url))
try:
if os.path.exists(apkname):
logging.info('{0} already exists'.format(apkname))
return
if os.path.exists(os.path.join('.', 'apkcrawler', apkname)):
logging.info('{0} already exists (in ./apkcrawler/)'.format(apkname))
return
if os.path.exists(os.path.join('..', 'apkcrawler', apkname)):
logging.info('{0} already exists (in ../apkcrawler/)'.format(apkname))
return
# Open the url
session = requests.Session()
r = session.get(url)
with open(apkname, 'wb') as local_file:
local_file.write(r.content)
logging.debug(('beta:' if isBeta else 'reg :') + apkname)
return (('beta:' if isBeta else '' ) + apkname)
except OSError:
logging.exception('!!! Filename is not valid: "{0}"'.format(apkname))
# END: def downloadApk
def checkOneApp(self, apkid):
"""
checkOneApp(apkid):
"""
logging.info('Checking app: {0}'.format(apkid))
filenames = []
url = 'http://apk-dl.com/' + apkid
session = requests.Session()
logging.debug('Requesting: ' + url)
resp = session.get(url)
html = unicodedata.normalize('NFKD', resp.text).encode('ascii', 'ignore')
try:
dom = BeautifulSoup(html, 'html5lib')
apklist = dom.findAll('ul', {'class': 'apks dlist'})[0]
apks = apklist.findAll('div', {'class': 'details'})
for apk in apks:
items = apk.findAll('div')
dApk = {}
for item in items:
itext = '{0}'.format(item.get_text().encode('ascii', 'ignore'))
itext = re.sub('\s', '', itext)
itextsp = itext.split(':', 1)
if len(itextsp) == 2:
dApk[str(itextsp[0])] = str(itextsp[1])
apkurl = apk.find('a', {'class': 'btn btn-success'})
if apkurl:
dApk['url'] = 'http:' + apkurl['href']
Debug.printDictionary(dApk)
if 'Version' in dApk and 'RequiresAndroid' in dApk:
(trash, sdk) = dApk['RequiresAndroid'].split('API:', 1)
sdk = sdk[0:-1]
(ver, vercode) = dApk['Version'].split('(Code:', 1)
ver = ver.split('(', 1)[0].strip()
vercode = vercode[0:-1].strip()
avi = ApkVersionInfo(name=apkid,
sdk=sdk,
ver=ver,
vercode=vercode,
download_src=dApk['url'],
crawler_name=self.__class__.__name__
)
if self.report.isThisApkNeeded(avi):
filenames.append(self.downloadApk(avi))
except IndexError:
logging.info('{0} not supported by apk-dl.com ...'.format(apkid))
except:
logging.exception('!!! Error parsing html from: "{0}"'.format(url))
return filenames
# END: def checkOneApp:
def crawl(self, threads=5):
"""
crawl(): check all apk-dl apps
"""
# Start checking all apkids ...
p = multiprocessing.Pool(processes=threads, maxtasksperchild=5) # Run only 5 tasks before re-placing the process
r = p.map_async(unwrap_self_checkOneApp, list(zip([self] * len(list(self.report.getAllApkIds())), list(self.report.getAllApkIds()))), callback=unwrap_callback)
r.wait()
(self.dlFiles, self.dlFilesBeta) = unwrap_getresults()
# END: crawl():
# END: class ApkdlCrawler
nonbeta = []
beta = []
def unwrap_callback(results):
for resultlist in results:
for result in resultlist:
if result:
if result.startswith('beta:'):
beta.append(result[5:])
else:
nonbeta.append(result)
def unwrap_getresults():
return (nonbeta, beta)
def unwrap_self_checkOneApp(arg, **kwarg):
return ApkdlCrawler.checkOneApp(*arg, **kwarg)
if __name__ == "__main__":
"""
main(): single parameter for report_sources.sh output
"""
logging.basicConfig(filename=logFile, filemode='w', level=logLevel, format=logFormat)
logging.getLogger("requests").setLevel(logging.WARNING)
lines = ''
if len(sys.argv[1:]) == 1:
with open(sys.argv[1]) as report:
lines = report.readlines()
else:
lines = sys.stdin.readlines()
report = ReportHelper(lines)
if len(list(report.getAllApkIds())) == 0:
print('ERROR: expecting:')
print(' - 1 parameter (report file from output of report_sources.sh)')
print(' or ')
print(' - stdin from report_sources.sh')
exit(1)
crawler = ApkdlCrawler(report)
crawler.crawl()
outputString = ' '.join(crawler.dlFiles)
if crawler.dlFilesBeta:
outputString += ' beta ' + ' '.join(crawler.dlFilesBeta)
if outputString:
print(outputString)
sys.stdout.flush()
logging.debug('Done ...')
| {
"pile_set_name": "Github"
} |
//
// optional.hpp
// blocksci_interface
//
// Created by Harry Kalodner on 11/1/18.
//
#ifndef generic_proxy_optional_hpp
#define generic_proxy_optional_hpp
#include "python_fwd.hpp"
#include <pybind11/pybind11.h>
void addOptionalProxyMethods(pybind11::class_<OptionalProxy, RangeProxy> &cl, pybind11::module &m);
#endif /* generic_proxy_optional_hpp */
| {
"pile_set_name": "Github"
} |
File: localTypeAliasConstructor.kt - 1fa1b861e3caf79f40a3bcdb27a72ebe
NL("\n")
NL("\n")
packageHeader
importList
topLevelObject
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("Cell")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("TC")
RANGLE(">")
primaryConstructor
classParameters
LPAREN("(")
classParameter
VAL("val")
simpleIdentifier
Identifier("x")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("TC")
RPAREN(")")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
simpleIdentifier
Identifier("id")
functionValueParameters
LPAREN("(")
functionValueParameter
parameter
simpleIdentifier
Identifier("x")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RPAREN(")")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
functionBody
block
LCURL("{")
NL("\n")
statements
statement
declaration
typeAlias
TYPE_ALIAS("typealias")
simpleIdentifier
Identifier("C")
ASSIGNMENT("=")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Cell")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
semis
NL("\n")
statement
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("Local")
primaryConstructor
classParameters
LPAREN("(")
classParameter
VAL("val")
simpleIdentifier
Identifier("cell")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("C")
RPAREN(")")
semis
NL("\n")
statement
declaration
propertyDeclaration
VAL("val")
variableDeclaration
simpleIdentifier
Identifier("cx")
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("C")
callSuffix
valueArguments
LPAREN("(")
valueArgument
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("x")
RPAREN(")")
semis
NL("\n")
statement
declaration
propertyDeclaration
VAL("val")
variableDeclaration
simpleIdentifier
Identifier("c")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("C")
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("Local")
postfixUnarySuffix
callSuffix
valueArguments
LPAREN("(")
valueArgument
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("cx")
RPAREN(")")
postfixUnarySuffix
navigationSuffix
memberAccessOperator
DOT(".")
simpleIdentifier
Identifier("cell")
semis
NL("\n")
statement
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
jumpExpression
RETURN("return")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("c")
postfixUnarySuffix
navigationSuffix
memberAccessOperator
DOT(".")
simpleIdentifier
Identifier("x")
semis
NL("\n")
RCURL("}")
semis
NL("\n")
EOF("<EOF>")
| {
"pile_set_name": "Github"
} |
.TH PCRE_FREE_SUBSTRING 3
.SH NAME
PCRE - Perl-compatible regular expressions
.SH SYNOPSIS
.rs
.sp
.B #include <pcre.h>
.PP
.SM
.B void pcre_free_substring(const char *\fIstringptr\fP);
.
.SH DESCRIPTION
.rs
.sp
This is a convenience function for freeing the store obtained by a previous
call to \fBpcre_get_substring()\fP or \fBpcre_get_named_substring()\fP. Its
only argument is a pointer to the string.
.P
There is a complete description of the PCRE native API in the
.\" HREF
\fBpcreapi\fP
.\"
page and a description of the POSIX API in the
.\" HREF
\fBpcreposix\fP
.\"
page.
| {
"pile_set_name": "Github"
} |
#!/bin/sh
##
## Copyright (c) 2014 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENTS. All contributing project authors may
## be found in the AUTHORS file in the root of the source tree.
##
## This file tests vpxdec. To add new tests to this file, do the following:
## 1. Write a shell function (this is your test).
## 2. Add the function to vpxdec_tests (on a new line).
##
. $(dirname $0)/tools_common.sh
# Environment check: Make sure input is available.
vpxdec_verify_environment() {
if [ ! -e "${VP8_IVF_FILE}" ] || [ ! -e "${VP9_WEBM_FILE}" ] || \
[ ! -e "${VP9_FPM_WEBM_FILE}" ] || \
[ ! -e "${VP9_LT_50_FRAMES_WEBM_FILE}" ] ; then
elog "Libvpx test data must exist in LIBVPX_TEST_DATA_PATH."
return 1
fi
if [ -z "$(vpx_tool_path vpxdec)" ]; then
elog "vpxdec not found. It must exist in LIBVPX_BIN_PATH or its parent."
return 1
fi
}
# Wrapper function for running vpxdec with pipe input. Requires that
# LIBVPX_BIN_PATH points to the directory containing vpxdec. $1 is used as the
# input file path and shifted away. All remaining parameters are passed through
# to vpxdec.
vpxdec_pipe() {
local readonly decoder="$(vpx_tool_path vpxdec)"
local readonly input="$1"
shift
cat "${input}" | eval "${VPX_TEST_PREFIX}" "${decoder}" - "$@" ${devnull}
}
# Wrapper function for running vpxdec. Requires that LIBVPX_BIN_PATH points to
# the directory containing vpxdec. $1 one is used as the input file path and
# shifted away. All remaining parameters are passed through to vpxdec.
vpxdec() {
local readonly decoder="$(vpx_tool_path vpxdec)"
local readonly input="$1"
shift
eval "${VPX_TEST_PREFIX}" "${decoder}" "$input" "$@" ${devnull}
}
vpxdec_can_decode_vp8() {
if [ "$(vp8_decode_available)" = "yes" ]; then
echo yes
fi
}
vpxdec_can_decode_vp9() {
if [ "$(vp9_decode_available)" = "yes" ]; then
echo yes
fi
}
vpxdec_vp8_ivf() {
if [ "$(vpxdec_can_decode_vp8)" = "yes" ]; then
vpxdec "${VP8_IVF_FILE}" --summary --noblit
fi
}
vpxdec_vp8_ivf_pipe_input() {
if [ "$(vpxdec_can_decode_vp8)" = "yes" ]; then
vpxdec_pipe "${VP8_IVF_FILE}" --summary --noblit
fi
}
vpxdec_vp9_webm() {
if [ "$(vpxdec_can_decode_vp9)" = "yes" ] && \
[ "$(webm_io_available)" = "yes" ]; then
vpxdec "${VP9_WEBM_FILE}" --summary --noblit
fi
}
vpxdec_vp9_webm_frame_parallel() {
if [ "$(vpxdec_can_decode_vp9)" = "yes" ] && \
[ "$(webm_io_available)" = "yes" ]; then
for threads in 2 3 4 5 6 7 8; do
vpxdec "${VP9_FPM_WEBM_FILE}" --summary --noblit --threads=$threads \
--frame-parallel
done
fi
}
vpxdec_vp9_webm_less_than_50_frames() {
# ensure that reaching eof in webm_guess_framerate doesn't result in invalid
# frames in actual webm_read_frame calls.
if [ "$(vpxdec_can_decode_vp9)" = "yes" ] && \
[ "$(webm_io_available)" = "yes" ]; then
local readonly decoder="$(vpx_tool_path vpxdec)"
local readonly expected=10
local readonly num_frames=$(${VPX_TEST_PREFIX} "${decoder}" \
"${VP9_LT_50_FRAMES_WEBM_FILE}" --summary --noblit 2>&1 \
| awk '/^[0-9]+ decoded frames/ { print $1 }')
if [ "$num_frames" -ne "$expected" ]; then
elog "Output frames ($num_frames) != expected ($expected)"
return 1
fi
fi
}
vpxdec_tests="vpxdec_vp8_ivf
vpxdec_vp8_ivf_pipe_input
vpxdec_vp9_webm
vpxdec_vp9_webm_frame_parallel
vpxdec_vp9_webm_less_than_50_frames"
run_tests vpxdec_verify_environment "${vpxdec_tests}"
| {
"pile_set_name": "Github"
} |
- BeanFactory : Spring框架的核心,实现了许多核心功能
- ApplicationContext 是Context模块的核心接口
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1994, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.tools.java;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.ByteArrayInputStream;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
/**
* WARNING: The contents of this source file are not part of any
* supported API. Code that depends on them does so at its own risk:
* they are subject to change or removal without notice.
*/
@SuppressWarnings("deprecation")
public final
class BinaryClass extends ClassDefinition implements Constants {
BinaryConstantPool cpool;
BinaryAttribute atts;
Vector<ClassDeclaration> dependencies;
private boolean haveLoadedNested = false;
/**
* Constructor
*/
public BinaryClass(Object source, ClassDeclaration declaration, int modifiers,
ClassDeclaration superClass, ClassDeclaration interfaces[],
Vector<ClassDeclaration> dependencies) {
super(source, 0, declaration, modifiers, null, null);
this.dependencies = dependencies;
this.superClass = superClass;
this.interfaces = interfaces;
}
/**
* Flags used by basicCheck() to avoid duplicate calls.
* (Part of fix for 4105911)
*/
private boolean basicCheckDone = false;
private boolean basicChecking = false;
/**
* Ready a BinaryClass for further checking. Note that, until recently,
* BinaryClass relied on the default basicCheck() provided by
* ClassDefinition. The definition here has been added to ensure that
* the information generated by collectInheritedMethods is available
* for BinaryClasses.
*/
protected void basicCheck(Environment env) throws ClassNotFound {
if (tracing) env.dtEnter("BinaryClass.basicCheck: " + getName());
// We need to guard against duplicate calls to basicCheck(). They
// can lead to calling collectInheritedMethods() for this class
// from within a previous call to collectInheritedMethods() for
// this class. That is not allowed.
// (Part of fix for 4105911)
if (basicChecking || basicCheckDone) {
if (tracing) env.dtExit("BinaryClass.basicCheck: OK " + getName());
return;
}
if (tracing) env.dtEvent("BinaryClass.basicCheck: CHECKING " + getName());
basicChecking = true;
super.basicCheck(env);
// Collect inheritance information.
if (doInheritanceChecks) {
collectInheritedMethods(env);
}
basicCheckDone = true;
basicChecking = false;
if (tracing) env.dtExit("BinaryClass.basicCheck: " + getName());
}
/**
* Load a binary class
*/
public static BinaryClass load(Environment env, DataInputStream in) throws IOException {
return load(env, in, ~(ATT_CODE|ATT_ALLCLASSES));
}
public static BinaryClass load(Environment env,
DataInputStream in, int mask) throws IOException {
// Read the header
int magic = in.readInt(); // JVM 4.1 ClassFile.magic
if (magic != JAVA_MAGIC) {
throw new ClassFormatError("wrong magic: " + magic + ", expected " + JAVA_MAGIC);
}
int minor_version = in.readUnsignedShort(); // JVM 4.1 ClassFile.minor_version
int version = in.readUnsignedShort(); // JVM 4.1 ClassFile.major_version
if (version < JAVA_MIN_SUPPORTED_VERSION) {
throw new ClassFormatError(
sun.tools.javac.Main.getText(
"javac.err.version.too.old",
String.valueOf(version)));
} else if ((version > JAVA_MAX_SUPPORTED_VERSION)
|| (version == JAVA_MAX_SUPPORTED_VERSION
&& minor_version > JAVA_MAX_SUPPORTED_MINOR_VERSION)) {
throw new ClassFormatError(
sun.tools.javac.Main.getText(
"javac.err.version.too.recent",
version+"."+minor_version));
}
// Read the constant pool
BinaryConstantPool cpool = new BinaryConstantPool(in);
// The dependencies of this class
Vector<ClassDeclaration> dependencies = cpool.getDependencies(env);
// Read modifiers
int classMod = in.readUnsignedShort() & ACCM_CLASS; // JVM 4.1 ClassFile.access_flags
// Read the class name - from JVM 4.1 ClassFile.this_class
ClassDeclaration classDecl = cpool.getDeclaration(env, in.readUnsignedShort());
// Read the super class name (may be null) - from JVM 4.1 ClassFile.super_class
ClassDeclaration superClassDecl = cpool.getDeclaration(env, in.readUnsignedShort());
// Read the interface names - from JVM 4.1 ClassFile.interfaces_count
ClassDeclaration interfaces[] = new ClassDeclaration[in.readUnsignedShort()];
for (int i = 0 ; i < interfaces.length ; i++) {
// JVM 4.1 ClassFile.interfaces[]
interfaces[i] = cpool.getDeclaration(env, in.readUnsignedShort());
}
// Allocate the class
BinaryClass c = new BinaryClass(null, classDecl, classMod, superClassDecl,
interfaces, dependencies);
c.cpool = cpool;
// Add any additional dependencies
c.addDependency(superClassDecl);
// Read the fields
int nfields = in.readUnsignedShort(); // JVM 4.1 ClassFile.fields_count
for (int i = 0 ; i < nfields ; i++) {
// JVM 4.5 field_info.access_flags
int fieldMod = in.readUnsignedShort() & ACCM_FIELD;
// JVM 4.5 field_info.name_index
Identifier fieldName = cpool.getIdentifier(in.readUnsignedShort());
// JVM 4.5 field_info.descriptor_index
Type fieldType = cpool.getType(in.readUnsignedShort());
BinaryAttribute atts = BinaryAttribute.load(in, cpool, mask);
c.addMember(new BinaryMember(c, fieldMod, fieldType, fieldName, atts));
}
// Read the methods
int nmethods = in.readUnsignedShort(); // JVM 4.1 ClassFile.methods_count
for (int i = 0 ; i < nmethods ; i++) {
// JVM 4.6 method_info.access_flags
int methMod = in.readUnsignedShort() & ACCM_METHOD;
// JVM 4.6 method_info.name_index
Identifier methName = cpool.getIdentifier(in.readUnsignedShort());
// JVM 4.6 method_info.descriptor_index
Type methType = cpool.getType(in.readUnsignedShort());
BinaryAttribute atts = BinaryAttribute.load(in, cpool, mask);
c.addMember(new BinaryMember(c, methMod, methType, methName, atts));
}
// Read the class attributes
c.atts = BinaryAttribute.load(in, cpool, mask);
// See if the SourceFile is known
byte data[] = c.getAttribute(idSourceFile);
if (data != null) {
DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(data));
// JVM 4.7.2 SourceFile_attribute.sourcefile_index
c.source = cpool.getString(dataStream.readUnsignedShort());
}
// See if the Documentation is know
data = c.getAttribute(idDocumentation);
if (data != null) {
c.documentation = new DataInputStream(new ByteArrayInputStream(data)).readUTF();
}
// Was it compiled as deprecated?
if (c.getAttribute(idDeprecated) != null) {
c.modifiers |= M_DEPRECATED;
}
// Was it synthesized by the compiler?
if (c.getAttribute(idSynthetic) != null) {
c.modifiers |= M_SYNTHETIC;
}
return c;
}
/**
* Called when an environment ties a binary definition to a declaration.
* At this point, auxiliary definitions may be loaded.
*/
public void loadNested(Environment env) {
loadNested(env, 0);
}
public void loadNested(Environment env, int flags) {
// Sanity check.
if (haveLoadedNested) {
// Duplicate calls most likely should not occur, but they do
// in javap. Be tolerant of them for the time being.
// throw new CompilerError("multiple loadNested");
if (tracing) env.dtEvent("loadNested: DUPLICATE CALL SKIPPED");
return;
}
haveLoadedNested = true;
// Read class-nesting information.
try {
byte data[];
data = getAttribute(idInnerClasses);
if (data != null) {
initInnerClasses(env, data, flags);
}
} catch (IOException ee) {
// The inner classes attribute is not well-formed.
// It may, for example, contain no data. Report this.
// We used to throw a CompilerError here (bug 4095108).
env.error(0, "malformed.attribute", getClassDeclaration(),
idInnerClasses);
if (tracing)
env.dtEvent("loadNested: MALFORMED ATTRIBUTE (InnerClasses)");
}
}
private void initInnerClasses(Environment env,
byte data[],
int flags) throws IOException {
DataInputStream ds = new DataInputStream(new ByteArrayInputStream(data));
int nrec = ds.readUnsignedShort(); // InnerClasses_attribute.number_of_classes
for (int i = 0; i < nrec; i++) {
// For each inner class name transformation, we have a record
// with the following fields:
//
// u2 inner_class_info_index; // CONSTANT_Class_info index
// u2 outer_class_info_index; // CONSTANT_Class_info index
// u2 inner_name_index; // CONSTANT_Utf8_info index
// u2 inner_class_access_flags; // access_flags bitmask
//
// The spec states that outer_class_info_index is 0 iff
// the inner class is not a member of its enclosing class (i.e.
// it is a local or anonymous class). The spec also states
// that if a class is anonymous then inner_name_index should
// be 0.
//
// Prior to jdk1.2, javac did not implement the spec. Instead
// it <em>always</em> set outer_class_info_index to the
// enclosing outer class and if the class was anonymous,
// it set inner_name_index to be the index of a CONSTANT_Utf8
// entry containing the null string "" (idNull). This code is
// designed to handle either kind of class file.
//
// See also the compileClass() method in SourceClass.java.
// Read in the inner_class_info
// InnerClasses_attribute.classes.inner_class_info_index
int inner_index = ds.readUnsignedShort();
// could check for zero.
ClassDeclaration inner = cpool.getDeclaration(env, inner_index);
// Read in the outer_class_info. Note that the index will be
// zero if the class is "not a member".
ClassDeclaration outer = null;
// InnerClasses_attribute.classes.outer_class_info_index
int outer_index = ds.readUnsignedShort();
if (outer_index != 0) {
outer = cpool.getDeclaration(env, outer_index);
}
// Read in the inner_name_index. This may be zero. An anonymous
// class will either have an inner_nm_index of zero (as the spec
// dictates) or it will have an inner_nm of idNull (for classes
// generated by pre-1.2 compilers). Handle both.
Identifier inner_nm = idNull;
// InnerClasses_attribute.classes.inner_name_index
int inner_nm_index = ds.readUnsignedShort();
if (inner_nm_index != 0) {
inner_nm = Identifier.lookup(cpool.getString(inner_nm_index));
}
// Read in the modifiers for the inner class.
// InnerClasses_attribute.classes.inner_name_index
int mods = ds.readUnsignedShort();
// Is the class accessible?
// The old code checked for
//
// (!inner_nm.equals(idNull) && (mods & M_PRIVATE) == 0)
//
// which we will preserve to keep it working for class files
// generated by 1.1 compilers. In addition we check for
//
// (outer != null)
//
// as an additional check that only makes sense with 1.2
// generated files. Note that it is entirely possible that
// the M_PRIVATE bit is always enough. We are being
// conservative here.
//
// The ATT_ALLCLASSES flag causes the M_PRIVATE modifier
// to be ignored, and is used by tools such as 'javap' that
// wish to examine all classes regardless of the normal access
// controls that apply during compilation. Note that anonymous
// and local classes are still not considered accessible, though
// named local classes in jdk1.1 may slip through. Note that
// this accessibility test is an optimization, and it is safe to
// err on the side of greater accessibility.
boolean accessible =
(outer != null) &&
(!inner_nm.equals(idNull)) &&
((mods & M_PRIVATE) == 0 ||
(flags & ATT_ALLCLASSES) != 0);
// The reader should note that there has been a significant change
// in the way that the InnerClasses attribute is being handled.
// In particular, previously the compiler called initInner() for
// <em>every</em> inner class. Now the compiler does not call
// initInner() if the inner class is inaccessible. This means
// that inaccessible inner classes don't have any of the processing
// from initInner() done for them: fixing the access flags,
// setting outerClass, setting outerMember in their outerClass,
// etc. We believe this is fine: if the class is inaccessible
// and binary, then everyone who needs to see its internals
// has already been compiled. Hopefully.
if (accessible) {
Identifier nm =
Identifier.lookupInner(outer.getName(), inner_nm);
// Tell the type module about the nesting relation:
Type.tClass(nm);
if (inner.equals(getClassDeclaration())) {
// The inner class in the record is this class.
try {
ClassDefinition outerClass = outer.getClassDefinition(env);
initInner(outerClass, mods);
} catch (ClassNotFound e) {
// report the error elsewhere
}
} else if (outer.equals(getClassDeclaration())) {
// The outer class in the record is this class.
try {
ClassDefinition innerClass =
inner.getClassDefinition(env);
initOuter(innerClass, mods);
} catch (ClassNotFound e) {
// report the error elsewhere
}
}
}
}
}
private void initInner(ClassDefinition outerClass, int mods) {
if (getOuterClass() != null)
return; // already done
/******
// Maybe set static, protected, or private.
if ((modifiers & M_PUBLIC) != 0)
mods &= M_STATIC;
else
mods &= M_PRIVATE | M_PROTECTED | M_STATIC;
modifiers |= mods;
******/
// For an inner class, the class access may have been weakened
// from that originally declared the source. We must take the
// actual access permissions against which we check any source
// we are currently compiling from the InnerClasses attribute.
// We attempt to guard here against bogus combinations of modifiers.
if ((mods & M_PRIVATE) != 0) {
// Private cannot be combined with public or protected.
mods &= ~(M_PUBLIC | M_PROTECTED);
} else if ((mods & M_PROTECTED) != 0) {
// Protected cannot be combined with public.
mods &= ~M_PUBLIC;
}
if ((mods & M_INTERFACE) != 0) {
// All interfaces are implicitly abstract.
// All interfaces that are members of a type are implicitly static.
mods |= (M_ABSTRACT | M_STATIC);
}
if (outerClass.isInterface()) {
// All types that are members of interfaces are implicitly
// public and static.
mods |= (M_PUBLIC | M_STATIC);
mods &= ~(M_PRIVATE | M_PROTECTED);
}
modifiers = mods;
setOuterClass(outerClass);
for (MemberDefinition field = getFirstMember();
field != null;
field = field.getNextMember()) {
if (field.isUplevelValue()
&& outerClass.getType().equals(field.getType())
&& field.getName().toString().startsWith(prefixThis)) {
setOuterMember(field);
}
}
}
private void initOuter(ClassDefinition innerClass, int mods) {
if (innerClass instanceof BinaryClass)
((BinaryClass)innerClass).initInner(this, mods);
addMember(new BinaryMember(innerClass));
}
/**
* Write the class out to a given stream. This function mirrors the loader.
*/
public void write(Environment env, OutputStream out) throws IOException {
DataOutputStream data = new DataOutputStream(out);
// write out the header
data.writeInt(JAVA_MAGIC);
data.writeShort(env.getMinorVersion());
data.writeShort(env.getMajorVersion());
// Write out the constant pool
cpool.write(data, env);
// Write class information
data.writeShort(getModifiers() & ACCM_CLASS);
data.writeShort(cpool.indexObject(getClassDeclaration(), env));
data.writeShort((getSuperClass() != null)
? cpool.indexObject(getSuperClass(), env) : 0);
data.writeShort(interfaces.length);
for (int i = 0 ; i < interfaces.length ; i++) {
data.writeShort(cpool.indexObject(interfaces[i], env));
}
// count the fields and the methods
int fieldCount = 0, methodCount = 0;
for (MemberDefinition f = firstMember; f != null; f = f.getNextMember())
if (f.isMethod()) methodCount++; else fieldCount++;
// write out each the field count, and then each field
data.writeShort(fieldCount);
for (MemberDefinition f = firstMember; f != null; f = f.getNextMember()) {
if (!f.isMethod()) {
data.writeShort(f.getModifiers() & ACCM_FIELD);
String name = f.getName().toString();
String signature = f.getType().getTypeSignature();
data.writeShort(cpool.indexString(name, env));
data.writeShort(cpool.indexString(signature, env));
BinaryAttribute.write(((BinaryMember)f).atts, data, cpool, env);
}
}
// write out each method count, and then each method
data.writeShort(methodCount);
for (MemberDefinition f = firstMember; f != null; f = f.getNextMember()) {
if (f.isMethod()) {
data.writeShort(f.getModifiers() & ACCM_METHOD);
String name = f.getName().toString();
String signature = f.getType().getTypeSignature();
data.writeShort(cpool.indexString(name, env));
data.writeShort(cpool.indexString(signature, env));
BinaryAttribute.write(((BinaryMember)f).atts, data, cpool, env);
}
}
// write out the class attributes
BinaryAttribute.write(atts, data, cpool, env);
data.flush();
}
/**
* Get the dependencies
*/
public Enumeration<ClassDeclaration> getDependencies() {
return dependencies.elements();
}
/**
* Add a dependency
*/
public void addDependency(ClassDeclaration c) {
if ((c != null) && !dependencies.contains(c)) {
dependencies.addElement(c);
}
}
/**
* Get the constant pool
*/
public BinaryConstantPool getConstants() {
return cpool;
}
/**
* Get a class attribute
*/
public byte getAttribute(Identifier name)[] {
for (BinaryAttribute att = atts ; att != null ; att = att.next) {
if (att.name.equals(name)) {
return att.data;
}
}
return null;
}
}
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser.
*/
@protocol ATAssetLinkControllerObserver <NSObject>
@required
- (void)assetLinkController:(ATAssetLinkController *)arg1 didFinishAsset:(ATAsset *)arg2;
- (void)assetLinkController:(ATAssetLinkController *)arg1 didUpdateAsset:(ATAsset *)arg2;
@optional
- (void)assetLinkController:(ATAssetLinkController *)arg1 didEnqueueAsset:(ATAsset *)arg2;
- (void)assetLinkController:(ATAssetLinkController *)arg1 didUpdateAssetState:(NSArray *)arg2;
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Docs For Class Swift_StreamFilters_StringReplacementFilterFactory</title>
<link rel="stylesheet" href="../media/stylesheet.css" />
<script src="../media/lib/classTree.js"></script>
<link id="webfx-tab-style-sheet" type="text/css" rel="stylesheet" href="../media/lib/tab.webfx.css" />
<script type="text/javascript" src="../media/lib/tabpane.js"></script>
<script language="javascript" type="text/javascript" src="../media/lib/ua.js"></script>
<script language="javascript" type="text/javascript">
var imgPlus = new Image();
var imgMinus = new Image();
imgPlus.src = "../media/images/plus.gif";
imgMinus.src = "../media/images/minus.gif";
function showNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgMinus.src;
oTable.style.display = "block";
}
function hideNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgPlus.src;
oTable.style.display = "none";
}
function nodeIsVisible(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
break;
}
return (oTable && oTable.style.display == "block");
}
function toggleNodeVisibility(Node){
if (nodeIsVisible(Node)){
hideNode(Node);
}else{
showNode(Node);
}
}
</script>
<!-- template designed by Julien Damon based on PHPEdit's generated templates, and tweaked by Greg Beaver -->
<body bgcolor="#ffffff" >
<!-- Start of Class Data -->
<h2>
Class Swift_StreamFilters_StringReplacementFilterFactory
</h2> (line <span class="linenumber">19</span>)
<div class="tab-pane" id="tabPane1">
<script type="text/javascript">
tp1 = new WebFXTabPane( document.getElementById( "tabPane1" ));
</script>
<div class="tab-page" id="Description">
<h2 class="tab">Description</h2>
<pre>
</pre>
<p>
<b><i>Located in File: <a href="_vendors---swiftMailer---classes---Swift---StreamFilters---StringReplacementFilterFactory.php.html">/vendors/swiftMailer/classes/Swift/StreamFilters/StringReplacementFilterFactory.php</a></i></b><br>
</p>
<!-- ========== Info from phpDoc block ========= -->
<h5>Creates filters for replacing needles in a string buffer.</h5>
<ul>
<li><strong>author:</strong> - Chris Corbyn</li>
</ul>
<br /><hr />
</div>
<script type="text/javascript">tp1.addTabPage( document.getElementById( "Description" ) );</script>
<div class="tab-page" id="tabPage1">
<h2 class="tab">Class Variables</h2>
<!-- ============ VARIABLE DETAIL =========== -->
<strong>Summary:</strong><br />
<hr />
<script type="text/javascript">tp1.addTabPage( document.getElementById( "tabPage1" ) );</script>
</div>
<div class="tab-page" id="constantsTabpage">
<h2 class="tab">Class Constants</h2>
<!-- ============ VARIABLE DETAIL =========== -->
<strong>Summary:</strong><br />
<hr />
<script type="text/javascript">tp1.addTabPage( document.getElementById( "constantsTabpage" ) );</script>
</div>
<div class="tab-page" id="tabPage2">
<h2 class="tab">Method Detail</h2>
<!-- ============ METHOD DETAIL =========== -->
<strong>Summary:</strong><br />
<div class="method-summary">
<div class="method-definition">
<span class="method-result"><a href="../Swift/Swift_StreamFilter.html">Swift_StreamFilter</a></span>
<a href="#methodcreateFilter" title="details" class="method-name">createFilter</a>
(<span class="var-type">string</span> <span class="var-name">$search</span>, <span class="var-type">string</span> <span class="var-name">$replace</span>)
</div>
</div>
<hr />
<A NAME='method_detail'></A>
<a name="methodcreateFilter" id="methodcreateFilter"><!-- --></a>
<div style="background='#ffffff'"><h4>
<img src="../media/images/PublicMethod.gif" border="0" /> <strong class="method">Method createFilter</strong> (line <span class="linenumber">32</span>)
</h4>
<h4><i><a href="../Swift/Swift_StreamFilter.html">Swift_StreamFilter</a></i> <strong>createFilter(
string
$search, string
$replace)</strong></h4>
<hr class="separator" />
<div class="notes">Implementation of:</div>
<dl>
<dt><a href="../Swift/Swift_ReplacementFilterFactory.html#methodcreateFilter">Swift_ReplacementFilterFactory::createFilter()</a></dt>
<dd>Create a filter to replace $search with $replace.</dd>
</dl>
<!-- ========== Info from phpDoc block ========= -->
<h5>Create a new StreamFilter to replace $search with $replace in a string.</h5>
<h4>Parameters</h4>
<ul>
<li><strong>string $search</strong>: </li>
<li><strong>string $replace</strong>: </li>
</ul>
<h4>Info</h4>
<ul>
<li><strong>access</strong> - public</li>
</ul>
</div>
<script type="text/javascript">tp1.addTabPage( document.getElementById( "tabPage2" ) );</script>
</div>
<div class="tab-page" id="iVars">
<h2 class="tab">Inherited Variables</h2>
<script type="text/javascript">tp1.addTabPage( document.getElementById( "iVars" ) );</script>
<!-- =========== VAR INHERITED SUMMARY =========== -->
<A NAME='var_inherited_summary'><!-- --></A>
<h3>Inherited Class Variable Summary</h3>
</div>
<div class="tab-page" id="iMethods">
<h2 class="tab">Inherited Methods</h2>
<script type="text/javascript">tp1.addTabPage( document.getElementById( "iMethods" ) );</script>
<!-- =========== INHERITED METHOD SUMMARY =========== -->
<A NAME='functions_inherited'><!-- --></A>
<h3>Inherited Method Summary</h3>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
setupAllTabs();
//]]>
</script>
<div id="credit">
<hr />
Documentation generated on Fri, 12 Nov 2010 20:45:30 +0000 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.3</a>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2017 XRADIO TECHNOLOGY CO., LTD. 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.
* 3. Neither the name of XRADIO TECHNOLOGY CO., LTD. nor the names of
* its contributors may 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 THE COPYRIGHT
* OWNER 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 "cmd_util.h"
#include "driver/chip/hal_prcm.h"
#define CMD_REBOOT_BY_WDG 1
#if CMD_REBOOT_BY_WDG
#include "driver/chip/hal_wdg.h"
enum cmd_status cmd_reboot(PRCM_CPUABootFlag flag)
{
cmd_write_respond(CMD_STATUS_OK, cmd_get_status_desc(CMD_STATUS_OK));
HAL_PRCM_SetCPUABootFlag(flag);
HAL_WDG_Reboot();
return CMD_STATUS_ACKED;
}
#else /* CMD_REBOOT_BY_WDG */
#include "driver/chip/hal_nvic.h"
#include "driver/chip/hal_global.h"
#include "driver/chip/system_chip.h"
#include "sys/interrupt.h"
#define CMD_BROM_RESET_HANDLER (*((volatile uint32_t *)0x4))
enum cmd_status cmd_reboot(PRCM_CPUABootFlag flag)
{
uint32_t handler;
cmd_write_respond(CMD_STATUS_OK, cmd_get_status_desc(CMD_STATUS_OK));
cmd_msleep(10);
HAL_PRCM_SetCPUABootFlag(flag);
handler = CMD_BROM_RESET_HANDLER;
#ifdef __CONFIG_CHIP_XR871
handler |= 0x1; /* set thumb bit */
#endif
arch_irq_disable();
HAL_PRCM_DisableSys2();
HAL_PRCM_DisableSys2Power();
HAL_GlobalInit();
SystemDeInit(0);
SCB->VTOR = 0x0;
__set_CONTROL(0); /* reset to Privileged Thread mode and use MSP */
__DSB();
__ISB();
((NVIC_IRQHandler)handler)();
return CMD_STATUS_ACKED;
}
#endif /* CMD_REBOOT_BY_WDG */
enum cmd_status cmd_reboot_exec(char *cmd)
{
return cmd_reboot(PRCM_CPUA_BOOT_FROM_COLD_RESET);
}
enum cmd_status cmd_upgrade_exec(char *cmd)
{
return cmd_reboot(PRCM_CPUA_BOOT_FROM_SYS_UPDATE);
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2020 The Knative 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 logging assists setting up test logging and using leveled logging in tests.
The TLogger is designed to assist the test writer in creating more useful tests and
collecting log data in multiple streams, optimizing for human readability in one and
machine readability in another. It's designed to mimic the testing.T object rather closely and
use Zap logging semantics, both things already in use in Knative, to minimize the time developers
need to spend learning the tool.
Inspired by and uses go-logr.
Advantages
The TLogger enhances test design through subtle nudges and affordances:
* It encourages only logging with .V(), giving the writer a nudge to think about how important it is,
but without requiring them to fit it in a narrowly-defined category.
* Reduces boilerplate of carrying around context for errors in several different variables,
using .WithValues(), which results in more consistent and reusable code across the tests.
Porting
To port code from using testing.T to logging.TLogger, the interfaces knative.dev/pkg/test.T and
knative.dev/pkg/test.TLegacy have been created. All library functions should be refactored to use
one interface and all .Log() calls rewritten to use structured format, which works with testing and
TLogger. If a library function needs test functions not available even in test.TLegacy,
it's probably badly written.
Then any test can be incrementally rewritten to use TLogger, as it coexists with testing.T without issue.
*/
package logging
| {
"pile_set_name": "Github"
} |
package com.baiyi.opscloud.common.exception;
import org.apache.commons.lang3.StringUtils;
/**
* @Author baiyi
* @Date 2020/4/19 12:20 下午
* @Version 1.0
*/
public enum BusinessErrorCodeEnum implements ErrorCode{
UNSPECIFIED("500", "网络异常,请稍后再试");
/** 错误码 */
private final String code;
/** 描述 */
private final String desc;
private BusinessErrorCodeEnum(final String code, final String desc) {
this.code = code;
this.desc = desc;
}
/**
* 根据编码查询枚举。
*
* @param code 编码。
* @return 枚举。
*/
public static BusinessErrorCodeEnum getByCode(String code) {
for (BusinessErrorCodeEnum value : BusinessErrorCodeEnum.values()) {
if (StringUtils.equals(code, value.getCode())) {
return value;
}
}
return UNSPECIFIED;
}
/**
* 枚举是否包含此code
* @param code 枚举code
* @return 结果
*/
public static Boolean contains(String code){
for (BusinessErrorCodeEnum value : BusinessErrorCodeEnum.values()) {
if (StringUtils.equals(code, value.getCode())) {
return true;
}
}
return false;
}
@Override
public String getCode() {
return code;
}
@Override
public String getDesc() {
return desc;
}
}
| {
"pile_set_name": "Github"
} |
//
// cs-tokenizer.cs: The Tokenizer for the C# compiler
// This also implements the preprocessor
//
// Author: Miguel de Icaza (miguel@gnu.org)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.Collections;
namespace Mono.CSharp
{
/// <summary>
/// Tokenizer for C# source code.
/// </summary>
public class Tokenizer : yyParser.yyInput
{
class KeywordEntry<T>
{
public readonly T Token;
public KeywordEntry<T> Next;
public readonly char[] Value;
public KeywordEntry (string value,T token)
{
this.Value = value.ToCharArray ();
this.Token = token;
}
}
sealed class IdentifiersComparer : IEqualityComparer<char[]>
{
readonly int length;
public IdentifiersComparer (int length)
{
this.length = length;
}
public bool Equals (char[] x, char[] y)
{
for (int i = 0; i < length; ++i)
if (x [i] != y [i])
return false;
return true;
}
public int GetHashCode (char[] obj)
{
int h = 0;
for (int i = 0; i < length; ++i)
h = (h << 5) - h + obj [i];
return h;
}
}
//
// This class has to be used by parser only, it reuses token
// details after each file parse completion
//
public class LocatedToken
{
public int row, column;
public string value;
public SourceFile file;
public LocatedToken ()
{
}
public LocatedToken (string value, Location loc)
{
this.value = value;
file = loc.SourceFile;
row = loc.Row;
column = loc.Column;
}
public override string ToString ()
{
return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
}
public Location Location {
get { return new Location (file, row, column); }
}
public string Value {
get { return value; }
}
}
public class LocatedTokenBuffer
{
readonly LocatedToken[] buffer;
public int pos;
public LocatedTokenBuffer ()
{
buffer = new LocatedToken[0];
}
public LocatedTokenBuffer (LocatedToken[] buffer)
{
this.buffer = buffer ?? new LocatedToken[0];
}
public LocatedToken Create (SourceFile file, int row, int column)
{
return Create (null, file, row, column);
}
public LocatedToken Create (string value, SourceFile file, int row, int column)
{
//
// TODO: I am not very happy about the logic but it's the best
// what I could come up with for now.
// Ideally we should be using just tiny buffer (256 elements) which
// is enough to hold all details for currect stack and recycle elements
// poped from the stack but there is a trick needed to recycle
// them properly.
//
LocatedToken entry;
if (pos >= buffer.Length) {
entry = new LocatedToken ();
} else {
entry = buffer[pos];
if (entry == null) {
entry = new LocatedToken ();
buffer[pos] = entry;
}
++pos;
}
entry.value = value;
entry.file = file;
entry.row = row;
entry.column = column;
return entry;
}
//
// Used for token not required by expression evaluator
//
[Conditional ("FULL_AST")]
public void CreateOptional (SourceFile file, int row, int col, ref object token)
{
token = Create (file, row, col);
}
}
public enum PreprocessorDirective
{
Invalid = 0,
Region = 1,
Endregion = 2,
If = 3 | RequiresArgument,
Endif = 4,
Elif = 5 | RequiresArgument,
Else = 6,
Define = 7 | RequiresArgument,
Undef = 8 | RequiresArgument,
Error = 9,
Warning = 10,
Pragma = 11 | CustomArgumentsParsing,
Line = 12 | CustomArgumentsParsing,
CustomArgumentsParsing = 1 << 10,
RequiresArgument = 1 << 11
}
readonly SeekableStreamReader reader;
readonly CompilationSourceFile source_file;
public CompilationSourceFile SourceFile { get { return source_file; } }
readonly CompilerContext context;
SourceFile current_source;
Location hidden_block_start;
int ref_line = 1;
int line = 1;
int col = 0;
int previous_col;
int current_token;
readonly int tab_size;
bool handle_get_set = false;
bool handle_remove_add = false;
bool handle_where = false;
bool handle_typeof = false;
bool lambda_arguments_parsing;
List<Location> escaped_identifiers;
int parsing_generic_less_than;
readonly bool doc_processing;
readonly LocatedTokenBuffer ltb;
//
// Used mainly for parser optimizations. Some expressions for instance
// can appear only in block (including initializer, base initializer)
// scope only
//
public int parsing_block;
internal bool query_parsing;
//
// When parsing type only, useful for ambiguous nullable types
//
public int parsing_type;
//
// Set when parsing generic declaration (type or method header)
//
public bool parsing_generic_declaration;
public bool parsing_generic_declaration_doc;
//
// The value indicates that we have not reach any declaration or
// namespace yet
//
public int parsing_declaration;
public bool parsing_attribute_section;
public bool parsing_modifiers;
//
// The special characters to inject on streams to run the unit parser
// in the special expression mode. Using private characters from
// Plane Sixteen (U+100000 to U+10FFFD)
//
// This character is only tested just before the tokenizer is about to report
// an error; So on the regular operation mode, this addition will have no
// impact on the tokenizer's performance.
//
public const int EvalStatementParserCharacter = 0x100000;
public const int EvalCompilationUnitParserCharacter = 0x100001;
public const int EvalUsingDeclarationsParserCharacter = 0x100002;
public const int DocumentationXref = 0x100003;
//
// XML documentation buffer. The save point is used to divide
// comments on types and comments on members.
//
StringBuilder xml_comment_buffer;
//
// See comment on XmlCommentState enumeration.
//
XmlCommentState xml_doc_state = XmlCommentState.Allowed;
//
// Whether tokens have been seen on this line
//
bool tokens_seen = false;
//
// Set to true once the GENERATE_COMPLETION token has bee
// returned. This helps produce one GENERATE_COMPLETION,
// as many COMPLETE_COMPLETION as necessary to complete the
// AST tree and one final EOF.
//
bool generated;
//
// Whether a token has been seen on the file
// This is needed because `define' is not allowed to be used
// after a token has been seen.
//
bool any_token_seen;
//
// Class variables
//
static readonly KeywordEntry<int>[][] keywords;
static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
static readonly HashSet<string> keyword_strings;
static readonly NumberStyles styles;
static readonly NumberFormatInfo csharp_format_info;
// Pragma arguments
static readonly char[] pragma_warning = "warning".ToCharArray ();
static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
static readonly char[] pragma_checksum = "checksum".ToCharArray ();
static readonly char[] line_hidden = "hidden".ToCharArray ();
static readonly char[] line_default = "default".ToCharArray ();
static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
bool startsLine = true;
internal SpecialsBag sbag;
public bool PropertyParsing {
get { return handle_get_set; }
set { handle_get_set = value; }
}
public bool EventParsing {
get { return handle_remove_add; }
set { handle_remove_add = value; }
}
public bool ConstraintsParsing {
get { return handle_where; }
set { handle_where = value; }
}
public bool TypeOfParsing {
get { return handle_typeof; }
set { handle_typeof = value; }
}
public XmlCommentState doc_state {
get { return xml_doc_state; }
set {
if (value == XmlCommentState.Allowed) {
check_incorrect_doc_comment ();
reset_doc_comment ();
}
xml_doc_state = value;
}
}
//
// This is used to trigger completion generation on the parser
public bool CompleteOnEOF;
void AddEscapedIdentifier (Location loc)
{
if (escaped_identifiers == null)
escaped_identifiers = new List<Location> ();
escaped_identifiers.Add (loc);
}
public bool IsEscapedIdentifier (ATypeNameExpression name)
{
return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
}
//
// Values for the associated token returned
//
internal int putback_char; // Used by repl only
object val;
//
// Pre-processor
//
const int TAKING = 1;
const int ELSE_SEEN = 4;
const int PARENT_TAKING = 8;
const int REGION = 16;
//
// pre-processor if stack state:
//
Stack<int> ifstack;
public const int MaxIdentifierLength = 512;
public const int MaxNumberLength = 512;
readonly char[] id_builder;
readonly Dictionary<char[], string>[] identifiers;
readonly char[] number_builder;
int number_pos;
char[] value_builder = new char[64];
public int Line {
get {
return ref_line;
}
set {
ref_line = value;
}
}
public int Column {
get {
return col;
}
set {
col = value;
}
}
//
// This is used when the tokenizer needs to save
// the current position as it needs to do some parsing
// on its own to deamiguate a token in behalf of the
// parser.
//
Stack<Position> position_stack = new Stack<Position> (2);
class Position
{
public int position;
public int line;
public int ref_line;
public int col;
public Location hidden;
public int putback_char;
public int previous_col;
public Stack<int> ifstack;
public int parsing_generic_less_than;
public int current_token;
public object val;
public Position (Tokenizer t)
{
position = t.reader.Position;
line = t.line;
ref_line = t.ref_line;
col = t.col;
hidden = t.hidden_block_start;
putback_char = t.putback_char;
previous_col = t.previous_col;
if (t.ifstack != null && t.ifstack.Count != 0) {
// There is no simple way to clone Stack<T> all
// methods reverse the order
var clone = t.ifstack.ToArray ();
Array.Reverse (clone);
ifstack = new Stack<int> (clone);
}
parsing_generic_less_than = t.parsing_generic_less_than;
current_token = t.current_token;
val = t.val;
}
}
public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session)
{
this.source_file = file;
this.context = file.Compiler;
this.current_source = file.SourceFile;
this.identifiers = session.Identifiers;
this.id_builder = session.IDBuilder;
this.number_builder = session.NumberBuilder;
this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
reader = input;
putback_char = -1;
xml_comment_buffer = new StringBuilder ();
doc_processing = context.Settings.DocumentationFile != null;
tab_size = context.Settings.TabSize;
}
public void PushPosition ()
{
position_stack.Push (new Position (this));
}
public void PopPosition ()
{
Position p = position_stack.Pop ();
reader.Position = p.position;
ref_line = p.ref_line;
line = p.line;
col = p.col;
hidden_block_start = p.hidden;
putback_char = p.putback_char;
previous_col = p.previous_col;
ifstack = p.ifstack;
parsing_generic_less_than = p.parsing_generic_less_than;
current_token = p.current_token;
val = p.val;
}
// Do not reset the position, ignore it.
public void DiscardPosition ()
{
position_stack.Pop ();
}
static void AddKeyword (string kw, int token)
{
keyword_strings.Add (kw);
AddKeyword (keywords, kw, token);
}
static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
{
AddKeyword (keywords_preprocessor, kw, directive);
}
static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
{
int length = kw.Length;
if (keywords[length] == null) {
keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
}
int char_index = kw[0] - '_';
var kwe = keywords[length][char_index];
if (kwe == null) {
keywords[length][char_index] = new KeywordEntry<T> (kw, token);
return;
}
while (kwe.Next != null) {
kwe = kwe.Next;
}
kwe.Next = new KeywordEntry<T> (kw, token);
}
//
// Class initializer
//
static Tokenizer ()
{
keyword_strings = new HashSet<string> ();
// 11 is the length of the longest keyword for now
keywords = new KeywordEntry<int>[11][];
AddKeyword ("__arglist", Token.ARGLIST);
AddKeyword ("__makeref", Token.MAKEREF);
AddKeyword ("__reftype", Token.REFTYPE);
AddKeyword ("__refvalue", Token.REFVALUE);
AddKeyword ("abstract", Token.ABSTRACT);
AddKeyword ("as", Token.AS);
AddKeyword ("add", Token.ADD);
AddKeyword ("base", Token.BASE);
AddKeyword ("bool", Token.BOOL);
AddKeyword ("break", Token.BREAK);
AddKeyword ("byte", Token.BYTE);
AddKeyword ("case", Token.CASE);
AddKeyword ("catch", Token.CATCH);
AddKeyword ("char", Token.CHAR);
AddKeyword ("checked", Token.CHECKED);
AddKeyword ("class", Token.CLASS);
AddKeyword ("const", Token.CONST);
AddKeyword ("continue", Token.CONTINUE);
AddKeyword ("decimal", Token.DECIMAL);
AddKeyword ("default", Token.DEFAULT);
AddKeyword ("delegate", Token.DELEGATE);
AddKeyword ("do", Token.DO);
AddKeyword ("double", Token.DOUBLE);
AddKeyword ("else", Token.ELSE);
AddKeyword ("enum", Token.ENUM);
AddKeyword ("event", Token.EVENT);
AddKeyword ("explicit", Token.EXPLICIT);
AddKeyword ("extern", Token.EXTERN);
AddKeyword ("false", Token.FALSE);
AddKeyword ("finally", Token.FINALLY);
AddKeyword ("fixed", Token.FIXED);
AddKeyword ("float", Token.FLOAT);
AddKeyword ("for", Token.FOR);
AddKeyword ("foreach", Token.FOREACH);
AddKeyword ("goto", Token.GOTO);
AddKeyword ("get", Token.GET);
AddKeyword ("if", Token.IF);
AddKeyword ("implicit", Token.IMPLICIT);
AddKeyword ("in", Token.IN);
AddKeyword ("int", Token.INT);
AddKeyword ("interface", Token.INTERFACE);
AddKeyword ("internal", Token.INTERNAL);
AddKeyword ("is", Token.IS);
AddKeyword ("lock", Token.LOCK);
AddKeyword ("long", Token.LONG);
AddKeyword ("namespace", Token.NAMESPACE);
AddKeyword ("new", Token.NEW);
AddKeyword ("null", Token.NULL);
AddKeyword ("object", Token.OBJECT);
AddKeyword ("operator", Token.OPERATOR);
AddKeyword ("out", Token.OUT);
AddKeyword ("override", Token.OVERRIDE);
AddKeyword ("params", Token.PARAMS);
AddKeyword ("private", Token.PRIVATE);
AddKeyword ("protected", Token.PROTECTED);
AddKeyword ("public", Token.PUBLIC);
AddKeyword ("readonly", Token.READONLY);
AddKeyword ("ref", Token.REF);
AddKeyword ("remove", Token.REMOVE);
AddKeyword ("return", Token.RETURN);
AddKeyword ("sbyte", Token.SBYTE);
AddKeyword ("sealed", Token.SEALED);
AddKeyword ("set", Token.SET);
AddKeyword ("short", Token.SHORT);
AddKeyword ("sizeof", Token.SIZEOF);
AddKeyword ("stackalloc", Token.STACKALLOC);
AddKeyword ("static", Token.STATIC);
AddKeyword ("string", Token.STRING);
AddKeyword ("struct", Token.STRUCT);
AddKeyword ("switch", Token.SWITCH);
AddKeyword ("this", Token.THIS);
AddKeyword ("throw", Token.THROW);
AddKeyword ("true", Token.TRUE);
AddKeyword ("try", Token.TRY);
AddKeyword ("typeof", Token.TYPEOF);
AddKeyword ("uint", Token.UINT);
AddKeyword ("ulong", Token.ULONG);
AddKeyword ("unchecked", Token.UNCHECKED);
AddKeyword ("unsafe", Token.UNSAFE);
AddKeyword ("ushort", Token.USHORT);
AddKeyword ("using", Token.USING);
AddKeyword ("virtual", Token.VIRTUAL);
AddKeyword ("void", Token.VOID);
AddKeyword ("volatile", Token.VOLATILE);
AddKeyword ("while", Token.WHILE);
AddKeyword ("partial", Token.PARTIAL);
AddKeyword ("where", Token.WHERE);
// LINQ keywords
AddKeyword ("from", Token.FROM);
AddKeyword ("join", Token.JOIN);
AddKeyword ("on", Token.ON);
AddKeyword ("equals", Token.EQUALS);
AddKeyword ("select", Token.SELECT);
AddKeyword ("group", Token.GROUP);
AddKeyword ("by", Token.BY);
AddKeyword ("let", Token.LET);
AddKeyword ("orderby", Token.ORDERBY);
AddKeyword ("ascending", Token.ASCENDING);
AddKeyword ("descending", Token.DESCENDING);
AddKeyword ("into", Token.INTO);
// Contextual async keywords
AddKeyword ("async", Token.ASYNC);
AddKeyword ("await", Token.AWAIT);
keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
AddPreprocessorKeyword ("if", PreprocessorDirective.If);
AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
csharp_format_info = NumberFormatInfo.InvariantInfo;
styles = NumberStyles.Float;
}
int GetKeyword (char[] id, int id_len)
{
//
// Keywords are stored in an array of arrays grouped by their
// length and then by the first character
//
if (id_len >= keywords.Length || keywords [id_len] == null)
return -1;
int first_index = id [0] - '_';
if (first_index > 'z' - '_')
return -1;
var kwe = keywords [id_len] [first_index];
if (kwe == null)
return -1;
int res;
do {
res = kwe.Token;
for (int i = 1; i < id_len; ++i) {
if (id [i] != kwe.Value [i]) {
res = 0;
kwe = kwe.Next;
break;
}
}
} while (res == 0 && kwe != null);
if (res == 0)
return -1;
int next_token;
switch (res) {
case Token.GET:
case Token.SET:
if (!handle_get_set)
res = -1;
break;
case Token.REMOVE:
case Token.ADD:
if (!handle_remove_add)
res = -1;
break;
case Token.EXTERN:
if (parsing_declaration == 0)
res = Token.EXTERN_ALIAS;
break;
case Token.DEFAULT:
if (peek_token () == Token.COLON) {
token ();
res = Token.DEFAULT_COLON;
}
break;
case Token.WHERE:
if (!handle_where && !query_parsing)
res = -1;
break;
case Token.FROM:
//
// A query expression is any expression that starts with `from identifier'
// followed by any token except ; , =
//
if (!query_parsing) {
if (lambda_arguments_parsing) {
res = -1;
break;
}
PushPosition ();
// HACK: to disable generics micro-parser, because PushPosition does not
// store identifiers array
parsing_generic_less_than = 1;
switch (xtoken ()) {
case Token.IDENTIFIER:
case Token.INT:
case Token.BOOL:
case Token.BYTE:
case Token.CHAR:
case Token.DECIMAL:
case Token.FLOAT:
case Token.LONG:
case Token.OBJECT:
case Token.STRING:
case Token.UINT:
case Token.ULONG:
next_token = xtoken ();
if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
goto default;
res = Token.FROM_FIRST;
query_parsing = true;
if (context.Settings.Version <= LanguageVersion.ISO_2)
Report.FeatureIsNotAvailable (context, Location, "query expressions");
break;
case Token.VOID:
Expression.Error_VoidInvalidInTheContext (Location, Report);
break;
default:
PopPosition ();
// HACK: A token is not a keyword so we need to restore identifiers buffer
// which has been overwritten before we grabbed the identifier
id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
return -1;
}
PopPosition ();
}
break;
case Token.JOIN:
case Token.ON:
case Token.EQUALS:
case Token.SELECT:
case Token.GROUP:
case Token.BY:
case Token.LET:
case Token.ORDERBY:
case Token.ASCENDING:
case Token.DESCENDING:
case Token.INTO:
if (!query_parsing)
res = -1;
break;
case Token.USING:
case Token.NAMESPACE:
// TODO: some explanation needed
check_incorrect_doc_comment ();
break;
case Token.PARTIAL:
if (parsing_block > 0) {
res = -1;
break;
}
// Save current position and parse next token.
PushPosition ();
next_token = token ();
bool ok = (next_token == Token.CLASS) ||
(next_token == Token.STRUCT) ||
(next_token == Token.INTERFACE) ||
(next_token == Token.VOID);
PopPosition ();
if (ok) {
if (next_token == Token.VOID) {
if (context.Settings.Version <= LanguageVersion.ISO_2)
Report.FeatureIsNotAvailable (context, Location, "partial methods");
} else if (context.Settings.Version == LanguageVersion.ISO_1)
Report.FeatureIsNotAvailable (context, Location, "partial types");
return res;
}
if (next_token < Token.LAST_KEYWORD) {
Report.Error (267, Location,
"The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
return token ();
}
res = -1;
break;
case Token.ASYNC:
if (parsing_modifiers) {
//
// Skip attributes section or constructor called async
//
if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
res = -1;
} else {
// async is keyword
}
} else if (parsing_block > 0) {
switch (peek_token ()) {
case Token.DELEGATE:
case Token.OPEN_PARENS_LAMBDA:
// async is keyword
break;
case Token.IDENTIFIER:
PushPosition ();
xtoken ();
if (xtoken () != Token.ARROW)
goto default;
PopPosition ();
break;
default:
// peek_token could overwrite id_buffer
id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
res = -1;
break;
}
} else {
res = -1;
}
if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
}
break;
case Token.AWAIT:
if (parsing_block == 0)
res = -1;
break;
}
return res;
}
static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
{
//
// Keywords are stored in an array of arrays grouped by their
// length and then by the first character
//
if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
return PreprocessorDirective.Invalid;
int first_index = id[0] - '_';
if (first_index > 'z' - '_')
return PreprocessorDirective.Invalid;
var kwe = keywords_preprocessor[id_len][first_index];
if (kwe == null)
return PreprocessorDirective.Invalid;
PreprocessorDirective res = PreprocessorDirective.Invalid;
do {
res = kwe.Token;
for (int i = 1; i < id_len; ++i) {
if (id[i] != kwe.Value[i]) {
res = 0;
kwe = kwe.Next;
break;
}
}
} while (res == PreprocessorDirective.Invalid && kwe != null);
return res;
}
public Location Location {
get {
return new Location (current_source, ref_line, col);
}
}
static bool is_identifier_start_character (int c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
}
static bool is_identifier_part_character (char c)
{
if (c >= 'a' && c <= 'z')
return true;
if (c >= 'A' && c <= 'Z')
return true;
if (c == '_' || (c >= '0' && c <= '9'))
return true;
if (c < 0x80)
return false;
return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
}
public static bool IsKeyword (string s)
{
return keyword_strings.Contains (s);
}
//
// Open parens micro parser. Detects both lambda and cast ambiguity.
//
int TokenizeOpenParens ()
{
int ptoken;
current_token = -1;
int bracket_level = 0;
bool is_type = false;
bool can_be_type = false;
while (true) {
ptoken = current_token;
token ();
switch (current_token) {
case Token.CLOSE_PARENS:
token ();
//
// Expression inside parens is lambda, (int i) =>
//
if (current_token == Token.ARROW)
return Token.OPEN_PARENS_LAMBDA;
//
// Expression inside parens is single type, (int[])
//
if (is_type)
return Token.OPEN_PARENS_CAST;
//
// Expression is possible cast, look at next token, (T)null
//
if (can_be_type) {
switch (current_token) {
case Token.OPEN_PARENS:
case Token.BANG:
case Token.TILDE:
case Token.IDENTIFIER:
case Token.LITERAL:
case Token.BASE:
case Token.CHECKED:
case Token.DELEGATE:
case Token.FALSE:
case Token.FIXED:
case Token.NEW:
case Token.NULL:
case Token.SIZEOF:
case Token.THIS:
case Token.THROW:
case Token.TRUE:
case Token.TYPEOF:
case Token.UNCHECKED:
case Token.UNSAFE:
case Token.DEFAULT:
case Token.AWAIT:
//
// These can be part of a member access
//
case Token.INT:
case Token.UINT:
case Token.SHORT:
case Token.USHORT:
case Token.LONG:
case Token.ULONG:
case Token.DOUBLE:
case Token.FLOAT:
case Token.CHAR:
case Token.BYTE:
case Token.DECIMAL:
case Token.BOOL:
return Token.OPEN_PARENS_CAST;
}
}
return Token.OPEN_PARENS;
case Token.DOT:
case Token.DOUBLE_COLON:
if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
goto default;
continue;
case Token.IDENTIFIER:
switch (ptoken) {
case Token.DOT:
if (bracket_level == 0) {
is_type = false;
can_be_type = true;
}
continue;
case Token.OP_GENERICS_LT:
case Token.COMMA:
case Token.DOUBLE_COLON:
case -1:
if (bracket_level == 0)
can_be_type = true;
continue;
default:
can_be_type = is_type = false;
continue;
}
case Token.OBJECT:
case Token.STRING:
case Token.BOOL:
case Token.DECIMAL:
case Token.FLOAT:
case Token.DOUBLE:
case Token.SBYTE:
case Token.BYTE:
case Token.SHORT:
case Token.USHORT:
case Token.INT:
case Token.UINT:
case Token.LONG:
case Token.ULONG:
case Token.CHAR:
case Token.VOID:
if (bracket_level == 0)
is_type = true;
continue;
case Token.COMMA:
if (bracket_level == 0) {
bracket_level = 100;
can_be_type = is_type = false;
}
continue;
case Token.OP_GENERICS_LT:
case Token.OPEN_BRACKET:
if (bracket_level++ == 0)
is_type = true;
continue;
case Token.OP_GENERICS_GT:
case Token.CLOSE_BRACKET:
--bracket_level;
continue;
case Token.INTERR_NULLABLE:
case Token.STAR:
if (bracket_level == 0)
is_type = true;
continue;
case Token.REF:
case Token.OUT:
can_be_type = is_type = false;
continue;
default:
return Token.OPEN_PARENS;
}
}
}
public static bool IsValidIdentifier (string s)
{
if (s == null || s.Length == 0)
return false;
if (!is_identifier_start_character (s [0]))
return false;
for (int i = 1; i < s.Length; i ++)
if (! is_identifier_part_character (s [i]))
return false;
return true;
}
bool parse_less_than ()
{
start:
int the_token = token ();
if (the_token == Token.OPEN_BRACKET) {
while (true) {
the_token = token ();
if (the_token == Token.EOF)
return true;
if (the_token == Token.CLOSE_BRACKET)
break;
}
the_token = token ();
} else if (the_token == Token.IN || the_token == Token.OUT) {
the_token = token ();
}
switch (the_token) {
case Token.IDENTIFIER:
case Token.OBJECT:
case Token.STRING:
case Token.BOOL:
case Token.DECIMAL:
case Token.FLOAT:
case Token.DOUBLE:
case Token.SBYTE:
case Token.BYTE:
case Token.SHORT:
case Token.USHORT:
case Token.INT:
case Token.UINT:
case Token.LONG:
case Token.ULONG:
case Token.CHAR:
case Token.VOID:
break;
case Token.OP_GENERICS_GT:
case Token.IN:
case Token.OUT:
return true;
default:
return false;
}
again:
the_token = token ();
if (the_token == Token.OP_GENERICS_GT)
return true;
else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
goto start;
else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
goto again;
else if (the_token == Token.OP_GENERICS_LT) {
if (!parse_less_than ())
return false;
goto again;
} else if (the_token == Token.OPEN_BRACKET) {
rank_specifiers:
the_token = token ();
if (the_token == Token.CLOSE_BRACKET)
goto again;
else if (the_token == Token.COMMA)
goto rank_specifiers;
return false;
}
return false;
}
bool parse_generic_dimension (out int dimension)
{
dimension = 1;
again:
int the_token = token ();
if (the_token == Token.OP_GENERICS_GT)
return true;
else if (the_token == Token.COMMA) {
dimension++;
goto again;
}
return false;
}
public int peek_token ()
{
int the_token;
PushPosition ();
the_token = token ();
PopPosition ();
return the_token;
}
//
// Tonizes `?' using custom disambiguous rules to return one
// of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
//
// Tricky expression look like:
//
// Foo ? a = x ? b : c;
//
int TokenizePossibleNullableType ()
{
if (parsing_block == 0 || parsing_type > 0)
return Token.INTERR_NULLABLE;
int d = peek_char ();
if (d == '?') {
get_char ();
return Token.OP_COALESCING;
}
switch (current_token) {
case Token.CLOSE_PARENS:
case Token.TRUE:
case Token.FALSE:
case Token.NULL:
case Token.LITERAL:
return Token.INTERR;
}
if (d != ' ') {
if (d == ',' || d == ';' || d == '>')
return Token.INTERR_NULLABLE;
if (d == '*' || (d >= '0' && d <= '9'))
return Token.INTERR;
}
PushPosition ();
current_token = Token.NONE;
int next_token;
switch (xtoken ()) {
case Token.LITERAL:
case Token.TRUE:
case Token.FALSE:
case Token.NULL:
case Token.THIS:
case Token.NEW:
next_token = Token.INTERR;
break;
case Token.SEMICOLON:
case Token.COMMA:
case Token.CLOSE_PARENS:
case Token.OPEN_BRACKET:
case Token.OP_GENERICS_GT:
case Token.INTERR:
next_token = Token.INTERR_NULLABLE;
break;
default:
next_token = -1;
break;
}
if (next_token == -1) {
switch (xtoken ()) {
case Token.COMMA:
case Token.SEMICOLON:
case Token.OPEN_BRACE:
case Token.CLOSE_PARENS:
case Token.IN:
next_token = Token.INTERR_NULLABLE;
break;
case Token.COLON:
next_token = Token.INTERR;
break;
default:
int ntoken;
int interrs = 1;
int colons = 0;
int braces = 0;
//
// All shorcuts failed, do it hard way
//
while ((ntoken = xtoken ()) != Token.EOF) {
if (ntoken == Token.OPEN_BRACE) {
++braces;
continue;
}
if (ntoken == Token.CLOSE_BRACE) {
--braces;
continue;
}
if (braces != 0)
continue;
if (ntoken == Token.SEMICOLON)
break;
if (ntoken == Token.COLON) {
if (++colons == interrs)
break;
continue;
}
if (ntoken == Token.INTERR) {
++interrs;
continue;
}
}
next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
break;
}
}
PopPosition ();
return next_token;
}
bool decimal_digits (int c)
{
int d;
bool seen_digits = false;
if (c != -1){
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = (char) c;
}
//
// We use peek_char2, because decimal_digits needs to do a
// 2-character look-ahead (5.ToString for example).
//
while ((d = peek_char2 ()) != -1){
if (d >= '0' && d <= '9'){
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = (char) d;
get_char ();
seen_digits = true;
} else
break;
}
return seen_digits;
}
static bool is_hex (int e)
{
return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
}
static TypeCode real_type_suffix (int c)
{
switch (c){
case 'F': case 'f':
return TypeCode.Single;
case 'D': case 'd':
return TypeCode.Double;
case 'M': case 'm':
return TypeCode.Decimal;
default:
return TypeCode.Empty;
}
}
ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
{
bool is_unsigned = false;
bool is_long = false;
if (c != -1){
bool scanning = true;
do {
switch (c){
case 'U': case 'u':
if (is_unsigned)
scanning = false;
is_unsigned = true;
get_char ();
break;
case 'l':
if (!is_unsigned){
//
// if we have not seen anything in between
// report this error
//
Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
}
goto case 'L';
case 'L':
if (is_long)
scanning = false;
is_long = true;
get_char ();
break;
default:
scanning = false;
break;
}
c = peek_char ();
} while (scanning);
}
if (is_long && is_unsigned){
return new ULongLiteral (context.BuiltinTypes, ul, loc);
}
if (is_unsigned){
// uint if possible, or ulong else.
if ((ul & 0xffffffff00000000) == 0)
return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
else
return new ULongLiteral (context.BuiltinTypes, ul, loc);
} else if (is_long){
// long if possible, ulong otherwise
if ((ul & 0x8000000000000000) != 0)
return new ULongLiteral (context.BuiltinTypes, ul, loc);
else
return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
} else {
// int, uint, long or ulong in that order
if ((ul & 0xffffffff00000000) == 0){
uint ui = (uint) ul;
if ((ui & 0x80000000) != 0)
return new UIntLiteral (context.BuiltinTypes, ui, loc);
else
return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
} else {
if ((ul & 0x8000000000000000) != 0)
return new ULongLiteral (context.BuiltinTypes, ul, loc);
else
return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
}
}
}
//
// given `c' as the next char in the input decide whether
// we need to convert to a special type, and then choose
// the best representation for the integer
//
ILiteralConstant adjust_int (int c, Location loc)
{
try {
if (number_pos > 9){
ulong ul = (uint) (number_builder [0] - '0');
for (int i = 1; i < number_pos; i++){
ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
}
return integer_type_suffix (ul, c, loc);
} else {
uint ui = (uint) (number_builder [0] - '0');
for (int i = 1; i < number_pos; i++){
ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
}
return integer_type_suffix (ui, c, loc);
}
} catch (OverflowException) {
Error_NumericConstantTooLong ();
return new IntLiteral (context.BuiltinTypes, 0, loc);
}
catch (FormatException) {
Report.Error (1013, Location, "Invalid number");
return new IntLiteral (context.BuiltinTypes, 0, loc);
}
}
ILiteralConstant adjust_real (TypeCode t, Location loc)
{
string s = new string (number_builder, 0, number_pos);
const string error_details = "Floating-point constant is outside the range of type `{0}'";
switch (t){
case TypeCode.Decimal:
try {
return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
} catch (OverflowException) {
Report.Error (594, Location, error_details, "decimal");
return new DecimalLiteral (context.BuiltinTypes, 0, loc);
}
case TypeCode.Single:
try {
return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
} catch (OverflowException) {
Report.Error (594, Location, error_details, "float");
return new FloatLiteral (context.BuiltinTypes, 0, loc);
}
default:
try {
return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
} catch (OverflowException) {
Report.Error (594, loc, error_details, "double");
return new DoubleLiteral (context.BuiltinTypes, 0, loc);
}
}
}
ILiteralConstant handle_hex (Location loc)
{
int d;
ulong ul;
get_char ();
while ((d = peek_char ()) != -1){
if (is_hex (d)){
number_builder [number_pos++] = (char) d;
get_char ();
} else
break;
}
string s = new String (number_builder, 0, number_pos);
try {
if (number_pos <= 8)
ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
else
ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
return integer_type_suffix (ul, peek_char (), loc);
} catch (OverflowException){
Error_NumericConstantTooLong ();
return new IntLiteral (context.BuiltinTypes, 0, loc);
}
catch (FormatException) {
Report.Error (1013, Location, "Invalid number");
return new IntLiteral (context.BuiltinTypes, 0, loc);
}
}
//
// Invoked if we know we have .digits or digits
//
int is_number (int c)
{
ILiteralConstant res;
#if FULL_AST
int read_start = reader.Position - 1;
if (c == '.') {
//
// Caller did peek_char
//
--read_start;
}
#endif
number_pos = 0;
var loc = Location;
bool hasLeadingDot = c == '.';
if (c >= '0' && c <= '9'){
if (c == '0'){
int peek = peek_char ();
if (peek == 'x' || peek == 'X') {
val = res = handle_hex (loc);
#if FULL_AST
res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
#endif
return Token.LITERAL;
}
}
decimal_digits (c);
c = get_char ();
}
//
// We need to handle the case of
// "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
//
bool is_real = false;
if (c == '.'){
if (decimal_digits ('.')){
is_real = true;
c = get_char ();
} else {
putback ('.');
number_pos--;
val = res = adjust_int (-1, loc);
#if FULL_AST
res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
#endif
return Token.LITERAL;
}
}
if (c == 'e' || c == 'E'){
is_real = true;
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = (char) c;
c = get_char ();
if (c == '+'){
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = '+';
c = -1;
} else if (c == '-') {
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = '-';
c = -1;
} else {
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = '+';
}
decimal_digits (c);
c = get_char ();
}
var type = real_type_suffix (c);
if (type == TypeCode.Empty && !is_real) {
putback (c);
res = adjust_int (c, loc);
} else {
is_real = true;
if (type == TypeCode.Empty) {
putback (c);
}
res = adjust_real (type, loc);
}
val = res;
#if FULL_AST
var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
if (chars[chars.Length - 1] == '\r')
Array.Resize (ref chars, chars.Length - 1);
res.ParsedValue = chars;
#endif
return Token.LITERAL;
}
//
// Accepts exactly count (4 or 8) hex, no more no less
//
int getHex (int count, out int surrogate, out bool error)
{
int i;
int total = 0;
int c;
int top = count != -1 ? count : 4;
get_char ();
error = false;
surrogate = 0;
for (i = 0; i < top; i++){
c = get_char ();
if (c >= '0' && c <= '9')
c = (int) c - (int) '0';
else if (c >= 'A' && c <= 'F')
c = (int) c - (int) 'A' + 10;
else if (c >= 'a' && c <= 'f')
c = (int) c - (int) 'a' + 10;
else {
error = true;
return 0;
}
total = (total * 16) + c;
if (count == -1){
int p = peek_char ();
if (p == -1)
break;
if (!is_hex ((char)p))
break;
}
}
if (top == 8) {
if (total > 0x0010FFFF) {
error = true;
return 0;
}
if (total >= 0x00010000) {
surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
total = ((total - 0x00010000) / 0x0400 + 0xD800);
}
}
return total;
}
int escape (int c, out int surrogate)
{
bool error;
int d;
int v;
d = peek_char ();
if (c != '\\') {
surrogate = 0;
return c;
}
switch (d){
case 'a':
v = '\a'; break;
case 'b':
v = '\b'; break;
case 'n':
v = '\n'; break;
case 't':
v = '\t'; break;
case 'v':
v = '\v'; break;
case 'r':
v = '\r'; break;
case '\\':
v = '\\'; break;
case 'f':
v = '\f'; break;
case '0':
v = 0; break;
case '"':
v = '"'; break;
case '\'':
v = '\''; break;
case 'x':
v = getHex (-1, out surrogate, out error);
if (error)
goto default;
return v;
case 'u':
case 'U':
return EscapeUnicode (d, out surrogate);
default:
surrogate = 0;
Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
return d;
}
get_char ();
surrogate = 0;
return v;
}
int EscapeUnicode (int ch, out int surrogate)
{
bool error;
if (ch == 'U') {
ch = getHex (8, out surrogate, out error);
} else {
ch = getHex (4, out surrogate, out error);
}
if (error)
Report.Error (1009, Location, "Unrecognized escape sequence");
return ch;
}
int get_char ()
{
int x;
if (putback_char != -1) {
x = putback_char;
putback_char = -1;
} else {
x = reader.Read ();
}
if (x == '\r') {
if (peek_char () == '\n') {
putback_char = -1;
}
x = '\n';
advance_line ();
} else if (x == '\n') {
advance_line ();
} else {
col++;
}
return x;
}
int get_char_withwithoutskippingwindowseol ()
{
int x;
if (putback_char != -1) {
x = putback_char;
putback_char = -1;
} else {
x = reader.Read ();
}
if (x == '\r') {
} else if (x == '\n') {
advance_line ();
} else {
col++;
}
return x;
}
void advance_line ()
{
line++;
ref_line++;
previous_col = col;
col = 0;
startsLine = true;
}
int peek_char ()
{
if (putback_char == -1)
putback_char = reader.Read ();
return putback_char;
}
int peek_char2 ()
{
if (putback_char != -1)
return putback_char;
return reader.Peek ();
}
public void putback (int c)
{
if (putback_char != -1) {
throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
}
if (c == '\n' || col == 0) {
// It won't happen though.
line--;
ref_line--;
col = previous_col;
}
else
col--;
putback_char = c;
}
public bool advance ()
{
return peek_char () != -1 || CompleteOnEOF;
}
public Object Value {
get {
return val;
}
}
public Object value ()
{
return val;
}
public int token ()
{
current_token = xtoken ();
return current_token;
}
int TokenizePreprocessorIdentifier (out int c)
{
int endLine, endCol;
return TokenizePreprocessorIdentifier (out c, out endLine, out endCol);
}
int TokenizePreprocessorIdentifier (out int c, out int endLine, out int endCol)
{
// skip over white space
do {
endLine = line;
endCol = col;
c = get_char ();
} while (c == ' ' || c == '\t');
int pos = 0;
while (c != -1 && c >= 'a' && c <= 'z') {
id_builder[pos++] = (char) c;
endCol = col + 1;
c = get_char ();
if (c == '\\') {
int peek = peek_char ();
if (peek == 'U' || peek == 'u') {
int surrogate;
c = EscapeUnicode (c, out surrogate);
if (surrogate != 0) {
if (is_identifier_part_character ((char) c)) {
id_builder[pos++] = (char) c;
}
c = surrogate;
}
}
}
}
return pos;
}
PreprocessorDirective get_cmd_arg (out string arg)
{
int c;
int startLine = line, startCol = col;
tokens_seen = false;
arg = "";
int endLine, endCol;
var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c, out endLine, out endCol));
if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0) {
if (position_stack.Count == 0)
sbag.AddPreProcessorDirective (startLine, startCol, line, col, cmd, null);
return cmd;
}
// skip over white space
while (c == ' ' || c == '\t') {
c = get_char ();
}
int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
int pos = 0;
while (c != -1 && c != '\n' && c != '\r') {
if (c == '\\' && has_identifier_argument >= 0) {
if (has_identifier_argument != 0) {
has_identifier_argument = 1;
int peek = peek_char ();
if (peek == 'U' || peek == 'u') {
int surrogate;
c = EscapeUnicode (c, out surrogate);
if (surrogate != 0) {
if (is_identifier_part_character ((char)c)) {
if (pos == value_builder.Length)
Array.Resize (ref value_builder, pos * 2);
value_builder [pos++] = (char)c;
}
c = surrogate;
}
}
} else {
has_identifier_argument = -1;
}
} else if (c == '/' && peek_char () == '/') {
//
// Eat single-line comments
//
get_char ();
do {
c = get_char ();
} while (c != -1 && c != '\n');
break;
}
endLine = line;
endCol = col + 1;
if (pos == value_builder.Length)
Array.Resize (ref value_builder, pos * 2);
value_builder[pos++] = (char) c;
c = get_char ();
}
if (pos != 0) {
if (pos > MaxIdentifierLength)
arg = new string (value_builder, 0, pos);
else
arg = InternIdentifier (value_builder, pos);
// Eat any trailing whitespaces
arg = arg.Trim (simple_whitespaces);
}
if (position_stack.Count == 0)
sbag.AddPreProcessorDirective (startLine, startCol, endLine, endCol, cmd, arg);
return cmd;
}
//
// Handles the #line directive
//
bool PreProcessLine ()
{
Location loc = Location;
int c;
int length = TokenizePreprocessorIdentifier (out c);
if (length == line_default.Length) {
if (!IsTokenIdentifierEqual (line_default))
return false;
current_source = source_file.SourceFile;
if (!hidden_block_start.IsNull) {
current_source.RegisterHiddenScope (hidden_block_start, loc);
hidden_block_start = Location.Null;
}
//ref_line = line;
return true;
}
if (length == line_hidden.Length) {
if (!IsTokenIdentifierEqual (line_hidden))
return false;
if (hidden_block_start.IsNull)
hidden_block_start = loc;
return true;
}
if (length != 0 || c < '0' || c > '9') {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
return false;
}
int new_line = TokenizeNumber (c);
if (new_line < 1) {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
return new_line != 0;
}
c = get_char ();
if (c == ' ') {
// skip over white space
do {
c = get_char ();
} while (c == ' ' || c == '\t');
} else if (c == '"') {
c = 0;
}
if (c != '\n' && c != '/' && c != '"') {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
return true;
}
string new_file_name = null;
if (c == '"') {
new_file_name = TokenizeFileName (ref c);
// skip over white space
while (c == ' ' || c == '\t') {
c = get_char ();
}
}
if (c == '\n') {
} else if (c == '/') {
ReadSingleLineComment ();
} else {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
Error_EndLineExpected ();
return true;
}
if (new_file_name != null) {
current_source = context.LookupFile (source_file, new_file_name);
source_file.AddIncludeFile (current_source);
}
if (!hidden_block_start.IsNull) {
current_source.RegisterHiddenScope (hidden_block_start, loc);
hidden_block_start = Location.Null;
}
//ref_line = new_line;
return true;
}
//
// Handles #define and #undef
//
void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
{
if (ident.Length == 0 || ident == "true" || ident == "false"){
Report.Error (1001, Location, "Missing identifier to pre-processor directive");
return;
}
if (ident.IndexOfAny (simple_whitespaces) != -1){
Error_EndLineExpected ();
return;
}
if (!is_identifier_start_character (ident [0]))
Report.Error (1001, Location, "Identifier expected: {0}", ident);
foreach (char c in ident.Substring (1)){
if (!is_identifier_part_character (c)){
Report.Error (1001, Location, "Identifier expected: {0}", ident);
return;
}
}
if (!caller_is_taking)
return;
if (is_define) {
//
// #define ident
//
if (context.Settings.IsConditionalSymbolDefined (ident))
return;
source_file.AddDefine (ident);
} else {
//
// #undef ident
//
source_file.AddUndefine (ident);
}
}
byte read_hex (out bool error)
{
int total;
int c = get_char ();
if ((c >= '0') && (c <= '9'))
total = (int) c - (int) '0';
else if ((c >= 'A') && (c <= 'F'))
total = (int) c - (int) 'A' + 10;
else if ((c >= 'a') && (c <= 'f'))
total = (int) c - (int) 'a' + 10;
else {
error = true;
return 0;
}
total *= 16;
c = get_char ();
if ((c >= '0') && (c <= '9'))
total += (int) c - (int) '0';
else if ((c >= 'A') && (c <= 'F'))
total += (int) c - (int) 'A' + 10;
else if ((c >= 'a') && (c <= 'f'))
total += (int) c - (int) 'a' + 10;
else {
error = true;
return 0;
}
error = false;
return (byte) total;
}
//
// Parses #pragma checksum
//
bool ParsePragmaChecksum ()
{
//
// The syntax is ` "foo.txt" "{guid}" "hash"'
//
// guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
//
int c = get_char ();
if (c != '"')
return false;
string file_name = TokenizeFileName (ref c);
// TODO: Any white-spaces count
if (c != ' ')
return false;
SourceFile file = context.LookupFile (source_file, file_name);
if (get_char () != '"' || get_char () != '{')
return false;
bool error;
byte[] guid_bytes = new byte [16];
int i = 0;
for (; i < 4; i++) {
guid_bytes [i] = read_hex (out error);
if (error)
return false;
}
if (get_char () != '-')
return false;
for (; i < 10; i++) {
guid_bytes [i] = read_hex (out error);
if (error)
return false;
guid_bytes [i++] = read_hex (out error);
if (error)
return false;
if (get_char () != '-')
return false;
}
for (; i < 16; i++) {
guid_bytes [i] = read_hex (out error);
if (error)
return false;
}
if (get_char () != '}' || get_char () != '"')
return false;
// TODO: Any white-spaces count
c = get_char ();
if (c != ' ')
return false;
if (get_char () != '"')
return false;
// Any length of checksum
List<byte> checksum_bytes = new List<byte> (16);
var checksum_location = Location;
c = peek_char ();
while (c != '"' && c != -1) {
checksum_bytes.Add (read_hex (out error));
if (error)
return false;
c = peek_char ();
}
if (c == '/') {
ReadSingleLineComment ();
} else if (get_char () != '"') {
return false;
}
if (context.Settings.GenerateDebugInfo) {
var chsum = checksum_bytes.ToArray ();
if (file.HasChecksum) {
if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
// TODO: Report.SymbolRelatedToPreviousError
Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
}
}
file.SetChecksum (guid_bytes, chsum);
current_source.AutoGenerated = true;
}
return true;
}
bool IsTokenIdentifierEqual (char[] identifier)
{
for (int i = 0; i < identifier.Length; ++i) {
if (identifier[i] != id_builder[i])
return false;
}
return true;
}
int TokenizeNumber (int value)
{
number_pos = 0;
decimal_digits (value);
uint ui = (uint) (number_builder[0] - '0');
try {
for (int i = 1; i < number_pos; i++) {
ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
}
return (int) ui;
} catch (OverflowException) {
Error_NumericConstantTooLong ();
return -1;
}
}
string TokenizeFileName (ref int c)
{
var string_builder = new StringBuilder ();
while (c != -1 && c != '\n') {
c = get_char ();
if (c == '"') {
c = get_char ();
break;
}
string_builder.Append ((char) c);
}
if (string_builder.Length == 0) {
Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
}
return string_builder.ToString ();
}
int TokenizePragmaNumber (ref int c)
{
number_pos = 0;
int number;
if (c >= '0' && c <= '9') {
number = TokenizeNumber (c);
c = get_char ();
// skip over white space
while (c == ' ' || c == '\t')
c = get_char ();
if (c == ',') {
c = get_char ();
}
// skip over white space
while (c == ' ' || c == '\t')
c = get_char ();
} else {
number = -1;
if (c == '/') {
ReadSingleLineComment ();
} else {
Report.Warning (1692, 1, Location, "Invalid number");
// Read everything till the end of the line or file
do {
c = get_char ();
} while (c != -1 && c != '\n');
}
}
return number;
}
void ReadSingleLineComment ()
{
if (peek_char () != '/')
Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
if (position_stack.Count == 0)
sbag.StartComment (SpecialsBag.CommentType.Single, startsLine, line, col - 1);
// Read everything till the end of the line or file
int c;
do {
c = get_char ();
if (position_stack.Count == 0)
sbag.PushCommentChar (c);
var pc = peek_char ();
if ((pc == '\n' || pc == -1) && position_stack.Count == 0)
sbag.EndComment (line, col + 1);
} while (c != -1 && c != '\n');
}
/// <summary>
/// Handles #pragma directive
/// </summary>
void ParsePragmaDirective (string arg)
{
int c;
int length = TokenizePreprocessorIdentifier (out c);
if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
length = TokenizePreprocessorIdentifier (out c);
//
// #pragma warning disable
// #pragma warning restore
//
if (length == pragma_warning_disable.Length) {
bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
// skip over white space
while (c == ' ' || c == '\t')
c = get_char ();
var loc = Location;
if (c == '\n' || c == '/') {
if (c == '/')
ReadSingleLineComment ();
//
// Disable/Restore all warnings
//
if (disable) {
Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
} else {
Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
}
} else {
//
// Disable/Restore a warning or group of warnings
//
int code;
do {
code = TokenizePragmaNumber (ref c);
if (code > 0) {
if (disable) {
Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
} else {
Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
}
}
} while (code >= 0 && c != '\n' && c != -1);
}
return;
}
}
Report.Warning (1634, 1, Location, "Expected disable or restore");
return;
}
//
// #pragma checksum
//
if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
if (c != ' ' || !ParsePragmaChecksum ()) {
Report.Warning (1695, 1, Location,
"Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
}
return;
}
Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
}
bool eval_val (string s)
{
if (s == "true")
return true;
if (s == "false")
return false;
return source_file.IsConditionalDefined (s);
}
bool pp_primary (ref string s)
{
s = s.Trim ();
int len = s.Length;
if (len > 0){
char c = s [0];
if (c == '('){
s = s.Substring (1);
bool val = pp_expr (ref s, false);
if (s.Length > 0 && s [0] == ')'){
s = s.Substring (1);
return val;
}
Error_InvalidDirective ();
return false;
}
if (is_identifier_start_character (c)){
int j = 1;
while (j < len){
c = s [j];
if (is_identifier_part_character (c)){
j++;
continue;
}
bool v = eval_val (s.Substring (0, j));
s = s.Substring (j);
return v;
}
bool vv = eval_val (s);
s = "";
return vv;
}
}
Error_InvalidDirective ();
return false;
}
bool pp_unary (ref string s)
{
s = s.Trim ();
int len = s.Length;
if (len > 0){
if (s [0] == '!'){
if (len > 1 && s [1] == '='){
Error_InvalidDirective ();
return false;
}
s = s.Substring (1);
return ! pp_primary (ref s);
} else
return pp_primary (ref s);
} else {
Error_InvalidDirective ();
return false;
}
}
bool pp_eq (ref string s)
{
bool va = pp_unary (ref s);
s = s.Trim ();
int len = s.Length;
if (len > 0){
if (s [0] == '='){
if (len > 2 && s [1] == '='){
s = s.Substring (2);
return va == pp_unary (ref s);
} else {
Error_InvalidDirective ();
return false;
}
} else if (s [0] == '!' && len > 1 && s [1] == '='){
s = s.Substring (2);
return va != pp_unary (ref s);
}
}
return va;
}
bool pp_and (ref string s)
{
bool va = pp_eq (ref s);
s = s.Trim ();
int len = s.Length;
if (len > 0){
if (s [0] == '&'){
if (len > 2 && s [1] == '&'){
s = s.Substring (2);
return (va & pp_and (ref s));
} else {
Error_InvalidDirective ();
return false;
}
}
}
return va;
}
//
// Evaluates an expression for `#if' or `#elif'
//
bool pp_expr (ref string s, bool isTerm)
{
bool va = pp_and (ref s);
s = s.Trim ();
int len = s.Length;
if (len > 0){
char c = s [0];
if (c == '|'){
if (len > 2 && s [1] == '|'){
s = s.Substring (2);
return va | pp_expr (ref s, isTerm);
} else {
Error_InvalidDirective ();
return false;
}
}
if (isTerm) {
Error_EndLineExpected ();
return false;
}
}
return va;
}
bool eval (string s)
{
bool v = pp_expr (ref s, true);
s = s.Trim ();
if (s.Length != 0){
return false;
}
return v;
}
void Error_NumericConstantTooLong ()
{
Report.Error (1021, Location, "Integral constant is too large");
}
void Error_InvalidDirective ()
{
Report.Error (1517, Location, "Invalid preprocessor directive");
}
void Error_UnexpectedDirective (string extra)
{
Report.Error (
1028, Location,
"Unexpected processor directive ({0})", extra);
}
void Error_TokensSeen ()
{
Report.Error (1032, Location,
"Cannot define or undefine preprocessor symbols after first token in file");
}
void Eror_WrongPreprocessorLocation ()
{
Report.Error (1040, Location,
"Preprocessor directives must appear as the first non-whitespace character on a line");
}
void Error_EndLineExpected ()
{
Report.Error (1025, Location, "Single-line comment or end-of-line expected");
}
//
// Raises a warning when tokenizer found documentation comment
// on unexpected place
//
void WarningMisplacedComment (Location loc)
{
if (doc_state != XmlCommentState.Error) {
doc_state = XmlCommentState.Error;
Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
}
}
//
// if true, then the code continues processing the code
// if false, the code stays in a loop until another directive is
// reached.
// When caller_is_taking is false we ignore all directives except the ones
// which can help us to identify where the #if block ends
bool ParsePreprocessingDirective (bool caller_is_taking)
{
string arg;
bool region_directive = false;
var directive = get_cmd_arg (out arg);
//
// The first group of pre-processing instructions is always processed
//
switch (directive) {
case PreprocessorDirective.Region:
region_directive = true;
arg = "true";
goto case PreprocessorDirective.If;
case PreprocessorDirective.Endregion:
if (ifstack == null || ifstack.Count == 0){
Error_UnexpectedDirective ("no #region for this #endregion");
return true;
}
int pop = ifstack.Pop ();
if ((pop & REGION) == 0)
Report.Error (1027, Location, "Expected `#endif' directive");
return caller_is_taking;
case PreprocessorDirective.If:
if (ifstack == null)
ifstack = new Stack<int> (2);
int flags = region_directive ? REGION : 0;
if (ifstack.Count == 0){
flags |= PARENT_TAKING;
} else {
int state = ifstack.Peek ();
if ((state & TAKING) != 0) {
flags |= PARENT_TAKING;
}
}
if (eval (arg) && caller_is_taking) {
ifstack.Push (flags | TAKING);
return true;
}
sbag.SkipIf ();
ifstack.Push (flags);
return false;
case PreprocessorDirective.Endif:
if (ifstack == null || ifstack.Count == 0){
Error_UnexpectedDirective ("no #if for this #endif");
return true;
} else {
pop = ifstack.Pop ();
if ((pop & REGION) != 0)
Report.Error (1038, Location, "#endregion directive expected");
if (arg.Length != 0) {
Error_EndLineExpected ();
}
if (ifstack.Count == 0)
return true;
int state = ifstack.Peek ();
return (state & TAKING) != 0;
}
case PreprocessorDirective.Elif:
if (ifstack == null || ifstack.Count == 0){
Error_UnexpectedDirective ("no #if for this #elif");
return true;
} else {
int state = ifstack.Pop ();
if ((state & REGION) != 0) {
Report.Error (1038, Location, "#endregion directive expected");
return true;
}
if ((state & ELSE_SEEN) != 0){
Error_UnexpectedDirective ("#elif not valid after #else");
return true;
}
if ((state & TAKING) != 0) {
ifstack.Push (0);
return false;
}
if (eval (arg) && ((state & PARENT_TAKING) != 0)){
ifstack.Push (state | TAKING);
return true;
}
ifstack.Push (state);
return false;
}
case PreprocessorDirective.Else:
if (ifstack == null || ifstack.Count == 0){
Error_UnexpectedDirective ("no #if for this #else");
return true;
} else {
int state = ifstack.Peek ();
if ((state & REGION) != 0) {
Report.Error (1038, Location, "#endregion directive expected");
return true;
}
if ((state & ELSE_SEEN) != 0){
Error_UnexpectedDirective ("#else within #else");
return true;
}
ifstack.Pop ();
if (arg.Length != 0) {
Error_EndLineExpected ();
return true;
}
bool ret = false;
if ((state & PARENT_TAKING) != 0) {
ret = (state & TAKING) == 0;
if (ret)
state |= TAKING;
else
state &= ~TAKING;
}
ifstack.Push (state | ELSE_SEEN);
return ret;
}
case PreprocessorDirective.Define:
if (any_token_seen){
Error_TokensSeen ();
return caller_is_taking;
}
PreProcessDefinition (true, arg, caller_is_taking);
return caller_is_taking;
case PreprocessorDirective.Undef:
if (any_token_seen){
Error_TokensSeen ();
return caller_is_taking;
}
PreProcessDefinition (false, arg, caller_is_taking);
return caller_is_taking;
case PreprocessorDirective.Invalid:
Report.Error (1024, Location, "Wrong preprocessor directive");
return true;
}
//
// These are only processed if we are in a `taking' block
//
if (!caller_is_taking)
return false;
switch (directive){
case PreprocessorDirective.Error:
Report.Error (1029, Location, "#error: '{0}'", arg);
return true;
case PreprocessorDirective.Warning:
Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
return true;
case PreprocessorDirective.Pragma:
if (context.Settings.Version == LanguageVersion.ISO_1) {
Report.FeatureIsNotAvailable (context, Location, "#pragma");
}
ParsePragmaDirective (arg);
return true;
case PreprocessorDirective.Line:
Location loc = Location;
if (!PreProcessLine ())
Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
return caller_is_taking;
}
throw new NotImplementedException (directive.ToString ());
}
private int consume_string (bool quoted)
{
int c;
int pos = 0;
Location start_location = Location;
if (quoted)
start_location = start_location - 1;
#if FULL_AST
int reader_pos = reader.Position;
#endif
while (true){
c = get_char_withwithoutskippingwindowseol ();
if (c == '"') {
if (quoted && peek_char () == '"') {
if (pos == value_builder.Length)
Array.Resize (ref value_builder, pos * 2);
value_builder[pos++] = (char) c;
get_char ();
continue;
}
string s;
if (pos == 0)
s = string.Empty;
else if (pos <= 4)
s = InternIdentifier (value_builder, pos);
else
s = new string (value_builder, 0, pos);
ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
val = res;
#if FULL_AST
res.ParsedValue = quoted ?
reader.ReadChars (reader_pos - 2, reader.Position - 1) :
reader.ReadChars (reader_pos - 1, reader.Position);
#endif
return Token.LITERAL;
}
if (c == '\n') {
if (!quoted) {
Report.Error (1010, Location, "Newline in constant");
val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
return Token.LITERAL;
}
} else if (c == '\\' && !quoted) {
int surrogate;
c = escape (c, out surrogate);
if (c == -1)
return Token.ERROR;
if (surrogate != 0) {
if (pos == value_builder.Length)
Array.Resize (ref value_builder, pos * 2);
value_builder[pos++] = (char) c;
c = surrogate;
}
} else if (c == -1) {
Report.Error (1039, Location, "Unterminated string literal");
return Token.EOF;
}
if (pos == value_builder.Length)
Array.Resize (ref value_builder, pos * 2);
value_builder[pos++] = (char) c;
}
}
private int consume_identifier (int s)
{
int res = consume_identifier (s, false);
if (doc_state == XmlCommentState.Allowed)
doc_state = XmlCommentState.NotAllowed;
startsLine = false;
return res;
}
int consume_identifier (int c, bool quoted)
{
//
// This method is very performance sensitive. It accounts
// for approximately 25% of all parser time
//
int pos = 0;
int column = col;
if (quoted)
--column;
if (c == '\\') {
int surrogate;
c = escape (c, out surrogate);
if (surrogate != 0) {
id_builder [pos++] = (char) c;
c = surrogate;
}
}
id_builder [pos++] = (char) c;
try {
while (true) {
c = reader.Read ();
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
id_builder [pos++] = (char) c;
continue;
}
if (c < 0x80) {
if (c == '\\') {
int surrogate;
c = escape (c, out surrogate);
if (is_identifier_part_character ((char) c))
id_builder[pos++] = (char) c;
if (surrogate != 0) {
c = surrogate;
}
continue;
}
} else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
id_builder [pos++] = (char) c;
continue;
}
putback_char = c;
break;
}
} catch (IndexOutOfRangeException) {
Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
--pos;
col += pos;
}
col += pos - 1;
//
// Optimization: avoids doing the keyword lookup
// on uppercase letters
//
if (id_builder [0] >= '_' && !quoted) {
int keyword = GetKeyword (id_builder, pos);
if (keyword != -1) {
val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
return keyword;
}
}
string s = InternIdentifier (id_builder, pos);
#if FULL_AST
if (quoted) {
val = ltb.Create ("@" + s, current_source, ref_line, column - 1);
} else {
val = ltb.Create (s, current_source, ref_line, column);
}
#else
val = ltb.Create (s, current_source, ref_line, column);
#endif
if (quoted && parsing_attribute_section)
AddEscapedIdentifier (((LocatedToken) val).Location);
return Token.IDENTIFIER;
}
string InternIdentifier (char[] charBuffer, int length)
{
//
// Keep identifiers in an array of hashtables to avoid needless
// allocations
//
var identifiers_group = identifiers [length];
string s;
if (identifiers_group != null) {
if (identifiers_group.TryGetValue (charBuffer, out s)) {
return s;
}
} else {
// TODO: this should be number of files dependant
// corlib compilation peaks at 1000 and System.Core at 150
int capacity = length > 20 ? 10 : 100;
identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
identifiers [length] = identifiers_group;
}
char[] chars = new char[length];
Array.Copy (charBuffer, chars, length);
s = new string (charBuffer, 0, length);
identifiers_group.Add (chars, s);
return s;
}
public int xtoken ()
{
int d, c;
// Whether we have seen comments on the current line
bool comments_seen = false;
while ((c = get_char ()) != -1) {
switch (c) {
case '\t':
col = ((col - 1 + tab_size) / tab_size) * tab_size;
continue;
case ' ':
case '\f':
case '\v':
case 0xa0:
case 0:
case 0xFEFF: // Ignore BOM anywhere in the file
continue;
/* This is required for compatibility with .NET
case 0xEF:
if (peek_char () == 0xBB) {
PushPosition ();
get_char ();
if (get_char () == 0xBF)
continue;
PopPosition ();
}
break;
*/
case '\\':
tokens_seen = true;
return consume_identifier (c);
case '{':
val = ltb.Create (current_source, ref_line, col);
return Token.OPEN_BRACE;
case '}':
val = ltb.Create (current_source, ref_line, col);
return Token.CLOSE_BRACE;
case '[':
// To block doccomment inside attribute declaration.
if (doc_state == XmlCommentState.Allowed)
doc_state = XmlCommentState.NotAllowed;
val = ltb.Create (current_source, ref_line, col);
if (parsing_block == 0 || lambda_arguments_parsing)
return Token.OPEN_BRACKET;
int next = peek_char ();
switch (next) {
case ']':
case ',':
return Token.OPEN_BRACKET;
case ' ':
case '\f':
case '\v':
case '\r':
case '\n':
case '/':
next = peek_token ();
if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
return Token.OPEN_BRACKET;
return Token.OPEN_BRACKET_EXPR;
default:
return Token.OPEN_BRACKET_EXPR;
}
case ']':
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.CLOSE_BRACKET;
case '(':
val = ltb.Create (current_source, ref_line, col);
//
// An expression versions of parens can appear in block context only
//
if (parsing_block != 0 && !lambda_arguments_parsing) {
//
// Optmize most common case where we know that parens
// is not special
//
switch (current_token) {
case Token.IDENTIFIER:
case Token.IF:
case Token.FOR:
case Token.FOREACH:
case Token.TYPEOF:
case Token.WHILE:
case Token.USING:
case Token.DEFAULT:
case Token.DELEGATE:
case Token.OP_GENERICS_GT:
return Token.OPEN_PARENS;
}
// Optimize using peek
int xx = peek_char ();
switch (xx) {
case '(':
case '\'':
case '"':
case '0':
case '1':
return Token.OPEN_PARENS;
}
lambda_arguments_parsing = true;
PushPosition ();
d = TokenizeOpenParens ();
PopPosition ();
lambda_arguments_parsing = false;
return d;
}
return Token.OPEN_PARENS;
case ')':
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.CLOSE_PARENS;
case ',':
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.COMMA;
case ';':
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.SEMICOLON;
case '~':
val = ltb.Create (current_source, ref_line, col);
return Token.TILDE;
case '?':
val = ltb.Create (current_source, ref_line, col);
return TokenizePossibleNullableType ();
case '<':
val = ltb.Create (current_source, ref_line, col);
if (parsing_generic_less_than++ > 0)
return Token.OP_GENERICS_LT;
return TokenizeLessThan ();
case '>':
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '=') {
get_char ();
return Token.OP_GE;
}
if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
parsing_generic_less_than--;
return Token.OP_GENERICS_GT;
}
if (d == '>') {
get_char ();
d = peek_char ();
if (d == '=') {
get_char ();
return Token.OP_SHIFT_RIGHT_ASSIGN;
}
return Token.OP_SHIFT_RIGHT;
}
return Token.OP_GT;
case '+':
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '+') {
d = Token.OP_INC;
} else if (d == '=') {
d = Token.OP_ADD_ASSIGN;
} else {
return Token.PLUS;
}
get_char ();
return d;
case '-':
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '-') {
d = Token.OP_DEC;
} else if (d == '=')
d = Token.OP_SUB_ASSIGN;
else if (d == '>')
d = Token.OP_PTR;
else {
return Token.MINUS;
}
get_char ();
return d;
case '!':
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_NE;
}
return Token.BANG;
case '=':
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '=') {
get_char ();
return Token.OP_EQ;
}
if (d == '>') {
get_char ();
return Token.ARROW;
}
return Token.ASSIGN;
case '&':
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '&') {
get_char ();
return Token.OP_AND;
}
if (d == '=') {
get_char ();
return Token.OP_AND_ASSIGN;
}
return Token.BITWISE_AND;
case '|':
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '|') {
get_char ();
return Token.OP_OR;
}
if (d == '=') {
get_char ();
return Token.OP_OR_ASSIGN;
}
return Token.BITWISE_OR;
case '*':
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_MULT_ASSIGN;
}
return Token.STAR;
case '/':
d = peek_char ();
if (d == '='){
val = ltb.Create (current_source, ref_line, col);
get_char ();
return Token.OP_DIV_ASSIGN;
}
// Handle double-slash comments.
if (d == '/') {
get_char ();
if (doc_processing) {
if (peek_char () == '/') {
get_char ();
// Don't allow ////.
if ((d = peek_char ()) != '/') {
if (position_stack.Count == 0)
sbag.PushCommentChar (d);
if (doc_state == XmlCommentState.Allowed)
handle_one_line_xml_comment ();
else if (doc_state == XmlCommentState.NotAllowed)
WarningMisplacedComment (Location - 3);
}
} else {
if (xml_comment_buffer.Length > 0)
doc_state = XmlCommentState.NotAllowed;
}
} else {
bool isDoc = peek_char () == '/';
if (position_stack.Count == 0)
sbag.StartComment (isDoc ? SpecialsBag.CommentType.Documentation : SpecialsBag.CommentType.Single, startsLine, line, col - 1);
if (isDoc)
get_char ();
}
d = peek_char ();
int endLine = line, endCol = col;
while ((d = get_char ()) != -1 && (d != '\n') && d != '\r') {
if (position_stack.Count == 0)
sbag.PushCommentChar (d);
endLine = line;
endCol = col;
}
if (position_stack.Count == 0)
sbag.EndComment (endLine, endCol + 1);
any_token_seen |= tokens_seen;
tokens_seen = false;
comments_seen = false;
continue;
} else if (d == '*'){
if (position_stack.Count == 0)
sbag.StartComment (SpecialsBag.CommentType.Multi, startsLine, line, col);
get_char ();
bool docAppend = false;
if (doc_processing && peek_char () == '*') {
int ch = get_char ();
// But when it is /**/, just do nothing.
if (peek_char () == '/') {
ch = get_char ();
if (position_stack.Count == 0) {
sbag.EndComment (line, col + 1);
}
continue;
} else {
if (position_stack.Count == 0)
sbag.PushCommentChar (ch);
}
if (doc_state == XmlCommentState.Allowed)
docAppend = true;
else if (doc_state == XmlCommentState.NotAllowed) {
WarningMisplacedComment (Location - 2);
}
}
int current_comment_start = 0;
if (docAppend) {
current_comment_start = xml_comment_buffer.Length;
xml_comment_buffer.Append (Environment.NewLine);
}
while ((d = get_char ()) != -1){
if (d == '*' && peek_char () == '/'){
get_char ();
if (position_stack.Count == 0)
sbag.EndComment (line, col + 1);
comments_seen = true;
break;
} else {
if (position_stack.Count == 0)
sbag.PushCommentChar (d);
}
if (docAppend)
xml_comment_buffer.Append ((char) d);
if (d == '\n'){
any_token_seen |= tokens_seen;
tokens_seen = false;
//
// Reset 'comments_seen' just to be consistent.
// It doesn't matter either way, here.
//
comments_seen = false;
}
}
if (!comments_seen)
Report.Error (1035, Location, "End-of-file found, '*/' expected");
if (docAppend)
update_formatted_doc_comment (current_comment_start);
continue;
}
val = ltb.Create (current_source, ref_line, col);
return Token.DIV;
case '%':
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_MOD_ASSIGN;
}
return Token.PERCENT;
case '^':
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_XOR_ASSIGN;
}
return Token.CARRET;
case ':':
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == ':') {
get_char ();
return Token.DOUBLE_COLON;
}
return Token.COLON;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
tokens_seen = true;
return is_number (c);
case '\n': // white space
any_token_seen |= tokens_seen;
tokens_seen = false;
comments_seen = false;
continue;
case '.':
tokens_seen = true;
d = peek_char ();
if (d >= '0' && d <= '9')
return is_number (c);
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.DOT;
case '#':
if (tokens_seen || comments_seen) {
Eror_WrongPreprocessorLocation ();
return Token.ERROR;
}
if (ParsePreprocessingDirective (true))
continue;
sbag.StartComment (SpecialsBag.CommentType.InactiveCode, false, line, 1);
bool directive_expected = false;
while ((c = get_char ()) != -1) {
if (col == 1) {
directive_expected = true;
} else if (!directive_expected) {
// TODO: Implement comment support for disabled code and uncomment this code
// if (c == '#') {
// Eror_WrongPreprocessorLocation ();
// return Token.ERROR;
// }
sbag.PushCommentChar (c);
continue;
}
if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' ) {
sbag.PushCommentChar (c);
continue;
}
if (c == '#') {
if (ParsePreprocessingDirective (false))
break;
}
sbag.PushCommentChar (c);
directive_expected = false;
}
sbag.EndComment (line, col);
if (c != -1) {
tokens_seen = false;
continue;
}
return Token.EOF;
case '"':
return consume_string (false);
case '\'':
return TokenizeBackslash ();
case '@':
c = get_char ();
if (c == '"') {
tokens_seen = true;
return consume_string (true);
}
if (is_identifier_start_character (c)){
return consume_identifier (c, true);
}
Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
return Token.ERROR;
case EvalStatementParserCharacter:
return Token.EVAL_STATEMENT_PARSER;
case EvalCompilationUnitParserCharacter:
return Token.EVAL_COMPILATION_UNIT_PARSER;
case EvalUsingDeclarationsParserCharacter:
return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
case DocumentationXref:
return Token.DOC_SEE;
}
if (is_identifier_start_character (c)) {
tokens_seen = true;
return consume_identifier (c);
}
if (char.IsWhiteSpace ((char) c))
continue;
Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
}
if (CompleteOnEOF){
if (generated)
return Token.COMPLETE_COMPLETION;
generated = true;
return Token.GENERATE_COMPLETION;
}
return Token.EOF;
}
int TokenizeBackslash ()
{
#if FULL_AST
int read_start = reader.Position;
#endif
Location start_location = Location;
int c = get_char ();
tokens_seen = true;
if (c == '\'') {
val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
Report.Error (1011, start_location, "Empty character literal");
return Token.LITERAL;
}
if (c == '\n') {
Report.Error (1010, start_location, "Newline in constant");
return Token.ERROR;
}
int d;
c = escape (c, out d);
if (c == -1)
return Token.ERROR;
if (d != 0)
throw new NotImplementedException ();
ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
val = res;
c = get_char ();
if (c != '\'') {
Report.Error (1012, start_location, "Too many characters in character literal");
// Try to recover, read until newline or next "'"
while ((c = get_char ()) != -1) {
if (c == '\n' || c == '\'')
break;
}
}
#if FULL_AST
res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
#endif
return Token.LITERAL;
}
int TokenizeLessThan ()
{
int d;
if (handle_typeof) {
PushPosition ();
if (parse_generic_dimension (out d)) {
val = d;
DiscardPosition ();
return Token.GENERIC_DIMENSION;
}
PopPosition ();
}
// Save current position and parse next token.
PushPosition ();
if (parse_less_than ()) {
if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
d = Token.OP_GENERICS_LT_DECL;
} else {
d = Token.OP_GENERICS_LT;
}
PopPosition ();
return d;
}
PopPosition ();
parsing_generic_less_than = 0;
d = peek_char ();
if (d == '<') {
get_char ();
d = peek_char ();
if (d == '=') {
get_char ();
return Token.OP_SHIFT_LEFT_ASSIGN;
}
return Token.OP_SHIFT_LEFT;
}
if (d == '=') {
get_char ();
return Token.OP_LE;
}
return Token.OP_LT;
}
//
// Handles one line xml comment
//
private void handle_one_line_xml_comment ()
{
int c;
while ((c = peek_char ()) == ' ') {
if (position_stack.Count == 0)
sbag.PushCommentChar (c);
get_char (); // skip heading whitespaces.
}
while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
if (position_stack.Count == 0)
sbag.PushCommentChar (c);
xml_comment_buffer.Append ((char) get_char ());
}
if (c == '\r' || c == '\n')
xml_comment_buffer.Append (Environment.NewLine);
}
//
// Remove heading "*" in Javadoc-like xml documentation.
//
private void update_formatted_doc_comment (int current_comment_start)
{
int length = xml_comment_buffer.Length - current_comment_start;
string [] lines = xml_comment_buffer.ToString (
current_comment_start,
length).Replace ("\r", "").Split ('\n');
// The first line starts with /**, thus it is not target
// for the format check.
for (int i = 1; i < lines.Length; i++) {
string s = lines [i];
int idx = s.IndexOf ('*');
string head = null;
if (idx < 0) {
if (i < lines.Length - 1)
return;
head = s;
} else
head = s.Substring (0, idx);
foreach (char c in head)
if (c != ' ')
return;
lines [i] = s.Substring (idx + 1);
}
xml_comment_buffer.Remove (current_comment_start, length);
xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
}
//
// Checks if there was incorrect doc comments and raise
// warnings.
//
public void check_incorrect_doc_comment ()
{
if (xml_comment_buffer.Length > 0)
WarningMisplacedComment (Location);
}
//
// Consumes the saved xml comment lines (if any)
// as for current target member or type.
//
public string consume_doc_comment ()
{
if (xml_comment_buffer.Length > 0) {
string ret = xml_comment_buffer.ToString ();
reset_doc_comment ();
return ret;
}
return null;
}
Report Report {
get { return context.Report; }
}
void reset_doc_comment ()
{
xml_comment_buffer.Length = 0;
}
public void cleanup ()
{
if (ifstack != null && ifstack.Count >= 1) {
int state = ifstack.Pop ();
if ((state & REGION) != 0)
Report.Error (1038, Location, "#endregion directive expected");
else
Report.Error (1027, Location, "Expected `#endif' directive");
}
}
}
//
// Indicates whether it accepts XML documentation or not.
//
public enum XmlCommentState {
// comment is allowed in this state.
Allowed,
// comment is not allowed in this state.
NotAllowed,
// once comments appeared when it is NotAllowed, then the
// state is changed to it, until the state is changed to
// .Allowed.
Error
}
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.iterator.provider;
import lombok.NonNull;
import org.deeplearning4j.iterator.LabeledSentenceProvider;
import org.nd4j.common.base.Preconditions;
import org.nd4j.common.primitives.Pair;
import org.nd4j.common.util.MathUtils;
import java.util.*;
/**
* Iterate over a set of sentences/documents,
* where the sentences and labels are provided in lists.
*
* @author Alex Black
*/
public class CollectionLabeledSentenceProvider implements LabeledSentenceProvider {
private final List<String> sentences;
private final List<String> labels;
private final Random rng;
private final int[] order;
private final List<String> allLabels;
private int cursor = 0;
public CollectionLabeledSentenceProvider(@NonNull List<String> sentences,
@NonNull List<String> labelsForSentences) {
this(sentences, labelsForSentences, new Random());
}
public CollectionLabeledSentenceProvider(@NonNull List<String> sentences, @NonNull List<String> labelsForSentences,
Random rng) {
if (sentences.size() != labelsForSentences.size()) {
throw new IllegalArgumentException("Sentences and labels must be same size (sentences size: "
+ sentences.size() + ", labels size: " + labelsForSentences.size() + ")");
}
this.sentences = sentences;
this.labels = labelsForSentences;
this.rng = rng;
if (rng == null) {
order = null;
} else {
order = new int[sentences.size()];
for (int i = 0; i < sentences.size(); i++) {
order[i] = i;
}
MathUtils.shuffleArray(order, rng);
}
//Collect set of unique labels for all sentences
Set<String> uniqueLabels = new HashSet<>(labelsForSentences);
allLabels = new ArrayList<>(uniqueLabels);
Collections.sort(allLabels);
}
@Override
public boolean hasNext() {
return cursor < sentences.size();
}
@Override
public Pair<String, String> nextSentence() {
Preconditions.checkState(hasNext(), "No next element available");
int idx;
if (rng == null) {
idx = cursor++;
} else {
idx = order[cursor++];
}
return new Pair<>(sentences.get(idx), labels.get(idx));
}
@Override
public void reset() {
cursor = 0;
if (rng != null) {
MathUtils.shuffleArray(order, rng);
}
}
@Override
public int totalNumSentences() {
return sentences.size();
}
@Override
public List<String> allLabels() {
return allLabels;
}
@Override
public int numLabelClasses() {
return allLabels.size();
}
}
| {
"pile_set_name": "Github"
} |
var apply = require('./_apply'),
baseRest = require('./_baseRest'),
customDefaultsMerge = require('./_customDefaultsMerge'),
mergeWith = require('./mergeWith');
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, customDefaultsMerge);
return apply(mergeWith, undefined, args);
});
module.exports = defaultsDeep;
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
# Test if the snapshot data is actually compressed.
import sys
import os
sys.path.append(os.getenv('TSTSRCDIR'))
from hot_snapshot import test_snapshot
test_snapshot('.lz4', b'\x04\x22\x4D\x18')
| {
"pile_set_name": "Github"
} |
//
// AppDelegate.h
// WizardWar
//
// Created by Sean Hess on 5/17/13.
// Copyright The LAB 2013. All rights reserved.
//
#import <UIKit/UIKit.h>
//#import "cocos2d.h"
@interface AppDelegate : NSObject <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow * window;
@end
| {
"pile_set_name": "Github"
} |
import PropTypes from 'prop-types';
import React from 'react';
import { Defs, G, LinearGradient, Path, Stop } from 'react-native-svg';
import Svg from '../Svg';
import { colors } from '@rainbow-me/styles';
const PasscodeIcon = ({ color, size, ...props }) => (
<Svg
height={size || 24}
viewBox="0 0 18 24"
width={size ? (size * 18) / 24 : '18'}
{...props}
>
<Defs>
<LinearGradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%">
<Stop offset="0%" stopColor={color} />
<Stop offset="34.274%" stopColor={color} />
<Stop offset="66.193%" stopColor={color} stopOpacity=".84" />
<Stop offset="100%" stopColor={color} stopOpacity=".64" />
</LinearGradient>
</Defs>
<G fill="none" fill-rule="nonzero">
<Path
d="M8.998 0c3.494 0 6.818 2.404 6.818 7.396v4.195c.98.096-3.564.11-13.636.04V7.395C2.18 2.404 5.504 0 8.998 0zm0 2.418c-2.351 0-4.296 1.681-4.296 4.742v3.36l8.592-.014V7.16c0-3.06-1.958-4.742-4.296-4.742z"
fill="url(#gradient)"
/>
<Path
d="M13.193 9c1.671 0 2.277.174 2.889.5.61.328 1.09.807 1.417 1.418.327.612.501 1.218.501 2.89v5.385c0 1.671-.174 2.277-.5 2.889a3.407 3.407 0 01-1.418 1.417c-.612.327-1.218.501-2.89.501H4.808c-1.671 0-2.277-.174-2.889-.5a3.407 3.407 0 01-1.417-1.418C.174 21.47 0 20.864 0 19.192v-5.385c0-1.671.174-2.277.5-2.889a3.407 3.407 0 011.418-1.417C2.53 9.174 3.136 9 4.808 9h8.385zm-4.18 3.102c-.506 0-.878.347-.812.919l.166 2.277-1.921-1.333a.844.844 0 00-.547-.19c-.422 0-.795.339-.795.827 0 .331.174.588.53.745l2.103 1.035-2.103 1.052c-.34.157-.53.406-.53.737 0 .48.373.836.795.836.207 0 .381-.066.538-.19l1.93-1.333-.174 2.219c-.05.521.265.902.82.902.546 0 .844-.364.794-.902l-.165-2.22 1.912 1.342c.158.124.34.199.555.199.414 0 .787-.356.787-.837 0-.33-.19-.596-.53-.745l-2.112-1.06 2.112-1.043c.34-.157.53-.414.53-.745 0-.489-.373-.828-.787-.828a.916.916 0 00-.555.19l-1.929 1.342.174-2.286c.058-.58-.29-.91-.787-.91z"
fill={color}
/>
</G>
</Svg>
);
PasscodeIcon.propTypes = {
color: PropTypes.string,
size: PropTypes.number,
};
PasscodeIcon.defaultProps = {
color: colors.white,
};
export default PasscodeIcon;
| {
"pile_set_name": "Github"
} |
-- Ensure you've run SalesOrdersStructure.sql
-- and SalesOrdersData.sql in the Sample Databases folder
-- in order to run this example.
USE SalesOrdersSample;
GO
-- Listing 2.11 Sample query SQL
SELECT EmployeeID, EmpFirstName, EmpLastName
FROM Employees
WHERE EmpState = 'WA'
AND EmpCity LIKE '%ELLE%'; | {
"pile_set_name": "Github"
} |
package qunar.tc.qconfig.client.spring;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PlaceholderConfigurerSupport;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.ConfigurablePropertyResolver;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import org.springframework.util.StringValueResolver;
import qunar.tc.qconfig.client.Feature;
import qunar.tc.qconfig.client.MapConfig;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author yiqun.fan create on 17-3-28.
*/
class QConfigPropertyAnnotationUtil {
private static final Logger logger = LoggerFactory.getLogger(QConfigPropertyAnnotationUtil.class);
// 拉取qconfig文件超时时间
private static final long DEFAULT_TIMEOUT_MILLISECOND = 60000;
static Map<String, Properties> loadQConfigFilesInAnnotation(ConfigurableListableBeanFactory beanFactory, ClassLoader beanClassLoader) {
Map<String, Properties> props = new HashMap<String, Properties>();
for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
Class<?> clz = getClassByBeanDefinitionName(beanFactory, beanDefinitionName, beanClassLoader);
if (clz == null) continue;
QConfigPropertySource annotation = AnnotationUtils.getAnnotation(clz, QConfigPropertySource.class);
if (annotation == null) continue;
String[] files = annotation.files();
List<String> filtedFiles = new ArrayList<String>();
for (String file : files) {
if (!Strings.isNullOrEmpty(file)) {
if (!props.containsKey(file)) {
filtedFiles.add(file);
}
}
}
if (filtedFiles.isEmpty()) continue;
try {
props.putAll(load(filtedFiles, annotation.trimValue(), annotation.timeout(), annotation.ignoreFileNotFound()));
} catch (Exception e) {
throw new RuntimeException("从qconfig读取配置文件失败", e);
}
}
return props;
}
private static Class<?> getClassByBeanDefinitionName(ConfigurableListableBeanFactory beanFactory, String beanDefinitionName, ClassLoader beanClassLoader) {
if (Strings.isNullOrEmpty(beanDefinitionName)) return null;
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
if (beanDefinition == null) return null;
if (beanDefinition instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDefinition).hasBeanClass()) {
return ((AbstractBeanDefinition) beanDefinition).getBeanClass();
}
String className = beanDefinition.getBeanClassName();
if (!Strings.isNullOrEmpty(className) && beanClassLoader != null) {
try {
return beanClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
logger.debug("找不到类: {}", className, e);
}
}
return null;
}
private static Map<String, Properties> load(List<String> files, boolean trimValue, long timeout, boolean ignoreFileNotFound) throws Exception {
if (files == null || files.isEmpty()) {
return Collections.emptyMap();
}
if (timeout <= 0) {
timeout = DEFAULT_TIMEOUT_MILLISECOND;
}
MapConfig[] configs = new MapConfig[files.size()];
ListenableFuture<?>[] futures = new ListenableFuture[files.size()];
for (int i = 0; i < files.size(); ++i) {
String file = files.get(i);
Map.Entry<Util.File, Feature> entry = Util.parse(file, trimValue);
configs[i] = MapConfig.get(entry.getKey().group, entry.getKey().file, entry.getValue());
futures[i] = configs[i].initFuture();
}
Map<String, Properties> filenameToPropsMap = new HashMap<String, Properties>();
ListenableFuture<?> future = ignoreFileNotFound ? Futures.successfulAsList(futures) : Futures.allAsList(futures);
try {
List result = (List) future.get(timeout, TimeUnit.MILLISECONDS);
for (int i = 0; i < configs.length; ++i) {
if (result.get(i) == null) continue;
filenameToPropsMap.put(files.get(i), configs[i].asProperties());
}
return filenameToPropsMap;
} catch (ExecutionException e) {
logger.error("从qconfig读取配置文件失败, files: {}", files, e.getCause());
throw e;
} catch (TimeoutException e) {
logger.error("从qconfig读取配置文件超时, files: {}", files, e);
throw e;
}
}
static StringValueResolver buildStringValueResolver(Map<String, Properties> filenameToPropsMap) {
MutablePropertySources propertySources = new MutablePropertySources();
for (Map.Entry<String, Properties> entry : filenameToPropsMap.entrySet()) {
propertySources.addFirst(new PropertiesPropertySource(entry.getKey(), entry.getValue()));
}
return buildStringValueResolver(new PropertySourcesPropertyResolver(propertySources));
}
private static StringValueResolver buildStringValueResolver(final ConfigurablePropertyResolver propertyResolver) throws BeansException {
final String placeholderPrefix = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX;
final String placeholderSuffix = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX;
final String valueSeparator = PlaceholderConfigurerSupport.DEFAULT_VALUE_SEPARATOR;
propertyResolver.setPlaceholderPrefix(placeholderPrefix);
propertyResolver.setPlaceholderSuffix(placeholderSuffix);
propertyResolver.setValueSeparator(valueSeparator);
return new StringValueResolver() {
public String resolveStringValue(String strVal) {
String key = parseKey(strVal);
if (!propertyResolver.containsProperty(key)) {
return strVal;
}
String resolved = propertyResolver.resolveRequiredPlaceholders(strVal);
return (resolved.equals("") ? null : resolved);
}
private String parseKey(String strVal) {
if (Strings.isNullOrEmpty(strVal) || !strVal.startsWith(placeholderPrefix) || !strVal.endsWith(placeholderSuffix)) {
return strVal;
}
int index = strVal.indexOf(valueSeparator, placeholderPrefix.length());
if (index < placeholderPrefix.length()) {
return strVal.substring(placeholderPrefix.length(), strVal.length() - placeholderSuffix.length());
} else {
return strVal.substring(placeholderPrefix.length(), index);
}
}
};
}
}
| {
"pile_set_name": "Github"
} |
[Rank]
S. Margaritae Mariae Alaquoque Virginis;;Duplex;;3;;vide C6
[Rule]
vide C6
Gloria
[Comment]
# 17 X – Św. Małgorzaty Marii Alacoque, Dziewicy
! 3 klasy
! Szaty białe
Św. Małgorzata Maria urodziła się w Burgundii w 1647 roku. Mając 24 lata wstąpiła do klasztoru Sióstr Wizytek w Paray-le-Monial. W szeregu objawień Pan Jezus przedstawił jej swoje Serce kochające ludzi i spragnione ich miłości oraz żądał ustanowienia w piątek po oktawie Bożego Ciała święta Jego Serca dla wynagrodzenia Mu zniewag, których doznaje w Najświętszym Sakramencie. Św. Małgorzata doznała wielu cierpień, zanim uwierzono jej posłannictwu. Zmarła 17 października 1690 roku.
[Introitus]
!Pnp 2:3
v. Usiadłam w cieniu Tego, za którym tęskniłam i owoc Jego słodki memu gardłu.
!Ps 83:2-3
Jak miłe są przybytki Twoje, Panie Zastępów! Wzdycha i tęskni moja dusza do przedsionków Pańskich.
&Gloria
v. Usiadłam w cieniu Tego, za którym tęskniłam i owoc Jego słodki memu gardłu.
[Oratio]
Panie Jezu Chryste, któryś św. Dziewicy Małgorzacie Marii cudownie odsłonił niedościgłe bogactwo Serca swego, daj nam, abyśmy dzięki jej zasługom i za jej przykładem miłując Ciebie we wszystkim i nade wszystko, mogli mieć w Sercu Twoim stałe mieszkanie:
$Qui vivis
[Lectio]
Czytanie z Listu świętego Pawła Apostoła do Efezjan.
!Ef 3:8-9; 14-19
!x! Św. Małgorzata Maria została wybrana, aby przypomnieć ludzkości «niedościgłe bogactwa Chrystusowe».
Bracia: Mnie najmniejszemu ze wszystkich świętych została dana ta łaska, abym poganom wieścił niedościgle bogactwa Chrystusowe i oświecał wszystkich, na czym polega ta tajemnica, zakryta od wieków w Bogu, który wszystko stworzył. Z tej to przyczyny zginam kolana przed Ojcem Pana naszego Jezusa Chrystusa, od którego bierze swe imię wszelkie ojcostwo na niebie i na ziemi, aby dał wam według bogactw chwały swojej, a za sprawą Ducha jego, wzmocnić się potężnie w wewnętrznego człowieka, tak aby przez wiarę Chrystus zamieszkał w sercach waszych. A wy, umocnieni i ugruntowani w miłości, abyście wraz ze wszystkimi świętymi pojąć mogli, jak ona jest rozległa i daleka, wzniosła i głęboka, abyście też mogli poznać, jak miłość Chrystusa przewyższa wszelką wiedzę, i ((w ten sposób)) byli napełnieni całą pełnością Bożą.
[Graduale]
!Pnp 8:7
Wody mnogie nie mogły ugasić miłości i rzeki nie zatopią jej.
!Ps 72:26
Niszczeje me ciało i serce moje: Bóg jest opoką mego serca i mym udziałem
w wieczności. Alleluja, alleluja.
!Pnp 7:10
Ja należę do umiłowanego mego i ku mnie się zwraca jego tęsknota. Alleluja.
[Evangelium]
@Sancti/02-24:Evangelium
[Offertorium]
!Zch 9:17
!x! Częsta i dobra Komunia jest wynagrodzeniem za lekceważenie Eucharystii przez oziębłych.
Cóż jest dobrem jego i co pięknem jego, jeno zboże wybranych i wino, które rodzi dziewice?
[Secreta]
Przyjmij, Panie, dary ludu Swojego i spraw, by nas zapalił ten Boski ogień, który wychodząc z Serca Syna Twojego, tak mocno płonął w świętej Małgorzacie Marii.
$Per eundem
[Communio]
!Pnp 6:2
Ja dla umiłowanego mego i dla mnie umiłowany mój; on pasie trzody swe wśród lilii.
[Postcommunio]
Przyjąwszy Sakrament Ciała i Krwi Twojej prosimy Cię, Panie Jezu, spraw za przyczyną św. Dziewicy Małgorzaty Marii, abyśmy wyzbyli się pychy i próżności świata i mogli się przyoblec w cichość oraz pokorę Twojego Serca:
$Qui vivis
| {
"pile_set_name": "Github"
} |
(defpackage #:ultralisp/models/check
(:use #:cl)
(:import-from #:ultralisp/models/project
#:get-name
#:project)
(:import-from #:mito
#:retrieve-by-sql
#:includes
#:count-dao
#:save-dao
#:select-dao
#:dao-table-class)
(:import-from #:sxql
#:from
#:make-sql-symbol
#:select
#:left-join
#:where
#:order-by)
(:import-from #:ultralisp/models/version
#:make-version
#:version)
(:import-from #:alexandria
#:make-keyword)
(:import-from #:anaphora
#:acond
#:it)
(:export
#:get-project-checks
#:make-added-project-check
#:make-via-webhook-check
#:make-via-cron-check
#:base-check
#:get-project
#:project-has-changes-p
#:get-description
#:get-type
#:get-check
#:get-pending-checks
#:get-processed-at
#:get-checks
#:get-error
#:get-all-checks
#:get-check-by-id
#:any-check
#:get-processed-in
#:get-last-project-check
#:get-pending-checks-count
#:get-pending-checks-for-disabled-projects
#:get-pending-checks-for-disabled-projects-count))
(in-package ultralisp/models/check)
(defparameter *allowed-check-types*
'(:added-project :via-cron :via-webhook))
(defclass any-check ()
())
(defmacro defcheck (name)
(let ((class-name (intern
(string-upcase
(format nil "~A-check"
name))))
(make-func-name (intern
(string-upcase
(format nil "make-~A-check"
name))))
(check-type (make-keyword name)))
`(progn
(export ',class-name)
(defclass ,class-name (any-check)
((type :col-type (or :text :null)
:initarg :type
:initform nil
:reader get-type
:documentation "Should be one of :added-project :via-webhook :via-cron"
:inflate (lambda (text)
(make-keyword (string-upcase text)))
:deflate #'symbol-name)
(project :col-type project
:initarg :project
:documentation "A link to a project to be checked."
:reader get-project)
(processed-at :col-type (or :timestamptz :null)
:initarg :processed-at
:initform nil
:accessor get-processed-at
:documentation "Date and time a check was finished at.")
(processed-in :col-type (or :float :null)
:initarg :processed-in
:initform nil
:accessor get-processed-in
:documentation "Number of seconds required to process this check.")
(error :col-type (or :text :null)
:initarg :error
:initform nil
:accessor get-error
:documentation "A error description. If processed-at is not null and error is nil,
then check is considered as successful."))
(:table-name "check")
(:metaclass dao-table-class))
(defmethod print-object ((check ,class-name) stream)
(print-unreadable-object (check stream :type t)
(format stream "~A~@[ ~A~]"
(get-name (get-project check))
(when (slot-boundp check 'processed-at)
(get-processed-at check)))))
(defun ,make-func-name (project)
"Creates or gets a check for the project.
As a second value, returns `t' if check was created, or nil
if it already existed in the database."
(check-type project project)
(let ((type ,check-type))
(log:info "Triggering a check for" project type)
(unless (member type *allowed-check-types*)
(let ((*print-case* :downcase))
(error "Unable to create check of type ~S"
type)))
(acond
((get-project-checks project :pending t)
(log:warn "Check already exists")
(values (first it) nil))
(t (values (mito:create-dao ',class-name
:project project
:type type)
t))))))))
(defcheck base)
(defcheck added-project)
(defcheck via-webhook)
(defcheck via-cron)
(defmethod get-error :around (check)
(unless (get-processed-at check)
(error "This check wasn't processed yet.")))
(defun upgrade-type (check)
(when check
(let* ((type (get-type check))
(real-type (case type
(:added-project 'added-project-check)
(:via-webhook 'via-webhook-check)
(:via-cron 'via-cron-check))))
(if real-type
(change-class check real-type)
check))))
(defun upgrade-types (checks)
(mapcar #'upgrade-type checks))
(defun get-pending-checks (&key limit)
(upgrade-types
(select-dao 'base-check
(includes 'project)
(left-join 'project
:on (:= 'check.project_id
'project.id))
(where (:is-null 'processed-at))
(when limit
(sxql:limit limit)))))
(defun cancel-pending-cron-checks ()
(loop for check in (select-dao 'base-check
(where (:and (:is-null 'processed-at)
(:= 'type "VIA-CRON"))))
do (setf (get-processed-at check) (local-time:now)
(get-processed-in check) 0)
(save-dao check)))
(defun get-pending-checks-count ()
(let ((sql (select ((:as (:count :*)
:count))
(from (make-sql-symbol (mito.dao::table-name (mito.util:ensure-class 'base-check))))
(left-join 'project
:on (:= 'check.project_id
'project.id))
(where (:and (:is-null 'processed_at)
:project.enabled)))))
(getf (first (retrieve-by-sql sql))
:count)))
(defun get-pending-checks-for-disabled-projects (&key limit)
(upgrade-types
(select-dao 'base-check
(includes 'project)
(left-join 'project
:on (:= 'check.project_id
'project.id))
(where (:and (:is-null 'processed-at)
(:not :project.enabled)))
(when limit
(sxql:limit limit)))))
(defun get-pending-checks-for-disabled-projects-count ()
(let ((sql (select ((:as (:count :*)
:count))
(from (make-sql-symbol (mito.dao::table-name (mito.util:ensure-class 'base-check))))
(left-join 'project
:on (:= 'check.project_id
'project.id))
(where (:and (:is-null 'processed_at)
(:not :project.enabled))))))
(getf (first (retrieve-by-sql sql))
:count)))
(defun get-all-checks ()
(upgrade-types
(select-dao 'base-check)))
(defun get-check-by-id (id)
(upgrade-type
(mito:find-dao 'base-check
:id id)))
(defun get-checks (version)
(check-type version version)
(upgrade-types
(mito:retrieve-dao 'base-check
:version version)))
(defun get-project-checks (project &key pending)
(check-type project project)
(upgrade-types
(if pending
(select-dao 'base-check
(where (:and (:is-null 'processed-at)
(:= 'project-id (mito:object-id project)))))
(mito:retrieve-dao 'base-check
:project project))))
(defun get-last-project-check (project)
"Returns a last perofrmed check"
(check-type project project)
(upgrade-type
(first
(select-dao 'base-check
(where (:and (:not (:is-null 'processed-at))
(:= 'project-id (mito:object-id project))))
(order-by (:desc 'processed-at))))))
| {
"pile_set_name": "Github"
} |
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
// ************************************************************************* //
// avtWebpage.C //
// ************************************************************************* //
#include <avtWebpage.h>
// ****************************************************************************
// Method: avtWebpage constructor
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// Modifications:
//
// Hank Childs, Fri Jun 15 16:50:12 PDT 2007
// Initialize "name".
//
// ****************************************************************************
avtWebpage::avtWebpage(const char *filename)
{
name = filename;
ofile = new ofstream(filename);
}
// ****************************************************************************
// Method: avtWebpage destructor
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
avtWebpage::~avtWebpage()
{
if (ofile != NULL)
delete ofile;
}
// ****************************************************************************
// Method: avtWebpage::GetName
//
// Purpose:
// Gets the filename of the webpage.
//
// Programmer: Hank Childs
// Creation: June 15, 2007
//
// ****************************************************************************
const char *
avtWebpage::GetName(void)
{
return name.c_str();
}
// ****************************************************************************
// Method: avtWebpage::InitializePage
//
// Purpose:
// Initializes the webpage.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::InitializePage(const char *heading)
{
*ofile << "<!doctype html public \"-//w3c//dtd html 4.0"
<< " transitional//en\">" << endl;
*ofile << "<html>" << endl;
*ofile << "<head>" << endl;
*ofile << " <title>" << heading << "</title>" << endl;
*ofile << "</head>" << endl;
*ofile << "<body>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::WriteTitle
//
// Purpose:
// Writes the title.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::WriteTitle(const char *title)
{
*ofile << "<center><b><font size=\"10\">" << title << "</font>"
<< "</b></center>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::FinalizePage
//
// Purpose:
// Finishes the webpage.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::FinalizePage(void)
{
*ofile << "</body>" << endl;
*ofile << "</html>" << endl;
ofile->close();
}
// ****************************************************************************
// Method: avtWebpage::AddLink
//
// Purpose:
// Adds a link to another webpage.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddLink(const char *file, const char *listing)
{
*ofile << "<p><a href=\"" << file << "\">" << listing << "</a></p>"
<< endl;
}
// ****************************************************************************
// Method: avtWebpage::AddOnPageLink
//
// Purpose:
// Adds a link to a section on the current webpage.
//
// Programmer: Hank Childs
// Creation: June 15, 2007
//
// ****************************************************************************
void
avtWebpage::AddOnPageLink(const char *section, const char *listing)
{
*ofile << "<p><a href=\"#" << section << "\">" << listing << "</a></p>"
<< endl;
}
// ****************************************************************************
// Method: avtWebpage::AddSectionForLinks
//
// Purpose:
// Adds a section header for making links.
//
// Programmer: Hank Childs
// Creation: June 15, 2007
//
// ****************************************************************************
void
avtWebpage::AddSectionForLinks(const char *section)
{
*ofile << "<a name=\"" << section << "\"></a>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddHeading
//
// Purpose:
// Adds a heading.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddHeading(const char *heading)
{
*ofile << "<p><b><font size=\"8\">" << heading << "</font></b></p>"
<< endl;
}
// ****************************************************************************
// Method: avtWebpage::AddSubheading
//
// Purpose:
// Adds a sub-heading.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddSubheading(const char *heading)
{
*ofile << "<p><b><font size=\"6\">" << heading << "</font></b></p>"
<< endl;
}
// ****************************************************************************
// Method: avtWebpage::AddEntry
//
// Purpose:
// Adds an entry to the webpage.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddEntry(const char *heading)
{
*ofile << "<p><b><font size=\"4\">" << heading << "</font></b></p>"
<< endl;
}
// ****************************************************************************
// Method: avtWebpage::StartTable
//
// Purpose:
// Starts a table.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::StartTable(void)
{
*ofile << "<table border>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::EndTable
//
// Purpose:
// Ends a table.
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::EndTable(void)
{
*ofile << "</table>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddTableEntry2
//
// Purpose:
// Adds a table entry with two columns
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddTableEntry2(const char *a1, const char *a2)
{
const char *b1 = (a1 != NULL ? a1 : "");
const char *b2 = (a2 != NULL ? a2 : "");
*ofile << "<tr><td>" << b1 << "</td><td>" << b2 << "</td></tr>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddTableEntry3
//
// Purpose:
// Adds a table entry with three columns
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddTableEntry3(const char *a1, const char *a2, const char *a3)
{
const char *b1 = (a1 != NULL ? a1 : "");
const char *b2 = (a2 != NULL ? a2 : "");
const char *b3 = (a3 != NULL ? a3 : "");
*ofile << "<tr><td>" << b1 << "</td><td>" << b2 << "</td><td>" << b3
<< "</td></tr>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddTableEntry4
//
// Purpose:
// Adds a table entry with four columns
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddTableEntry4(const char *a1, const char *a2, const char *a3,
const char *a4)
{
const char *b1 = (a1 != NULL ? a1 : "");
const char *b2 = (a2 != NULL ? a2 : "");
const char *b3 = (a3 != NULL ? a3 : "");
const char *b4 = (a4 != NULL ? a4 : "");
*ofile << "<tr><td>" << b1 << "</td><td>" << b2 << "</td><td>" << b3
<< "</td><td>" << b4 << "</td></tr>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddTableHeader2
//
// Purpose:
// Adds a table header with two columns
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddTableHeader2(const char *a1, const char *a2)
{
const char *b1 = (a1 != NULL ? a1 : "");
const char *b2 = (a2 != NULL ? a2 : "");
*ofile << "<tr><td><b><i>" << b1 << "</b></i></td><td><b><i>"
<< b2 << "</b></i></td></tr>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddTableHeader3
//
// Purpose:
// Adds a table header with three columns
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddTableHeader3(const char *a1, const char *a2, const char *a3)
{
const char *b1 = (a1 != NULL ? a1 : "");
const char *b2 = (a2 != NULL ? a2 : "");
const char *b3 = (a3 != NULL ? a3 : "");
*ofile << "<tr><td><b><i>" << b1 << "</b></i></td><td><b><i>"
<< b2 << "</b></i></td><td><b><i>" << b3
<< "</b></i></td></tr>" << endl;
}
// ****************************************************************************
// Method: avtWebpage::AddTableHeader4
//
// Purpose:
// Adds a table header with four columns
//
// Programmer: Hank Childs
// Creation: December 21, 2006
//
// ****************************************************************************
void
avtWebpage::AddTableHeader4(const char *a1, const char *a2, const char *a3,
const char *a4)
{
const char *b1 = (a1 != NULL ? a1 : "");
const char *b2 = (a2 != NULL ? a2 : "");
const char *b3 = (a3 != NULL ? a3 : "");
const char *b4 = (a4 != NULL ? a4 : "");
*ofile << "<tr><td><b><i>" << b1 << "</b></i></td><td><b><i>"
<< b2 << "</b></i></td><td><b><i>" << b3
<< "</b></i></td><td><b><i>" << b4 << "</b></i></td></tr>" << endl;
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* ResponseListener fixes the Response headers based on the Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ResponseListener implements EventSubscriberInterface
{
private $charset;
public function __construct(string $charset)
{
$this->charset = $charset;
}
/**
* Filters the Response.
*/
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$response = $event->getResponse();
if (null === $response->getCharset()) {
$response->setCharset($this->charset);
}
$response->prepare($event->getRequest());
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => 'onKernelResponse',
);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<MessageTemplate>
<To>{{ NewsLetterSubscription.Email }}</To>
<Subject>{{ Campaign.Subject }}</Subject>
<ModelTypes>NewsletterSubscription, Campaign</ModelTypes>
<Body><![CDATA[{% extends 'master' %}
{% block 'body' %}
{{ Campaign.Body }}
{% endblock %}]]></Body>
</MessageTemplate> | {
"pile_set_name": "Github"
} |
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2014, Willow Garage, Inc.
* Copyright (c) 2014-2016, Open Source Robotics Foundation
* 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.
* * Neither the name of Open Source Robotics Foundation nor the names of its
* contributors may 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 THE
* COPYRIGHT OWNER 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.
*/
/** @author Jia Pan */
#include "fcl/narrowphase/detail/traversal/collision/collision_traversal_node_base-inl.h"
namespace fcl
{
namespace detail
{
template
class CollisionTraversalNodeBase<double>;
} // namespace detail
} // namespace fcl
| {
"pile_set_name": "Github"
} |
V ==K Pair ( Pair ( 1 , Wrapper ( 2 , .Bottoms ) , .Bottoms ) , Pair ( 3 , 4 , .Bottoms ) , .Bottoms )
| {
"pile_set_name": "Github"
} |
package com.yaoyumeng.v2ex2.utils;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* Created by yw on 2015/5/9.
*/
public class InputUtils {
public static void popSoftkeyboard(Context ctx, View view, boolean wantPop) {
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
if (wantPop) {
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
| {
"pile_set_name": "Github"
} |
#include <functional>
#include "depth_market.h"
#include "base_strategy.h"
extern std::function<void(const QString&, int, double, int)> buyLimit;
extern std::function<void(const QString&, int, double, int)> sellLimit;
BaseStrategy::BaseStrategy(DepthMarketCollection *pDMC) :
pDepthMarkets(pDMC)
{
//
}
BaseStrategy::~BaseStrategy()
{
//
}
void BaseStrategy::buyUnderlying(int underlyingIdx, int vol, double price, int orderType)
{
const QString underlyingID = pDepthMarkets->getUnderlyingIDByIdx(underlyingIdx);
buyLimit(underlyingID, vol, price, orderType);
}
void BaseStrategy::sellUnderlying(int underlyingIdx, int vol, double price, int orderType)
{
const QString underlyingID = pDepthMarkets->getUnderlyingIDByIdx(underlyingIdx);
sellLimit(underlyingID, vol, price, orderType);
}
void BaseStrategy::buyOption(int underlyingIdx, OPTION_TYPE type, int kIdx, int vol, double price, int orderType)
{
const QString optionID = pDepthMarkets->makeOptionByIdx(underlyingIdx, type, kIdx);
buyLimit(optionID, vol, price, orderType);
}
void BaseStrategy::sellOption(int underlyingIdx, OPTION_TYPE type, int kIdx, int vol, double price, int orderType)
{
const QString optionID = pDepthMarkets->makeOptionByIdx(underlyingIdx, type, kIdx);
sellLimit(optionID, vol, price, orderType);
}
| {
"pile_set_name": "Github"
} |
// 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.
//
// A QuicSession, which demuxes a single connection to individual streams.
#ifndef NET_QUIC_QUIC_SESSION_H_
#define NET_QUIC_QUIC_SESSION_H_
#include <stddef.h>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "base/compiler_specific.h"
#include "base/containers/small_map.h"
#include "base/macros.h"
#include "base/strings/string_piece.h"
#include "net/base/ip_endpoint.h"
#include "net/quic/core/quic_connection.h"
#include "net/quic/core/quic_crypto_stream.h"
#include "net/quic/core/quic_packet_creator.h"
#include "net/quic/core/quic_protocol.h"
#include "net/quic/core/quic_write_blocked_list.h"
#include "net/quic/core/reliable_quic_stream.h"
namespace net {
class QuicCryptoStream;
class QuicFlowController;
class ReliableQuicStream;
namespace test {
class QuicSessionPeer;
} // namespace test
class NET_EXPORT_PRIVATE QuicSession : public QuicConnectionVisitorInterface {
public:
// CryptoHandshakeEvent enumerates the events generated by a QuicCryptoStream.
enum CryptoHandshakeEvent {
// ENCRYPTION_FIRST_ESTABLISHED indicates that a full client hello has been
// sent by a client and that subsequent packets will be encrypted. (Client
// only.)
ENCRYPTION_FIRST_ESTABLISHED,
// ENCRYPTION_REESTABLISHED indicates that a client hello was rejected by
// the server and thus the encryption key has been updated. Therefore the
// connection should resend any packets that were sent under
// ENCRYPTION_INITIAL. (Client only.)
ENCRYPTION_REESTABLISHED,
// HANDSHAKE_CONFIRMED, in a client, indicates the the server has accepted
// our handshake. In a server it indicates that a full, valid client hello
// has been received. (Client and server.)
HANDSHAKE_CONFIRMED,
};
// Does not take ownership of |connection|.
QuicSession(QuicConnection* connection, const QuicConfig& config);
~QuicSession() override;
virtual void Initialize();
// QuicConnectionVisitorInterface methods:
void OnStreamFrame(const QuicStreamFrame& frame) override;
void OnRstStream(const QuicRstStreamFrame& frame) override;
void OnGoAway(const QuicGoAwayFrame& frame) override;
void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
void OnBlockedFrame(const QuicBlockedFrame& frame) override;
void OnConnectionClosed(QuicErrorCode error,
const std::string& error_details,
ConnectionCloseSource source) override;
void OnWriteBlocked() override {}
void OnSuccessfulVersionNegotiation(const QuicVersion& version) override;
void OnCanWrite() override;
void OnCongestionWindowChange(QuicTime /*now*/) override {}
void OnConnectionMigration(PeerAddressChangeType type) override {}
// Deletes streams that are safe to be deleted now that it's safe to do so (no
// other operations are being done on the streams at this time).
void PostProcessAfterData() override;
bool WillingAndAbleToWrite() const override;
bool HasPendingHandshake() const override;
bool HasOpenDynamicStreams() const override;
void OnPathDegrading() override;
// Called on every incoming packet. Passes |packet| through to |connection_|.
virtual void ProcessUdpPacket(const IPEndPoint& self_address,
const IPEndPoint& peer_address,
const QuicReceivedPacket& packet);
// Called by streams when they want to write data to the peer.
// Returns a pair with the number of bytes consumed from data, and a boolean
// indicating if the fin bit was consumed. This does not indicate the data
// has been sent on the wire: it may have been turned into a packet and queued
// if the socket was unexpectedly blocked.
// If provided, |ack_notifier_delegate| will be registered to be notified when
// we have seen ACKs for all packets resulting from this call.
virtual QuicConsumedData WritevData(
ReliableQuicStream* stream,
QuicStreamId id,
QuicIOVector iov,
QuicStreamOffset offset,
bool fin,
QuicAckListenerInterface* ack_notifier_delegate);
// Called by streams when they want to close the stream in both directions.
virtual void SendRstStream(QuicStreamId id,
QuicRstStreamErrorCode error,
QuicStreamOffset bytes_written);
// Called when the session wants to go away and not accept any new streams.
void SendGoAway(QuicErrorCode error_code, const std::string& reason);
// Removes the stream associated with 'stream_id' from the active stream map.
virtual void CloseStream(QuicStreamId stream_id);
// Returns true if outgoing packets will be encrypted, even if the server
// hasn't confirmed the handshake yet.
virtual bool IsEncryptionEstablished();
// For a client, returns true if the server has confirmed our handshake. For
// a server, returns true if a full, valid client hello has been received.
virtual bool IsCryptoHandshakeConfirmed();
// Called by the QuicCryptoStream when a new QuicConfig has been negotiated.
virtual void OnConfigNegotiated();
// Called by the QuicCryptoStream when the handshake enters a new state.
//
// Clients will call this function in the order:
// ENCRYPTION_FIRST_ESTABLISHED
// zero or more ENCRYPTION_REESTABLISHED
// HANDSHAKE_CONFIRMED
//
// Servers will simply call it once with HANDSHAKE_CONFIRMED.
virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event);
// Called by the QuicCryptoStream when a handshake message is sent.
virtual void OnCryptoHandshakeMessageSent(
const CryptoHandshakeMessage& message);
// Called by the QuicCryptoStream when a handshake message is received.
virtual void OnCryptoHandshakeMessageReceived(
const CryptoHandshakeMessage& message);
// Returns mutable config for this session. Returned config is owned
// by QuicSession.
QuicConfig* config();
// Returns true if the stream existed previously and has been closed.
// Returns false if the stream is still active or if the stream has
// not yet been created.
bool IsClosedStream(QuicStreamId id);
QuicConnection* connection() { return connection_; }
const QuicConnection* connection() const { return connection_; }
size_t num_active_requests() const { return dynamic_stream_map_.size(); }
const IPEndPoint& peer_address() const { return connection_->peer_address(); }
QuicConnectionId connection_id() const {
return connection_->connection_id();
}
// Returns the number of currently open streams, excluding the reserved
// headers and crypto streams, and never counting unfinished streams.
virtual size_t GetNumActiveStreams() const;
// Returns the number of currently open peer initiated streams, excluding the
// reserved headers and crypto streams.
virtual size_t GetNumOpenIncomingStreams() const;
// Returns the number of currently open self initiated streams, excluding the
// reserved headers and crypto streams.
virtual size_t GetNumOpenOutgoingStreams() const;
// Returns the number of "available" streams, the stream ids less than
// largest_peer_created_stream_id_ that have not yet been opened.
virtual size_t GetNumAvailableStreams() const;
// Add the stream to the session's write-blocked list because it is blocked by
// connection-level flow control but not by its own stream-level flow control.
// The stream will be given a chance to write when a connection-level
// WINDOW_UPDATE arrives.
void MarkConnectionLevelWriteBlocked(QuicStreamId id);
// Returns true if the session has data to be sent, either queued in the
// connection, or in a write-blocked stream.
bool HasDataToWrite() const;
bool goaway_sent() const;
bool goaway_received() const;
QuicErrorCode error() const { return error_; }
Perspective perspective() const { return connection_->perspective(); }
QuicFlowController* flow_controller() { return &flow_controller_; }
// Returns true if connection is flow controller blocked.
bool IsConnectionFlowControlBlocked() const;
// Returns true if any stream is flow controller blocked.
bool IsStreamFlowControlBlocked();
size_t max_open_incoming_streams() const {
return max_open_incoming_streams_;
}
size_t max_open_outgoing_streams() const {
return max_open_outgoing_streams_;
}
size_t MaxAvailableStreams() const;
// Returns existing static or dynamic stream with id = |stream_id|. If no
// such stream exists, and |stream_id| is a peer-created dynamic stream id,
// then a new stream is created and returned. In all other cases, nullptr is
// returned.
ReliableQuicStream* GetOrCreateStream(const QuicStreamId stream_id);
// Mark a stream as draining.
virtual void StreamDraining(QuicStreamId id);
// Returns true if this stream should yield writes to another blocked stream.
bool ShouldYield(QuicStreamId stream_id);
protected:
using StaticStreamMap =
base::SmallMap<std::unordered_map<QuicStreamId, ReliableQuicStream*>, 2>;
using DynamicStreamMap =
base::SmallMap<std::unordered_map<QuicStreamId, ReliableQuicStream*>, 10>;
// Creates a new stream to handle a peer-initiated stream.
// Caller does not own the returned stream.
// Returns nullptr and does error handling if the stream can not be created.
virtual ReliableQuicStream* CreateIncomingDynamicStream(QuicStreamId id) = 0;
// Create a new stream to handle a locally-initiated stream.
// Caller does not own the returned stream.
// Returns nullptr if max streams have already been opened.
virtual ReliableQuicStream* CreateOutgoingDynamicStream(
SpdyPriority priority) = 0;
// Return the reserved crypto stream.
virtual QuicCryptoStream* GetCryptoStream() = 0;
// Adds |stream| to the dynamic stream map.
// Takes ownership of |stream|.
virtual void ActivateStream(ReliableQuicStream* stream);
// Returns the stream ID for a new outgoing stream, and increments the
// underlying counter.
QuicStreamId GetNextOutgoingStreamId();
// Returns existing stream with id = |stream_id|. If no such stream exists,
// and |stream_id| is a peer-created id, then a new stream is created and
// returned. However if |stream_id| is a locally-created id and no such stream
// exists, the connection is closed.
// Caller does not own the returned stream.
ReliableQuicStream* GetOrCreateDynamicStream(QuicStreamId stream_id);
// Performs the work required to close |stream_id|. If |locally_reset|
// then the stream has been reset by this endpoint, not by the peer.
virtual void CloseStreamInner(QuicStreamId stream_id, bool locally_reset);
// When a stream is closed locally, it may not yet know how many bytes the
// peer sent on that stream.
// When this data arrives (via stream frame w. FIN, or RST) this method
// is called, and correctly updates the connection level flow controller.
void UpdateFlowControlOnFinalReceivedByteOffset(
QuicStreamId id,
QuicStreamOffset final_byte_offset);
// Return true if given stream is peer initiated.
bool IsIncomingStream(QuicStreamId id) const;
StaticStreamMap& static_streams() { return static_stream_map_; }
const StaticStreamMap& static_streams() const { return static_stream_map_; }
DynamicStreamMap& dynamic_streams() { return dynamic_stream_map_; }
const DynamicStreamMap& dynamic_streams() const {
return dynamic_stream_map_;
}
std::vector<ReliableQuicStream*>* closed_streams() {
return &closed_streams_;
}
void set_max_open_incoming_streams(size_t max_open_incoming_streams);
void set_max_open_outgoing_streams(size_t max_open_outgoing_streams);
void set_largest_peer_created_stream_id(
QuicStreamId largest_peer_created_stream_id) {
largest_peer_created_stream_id_ = largest_peer_created_stream_id;
}
void set_error(QuicErrorCode error) { error_ = error; }
QuicWriteBlockedList* write_blocked_streams() {
return &write_blocked_streams_;
}
size_t GetNumDynamicOutgoingStreams() const;
size_t GetNumDrainingOutgoingStreams() const;
size_t num_locally_closed_incoming_streams_highest_offset() const {
return num_locally_closed_incoming_streams_highest_offset_;
}
size_t GetNumLocallyClosedOutgoingStreamsHighestOffset() const;
// Returns true if the stream is still active.
bool IsOpenStream(QuicStreamId id);
QuicStreamId next_outgoing_stream_id() const {
return next_outgoing_stream_id_;
}
// Close connection when receive a frame for a locally-created nonexistant
// stream.
// Prerequisite: IsClosedStream(stream_id) == false
// Server session might need to override this method to allow server push
// stream to be promised before creating an active stream.
virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id);
bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id);
void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id,
QuicStreamOffset offset);
// If stream is a locally closed stream, this RST will update FIN offset.
// Otherwise stream is a preserved stream and the behavior of it depends on
// derived class's own implementation.
virtual void HandleRstOnValidNonexistentStream(
const QuicRstStreamFrame& frame);
private:
friend class test::QuicSessionPeer;
// Called in OnConfigNegotiated when we receive a new stream level flow
// control window in a negotiated config. Closes the connection if invalid.
void OnNewStreamFlowControlWindow(QuicStreamOffset new_window);
// Called in OnConfigNegotiated when we receive a new connection level flow
// control window in a negotiated config. Closes the connection if invalid.
void OnNewSessionFlowControlWindow(QuicStreamOffset new_window);
// Keep track of highest received byte offset of locally closed streams, while
// waiting for a definitive final highest offset from the peer.
std::map<QuicStreamId, QuicStreamOffset>
locally_closed_streams_highest_offset_;
QuicConnection* connection_;
std::vector<ReliableQuicStream*> closed_streams_;
QuicConfig config_;
// The maximum number of outgoing streams this connection can open.
size_t max_open_outgoing_streams_;
// The maximum number of incoming streams this connection will allow.
size_t max_open_incoming_streams_;
// Static streams, such as crypto and header streams. Owned by child classes
// that create these streams.
StaticStreamMap static_stream_map_;
// Map from StreamId to pointers to streams. Owns the streams.
DynamicStreamMap dynamic_stream_map_;
// The ID to use for the next outgoing stream.
QuicStreamId next_outgoing_stream_id_;
// Set of stream ids that are less than the largest stream id that has been
// received, but are nonetheless available to be created.
std::unordered_set<QuicStreamId> available_streams_;
// Set of stream ids that are "draining" -- a FIN has been sent and received,
// but the stream object still exists because not all the received data has
// been consumed.
std::unordered_set<QuicStreamId> draining_streams_;
// A list of streams which need to write more data.
QuicWriteBlockedList write_blocked_streams_;
QuicStreamId largest_peer_created_stream_id_;
// A counter for peer initiated streams which are in the dynamic_stream_map_.
size_t num_dynamic_incoming_streams_;
// A counter for peer initiated streams which are in the draining_streams_.
size_t num_draining_incoming_streams_;
// A counter for peer initiated streams which are in the
// locally_closed_streams_highest_offset_.
size_t num_locally_closed_incoming_streams_highest_offset_;
// The latched error with which the connection was closed.
QuicErrorCode error_;
// Used for connection-level flow control.
QuicFlowController flow_controller_;
// The stream id which was last popped in OnCanWrite, or 0, if not under the
// call stack of OnCanWrite.
QuicStreamId currently_writing_stream_id_;
DISALLOW_COPY_AND_ASSIGN(QuicSession);
};
} // namespace net
#endif // NET_QUIC_QUIC_SESSION_H_
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018-20 IBM Corporation
*
* 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.
*/
import Debug from 'debug'
import { REPL, inBrowser, isHeadless, hasProxy, CodedError, i18n } from '@kui-shell/core'
const strings = i18n('plugin-kubectl')
const debug = Debug('plugin-kubectl/util/fetch-file')
async function needle({ qexec }: REPL, method: 'get', url: string): Promise<{ statusCode: number; body: string }> {
if (isHeadless()) {
const needle = await import('needle')
debug('fetch via needle', needle)
return needle(method, url, { follow_max: 10 }).then(_ => ({ statusCode: _.statusCode, body: _.body }))
} else if (inBrowser()) {
// Unfortunately, we cannot rely on being able to fetch files
// directly from a browser. For one, if the remote site does not
// offer an Access-Control-Allow-Origin, then well behaving
// browsers will refuse to load their content;
// e.g. https://k8s.io/examples/controllers/nginx-deployment.yaml
// Solution: have the kui proxy do this
if (!hasProxy()) {
throw new Error(strings('Unable to fetch remote file'))
} else {
debug('fetch via proxy')
const body = await qexec<string>(`_fetchfile ${url}`)
debug('fetched via proxy', body)
return {
statusCode: 200,
body
}
}
/* return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(method, url, true)
xhr.withCredentials = true
xhr.addEventListener('error', () => {
console.error('error in xhr', xhr)
reject(xhr.response || 'Internal Error')
})
xhr.addEventListener('load', () => {
resolve({
statusCode: xhr.status,
body: typeof xhr.response === 'string' ? xhr.response : xhr.response.response
})
})
xhr.send()
}) */
} else {
debug('fetch via electron.net')
const { net } = (await import('electron')).remote
return new Promise((resolve, reject) => {
const request = net.request({
method,
url,
redirect: 'follow'
})
request.on('response', response => {
const statusCode = response.statusCode
debug('got response', statusCode)
// we will accumulate the body chunks below
let body = ''
// Warning: you must register 'end' before 'data'.
// https://github.com/electron/electron/issues/12545
response.on('end', () => {
debug('got end')
if (response.statusCode < 300) {
resolve({ statusCode, body })
} else {
const error: CodedError = new Error(body)
error.statusCode = statusCode
reject(error)
}
})
response.on('data', chunk => {
// debug('got chunk', chunk.toString())
body += chunk.toString()
})
})
request.end()
})
}
}
/**
* Either fetch a remote file or read a local one
*
*/
export function fetchFile(repl: REPL, url: string): Promise<(string | Buffer)[]> {
debug('fetchFile', url)
const urls = url.split(/,/)
return Promise.all(
urls.map(async url => {
if (url.match(/http(s)?:\/\//)) {
debug('fetch remote', url)
const fetchOnce = () => needle(repl, 'get', url).then(_ => _.body)
const retry = (delay: number) => async (err: Error) => {
if (/timeout/.test(err.message) || /hang up/.test(err.message) || /hangup/.test(err.message)) {
debug('retrying', err)
await new Promise(resolve => setTimeout(resolve, delay))
return fetchOnce()
} else {
throw err
}
}
// fetch with three retries
return fetchOnce()
.catch(retry(500))
.catch(retry(1000))
.catch(retry(5000))
} else {
const filepath = url
debug('fetch local', filepath)
const stats = (await repl.rexec<{ data: string }>(`vfs fstat ${repl.encodeComponent(filepath)} --with-data`))
.content
return stats.data
}
})
)
}
/** same as fetchFile, but returning a string rather than a Buffer */
export async function fetchFileString(repl: REPL, url: string): Promise<string[]> {
const files = await fetchFile(repl, url)
return files.map(_ => _.toString())
}
export async function fetchFileKustomize(repl: REPL, url: string): Promise<{ data: string; dir?: string }> {
const stats = (
await repl.rexec<{ data: string; dir?: string }>(`_fetchfile ${repl.encodeComponent(url)} --kustomize`)
).content
return stats
}
export default fetchFileString
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.