query stringlengths 4 15k | positive stringlengths 5 373k | source stringclasses 7
values | hard_negatives listlengths 1 1 |
|---|---|---|---|
Perform an ajax request to get comments for a node
and insert the comments into the comments tree. | function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source... | csn | [
"public function CommentsForm()\n {\n // Check if enabled\n $enabled = $this->getCommentsEnabled();\n if ($enabled && $this->owner->getCommentsOption('include_js')) {\n Requirements::javascript('//code.jquery.com/jquery-3.3.1.min.js');\n Requirements::javascript('silver... |
Perform an ajax request to get comments for a node
and insert the comments into the comments tree. | function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source... | csn | [
"public function store($content)\n {\n $comment = $this->client->post(\n sprintf('buckets/%d/recordings/%d/comments.json', $this->bucket, $this->parent),\n [\n 'json' => [\n 'content' => $content,\n ],\n ]\n );\n\n ... |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn | [
"func (m *Client) NewReader(o string) (io.ReadCloser, error) {\n\treturn m.NewReaderWithContext(context.Background(), o)\n}"
] |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn | [
"func (l *LocalStore) NewReader(o string) (io.ReadCloser, error) {\n\treturn l.NewReaderWithContext(context.Background(), o)\n}"
] |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn | [
"func WithReader(r reader.Reader) loader.Option {\n\treturn func(o *loader.Options) {\n\t\to.Reader = r\n\t}\n}"
] |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn | [
"func NewReader(r io.Reader) *Reader {\n\treturn &Reader{\n\t\tr: r,\n\t\tctx: context.Background(),\n\t}\n}"
] |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn | [
"func (vp *ValidatingPool) GetReadSeeker(fileIndex int64) (io.ReadSeeker, error) {\n\treturn vp.Pool.GetReadSeeker(fileIndex)\n}"
] |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | csn | [
"def stationary_distribution_sensitivity(T, j):\n r\"\"\"Calculate the sensitivity matrix for entry j the stationary\n distribution vector given transition matrix T.\n\n Parameters\n ----------\n T : numpy.ndarray shape = (n, n)\n Transition matrix\n j : int\n entry of stationary dis... |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | csn | [
"def _log_posterior(theta, counts, alpha, beta, n):\n \"\"\"Log of the posterior probability and gradient\n\n Parameters\n ----------\n theta : ndarray, shape=(n_params,)\n The free parameters of the reversible rate matrix\n counts : ndarray, shape=(n, n)\n The count matrix (sufficient ... |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | csn | [
"def compute_probab_ratios(p_new, p_old, actions, reward_mask):\n \"\"\"Computes the probability ratios for each time-step in a trajectory.\n\n Args:\n p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy\n network assigns to all the actions at each time-step in each batch using\n ... |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | csn | [
"def viterbi(self,observations):\n \"\"\" The probability of occurence of the observation sequence\n\n **Arguments**:\n\n :param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object. \n :type observations: A list or t... |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | csn | [
"def propose(self):\n \"\"\"\n This method proposes values for stochastics based on the empirical\n covariance of the values sampled so far.\n\n The proposal jumps are drawn from a multivariate normal distribution.\n \"\"\"\n\n arrayjump = np.dot(\n self.proposal... |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
... | csn | [
"def pages_dynamic_tree_menu(context, page, url='/'):\n \"\"\"\n Render a \"dynamic\" tree menu, with all nodes expanded which are either\n ancestors or the current page itself.\n\n Override ``pages/dynamic_tree_menu.html`` if you want to change the\n design.\n\n :param page: the current page\n ... |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
... | csn | [
"private void mapTreeHierarchy(final WComponent currentComponent,\n\t\t\tfinal StringTreeNode currentNode, final WText selectedMenuText) {\n\t\tif (currentNode.isLeaf()) {\n\t\t\tWMenuItem menuItem = new WMenuItem(currentNode.getData(), new ExampleMenuAction(\n\t\t\t\t\tselectedMenuText));\n\t\t\tmenuItem.setAction... |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
... | csn | [
"protected function buildDisplayTree(\n SwatTreeFlydownNode $tree,\n SwatTreeFlydownNode $parent,\n $path = array()\n ) {\n $flydown_option = $tree->getOption();\n $path[] = $flydown_option->value;\n $new_node = new SwatTreeFlydownNode($path, $flydown_option->title);\n\n... |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
... | csn | [
"def mk_dropdown_tree(cls, model, for_node=None):\n \"\"\" Creates a tree-like list of choices \"\"\"\n\n options = [(0, _('-- root --'))]\n for node in model.get_root_nodes():\n cls.add_subtree(for_node, node, options)\n return options"
] |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
... | csn | [
"public function treePageDefaultUpdate(ServerRequestInterface $request): ResponseInterface\n {\n $main_blocks = (array) $request->get('main');\n $side_blocks = (array) $request->get('side');\n\n $this->updateTreeBlocks(-1, $main_blocks, $side_blocks);\n\n return redirect(route('admin-... |
Payment options.
@return array | public static function getOptions()
{
$options = [];
$options[] = [
'id' => Operation::PRODUCT_VISA,
'label' => "Visa",
];
$options[] = [
'id' => Operation::PRODUCT_MASTERCARD,
'label' => "Mastercard",
];
$options[] = [... | csn | [
"public function toOptionArray()\n {\n $return = [];\n\n $paymentMethodCodes = $this->_installmentsHelper->getAllInstallmentPaymentMethodCodes();\n foreach ($paymentMethodCodes as $paymentMethodCode) {\n $return[] = [\n 'value' => $paymentMethodCode,\n ... |
Payment options.
@return array | public static function getOptions()
{
$options = [];
$options[] = [
'id' => Operation::PRODUCT_VISA,
'label' => "Visa",
];
$options[] = [
'id' => Operation::PRODUCT_MASTERCARD,
'label' => "Mastercard",
];
$options[] = [... | csn | [
"public function getOptions()\n {\n $options = parent::getOptions();\n\n foreach ($options as $option) {\n $option->Name = \"{$this->name}[]\";\n }\n\n return $options;\n }"
] |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | csn | [
"public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | csn | [
"async def get_friendly_name(self) -> Text:\n \"\"\"\n Let's use the first name of the user as friendly name. In some cases\n the user object is incomplete, and in those cases the full user is\n fetched.\n \"\"\"\n\n if 'first_name' not in self._user:\n user = aw... |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | csn | [
"public function get($profileId, array $parameters = [])\n {\n if($profileId === 'me') {\n return $this->getCurrent($parameters);\n }\n\n return $this->rest_read($profileId, $parameters);\n }"
] |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | csn | [
"def get_user_name():\n \"\"\"Get user name provide by operating system\n \"\"\"\n\n if sys.platform == 'win32':\n #user = os.getenv('USERPROFILE')\n user = os.getenv('USERNAME')\n else:\n user = os.getenv('LOGNAME')\n\n return user"
] |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | csn | [
"def list_profile(hostname, username, password, profile_type, name=None, ):\n '''\n A function to connect to a bigip device and list an existing profile. If no name is provided than all\n profiles of the specified type will be listed.\n\n hostname\n The host/address of the bigip device\n user... |
Wrapper works for conversion.
Args:
- filename -- str, file to be converted | def f2format(filename):
"""Wrapper works for conversion.
Args:
- filename -- str, file to be converted
"""
print('Now converting %r...' % filename)
# fetch encoding
encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING)
lineno = dict() # line number -> file offset
conten... | csn | [
"def open_as_needed(filename):\n \"\"\"Return a file-object given either a filename or an object.\n\n Handles opening with the right class based on the file extension.\n\n \"\"\"\n if hasattr(filename, 'read'):\n return filename\n\n if filename.endswith('.bz2'):\n return bz2.BZ2File(fil... |
Wrapper works for conversion.
Args:
- filename -- str, file to be converted | def f2format(filename):
"""Wrapper works for conversion.
Args:
- filename -- str, file to be converted
"""
print('Now converting %r...' % filename)
# fetch encoding
encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING)
lineno = dict() # line number -> file offset
conten... | csn | [
"def write(self, session, directory, name, maskMap):\n \"\"\"\n Write from database to file.\n\n *session* = SQLAlchemy session object\\n\n *directory* = to which directory will the files be written (e.g.: '/example/path')\\n\n *name* = name of file that will be written (e.g.: 'my... |
Wrapper works for conversion.
Args:
- filename -- str, file to be converted | def f2format(filename):
"""Wrapper works for conversion.
Args:
- filename -- str, file to be converted
"""
print('Now converting %r...' % filename)
# fetch encoding
encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING)
lineno = dict() # line number -> file offset
conten... | csn | [
"def read_file(file_path, filename=None):\n \"\"\" Open file by path and optional filename\n\n If no file name is given the path is interpreted as direct path to the file to be read.\n If there is no file at location the return value will be None to offer a option for case handling.\n\n :param str file_... |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(... | csn | [
"public void detach()\r\n {\r\n textComponent.removePropertyChangeListener(\r\n documentPropertyChangeListener);\r\n Document document = textComponent.getDocument();\r\n document.removeUndoableEditListener(undoableEditListener);\r\n textComponent.getInputMap().remove(undoKe... |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(... | csn | [
"function() {\n var t = this;\n UI.hideToolTips();\n UI.pageView.model.get('components').remove(t.model);\n t.connectMonitor(false);\n t.view.remove();\n }"
] |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(... | csn | [
"function() {\n\t\t\tvar self = this;\n\t\t\tvar eventNS = self.eventNS;\n\t\t\tvar revertSettings = self.revertSettings;\n\t\n\t\t\tself.trigger('destroy');\n\t\t\tself.off();\n\t\t\tself.$wrapper.remove();\n\t\t\tself.$dropdown.remove();\n\t\n\t\t\tself.$input\n\t\t\t\t.html('')\n\t\t\t\t.append(revertSettings.$c... |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(... | csn | [
"function destroy() {\n var element = this.element,\n options = this.options;\n\n\n if (!getData(element, NAMESPACE)) {\n return this;\n }\n\n this.destroyed = true;\n\n if (this.ready) {\n if (this.played) {\n this.stop();\n }\n\n if (options.inline) {\n if (... |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(... | csn | [
"function onDeactivateEvent() {\n // cancel all event subscriptions\n me.event.unsubscribe(this.vpChangeHdlr);\n me.event.unsubscribe(this.vpResizeHdlr);\n me.event.unsubscribe(this.vpLoadedHdlr);\n }"
] |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn | [
"def delete(self, invoice_id, **kwargs):\n \"\"\"\"\n Delete an invoice\n You can delete an invoice which is in the draft state.\n\n Args:\n invoice_id : Id for delete the invoice\n Returns:\n The response is always be an empty array like this - []\n \... |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn | [
"def delete_additional_charge(self, recurring_billing_id):\n \"\"\"\n Remove an extra charge from an invoice.\n\n Args:\n recurring_billing_id: Identifier of the additional charge.\n\n Returns:\n\n \"\"\"\n fmt = 'recurringBillItems/{}'.format(recurring_billing_i... |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn | [
"def cancel(self, refund=True):\n \"\"\"Cancel this order, optionally refunding it\n \"\"\"\n if refund:\n self.refund()\n self.status = self.CANCELLED\n self.save()"
] |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn | [
"public static function cancel($transactionUUID, $client = null) {\n return Recurly_Base::_post('/purchases/transaction-uuid-' . rawurlencode($transactionUUID) . '/cancel', null, $client);\n }"
] |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn | [
"def _cancel_callback(self, request_id):\n \"\"\"Construct a cancellation callback for the given request ID.\"\"\"\n def callback(future):\n if future.cancelled():\n self.notify(CANCEL_METHOD, {'id': request_id})\n future.set_exception(JsonRpcRequestCancelled()... |
Initializes a new service. | @SuppressWarnings("unchecked")
private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
RaftServiceContext oldService = raft.getServices().getService(serviceName);
ServiceConfig serviceConfig = config == null ? new ServiceConfig() ... | csn | [
"protected synchronized void initialize() {\n String invocationServiceName = this.invocationServiceName;\n invocationService = (InvocationService)\n CacheFactory.getService(invocationServiceName);\n if (invocationService == null) {\n throw new IllegalArgumentException(... |
Initializes a new service. | @SuppressWarnings("unchecked")
private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
RaftServiceContext oldService = raft.getServices().getService(serviceName);
ServiceConfig serviceConfig = config == null ? new ServiceConfig() ... | csn | [
"def create(self, module_name, class_name,\n args=None, kwargs=None, factory_method=None,\n factory_args=None, factory_kwargs=None, static=False,\n calls=None):\n \"\"\" Initializes an instance of the service \"\"\"\n if args is None:\n args = []\n ... |
Initializes a new service. | @SuppressWarnings("unchecked")
private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
RaftServiceContext oldService = raft.getServices().getService(serviceName);
ServiceConfig serviceConfig = config == null ? new ServiceConfig() ... | csn | [
"public void start() {\n\t\tif (socket == null) {\n\t\t\tthrow new RuntimeException(\"Cannot bind a server that has not been initialized!\");\n\t\t}\n\t\trunning = true;\n\n\t\tThread t = new Thread(this);\n\t\tt.setName(\"HttpServer\");\n\t\tt.start();\n\t}"
] |
Initializes a new service. | @SuppressWarnings("unchecked")
private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
RaftServiceContext oldService = raft.getServices().getService(serviceName);
ServiceConfig serviceConfig = config == null ? new ServiceConfig() ... | csn | [
"public void start() throws Exception {\n Injector injector = Guice.createInjector(\n new ConfigModule(conf),\n new ZKModule(),\n new DiscoveryModules().getDistributedModules(),\n new TransactionModules().getDistributedModules(),\n new TransactionClientModule()\n );\n\n ZKClientSer... |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namesp... | csn | [
"func (adm *AdminClient) GetConfig() ([]byte, error) {\n\t// Execute GET on /minio/admin/v1/config to get config of a setup.\n\tresp, err := adm.executeMethod(\"GET\",\n\t\trequestData{relPath: \"/v1/config\"})\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http... |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namesp... | csn | [
"func (a *Application) LeaderSettings() (map[string]string, error) {\n\t// There's no compelling reason to have these methods on Application -- and\n\t// thus require an extra db read to access them -- but it stops the State\n\t// type getting even more cluttered.\n\n\tdoc, err := readSettingsDoc(a.st.db(), setting... |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namesp... | csn | [
"func (b *settingBiz) Get() (setting *model.Setting, err error) {\n\tdo(func(d dao.Interface) {\n\t\tsetting, err = d.SettingGet()\n\t})\n\treturn\n}"
] |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namesp... | csn | [
"func charmConfigFromGetYaml(yamlContents map[string]interface{}) (charm.Settings, error) {\n\tonlySettings := charm.Settings{}\n\tsettingsMap, ok := yamlContents[\"settings\"].(map[interface{}]interface{})\n\tif !ok {\n\t\treturn nil, errors.New(\"unknown format for settings\")\n\t}\n\n\tfor setting := range setti... |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namesp... | csn | [
"func (c ConfigStore) Get(ctx context.Context) (*chronograf.Config, error) {\n\treturn c.Config, nil\n}"
] |
Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph | def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | csn | [
"def get_subgraph_by_second_neighbors(graph, nodes: Iterable[BaseEntity], filter_pathologies: bool = False):\n \"\"\"Get a graph around the neighborhoods of the given nodes and expand to the neighborhood of those nodes.\n\n Returns none if none of the nodes are in the graph.\n\n :param pybel.BELGraph graph... |
Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph | def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | csn | [
"def get_downstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):\n \"\"\"Induce a sub-graph from all of the downstream causal entities of the nodes in the nbunch.\n\n :type graph: pybel.BELGraph\n :rtype: pybel.BELGraph\n \"\"\"\n return get_subgraph_by_edge_filter(graph, ... |
Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph | def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | csn | [
"def get_upstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):\n \"\"\"Induce a sub-graph from all of the upstream causal entities of the nodes in the nbunch.\n\n :type graph: pybel.BELGraph\n :rtype: pybel.BELGraph\n \"\"\"\n return get_subgraph_by_edge_filter(graph, buil... |
Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph | def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | csn | [
"def _create_complete_graph(node_ids):\n \"\"\"Create a complete graph from the list of node ids.\n\n Args:\n node_ids: a list of node ids\n\n Returns:\n An undirected graph (as a networkx.Graph)\n \"\"\"\n g = nx.Graph()\n g.add_nodes_from(node_ids)\n for (i, j) in combinations(n... |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | csn | [
"def gradient_factory(name):\n \"\"\"Create gradient `Functional` for some ufuncs.\"\"\"\n\n if name == 'sin':\n def gradient(self):\n \"\"\"Return the gradient operator.\"\"\"\n return cos(self.domain)\n elif name == 'cos':\n def gradient(self):\n \"\"\"Retur... |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | csn | [
"def _forward_mode(self, *args):\n \"\"\"Forward mode differentiation for a sum\"\"\"\n # (f+g)(x) = f(x) + g(x)\n f_val, f_diff = self.f._forward_mode(*args)\n g_val, g_diff = self.g._forward_mode(*args)\n # The function value and derivative is the sum of f and g\n val = f... |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | csn | [
"def grad(self, X, *params):\n \"\"\"\n Return the gradient of the basis function for each parameter.\n\n Parameters\n ----------\n X : ndarray\n (N, d) array of observations where N is the number of samples, and\n d is the dimensionality of X.\n *para... |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | csn | [
"def backward(outputs, out_grads=None, retain_graph=False):\n \"\"\"Compute the gradients of outputs w.r.t variables.\n\n Parameters\n ----------\n outputs: list of NDArray\n out_grads: list of NDArray or None\n \"\"\"\n assert isinstance(outputs, (list, tuple)), \\\n \"outputs must be a... |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | csn | [
"def gradient(self):\n \"\"\"Gradient of the compositon according to the chain rule.\"\"\"\n func = self.left\n op = self.right\n\n class FunctionalCompositionGradient(Operator):\n\n \"\"\"Gradient of the compositon according to the chain rule.\"\"\"\n\n def __init_... |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn | [
"private function isExclude(string $key): bool\n {\n if (!empty($this->excludes) && in_array($key, $this->excludes, true)) {\n return true;\n }\n\n if (!empty($this->only) && !in_array($key, $this->only, true)) {\n return true;\n }\n\n return false;\n }... |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn | [
"public function exists(?string $key = null) : bool\n {\n $key = $this->constructKey($key);\n\n return $this->parseKey($key, function ($part, $result) {\n return array_key_exists($part, $result);\n });\n }"
] |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn | [
"public function is(string $key): bool\n {\n return isset($this->meta[$key]) && (bool)$this->meta[$key];\n }"
] |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn | [
"public function has($key)\n\t{\n\t\tif (count(func_get_args()) > 1)\n\t\t{\n\t\t\tforeach (func_get_args() as $value)\n\t\t\t{\n\t\t\t\tif ( ! $this->has($value)) return false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tif (is_bool($this->input($key)) || is_array($this->input($key)))\n\t\t{\n\t\t\treturn true;\n... |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn | [
"protected function filterWouldMatch($filterValue, $value, $key)\n {\n if ($value === null) {\n return $filterValue === null;\n }\n\n if (is_array($filterValue)) {\n return is_array($value) ? $filterValue == $value : in_array($value, $filterValue);\n }\n\n ... |
Borrow an object from the pool, or create a new object
if no valid objects in the pool
@return {@link Entry} to the pooled object
@throws E exception thrown by initializer | public Entry borrow() throws E {
long now = System.currentTimeMillis();
if (timeout > 0) {
long accessed_ = accessed.get();
if (now > accessed_ + Time.SECOND &&
accessed.compareAndSet(accessed_, now)) {
Entry entry;
while ((entry = deque.pollLast()) != null) {
// inactiveCount.decrem... | csn | [
"func NewObjectPool(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig) *ObjectPool {\n\treturn NewObjectPoolWithAbandonedConfig(ctx, factory, config, nil)\n}"
] |
Borrow an object from the pool, or create a new object
if no valid objects in the pool
@return {@link Entry} to the pooled object
@throws E exception thrown by initializer | public Entry borrow() throws E {
long now = System.currentTimeMillis();
if (timeout > 0) {
long accessed_ = accessed.get();
if (now > accessed_ + Time.SECOND &&
accessed.compareAndSet(accessed_, now)) {
Entry entry;
while ((entry = deque.pollLast()) != null) {
// inactiveCount.decrem... | csn | [
"public static Object instantiate(Class clazz) throws InstantiationException\r\n {\r\n Object result = null;\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz);\r\n }\r\n catch(IllegalAccessException e)\r\n {\r\n try\r\n {\r\n ... |
Borrow an object from the pool, or create a new object
if no valid objects in the pool
@return {@link Entry} to the pooled object
@throws E exception thrown by initializer | public Entry borrow() throws E {
long now = System.currentTimeMillis();
if (timeout > 0) {
long accessed_ = accessed.get();
if (now > accessed_ + Time.SECOND &&
accessed.compareAndSet(accessed_, now)) {
Entry entry;
while ((entry = deque.pollLast()) != null) {
// inactiveCount.decrem... | csn | [
"@SuppressWarnings(\"unchecked\")\n public T get() {\n try {\n isLoaded();\n return (T) this;\n } catch (Error e) {\n load();\n }\n\n isLoaded();\n\n return (T) this;\n }"
] |
Borrow an object from the pool, or create a new object
if no valid objects in the pool
@return {@link Entry} to the pooled object
@throws E exception thrown by initializer | public Entry borrow() throws E {
long now = System.currentTimeMillis();
if (timeout > 0) {
long accessed_ = accessed.get();
if (now > accessed_ + Time.SECOND &&
accessed.compareAndSet(accessed_, now)) {
Entry entry;
while ((entry = deque.pollLast()) != null) {
// inactiveCount.decrem... | csn | [
"public java.util.List<ObjectId> getObjectId() {\n if (objectId == null) {\n objectId = new ArrayList<ObjectId>();\n }\n return this.objectId;\n }"
] |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an obje... | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.par... | csn | [
"function Client(options, isSecure) {\n\n // Invokes with new if called without\n if (false === (this instanceof Client)) {\n return new Client(options, isSecure)\n }\n\n // If a string URI is passed in, converts to URI fields\n if (typeof options === 'string') {\n options = url.parse(options)\n optio... |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an obje... | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.par... | csn | [
"function(options) {\n EventEmitter.call(this);\n\n this.node = options.node;\n this.https = options.https || this.node.https;\n this.httpsOptions = options.httpsOptions || this.node.httpsOptions;\n this.bwsPort = options.bwsPort || baseConfig.port;\n this.messageBrokerPort = options.messageBrokerPort || 3380... |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an obje... | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.par... | csn | [
"function(config){\n this.options = {\n hostname : config.url,\n port : 443,\n path : '', //override\n method : '', //override\n auth : config.user + ':' + config.passwd,\n headers : config.headers\n };\n}"
] |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an obje... | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.par... | csn | [
"function Server(opts){\n // Shorthand, no \"new\" required.\n if (!(this instanceof Server))\n return new Server(...arguments);\n\n if (typeof opts !== 'object')\n opts = {};\n\n this.clients = opts.dummies || [];\n\n this.server = opts.server || new SocketServer(socket => {\n let client = new Client... |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an obje... | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.par... | csn | [
"function Connection(options) {\n\t\n\tif (!(this instanceof Connection)){\n\t\treturn new Connection(options);\n\t}\n\t\n\t\n\tthis.prefixCounter = 0;\n\tthis.serverMessages = {};\n\tthis._options = {\n\t\tusername: options.username || options.user || '',\n\t\tpassword: options.password || '',\n\t\thost: options.h... |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
... | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
... | csn | [
"def alias(*aliases):\n \"\"\"\n Decorating a class with @alias('FOO', 'BAR', ..) allows the class to\n be referenced by each of the names provided as arguments.\n \"\"\"\n def decorator(cls):\n # alias must be set in globals from caller's frame\n caller = sys._getframe(1)\n glob... |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
... | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
... | csn | [
"def register(self, f, *args, **kwargs):\n \"\"\"\n Register a function and arguments to be called later.\n \"\"\"\n self._functions.append(lambda: f(*args, **kwargs))"
] |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
... | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
... | csn | [
"def _register_handler(event, fun, external=False):\n \"\"\"Register a function to be an event handler\"\"\"\n registry = core.HANDLER_REGISTRY\n if external:\n registry = core.EXTERNAL_HANDLER_REGISTRY\n\n if not isinstance(event, basestring):\n # If not basestring, it is a BaseEvent subc... |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
... | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
... | csn | [
"def add_handlers(self, namespace):\n \"\"\"\n Add handler functions from the given `namespace`, for instance a module.\n\n The namespace may be a string, in which case it is expected to be a name of a module.\n It may also be a dictionary mapping names to functions.\n\n Only non-... |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
... | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
... | csn | [
"def parametrized_class(decorator):\n '''Decorator used to make simple class decorator with arguments.\n Doesn't really do anything, just here to have a central\n implementation of the simple class decorator.'''\n\n def decorator_builder(*args, **kwargs):\n\n def meta_decorator(cls):\n ... |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collatio... | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | csn | [
"def generate_csv(data):\n \"\"\"Generate a CSV of the abilities for easy commenting.\"\"\"\n print(\",\".join([\n \"ability_id\",\n \"link_name\",\n \"link_index\",\n \"button_name\",\n \"hotkey\",\n \"friendly_name\",\n \"remap_to\",\n \"mismatch\",\n ]))\n for ability ... |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collatio... | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | csn | [
"def get_actions(self, request, view):\n \"\"\"\n Return metadata for resource-specific actions,\n such as start, stop, unlink\n \"\"\"\n metadata = OrderedDict()\n actions = self.get_resource_actions(view)\n\n resource = view.get_object()\n for action_name, a... |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collatio... | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | csn | [
"private void registerRefEntityIndexActions() {\n // bidirectional attribute: register indexing actions for other side\n getEntityType()\n .getMappedByAttributes()\n .forEach(\n mappedByAttr -> {\n EntityType refEntity = mappedByAttr.getRefEntity();\n indexAc... |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collatio... | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | csn | [
"def _parse_action(self, action, current_time):\n \"\"\"Parse a player action.\n\n TODO: handle cancels\n \"\"\"\n if action.action_type == 'research':\n name = mgz.const.TECHNOLOGIES[action.data.technology_type]\n self._research[action.data.player_id].append({\n ... |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collatio... | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | csn | [
"def get_indices(self, include_aliases=False):\n \"\"\"\n Get a dict holding an entry for each index which exists.\n\n If include_alises is True, the dict will also contain entries for\n aliases.\n\n The key for each entry in the dict is the index or alias name. The\n valu... |
Check if sending the given message was enabled by the client.
@param message
the message to check
@return true if the message should be sent, false otherwise (and the message is discarded) | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
... | csn | [
"public boolean supportDeliveryMode( int deliveryMode )\n {\n \tswitch (deliveryMode)\n \t{\n \t\tcase DeliveryMode.PERSISTENT : return initialBlockCount > 0;\n \t\tcase DeliveryMode.NON_PERSISTENT : return maxNonPersistentMessages > 0;\n \t\tdefault :\n \t\t\tthrow new IllegalArgumentExcep... |
Check if sending the given message was enabled by the client.
@param message
the message to check
@return true if the message should be sent, false otherwise (and the message is discarded) | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
... | csn | [
"public boolean isInvite() {\n if (message == null) {\n return false;\n }\n\n return (((Request) message).getMethod().equals(Request.INVITE));\n }"
] |
Check if sending the given message was enabled by the client.
@param message
the message to check
@return true if the message should be sent, false otherwise (and the message is discarded) | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
... | csn | [
"public boolean isBye() {\n if (message == null) {\n return false;\n }\n\n return (((Request) message).getMethod().equals(Request.BYE));\n }"
] |
Check if sending the given message was enabled by the client.
@param message
the message to check
@return true if the message should be sent, false otherwise (and the message is discarded) | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
... | csn | [
"public void send(Packet packet) {\n if (log.isTraceEnabled()) {\n log.trace(\"send packet: {}\", packet);\n }\n // no handshake flag, queue the packet\n if (session.containsAttribute(Constants.HANDSHAKE_COMPLETE)) {\n try {\n // clear any queued item... |
Moves the positon based on a direction.
@param int $direction
@return void | public function move($direction)
{
if ($direction === self::DIR_FORWARD) {
return $this->next();
} elseif ($direction === self::DIR_BACKWARD) {
return $this->prev();
}
throw new InvalidArgumentException(sprintf('Unknown direction %s', $direction));
} | csn | [
"function directionStr(direction) {\n if (direction == DIRECTION_DOWN) {\n return 'down';\n } else if (direction == DIRECTION_UP) {\n return 'up';\n } else if (direction == DIRECTION_LEFT) {\n return 'left';\n } else if (direction == DIRECTION_RIGHT) {\n return 'right';\n ... |
Moves the positon based on a direction.
@param int $direction
@return void | public function move($direction)
{
if ($direction === self::DIR_FORWARD) {
return $this->next();
} elseif ($direction === self::DIR_BACKWARD) {
return $this->prev();
}
throw new InvalidArgumentException(sprintf('Unknown direction %s', $direction));
} | csn | [
"public function direction()\n {\n if (empty($this->direction)) {\n $rtlScripts = ['Arab', 'Hebr', 'Mong', 'Tfng', 'Thaa'];\n\n $this->setDirection(\n in_array($this->script, $rtlScripts)\n ? self::DIRECTION_RIGHT_TO_LEFT\n : self:... |
Moves the positon based on a direction.
@param int $direction
@return void | public function move($direction)
{
if ($direction === self::DIR_FORWARD) {
return $this->next();
} elseif ($direction === self::DIR_BACKWARD) {
return $this->prev();
}
throw new InvalidArgumentException(sprintf('Unknown direction %s', $direction));
} | csn | [
"function(angle) {\n this.dir = (this.dir + angle + circle) % circle;\n\n // Calculate the rotation vector and update the orientation of the listener.\n var x = Math.cos(this.dir);\n var y = 0;\n var z = Math.sin(this.dir);\n Howler.orientation(x, y, z, 0, 1, 0);\n }"
] |
Moves the positon based on a direction.
@param int $direction
@return void | public function move($direction)
{
if ($direction === self::DIR_FORWARD) {
return $this->next();
} elseif ($direction === self::DIR_BACKWARD) {
return $this->prev();
}
throw new InvalidArgumentException(sprintf('Unknown direction %s', $direction));
} | csn | [
"public static function arrow(string $direction) : string\n {\n switch ($direction) {\n case \"up\": \t $output = '<span class=\"arrow\">↑</span>'; break;\n case \"down\": $output = '<span class=\"arrow\">↓</span>'; break;\n case \"left\": $output = '<span cla... |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn | [
"func (b *KubeletBuilder) addContainerizedMounter(c *fi.ModelBuilderContext) error {\n\tif !b.usesContainerizedMounter() {\n\t\treturn nil\n\t}\n\n\t// This is not a race because /etc is ephemeral on COS, and we start kubelet (also in /etc on COS)\n\n\t// So what we do here is we download a tarred container image, ... |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn | [
"func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {\n\tartifact := new(FileArtifact)\n\n\tif b.config.Source != \"\" {\n\t\tsource, err := os.Open(b.config.Source)\n\t\tdefer source.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create will tr... |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn | [
"func New(src, packageName string) (*Mocker, error) {\n\tsrcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Couldn't load source package: %s\", err)\n\t}\n\tpkgPath := srcPkg.PkgPath\n\n\tif len(packageName) == 0 {\n\t\tpackageName = srcPkg.Name\n\t} else {\n\t... |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn | [
"func NewSafeFormatAndMountFromHost(pluginName string, host volume.VolumeHost) *mount.SafeFormatAndMount {\n\tmounter := host.GetMounter(pluginName)\n\texec := host.GetExec(pluginName)\n\treturn &mount.SafeFormatAndMount{Interface: mounter, Exec: exec}\n}"
] |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn | [
"func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\tquery, err := cli.imageBuildOptionsToQuery(options)\n\tif err != nil {\n\t\treturn types.ImageBuildResponse{}, err\n\t}\n\n\theaders := http.Header(make(map[string][]st... |
Get an instance of a validation class.
@param string $name
@return validator\Validation
@throws exceptions\ValidatorException | private function getValidation(string $name): validator\Validation
{
if (!isset($this->validations[$name])) {
if (isset($this->validationRegister[$name])) {
$class = $this->validationRegister[$name];
} else {
throw new exceptions\ValidatorException("Va... | csn | [
"public function setValidator($name, Validator $validator)\n {\n $validator->setProvider(self::VALIDATOR_PROVIDER_NAME, $this);\n $this->_validators[$name] = $validator;\n\n return $this;\n }"
] |
Get an instance of a validation class.
@param string $name
@return validator\Validation
@throws exceptions\ValidatorException | private function getValidation(string $name): validator\Validation
{
if (!isset($this->validations[$name])) {
if (isset($this->validationRegister[$name])) {
$class = $this->validationRegister[$name];
} else {
throw new exceptions\ValidatorException("Va... | csn | [
"public function getClassName($name)\n {\n if (!$this->has($name)) {\n return false;\n }\n $helper = $this->get($name);\n return get_class($helper);\n }"
] |
Get an instance of a validation class.
@param string $name
@return validator\Validation
@throws exceptions\ValidatorException | private function getValidation(string $name): validator\Validation
{
if (!isset($this->validations[$name])) {
if (isset($this->validationRegister[$name])) {
$class = $this->validationRegister[$name];
} else {
throw new exceptions\ValidatorException("Va... | csn | [
"public static function get($name)\n {\n if (!isset(static::$types[$name])) {\n if (!static::has($name)) {\n throw new \\InvalidArgumentException(sprintf('The type \"%s\" does not exists.', $name));\n }\n\n static::$types[$name] = new static::$map[$name];\n ... |
// Returns a visualization of the string. | func (s StringObject) String() string {
return fmt.Sprintf("StringObject{Key: %s, Value: '%s'}", DataToString(s.Key), DataToString(s.Value))
} | csn | [
"func (prof *Profiler) Serialize(u *structs.DevUsage) ([]byte, error) {\n\treturn json.Marshal(u)\n}"
] |
Loads all data for zones that belong to provided layout. | public function loadLayoutZonesData(Layout $layout): array
{
$query = $this->getZoneSelectQuery();
$query->where(
$query->expr()->eq('layout_id', ':layout_id')
)
->setParameter('layout_id', $layout->id, Type::INTEGER)
->orderBy('identifier', 'ASC');
$this... | csn | [
"public function getLayoutBlock($zone = null)\n {\n if (!is_null($zone)) {\n $layoutBlocks = $this->layoutBlock->filter(\n function ($layoutBlock) use ($zone) {\n return $layoutBlock->getZone() == $zone && $layoutBlock->isActive();\n }\n ... |
Loads all data for zones that belong to provided layout. | public function loadLayoutZonesData(Layout $layout): array
{
$query = $this->getZoneSelectQuery();
$query->where(
$query->expr()->eq('layout_id', ':layout_id')
)
->setParameter('layout_id', $layout->id, Type::INTEGER)
->orderBy('identifier', 'ASC');
$this... | csn | [
"public function mapZone(PersistenceZone $zone): Zone\n {\n $zoneData = [\n 'identifier' => $zone->identifier,\n 'layoutId' => $zone->layoutId,\n 'status' => $zone->status,\n 'linkedZone' => function () use ($zone): ?Zone {\n if ($zone->linkedLayo... |
Loads all data for zones that belong to provided layout. | public function loadLayoutZonesData(Layout $layout): array
{
$query = $this->getZoneSelectQuery();
$query->where(
$query->expr()->eq('layout_id', ':layout_id')
)
->setParameter('layout_id', $layout->id, Type::INTEGER)
->orderBy('identifier', 'ASC');
$this... | csn | [
"public function get_all_block_regions() {\n $regions = array();\n foreach ($this->layouts as $layoutinfo) {\n foreach ($layoutinfo['regions'] as $region) {\n $regions[$region] = $this->get_region_name($region, $this->name);\n }\n }\n return $regions;... |
Loads all data for zones that belong to provided layout. | public function loadLayoutZonesData(Layout $layout): array
{
$query = $this->getZoneSelectQuery();
$query->where(
$query->expr()->eq('layout_id', ':layout_id')
)
->setParameter('layout_id', $layout->id, Type::INTEGER)
->orderBy('identifier', 'ASC');
$this... | csn | [
"function listZones() {\n return self.cloudflareClient.findZones({page: 1, per_page: self.perPage})\n .then(function (response) {\n let promises = [Promise.resolve(response)];\n for (let i = 2; i <= response.data['result_info']['total_pages']; i++) {\n promises.push(self.cloudflareCli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.