code stringlengths 46 37.2k | language stringclasses 9
values | AST_depth int64 3 30 | alphanumeric_fraction float64 0.2 0.91 | max_line_length int64 13 399 | avg_line_length float64 5.67 140 | num_lines int64 7 299 | original_docstring stringlengths 22 42.6k | source stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
pub fn assert_json_matches_no_panic<Lhs, Rhs>(
lhs: &Lhs,
rhs: &Rhs,
config: Config,
) -> Result<(), String>
where
Lhs: Serialize,
Rhs: Serialize,
{
let lhs = serde_json::to_value(lhs).unwrap_or_else(|err| {
panic!(
"Couldn't convert left hand side value to JSON. Serde error:... | rust | 18 | 0.476132 | 78 | 23.787879 | 33 | /// Compares two JSON values without panicking.
///
/// Instead it returns a `Result` where the error is the message that would be passed to `panic!`.
/// This is might be useful if you want to control how failures are reported and don't want to deal
/// with panics. | function |
func (r *Handler) SetContext(ctx context.Context) *Handler {
if r == nil {
return r
}
if r.clientName == rjs.ClientGoRedis {
if old, ok := r.implementation.(*clients.GoRedis); ok {
return &Handler{
clientName: r.clientName,
implementation: clients.NewGoRedisClient(ctx, old.Conn),
}
}
}
ret... | go | 17 | 0.654434 | 60 | 22.428571 | 14 | // SetContext helps redis-clients, provide use of command level context
// in the ReJSON commands.
// Currently, only go-redis@v8 supports command level context, therefore
// a separate method is added to support it, maintaining the support for
// other clients and for backward compatibility. (nitishm/go-rejson#46) | function |
public class MergekSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length < 1) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>(){
@Override
public int compare(ListNode node1, ListNode node2){
... | java | 16 | 0.527943 | 102 | 30.185185 | 27 | /**
* Creator : wangtaishan
* Date : 2018/9/2
* Title : 23. Merge k Sorted Lists
* Description :
*
*Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*
* Example:
*
* Input:
* [
* 1->4->5,
* 1->3->4,
* 2->6
* ]
* Output: 1->1->2->3->4->4->5->6
*
*... | class |
final class ServletContextCleaner {
private static final Logger LOG = LoggerFactory.getLogger(ServletContextCleaner.class);
private static final Set<String> REMOVE_PREFIX = ImmutableSet.of(
"org.jboss.resteasy",
"resteasy",
"org.apache.shiro",
"sonia.scm"
);
private ServletContextCleaner() {
... | java | 13 | 0.666953 | 89 | 24.911111 | 45 | /**
* Remove cached resources from {@link ServletContext} to allow a clean restart of scm-manager without stale or
* duplicated data.
*
* @since 2.0.0
*/ | class |
class Device:
"""GPU Device class.
This class manages GPU id.
The purpose of this device class instead of PyTorch device class is
to assign GPU ids when the algorithm is trained in parallel with
scikit-learn utilities such as `sklearn.model_selection.cross_validate` or
`sklearn.model_selection.... | python | 12 | 0.573006 | 78 | 26.644068 | 59 | GPU Device class.
This class manages GPU id.
The purpose of this device class instead of PyTorch device class is
to assign GPU ids when the algorithm is trained in parallel with
scikit-learn utilities such as `sklearn.model_selection.cross_validate` or
`sklearn.model_selection.GridSearchCV`.
.... | class |
def minutes_for_days(cal, ordered_days=False):
random.seed('deterministic')
if ordered_days:
ordered_session_list = random.sample(list(cal.all_sessions), 500)
ordered_session_list.sort()
def session_picker(day):
return ordered_session_list[day]
else:
def session_p... | python | 14 | 0.636743 | 73 | 39 | 12 |
500 randomly selected days.
This is used to make sure our test coverage is unbiased towards any rules.
We use a random sample because testing on all the trading days took
around 180 seconds on my laptop, which is far too much for normal unit
testing.
We manually set the seed so that this will ... | function |
public class DeclinedPaymentException : DeclinedTransactionException
{
public CreatePaymentResult CreatePaymentResult => _errors?.PaymentResult;
public DeclinedPaymentException(System.Net.HttpStatusCode statusCode, string responseBody, PaymentErrorResponse errors)
: base(BuildMessage(err... | c# | 13 | 0.651087 | 127 | 47.473684 | 19 | /// <summary>
/// Represents an error response from a create payment call.
/// </summary> | class |
public static HttpRequestProperties ODataProperties(this HttpRequest request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
HttpRequestProperties properties;
if (!HttpRequestPropertiesDict.TryGetValue(request, out prop... | c# | 11 | 0.56926 | 80 | 36.714286 | 14 | /// <summary>
/// Gets the <see cref="HttpRequestProperties"/> instance containing OData methods and properties
/// for given <see cref="HttpRequest"/>.
/// </summary>
/// <param name="request">The request of interest.</param>
/// <returns>
/// An object through which OData methods and properties for given <paramref na... | function |
Value merge_defs(Source::Pos pos, rc<Env> env, optional<const Value&> existing, const Value& fresh) {
if (!existing) return fresh;
else if (fresh.type.of(K_UNDEFINED)) return *existing;
else if (existing->type.of(K_UNDEFINED)) return fresh;
else if (existing->type.of(K_FORM_FN)) {
... | c++ | 26 | 0.50811 | 106 | 44.685185 | 54 | // Unifies two values representing functions, which may or may not be fully-defined.
// In general, this function intends to:
// - Replace undefined/form-level versions of functions with their concrete values.
// - Merge values with different forms into form-level intersections.
// - Merge values with different ... | function |
public boolean process( int sideLength,
@Nullable double[] diag,
@Nullable double[] off,
double[] eigenvalues ) {
if (diag != null && off != null)
helper.init(diag, off, sideLength);
if (Q == null)
... | java | 9 | 0.492481 | 52 | 37.071429 | 14 | /**
* Computes the eigenvalue of the provided tridiagonal matrix. Note that only the upper portion
* needs to be tridiagonal. The bottom diagonal is assumed to be the same as the top.
*
* @param sideLength Number of rows and columns in the input matrix.
* @param diag Diagonal elements from tr... | function |
func waitForDeletion(ctx context.Context, clientset k8sclient.Interface, pvcName, ns string) error {
for true {
_, err := clientset.CoreV1().PersistentVolumeClaims(ns).Get(ctx, pvcName, metav1.GetOptions{})
if k8serrors.IsNotFound(err) {
break
} else if err != nil {
return err
}
select {
case <-time.... | go | 13 | 0.684426 | 100 | 27.764706 | 17 | // waitForDeletion waits for the provided pvcName to not be found, and returns early if any error besides 'not found' is given | function |
static void eqos_eee_ctrl_timer(unsigned long data)
{
struct eqos_prv_data *pdata =
(struct eqos_prv_data *)data;
DBGPR_EEE("-->eqos_eee_ctrl_timer\n");
eqos_enable_eee_mode(pdata);
DBGPR_EEE("<--eqos_eee_ctrl_timer\n");
} | c | 8 | 0.688596 | 51 | 27.625 | 8 | /*!
* \brief API to control EEE mode.
*
* \details This function will move the MAC transmitter in LPI mode
* if there is no data transfer and MAC is not already in LPI state.
*
* \param[in] data - data hook
*
* \return void
*/ | function |
def create_streamer(file, connect_to='tcp://127.0.0.1:5555', loop=True):
if os.path.isfile(file):
cap = cv2.VideoCapture(file)
else:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file)
sender = imagezmq.ImageSender(connect_to=connect_to)
host_name = socket.gethostname(... | python | 14 | 0.576854 | 78 | 33.625 | 16 |
You can use this function to emulate an IP camera for the counting apps.
Parameters
----------
file : str
Path to the video file you want to stream.
connect_to : str, optional
Where the video shall be streamed to.
The default is 'tcp://127.0.0.1:5555'.
loop : bool, opti... | function |
private Thread CreateNewThread(string customName)
{
TurboContract.Ensures(TurboContract.Result<Thread>() != null);
Thread res = new Thread(ThreadStartUpProc);
int threadNum = Interlocked.Increment(ref _currentThreadNum);
res.IsBackground = _isBackgroundThreads;
... | c# | 13 | 0.576329 | 90 | 47.666667 | 12 | /// <summary>
/// Creates a new Thread (does not start that Thread)
/// </summary>
/// <param name="customName">Specific name for thread</param>
/// <returns>Created thread</returns> | function |
public class DeviceRemovedEventArgs
{
public ButtplugClientDevice Device { get; }
public DeviceRemovedEventArgs(ButtplugClientDevice aDevice)
{
Device = aDevice;
}
} | c# | 8 | 0.626728 | 67 | 26.25 | 8 | /// <summary>
/// Event wrapper for Buttplug DeviceAdded or DeviceRemoved messages. Used when the server
/// informs the client of a device connecting or disconnecting.
/// </summary> | class |
boolean validatePanel() {
if (manualRadioButton.isSelected()) {
return manualImageDirPath != null && manualImageDirPath.toFile().exists();
} else if (imageTable.getSelectedRow() != -1) {
Path path = Paths.get((String) imageTableModel.getValueAt(imageTable.convertRowIndexToModel(i... | java | 17 | 0.609342 | 138 | 46.2 | 10 | /**
* Should we enable the next button of the wizard?
*
* @return true if a proper image has been selected, false otherwise
*/ | function |
static bool s10_free_buffers(struct fpga_manager *mgr)
{
struct s10_priv *priv = mgr->priv;
uint num_free = 0;
uint i;
for (i = 0; i < NUM_SVC_BUFS; i++) {
if (!priv->svc_bufs[i].buf) {
num_free++;
continue;
}
if (!test_and_set_bit_lock(SVC_BUF_LOCK,
&priv->svc_bufs[i].lock)) {
stratix10_svc_... | c | 14 | 0.585837 | 54 | 22.35 | 20 | /*
* Free buffers allocated from the service layer's pool that are not in use.
* Return true when all buffers are freed.
*/ | function |
public String generateUsername(String regName) {
if (regName.equals("{PLATFORM}")) {
return JiveGlobals.getProperty("plugin.gateway.facebook.platform.apikey")+"|"+JiveGlobals.getProperty("plugin.gateway.facebook.platform.apisecret");
}
else if (regName.indexOf("@") > -1) {
... | java | 14 | 0.515707 | 160 | 35.428571 | 21 | /**
* Returns a username based off of a registered name (possible JID) passed in.
*
* If it already looks like a username, returns what was passed in.
*
* @param regName Registered name to turn into a username.
* @return Converted registered name.
*/ | function |
lstm* reset_lstm(lstm* f){
if(f == NULL)
return NULL;
int i,j,k;
for(i = 0; i < 4; i++){
for(j = 0; j < f->output_size*f->input_size; j++){
if(exists_d_params_lstm(f)){
f->d_w[i][j] = 0;
}
}
for(j = 0; j < f->output_size*f->output_size;... | c | 15 | 0.391763 | 127 | 33.947368 | 57 | /* this function reset all the arrays of a lstm layer
* used during the feed forward and backpropagation
* You have a lstm* f structure, this function resets all the arrays used
* for the feed forward and back propagation with partial derivatives D inculded
* but the weights and D1 and D2 don't change
*
*
* In... | function |
def create_card_with_note(self, note):
url = self._build_url("projects", "columns", str(self.id), "cards")
json = None
if note:
json = self._json(
self._post(
url, data={"note": note}, headers=Project.CUSTOM_HEADERS
),
... | python | 15 | 0.479899 | 76 | 35.272727 | 11 | Create a note card in this project column.
:param str note:
(required), the note content
:returns:
the created card
:rtype:
:class:`~github3.projects.ProjectCard`
| function |
public class SwingFormComponentListener implements ComponentListener {
private JPanel panel = null;
private static final String J_FILE_CHOOSER = "JFileChooser";
private final Map<String,SwingField> field_map;
private final AppContext conn;
private final Logger log;
public SwingFormComponentListener(A... | java | 16 | 0.666219 | 82 | 26.82243 | 214 | /** class to map {@link Field}s to {@link SwingField}s and handle events.
* This also performs the default mapping of Forms to panels.
* @author spb
*
*/ | class |
def update_memory(self, dataset, t, batch_size):
dataloader = DataLoader(dataset, batch_size=batch_size)
tot = 0
for mbatch in dataloader:
x, y, tid = mbatch[0], mbatch[1], mbatch[-1]
if tot + x.size(0) <= self.patterns_per_experience:
if t not in self.mem... | python | 18 | 0.406111 | 78 | 51.4 | 30 |
Update replay memory with patterns from current experience.
| function |
class RingBuffer {
private byte[][] buffers;
private int unit;
private int count;
private long capacity;
/**
* Index number of the next position to be read (index number starts from 0)
* */
private volatile long readPos;
/**
* The index number of ... | java | 15 | 0.558054 | 93 | 29.287234 | 188 | /**
* 1. Both write and read allow concurrent operations
* 2. Both sliceasreadonly and read allow concurrent operations
* 3. Both sliceasreadonly and write do not allow concurrent operations
* 4. Write or read operations are not allowed during truncate, reset and release operations
*
* */ | class |
func (ccs *crChains) makeChainForNewOp(targetPtr data.BlockPointer, newOp op) error {
switch realOp := newOp.(type) {
case *createOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *rmOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *renameOp:
co, err ... | go | 13 | 0.714545 | 85 | 30.457143 | 35 | // makeChainForNewOp makes a new chain for an op that does not yet
// have its pointers initialized. It does so by setting Unref and Ref
// to be the same for the duration of this function, and calling the
// usual makeChainForOp method. This function is not goroutine-safe
// with respect to newOp. Also note that re... | function |
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public static bool RemoveAllACE(string dc,
string distinguishedname,
string username,
... | c# | 15 | 0.53966 | 120 | 44.580645 | 31 | /// <summary>
/// Removes all ACE rights for the ntSecurityDescriptor for specified user.
/// </summary>
/// <param name="distinguishedname">specifies dn</param>
/// <param name="username">user name</param>
/// <param name="password">password</param>
/// <returns></returns> | function |
protected long allocateSecondary(long size){
secondaryLock.readLock().lock();
try {
while(true){
final long out = secondaryWritePos.get();
final long newSecondaryPos = out + size;
if(newSecondaryPos >= secondaryMapper.size()){
break;
} else {
if(secondaryWritePos.compareAndSet(out, newS... | java | 13 | 0.675599 | 74 | 26.307692 | 26 | /**Allocates the given amount of space in secondary storage, and returns a
* pointer to it. Expands secondary storage if necessary.*/ | function |
ecma_string_t *
ecma_stringbuilder_finalize (ecma_stringbuilder_t *builder_p)
{
ecma_stringbuilder_header_t *header_p = builder_p->header_p;
JERRY_ASSERT (header_p != NULL);
const lit_utf8_size_t string_size = ECMA_STRINGBUILDER_STRING_SIZE (header_p);
lit_utf8_byte_t *string_begin_p = ECMA_STRINGBUILDER_STRIN... | c | 12 | 0.686738 | 115 | 43.596491 | 57 | /**
* Finalize a string builder, returning the created string, and releasing the underlying buffer.
*
* Note:
* The builder should no longer be used.
*
* @return the created string
*/ | function |
public bool LosslessCompress(Stream stream)
{
ImageOptimizerHelper.CheckStream(stream);
bool isCompressed = false;
long startPosition = stream.Position;
using (var images = new MagickImageCollection(stream))
{
if (images.Count == 1)
... | c# | 15 | 0.559687 | 88 | 38.384615 | 13 | /// <summary>
/// Performs lossless compression on the specified stream. If the new stream size is not smaller
/// the stream won't be overwritten.
/// </summary>
/// <param name="stream">The stream of the gif image to compress.</param>
/// <returns>True when the image could be compressed otherwise false.</returns> | function |
public class RunningTextRunnable implements Runnable
{
private static final String TAG = RunningTextRunnable.class.getSimpleName();
private static final int MAX_CHARS_PER_CYCLE = 4;
private IRunningTextContext context;
private String text;
private int beginIndex = 0;
private boolean isFirstRun ... | java | 12 | 0.592593 | 86 | 27.242424 | 66 | /**
* Running text Runnable that prepares the given text to be
* more segment display friendly.
*
* Original inspiration:
* - Author: JS Koran (https://github.com/jdkoren)
* - Gist: https://gist.github.com/jdkoren/a3c37883f839c0b3adcee43821128329
*/ | class |
def gmass(x=None, y=None, z=None, dx=None, dy=None, dz=None, model=None, ppar=None, **kwargs):
ncell = x.shape[0]
rho = np.zeros([ncell, kwargs['nsample']], dtype=np.float64)
for isample in range(int(kwargs['nsample'])):
xoffset = (np.random.random_sample(ncell) - 0.5) * dx * 4.0
yoffset = (... | python | 14 | 0.596394 | 95 | 50.571429 | 14 |
Example function to be used as decision function for resolving cells in tree building. It calculates the gas density
at a random sample of coordinates within a given cell than take the ratio of the max/min density. If it is larger
than a certain threshold value it will return True (i.e. the cell should be ... | function |
public static String toCSSBackgroundProperty(String dataUrl, Repetition repetition) {
if (dataUrl != null && dataUrl.trim().length() > 0) {
String repetitionToApply = Key.isValid(repetition) ? repetition.value() : Constants.EMPTY_STRING;
return applyTemplate(PATTERN_TEMPLATE, dataUrl, repetitionToApply);
}
... | java | 10 | 0.756374 | 100 | 49.571429 | 7 | /**
* Returns a URL CSS property for the data URL for the current content of the canvas element.
*
* @param dataUrl the data URL for the current content of the canvas element
* @param repetition repetition of image
* @return a URL CSS property for the current content of the canvas element
*/ | function |
def _lock(self):
lock_failure_response = 'false'
key_success_status_code = 200
endpoint = self._endpoint(self._kv_endpoints['kv'], self._lock_key)
params = {'acquire': self._session_id}
acquire_response = requests.put(endpoint, params=params,
data=self._lock_valu... | python | 13 | 0.60509 | 77 | 49.571429 | 21 |
At this point we should have a session and heartbeating working so we can
acquire a key to act as the lock for the session. If we fail to acquire the key
then throw an exception.
| function |
def matchTransforms(self, obj, position=True, rotation=True, scale=True):
if position:
self._nativePointer.Kinematics.Global.Parameters('posx').Value = obj.nativePointer().Kinematics.Global.Parameters('posx').Value
self._nativePointer.Kinematics.Global.Parameters('posy').Value = obj.nativePointer().Kinematics.G... | python | 14 | 0.777037 | 130 | 83.4375 | 16 |
Currently the auto-key support is a bit lite, but it should cover most of the cases.
| function |
def asarray(val, dtype=None):
if dtype:
dtype = utils.to_tf_type(dtype)
if isinstance(val, arrays.ndarray) and (
not dtype or utils.to_numpy_type(dtype) == val.dtype):
return val
return array(val, dtype, copy=False) | python | 10 | 0.676596 | 60 | 32.714286 | 7 | Return ndarray with contents of `val`.
Args:
val: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
dtype: Optional, defaults to dtype of the `val`. The type of the
resulting ndarray. Could be a python type, a NumPy type or a T... | function |
def _get_tlrd_pages(self, uri):
def count(data):
pages = 0
platforms = 0
translations = 0
for translation in data:
translations = translations + 1
for platform in data[translation]:
platforms = platforms + 1
... | python | 22 | 0.474992 | 84 | 40.333333 | 75 | Get all ``tldr pages``.
Read all tldr pages from the given URI. The pages are returned in a
dictionary that contains keys for translations and tldr platforms.
The tldr pages are in a list of full GitHub raw URLs under each
platform.
Args:
uri (str): URI where the tl... | function |
class MessageProvider {
constructor() {
this.messages = [];
}
/**
* info - this method flags the current message to be presented as an
* informational message in the UI.
* For more information, see:
* https://developer.gtnexus.com/platform/scripts/built-in-... | javascript | 14 | 0.529177 | 101 | 23.54902 | 51 | /**
* The MessageProvider allows scripting to display informational or error
* messages on the user interface to end users.
*
* For more information, see:
* https://developer.gtnexus.com/platform/scripts/built-in-functions/error-messages-to-ui
*/ | class |
def __gen_load(self, load):
concurrency = load.concurrency if load.concurrency is not None else 1
load_elem = etree.Element("load")
if load.duration:
duration, unit = self.__time_to_tsung_time(int(round(load.duration)))
load_elem.set('duration', str(duration))
... | python | 14 | 0.532274 | 87 | 44.818182 | 22 |
Generate Tsung load profile.
Tsung load progression is scenario-based. Virtual users are erlang processes which are spawned according to
load profile. Each user executes assigned session (requests + think-time + logic) and then dies.
:param scenario:
:param load:
:retur... | function |
public bool TryRequestAdditionalTime(int minutes)
{
Log.Debug($"AlgorithmTimeLimitManager.TryRequestAdditionalTime({minutes}): Requesting additional time. Available: {AdditionalTimeBucket.AvailableTokens}");
if (AdditionalTimeBucket.TryConsume(minutes))
{
var ... | c# | 13 | 0.648649 | 167 | 52.909091 | 11 | /// <summary>
/// Attempts to requests additional time to continue executing the current time step.
/// At time of writing, this is intended to be used to provide training scheduled events
/// additional time to allow complex training models time to execute while also preventing
/// abuse by enforcing certain control p... | function |
def load(path: Union[pathlib.Path, str] = None, text: str = None) -> Dict[str, Dict[str, Union[bytes, int, str]]]:
if not path and not text:
raise exceptions.FRUException('*path* or *text* must be specified')
data = {
'common': shared.get_default_common_section(),
'board': shared.get_def... | python | 17 | 0.564033 | 114 | 42.835821 | 67 | Load a TOML file and return its data as a dictionary.
If *path* is specified it must be a TOML-formatted file.
If *text* is specified it must be a TOML-formatted string.
| function |
func (d *DockerOps) StartSMBServer(volName string) (int, string, bool) {
var service swarm.ServiceSpec
var options dockerTypes.ServiceCreateOptions
service.Name = serviceNamePrefix + volName
service.TaskTemplate.ContainerSpec.Image = sambaImageName
containerArgs := []string{"-s",
FileShareName + ";/mount;yes;no;... | go | 14 | 0.735263 | 88 | 32.946429 | 56 | // StartSMBServer - Start SMB server
// Input - Name of the volume for which SMB has to be started
// Output
// int: The overlay network port number on which the
// newly created SMB server listens. This port
// is opened on every host VM in the swarm.
// string: Name of the S... | function |
def validateMetaDataService(smallKey, workspace, metaDataUrl, logs, geocatUrl, geocatUsername, geocatPassword):
isValid =True
jsonPath = os.path.join(workspace, smallKey + '.json')
jsonData = open(jsonPath)
jsonObj = json.load(jsonData)
jsonData.close()
uuid = jsonObj['config']['UUID']
metaD... | python | 17 | 0.657512 | 111 | 50.625 | 24 | Validate meta data setvice in the Data Catalogue
Args:
smallKey: ID of shapefile.
workspace: Folder in which data is unzipped to.
metaDataUrl:Malformed metadata url
logs: log list holds all log items for current publication
geocatUrl: The URL to the Data Catalogue
ge... | function |
Configuration toConfigurationNode(
ConvertedConfiguration awsConfiguration, Region region, Warnings warnings) {
Configuration cfgNode =
Utils.newAwsConfiguration(
nodeName(_subnetId), "aws", _tags, DeviceModel.AWS_SUBNET_PRIVATE);
cfgNode.getVendorFamily().getAws().setVpcId(_vpcId);
... | java | 17 | 0.576833 | 99 | 43.068966 | 87 | /**
* Returns the {@link Configuration} node for this subnet.
*
* <p>We also do the work needed to connect to the VPC router here: Add an interface on the VPC
* router and create the necessary static routes.
*/ | function |
[DllImport(api_ms_win_service_management_l2_1_0, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeServiceConfig(
SafeServiceHandle hService,
ServiceType dwServiceType,
ServiceStartType dwStartType... | c# | 8 | 0.642623 | 97 | 42.642857 | 14 | /// <summary>
/// Changes the configuration parameters of a service.
/// To change the optional configuration parameters, use the <see cref="ChangeServiceConfig2(SafeServiceHandle, ServiceInfoLevel, void*)"/> function.
/// </summary>
/// <param name="hService">
/// A handle to the service.
/// This handle is returned b... | function |
CSGObject*
ListOfCSGObjects::createCsgObject()
{
CSGObject* csgo = NULL;
try
{
SPATIAL_CREATE_NS(spatialns, getSBMLNamespaces());
csgo = new CSGObject(spatialns);
delete spatialns;
}
catch (...)
{
}
if(csgo != NULL)
{
appendAndOwn(csgo);
}
return csgo;
} | c++ | 10 | 0.62116 | 54 | 14.473684 | 19 | /**
* Creates a new CSGObject object, adds it to this ListOfCSGObjects
* CSGObject and returns the CSGObject object created.
*
* @return a new CSGObject object instance
*
* @see addCSGObject(const CSGObject* csgo)
*/ | function |
public sealed class UnicastIPAddressInformation : IPAddressInformation
{
private IP_ADAPTER_UNICAST_ADDRESS iaua;
internal UnicastIPAddressInformation(IP_ADAPTER_UNICAST_ADDRESS unicastAddress)
{
this.iaua = unicastAddress;
address = GetAddressFromSocketAddress(iaua.A... | c# | 12 | 0.507576 | 87 | 26.415094 | 53 | /// <summary>
/// Provides information about a network interface's unicast address.
/// </summary> | class |
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Token = new Property(1, String.class, "token", false, "TOKEN");
public final static Property Firstname = new Property(2, String.class, "firstname", fals... | java | 8 | 0.69808 | 131 | 94.583333 | 12 | /**
* Properties of entity DbUser.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/ | class |
private Command prepareChange(String args) {
String[] argComponents= args.trim().split(DELIMITER_BLANK_SPACE);
if(argComponents[CHANGE_LOCATION].equals("location") && argComponents[CHANGE_LOCATION_TO].equals("to")){
return new ChangeCommand(argComponents[CHANGE_LOCATION_TO_PATH]);
} ... | java | 11 | 0.688453 | 116 | 56.5 | 8 | /**
* Parses arguments in the context of the change data file location command.
*
* @param args
* full command args string
* @return the prepared command
*/ | function |
int webots_physics_collide(dGeomID g1, dGeomID g2) {
dContact contact[10];
dVector3 start, d;
int i, n, ray_color;
if (dAreGeomsSame(g1, ray_geom) || dAreGeomsSame(g2, ray_geom)) {
if ((dAreGeomsSame(g2, ray_geom) && (dSpaceQuery((dSpaceID)robot_geom, g1) == 1 || dGeomIsSpace(g1))) ||
(dAreGeomsSame... | c | 18 | 0.606202 | 118 | 41.053571 | 56 | /*
* This function is called every time a collision is detected between two
* Geoms. It allows you to handle the collisions as you want.
* Here you can either simply detect collisions for informations, disable
* useless collisions or handle them.
* This function is called various times for each time step.
* For a... | function |
def sample_teacher_forcing(self, inp):
batch_size, _ = inp.size()
hidden = self.init_hidden(batch_size)
pred = self.forward(inp, hidden)
samples = torch.argmax(pred, dim=-1).view(batch_size, -1)
log_prob = F.nll_loss(pred, samples.view(-1), reduction='none').view(batch_size, -1)
... | python | 12 | 0.616477 | 92 | 49.428571 | 7 |
Generating samples from the real data via teacher forcing
:param inp: batch_size * seq_len
:param target: batch_size * seq_len
:return
samples: batch_size * seq_len
log_prob: batch_size * seq_len (log probabilities)
| function |
def train_model(train_data, dev_data, model, gen, args):
if args.cuda:
model = model.cuda()
gen = gen.cuda()
args.lr = args.init_lr
optimizer = utils.get_optimizer([model, gen], args)
num_epoch_sans_improvement = 0
epoch_stats = metrics.init_metrics_dictionary(modes=['train', 'dev'])... | python | 18 | 0.535625 | 113 | 40.038462 | 78 |
Train model and tune on dev set. If model doesn't improve dev performance within args.patience
epochs, then halve the learning rate, restore the model to best and continue training.
At the end of training, the function will restore the model to best dev version.
returns epoch_stats: a dictionary of e... | function |
AzFramework::PhysicsComponentNotifications::Collision StarterGameUtility::CreatePseudoCollisionEvent(const AZ::EntityId& entity, const AZ::Vector3& position, const AZ::Vector3& normal, const AZ::Vector3& direction)
{
AzFramework::PhysicsComponentNotifications::Collision coll;
coll.m_entity = entity;... | c++ | 7 | 0.715164 | 214 | 53.333333 | 9 | // This function was created because I couldn't populate the 'Collision' struct in Lua. | function |
def count_frequencies(file) -> dict:
dictionary = {}
for line in file:
for char in line:
if char not in dictionary:
dictionary[char] = 1
else:
dictionary[char] = dictionary[char] + 1
return dictionary | python | 14 | 0.536232 | 55 | 29.777778 | 9 |
This function opens a text file as an argument and then returns the
frequencies each character occurs in the text file. The characters
are then sorted out by order starting from the lowest frequency to
the highest. Values sorted by ascending order.
| function |
public class AMF3StringProtocol extends AbstractNettyProtocol
{
/**
* The maximum size of the incoming message in bytes. The
* {@link DelimiterBasedFrameDecoder} will use this value in order to throw
* a {@link TooLongFrameException}.
*/
int maxFrameSize;
/**
* The flash client would encode the AMF3 bytes ... | java | 12 | 0.761189 | 79 | 25.859649 | 114 | /**
* This protocol defines AMF3 that is base 64 and String encoded sent over the
* wire. Used by XMLSocket flash clients to send AMF3 data.
*
* @author Abraham Menacherry
*
*/ | class |
public String invoke(List<String> formInputNames, List<String> formInputValues) throws IOException {
StringBuilder query = new StringBuilder("");
for(int i=0; i<formInputNames.size(); i++) {
query.append(formInputNames.get(i));
String value = formInputValues.get(i);
if(!StringUtils.isEmpty(value)) {
qu... | java | 14 | 0.644197 | 100 | 36.894737 | 38 | /**
* It invokes the web page with the form attributes and values that are passed to the function,
* and then returns the resulting page that is returned by the web server
* @param formInputNames - The names of the form attributes to send to the server
* @param formInputValues - Values of the correspondin... | function |
def generate_answers(self, levers):
question_set = self.test_set['data']
k_retrieve = levers['k_retrieve']
k_read = levers['k_read']
answer_set = []
elapsed_times = []
for qa in question_set:
question = qa['question']
ground_truth = qa['answer']
... | python | 14 | 0.576417 | 124 | 48.942857 | 35 |
Given a set of questions and answers, this method runs through each, returning
a predicted answer from Haystack Finder's get_answers method
Each prediction is then scored using evaluate_answers, and the results
are stored and then returned in the answer_set list of dictionaries
... | function |
private void processIter(DetailAST root, AstState astState) {
DetailAST curNode = root;
while (curNode != null) {
notifyVisit(curNode, astState);
DetailAST toVisit = curNode.getFirstChild();
while (curNode != null && toVisit == null) {
notifyLeave(curN... | java | 13 | 0.503597 | 61 | 36.133333 | 15 | /**
* Processes a node calling interested checks at each node.
* Uses iterative algorithm.
* @param root the root of tree for process
* @param astState state of AST.
*/ | function |
public class MainScene {
private JPanel JPanel;
//Init main screen label
JLabel Action_with_requirements = new JLabel("Action_with_requirement {E} / {$}") ;
JLabel Action_Set_Rqrm;
JLabel Action_no_requirement;
JLabel Action_Set_Free;
JLabel Main_Scene_wallpaper = new JLabel("");
final JToggleButton tglbt... | java | 19 | 0.69197 | 127 | 39.880342 | 117 | /**
* Main Scene Class is implemented as a View class (Project is trying to approach to Model-view-controller design pattern)
* This class implemented to display content to the user
* Contain all label and a toggle button in MainScene for displaying certain Info
* @author Edward Wong - University of Canterbury SEN... | class |
private void DisplayAutomaticInspectorGUI()
{
EditorGUILayout.Separator();
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.MiddleCenter;
style.fontStyle = FontStyle.Bold;
EditorGUILayout.Foldout(true, "Automatic " + target.GetType().ToString() + " Properties", s... | c# | 14 | 0.658402 | 105 | 39.444444 | 9 | /// <summary>
/// This displays the automatic inspector gui. Call this if you have public members
/// you wish to edit automatically without manually setting up your inspector gui.
/// </summary> | function |
static void ConnCompAndRectangularize(Image pix, DebugPixa *pixa_debug, Boxa **boxa,
Pixa **pixa) {
*boxa = nullptr;
*pixa = nullptr;
if (textord_tabfind_show_images && pixa_debug != nullptr) {
pixa_debug->AddPix(pix, "Conncompimage");
}
*boxa = pixConnComp(pix, pixa,... | c++ | 12 | 0.591716 | 94 | 40 | 33 | // Generates a Boxa, Pixa pair from the input binary (image mask) pix,
// analogous to pixConnComp, except that connected components which are nearly
// rectangular are replaced with solid rectangles.
// The returned boxa, pixa may be nullptr, meaning no images found.
// If not nullptr, they must be destroyed by the ca... | function |
int AppReadTimeSeriesFile(
REAL8 ***recs,
size_t *nrSteps,
size_t *nrCols,
BOOL *geoeas,
const char *inputFile,
const char *mv,
CSF_VS vs,
CSF_CR cr,
int sepChar)
{
size_t i,c,lineDelta;
size_t nrRecordsRead,nrMVv... | c | 20 | 0.491071 | 73 | 24.861538 | 65 | /* Read a timeseries file.
* Errors are printed to ErrorNested, the name of the input file is not
* printed on Error.
* Returns 1 in case of error, 0 otherwise.
*/ | function |
private void searchForLanguageConstants(
GoogleAdsClient googleAdsClient, long customerId, String languageName) {
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
String searchQuery =
"SELECT language_constant.id,... | java | 15 | 0.620875 | 92 | 44.030303 | 33 | /**
* Searches for language constants where the name includes the specified language name.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param languageName the string to use for searching for language constants.
*/ | function |
def login(host, protocol="https", port=443, **kwargs):
base_url = "{protocol}://{host}:{port}"\
.format(protocol=protocol,
host=host,
port=int(port))
conn = requests.Session()
if "username" and "password" in kwargs:
conn.auth = (kwargs[... | python | 10 | 0.561459 | 60 | 35.057143 | 35 | Login to the rest http plugin
Args:
host (str): rest http host
protocol (Optional[str]): rest http protocol
port (Optional[int]): rest http port
Kwargs:
token (str): rest http token
username (str): rest http username
password (str): rest http password
c... | function |
def validate_file(filename):
with open(filename, 'r') as infp:
try:
data = read_yaml(infp)
except Exception as e:
click.secho('%s: could not parse YAML: %s' % (filename, e), fg='red', bold=True)
return 1
validator = get_validator()
errors = sorted(
... | python | 16 | 0.560703 | 92 | 38.15625 | 32 |
Validate `filename`, print its errors, and return the number of errors.
:param filename: YAML filename
:type filename: str
:return: Number of errors
:rtype: int
| function |
private void initTile(int tileNum) throws IOException {
if(tilePartPositions == null) in.seek(lastPos);
String strInfo = "";
int ncbQuit = -1;
boolean isTilePartRead = false;
boolean isEOFEncountered = false;
try {
int tpNum = 0;
while(remainingTil... | java | 21 | 0.433004 | 84 | 41.918605 | 172 | /**
* Read all tile-part headers of the requested tile. All tile-part
* headers prior to the last tile-part header of the current tile will
* also be read.
*
* @param tileNum The index of the tile for which to read tile-part
* headers.
*/ | function |
func (in *ReportDataSourceSpec) DeepCopy() *ReportDataSourceSpec {
if in == nil {
return nil
}
out := new(ReportDataSourceSpec)
in.DeepCopyInto(out)
return out
} | go | 7 | 0.72619 | 66 | 20.125 | 8 | // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReportDataSourceSpec. | function |
public Object
update
(
PluginUpdateReq req
)
{
TaskTimer timer = new TaskTimer();
timer.acquire();
pPluginLock.acquireReadLock();
try {
timer.resume();
Long cycleID = req.getCycleID();
TripleMap<String, String, VersionID, Object[]> builders =
pBuilderCollection.c... | java | 16 | 0.601767 | 93 | 43.955882 | 68 | /**
* Get any new or updated plugin classes.
*
* @param req
* The request.
*
* @return
* <CODE>PluginUpdateRsp</CODE> if successful or
* <CODE>FailureRsp</CODE> if unable to get the updated plugins.
*/ | function |
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool CompareExchange(ref double location1, double value, ref double comparand)
{
var comparandLocal = comparand;
comparand = Interlocked.CompareExchange(ref location1, value, comparandLocal);
return comp... | c# | 9 | 0.696379 | 100 | 50.428571 | 7 | /// <summary>
/// Compares two double-precision floating point numbers for equality and, if they are equal, replaces the first
/// value.
/// </summary>
/// <param name="location1">
/// The destination, whose value is compared with <paramref name="comparand" /> and possibly
/// replaced.
/// </param>
//... | function |
function _updateButtonState() {
if (this.voice.followed) {
this.dom.updateHTML(this.el, this.constructor.FOLLOWING_TEXT);
} else {
this.dom.updateHTML(this.el, this.constructor.FOLLOW_TEXT);
}
return this;
} | javascript | 11 | 0.532203 | 78 | 36 | 8 | /* Updates the button's text based on if currentPerson is following the
* current voice.
* @method _updateButtonState <private> [Function]
* @return VoiceFollowButton
*/ | function |
pub fn parse(&self) -> Result<String, Error> {
match self {
Self::Text(contents) | Self::Html(contents) => Ok(contents.to_string()),
Self::Mjml(mjml) => {
let parsed = mrml::parse(mjml).map_err(|e| Error::Markup {
source: anyhow::Error::msg(e.to_string... | rust | 20 | 0.414395 | 84 | 42.714286 | 21 | /// Parse the markup into a string. Some types of markup need to parsed
/// (MJML), while others can directly return their contents (Text). | function |
static void
mcp5x_set_intr(nv_port_t *nvp, int flag)
{
nv_ctl_t *nvc = nvp->nvp_ctlp;
ddi_acc_handle_t bar5_hdl = nvc->nvc_bar_hdl[5];
uint16_t intr_bits =
MCP5X_INT_ADD|MCP5X_INT_REM|MCP5X_INT_COMPLETE;
uint16_t int_en;
if (flag & NV_INTR_DISABLE_NON_BLOCKING) {
int_en = nv_get16(bar5_hdl, nvp->nvp_mcp5x_i... | c | 10 | 0.643333 | 70 | 32.361111 | 36 | /*
* enable or disable the 3 interrupts the driver is interested in:
* completion interrupt, hot add, and hot remove interrupt.
*/ | function |
public static void writePlistFile(Map<String, Object> eoModelMap, String eomodeldFullPath, String filename, boolean useXml) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter plistWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(eomodeldFullP... | java | 15 | 0.667035 | 184 | 68.615385 | 13 | /**
* Writes model information in the Apple EOModelBundle format.
*
* For document structure and definition see: http://developer.apple.com/documentation/InternetWeb/Reference/WO_BundleReference/Articles/EOModelBundle.html
*
* @param eoModelMap
* @param eomodeldFullPath
* @param filen... | function |
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
{
components.Dispose();
}
if (this.fSy... | c# | 12 | 0.549912 | 114 | 37.133333 | 15 | /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> | function |
def capture_time_domain(self, rfe_mode, freq, rbw, device_settings=None,
min_points=128):
prop = self.real_device.properties
self.configure_device(dict(
freq=freq,
rfe_mode=rfe_mode,
**(device_settings if device_settings else {})))
if self._config... | python | 12 | 0.590454 | 72 | 42.333333 | 30 |
Initiate a capture of raw time domain IQ or I-only data
:param rfe_mode: radio front end mode, e.g. 'ZIF', 'SH', ...
:param freq: center frequency
:param rbw: requested RBW in Hz (output RBW may be smaller than
requested)
:type rbw: float
:param devi... | function |
inline
itk::TransformBase::Pointer
readTransformBase( std::string fileName )
{
typedef itk::TransformFileReader TransformReaderType;
typedef TransformReaderType::TransformListType TransformListType;
TransformReaderType::Pointer reader = TransformReaderType::New();
reader->SetFileName( ... | c++ | 10 | 0.666667 | 92 | 35.173913 | 23 | /**
* Reads a transform from a text file and returns a TransformBase::Pointer object.
* @param fileName path to the input transformation file
* @return transformation read as TransformBase::Pointer object
*/ | function |
def lookUpForSolver(self):
if self.solver == None or self.solver == '*' or self.solver == 'symbolicsys':
return self._symbolicSysSolveMechanism
elif self.solver == 'sympy':
return self._sympySolveMechanism
else:
raise AbsentRequiredObjectError("element from {}... | python | 11 | 0.642857 | 104 | 51.142857 | 7 |
Define the solver mechanism used for solution of the problem, given the name of desired mechanism in the instantiation of current Solver object
Uses the mechanism provided by the pyneqsys package
| function |
def csr_sum_indices(csr_matrices):
if len(csr_matrices) == 0: return [], _np.empty(0, int), _np.empty(0, int), 0
N = csr_matrices[0].shape[0]
for mx in csr_matrices:
assert(mx.shape == (N, N)), "Matrices must have the same square shape!"
indptr = [0]
indices = []
csr_sum_array = [list() ... | python | 16 | 0.5625 | 81 | 42.681818 | 22 |
Precomputes the indices needed to sum a set of CSR sparse matrices.
Computes the index-arrays needed for use in :method:`csr_sum`,
along with the index pointer and column-indices arrays for constructing
a "template" CSR matrix to be the destination of `csr_sum`.
Parameters
----------
csr_... | function |
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
domainLNEClass = createEClass(DOMAIN_LN);
createEReference(domainLNEClass, DOMAIN_LN__MODE);
createEReference(domainLNEClass, DOMAIN_LN__BEHAVIOUR);
createEReference(domainLNEClass, DOMAIN_LN__HEALTH);
createEReference(domainLN... | java | 7 | 0.775568 | 57 | 38.222222 | 9 | /**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | function |
protected Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = new Jackson2ObjectMapperBuilder();
jackson2ObjectMapperBuilder.indentOutput(true);
/*
* Install the custom Jackson module that supports serializing and de-serializing ISO 8601... | java | 8 | 0.794212 | 99 | 55.636364 | 11 | /**
* Returns the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON
* processor package.
*
* @return the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON
* processor package
*/ | function |
public virtual void ClearMap()
{
if (HasQuit && (Application.isPlaying || !mapsService.MapPreviewOptions.Enable))
{
return;
}
if (mapsService.GameObjectManager != null)
{
mapsService.GameObjectManager.DestroyAll();
... | c# | 11 | 0.489407 | 92 | 30.533333 | 15 | /// <summary>
/// Notifies the sdk that we are destroying geometry so that it can be reloaded from the apis
/// correctly.
/// This function also destroy the <see cref="GameObject"/>s in the scene.
/// The MapsService keeps an internal cache of <see cref="GameObject"/>s, and their
/// relationships to MapFeatures. When... | function |
class rESOURCEpOOL {
constructor({name, size, available, resourceType, resources}) {
this.name = name;
if (Number.isInteger( size) || size === Infinity) { // a count pool
this.size = size;
if (!Number.isInteger( available)) this.available = size;
else this.available = available;
} else ... | javascript | 20 | 0.607204 | 109 | 35.664063 | 128 | /****************************************************************************
A resource pool can take one of two forms:
(1) a count pool abstracts away from individual resources and just maintains
an "available" counter of the available resources of some type
(2) an individual pool is a collection of individual re... | class |
public class SOAPAttachmentHandler implements XMLAttachmentMarshaller {
private int count = 0;
private HashMap<String, DataHandler> attachments = new HashMap<String,DataHandler>();
public boolean hasAttachments() {
return attachments.size() > 0;
}
public Map<String, DataHandler> getAttach... | java | 12 | 0.644112 | 93 | 31.041667 | 48 | /**
* <p><b>INTERNAL</b>: implementation of EclipseLink {@link XMLAttachmentMarshaller} implementation
* handles binary attachments
*
* @author Mike Norman - michael.norman@oracle.com
* @since EclipseLink 1.x
*/ | class |
int Aggregator_distinct::composite_key_cmp(void* arg, uchar* key1, uchar* key2)
{
Aggregator_distinct *aggr= (Aggregator_distinct *) arg;
Field **field = aggr->table->field;
Field **field_end= field + aggr->table->s->fields;
uint32 *lengths=aggr->field_lengths;
for (; field < field_end; ++field)
{
Fi... | c++ | 9 | 0.60334 | 79 | 25.666667 | 18 | /**
Correctly compare composite keys.
Used by the Unique class to compare keys. Will do correct comparisons
for composite keys with various field types.
@param arg Pointer to the relevant Aggregator_distinct instance
@param key1 left key image
@param key2 right key image
@return compar... | function |
class CaptionBubbleLabel : public views::Label {
public:
METADATA_HEADER(CaptionBubbleLabel);
#if defined(NEED_FOCUS_FOR_ACCESSIBILITY)
CaptionBubbleLabel() {
ax_mode_observer_ =
std::make_unique<CaptionBubbleLabelAXModeObserver>(this);
SetFocusBehaviorForAccessibility();
}
#else
CaptionBubbleL... | c++ | 15 | 0.678104 | 77 | 39.952381 | 84 | // CaptionBubble implementation of Label. This class takes care of setting up
// the accessible virtual views of the label in order to support braille
// accessibility. The CaptionBubbleLabel is a readonly document with a paragraph
// inside. Inside the paragraph are staticText nodes, one for each visual line
// in the... | class |
public abstract class BsWhiteOnlyOneToOneFrom extends AbstractEntity implements DomainEntity {
// ===================================================================================
// Definition
// ... | java | 14 | 0.449967 | 149 | 42.394118 | 170 | /**
* The entity of WHITE_ONLY_ONE_TO_ONE_FROM as TABLE. <br>
* <pre>
* [primary-key]
* FROM_ID
*
* [column]
* FROM_ID, FROM_NAME
*
* [sequence]
*
*
* [identity]
* FROM_ID
*
* [version-no]
*
*
* [foreign table]
* WHITE_ONLY_ONE_TO_ONE_TO(AsOne)
*
* [re... | class |
public void SetBaseline(IGridView<T> baseline)
{
if (baseline.Width != BaseGrid.Width || baseline.Height != BaseGrid.Height)
throw new ArgumentException(
$"Baseline grid view's width/height must be same as {nameof(BaseGrid)}.",
nameof(baseline)... | c# | 14 | 0.587121 | 114 | 51.9 | 10 | /// <summary>
/// Sets the baseline values (eg. values before any diffs are recorded) to the values from the given grid view.
/// Only valid to do before any diffs are recorded.
/// </summary>
/// <param name="baseline">Baseline values to use. Must have same width/height as <see cref="BaseGrid"/>.</param> | function |
static truncateToWidth(
context,
str,
width,
fontWidth = GridRenderer.DEFAULT_FONT_WIDTH
) {
if (width <= 0 || str.length <= 0) {
return '';
}
const lo = Math.min(
Math.max(0, Math.floor(width / fontWidth / 2) - 5),
str.length
);
const hi = Math.min(Math.ceil((wid... | javascript | 12 | 0.592166 | 75 | 26.1875 | 16 | /**
* Truncate a string (if necessary) to fit in the specified width.
* First uses the estimated font width to calculate a lower/upper bound
* Then uses binary search within those bounds to find the exact max length
* @param {Context} context The drawing context
* @param {string} str The string to calcul... | function |
private static CharPred allCharsExcept(Character excluded,
boolean returnPred){
if(excluded == null){
if(returnPred)
return(SlowExample.TRUE_RET);
else
return(StdCharPred.TRUE);
}
char prev = excluded; prev--;
char next = excluded; nex... | java | 12 | 0.44012 | 78 | 40.8125 | 16 | /**
* allCharsExcept() builds a CharPred predicate that accepts any character
* except for "excluded". If "excluded" is null, it returns the TRUE
* predicate.
*
* @param excluded the character to exclude
* @param returnPred whether or not we should generate a return predicate
* @return the predica... | function |
public class CustomServerPlatformAdapter extends ServerPlatformAdapter {
// property change
public final static String SERVER_CLASS_NAME_PROPERTY = "serverClassName";
public final static String EXTERNAL_TRANSACTION_CONTROLLER_CLASS_PROPERTY = "externalTransactionControllerClass";
/**
* Default constructor
... | java | 15 | 0.724046 | 129 | 25.925234 | 107 | /**
* Session Configuration model adapter class for the
* TopLink Foudation Library class CustomServerPlatformConfig
*
* @see CustomServerPlatformConfig
*
* @author Tran Le
*/ | class |
def add_artificial_noise(sci_image,var_image,model_image):
Max_SN_now=np.max(sci_image)/np.max(np.sqrt(var_image))
dif_in_SN=Max_SN_now/220
artifical_noise=np.zeros_like(model_image)
artifical_noise=np.array(artifical_noise)
min_var_value=np.min(var_image)
for i in range(len(artifical_noise)):
... | python | 16 | 0.654646 | 111 | 54.538462 | 13 |
add extra noise so that it has comparable noise as if the max flux in the image (in the single pixel) is 40000
@array[in] sci_image numpy array with the values for the cutout of the science image (20x20 cutout)
@array[in] var_image numpy array with the cutout for the cutout... | function |
def register_jvm_tool(self, key, tools, ini_section=None, ini_key=None):
if not tools:
raise ValueError("No implementations were provided for tool '%s'" % key)
self._products.require_data('jvm_build_tools_classpath_callbacks')
tool_product_map = self._products.get_data('jvm_build_tools') or {}
too... | python | 12 | 0.663812 | 96 | 57.4375 | 16 | Register a list of targets against a key.
We can later use this key to get a callback that will resolve these targets.
Note: Not reentrant. We assume that all registration is done in the main thread.
| function |
public Matrix GetDampedPseudoInverse(double lambda)
{
Matrix result = null;
Matrix transpose = Transpose();
if (NrRows >= NrCols)
{
result = (transpose * this + lambda * lambda * Matrix.Eye(NrCols)).GetInvert() * transpose;
}
... | c# | 17 | 0.493204 | 107 | 35.857143 | 14 | /// <summary>
/// The damping makes the pseudo inverse more stable in close to singular cases
/// Calling it with dambda = 0 results in a normal pseudo invers
/// </summary>
/// <param name="lambda"></param>
/// <returns></returns> | function |
public bool VerifyInput(string hashedInput, object rawData)
{
if (hashedInput == Hasher.Add0x(HashWithSalt(Parser.JsonEncode(rawData))))
{
return true;
}
return false;
} | c# | 15 | 0.526104 | 86 | 30.25 | 8 | /// <summary>
/// Takes the raw input and hashed_input, and makes a comparison.
/// </summary>
/// <param name="hashedInput"></param>
/// <param name="rawData"></param>
/// <returns>value (boolean): are they the same or not</returns> | function |
private void computeFVs(List<DTGraph<ApproxStringLabel,ApproxStringLabel>> graphs, SparseVector[] featureVectors, double weight, int lastIndex) {
int index;
for (int i = 0; i < graphs.size(); i++) {
featureVectors[i].setLastIndex(lastIndex);
for (DTNode<ApproxStringLabel,ApproxStringLabel> vertex : graphs.get... | java | 15 | 0.684268 | 145 | 44.5 | 20 | /**
* Compute feature vector for the graphs based on the label dictionary created in the previous two steps
*
* @param graphs
* @param featureVectors
* @param startLabel
* @param currentLabel
*/ | function |
static void nasmt_nl_data_ready (struct sk_buff *skb)
{
struct nlmsghdr *nlh = NULL;
#ifdef NETLINK_DEBUG
printk("nasmt_nl_data_ready - begin \n");
#endif
if (!skb) {
printk("nasmt_nl_data_ready - input parameter skb is NULL \n");
return;
}
#ifdef NETLINK_DEBUG
printk("nasmt_nl_data_ready - Received s... | c | 9 | 0.674584 | 67 | 25.375 | 16 | // This can also be implemented using thread to get the data from PDCP without blocking.
//---------------------------------------------------------------------------
// Function for transfer with PDCP (from NASLITE) | function |
int ardp_receive (int sock, char **s)
{
int n, rec, sa_len;
struct sockaddr_in source;
struct ardpdata a;
*s = NULL;
sa_len = sizeof (struct sockaddr_in);
rec = recvfrom (sock, recv_buffer, RECV_SIZE, 0, (struct sockaddr *) &source, &sa_len);
if (sa_len != sizeof (str... | c | 13 | 0.459135 | 91 | 23.019231 | 52 | /* ----------------------------------------------------------------------------
receives data from server. returns length of malloc()ed buffer (s), or -1 if error.
0 indicates that pending data were discarded and no useful input is available */ | function |
private void OnClearPane(object sender, EventArgs args)
{
if (!mefTextBuffer.EditInProgress)
{
ClearReadOnlyRegion();
SetCursorAtEndOfBuffer();
}
} | c# | 9 | 0.506494 | 55 | 28 | 8 | /// <summary>
/// Function called when the user select the "Clear Pane" menu item from the context menu.
/// This will clear the content of the console window leaving only the console cursor and
/// resizing the read-only region.
/// </summary> | function |
static void
nfsd_sanitize_attrs(struct inode *inode, struct iattr *iap)
{
#define BOTH_TIME_SET (ATTR_ATIME_SET | ATTR_MTIME_SET)
#define MAX_TOUCH_TIME_ERROR (30*60)
if ((iap->ia_valid & BOTH_TIME_SET) == BOTH_TIME_SET &&
iap->ia_mtime.tv_sec == iap->ia_atime.tv_sec) {
time_t delta = iap->ia_atime.tv_sec - get... | c | 12 | 0.588486 | 66 | 29.290323 | 31 | /*
* Go over the attributes and take care of the small differences between
* NFS semantics and what Linux expects.
*/ | function |
public class DataObjectWithMapAddersConverter {
private static final Base64.Decoder BASE64_DECODER = JsonUtil.BASE64_DECODER;
private static final Base64.Encoder BASE64_ENCODER = JsonUtil.BASE64_ENCODER;
public static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, DataObjectWithMapAdders obj... | java | 28 | 0.582733 | 151 | 44.870968 | 124 | /**
* Converter and mapper for {@link io.vertx.codegen.testmodel.DataObjectWithMapAdders}.
* NOTE: This class has been automatically generated from the {@link io.vertx.codegen.testmodel.DataObjectWithMapAdders} original class using Vert.x codegen.
*/ | class |
def parse_provinces(provinces, savegame):
provinces = split("-(\d+)=[{]", provinces)[1:]
province_id_list = provinces[::2]
province_list = provinces[1::2]
for province, x in zip(province_list, range(len(province_list))):
province_list[x] = province.split("history")[0]
province_list[x] += province.split("discove... | python | 18 | 0.650989 | 100 | 38.241379 | 58 | First part of the main parser.
Parses all province-related information.
Takes only content from start till end of province information of the savegame.
Return list of lists with all revelant stats for each province.
Each Province has its own sub-list with following information (in order):
[Province_ID, Name,... | function |
static short fsys_copy(const char * src_path, const char * dst_path) {
unsigned char buffer[256];
t_file_info file;
short fd_src = -1;
short fd_dst = -1;
short result = 0;
short n = 0;
if (strcicmp(src_path, dst_path) == 0) {
return ERR_COPY_SELF;
}
result = sys_fsys_stat(src... | c | 15 | 0.472107 | 74 | 27.619048 | 42 | /**
* Perform the actual copy of the files, given the full paths to the files
*
* @param src_path the path to the source file to be copied
* @param dst_path the path to the destination file (will be deleted if it already exists)
* @return 0 on success, a negative number on error
*/ | function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.