ngram
listlengths
0
67.8k
[ "OptimizationTask): compute = worker.compute_optimization elif isinstance(task, HessianTask): compute = worker.compute_hessian else: raise NotImplementedError()", "to see if a QC task has already been executed and if not", "import redis from openff.toolkit.topology import Molecule from openff.bespokefit.executo...
[ "build the sequence if the node operation exists if operation not in instance.node.operations:", "% node.id) continue # Iterate over each node instance for instance in node.instances:", "sg_start.sequence() seq_start.add(*build_instance_sequence( instance, OP_START, 'Starting', 'Started')) # Create subgraph dep...
[ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "try: with socket(AF_INET, SOCK_STREAM) as sock: sock.connect( (self.recver_ip, self._worker_ports[worker_num]) ) sock.send(self.token) assert sock.recv(1)", "self._progress_bar.stop() self._sending_file = False return printerr...
[ "= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) assert isinstance(model.get_input_embeddings(), tf.keras.layers.Layer) x", "# IMO there is a problem with the signature check. # Test passes", "or a and b arent both tensors, raise ...
[ "np.argmax(y_raw, axis=-1) y_prob = softmax(y_raw, axis=-1) if 'probabilities' in measures: return_values['probabilities'] = y_prob", "np.array([ sklearn.metrics.mean_squared_error(y_true, raw) for raw in y_raw ]) if 'accuracy' in measures: return_values['accuracy']", "for pred in y_pred ]) if 'kappa' in measur...
[ "months=+1), relativedelta(years=+3, months=+2), ), \"backwards\": (relativedelta(months=+1), relativedelta(days=+1)), \"starts_with_normal\": (relativedelta(), relativedelta(days=+14)), \"ends_with_normal\": (relativedelta(days=+14), relativedelta(months=+1)),", "check_order=True, ): def decorator(func): def wra...
[ "<a href=\"http://www.python.org\">Python</a>...</p>' + # '</body></html>', 'html', 'utf-8') # 发送带附件的邮件 # 邮件对象: msg =", "from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email.utils import parseaddr, formataddr", "添加到MIMEMultipart: msg.attach(mime) msg['From'] = _for...
[ "unit.gigabyte, wallclock_time_limit=\"05:59\", ) worker_script_commands = [\"conda activate forcebalance\", \"module load cuda/10.1\"] calculation_backend =", "for the results. results, _ = request.results(True, 5) results.json(f\"results.json\") if __name__ == \"__main__\":", "# on a HPC resources with the LS...
[ "SimulationIteration logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) class TestProfileIDM(unittest.TestCase): \"\"\" Profiling test for IDM agents.", "nuplan.planning.scenario_builder.nuplan_db.test.nuplan_scenario_test_utils import get_test_nuplan_scenario from nuplan.planning.simula...
[ "agent.adapt_param_noise(obs0) epoch_adaptive_distances.append(distance) cl, al = agent.train() epoch_critic_losses.append(cl) epoch_actor_losses.append(al) agent.update_target_net() # Evaluate. eval_episode_rewards =", "elif 'ou' in current_noise_type: _, stddev = current_noise_type.split('_') action_noise = Orn...
[ "e html = trans.render(transaction=self._transaction, printed_at=datetime.now().strftime('%d/%m/%Y, %I:%M:%S %p')) doc = QTextDocument(self) doc.setHtml(html) doc.print_(printer) return", "QPrintDialog(printer, self.parentWidget()).exec_() != QDialog.Accepted: return None try: trans = jinja_env.get_template('tran...
[ "str(self.view(np.ndarray)) + ' ' + str(self.units) # # Start unit conversion methods #", "python syntax (cm**3, not cm^3). registry : A UnitRegistry object The registry to", "== 'particle': units = finfo.output_units else: units = finfo.units if isinstance(x, YTArray): arr", "registry=unit_registry) else: re...
[ "get_user(self, obj): return str(obj.user.username) def get_image(self, obj): try: image = obj.image.url except: image", "url = post_detail_url user = serializers.SerializerMethodField() class Meta: model = Post fields =", "fields = [ 'url', 'id', 'title', 'slug', 'content', 'publish', 'user', 'image', 'html', ...
[ "self.oHelper.SetValue('XXX_DATATE', '07/08/2020') self.oHelper.ScrollGrid(column='Agência', match_value='000048', grid_number=1) '''self.oHelper.ClickGridCell(\"\", row=2, grid_number=1)''' self.oHelper.ClickBox(\"\", contents_list='', select_all=False, grid_number=1) self.oHelper.SetButton('Concluir')", "Webapp...
[ "django.http import HttpResponse,FileResponse,JsonResponse from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_xops.basic", "from ..serializers.{model_name}_serializers import * class {model_camel_case_name}View(ModelViewSet): q...
[ "collector is invoked. #### Dependencies None #### Usage Add the collector config as", "class HeartbeatCollector(diamond.collector.Collector): def __init__(self, *args, **kwargs): super(HeartbeatCollector, self).__init__(*args, **kwargs) self.hostname = self.get_hostname() self.ttl", "netuitive = None class Hea...
[ "exp1_GD.std()]) stat1_GD.index = [\"Best\", \"Median\", \"Std.\"] stat2_GD = pd.DataFrame([exp2_GD.min(), exp2_GD.median(), exp2_GD.std()]) stat2_GD.index =", "best algorithm meds1_Hypervolume = stat1_Hypervolume.loc[\"Median\"].sort_values( ascending=False) best1_Hypervolume = list(meds1_Hypervolume.index[:2]) ...
[ "print('\\n>>> Using calc_spatialCorrHeight function!') ### Import modules import numpy as np if weight", "P Levels)!') return wcov def corr(x, y, w): \"\"\"Weighted Correlation\"\"\" wcor = cov(x,", "----- [1] calcDecJan(varx,vary,lat,lon,level,levsq) [2] calcDecJanFeb(varx,vary,lat,lon,level,levsq) [3] calc_i...
[ "None: A = tir.match_buffer(a, (128, 128)) B = tir.alloc_buffer((128, 128)) C = tir.match_buffer(c,", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "@tvm.script.tir def elementwise(a: ty.handle, c: ty.handle) -> None: A = tir.match_buffer(a, (128, 128))", "128)) C = tir.match...
[ "open(job.logname, \"r\") as f: while True: r = f.read(4096) if r: yield r", "self.proc.communicate(self.inputobj) if self.proc.returncode == 0: outobj = yaml.load(self.stdoutdata, Loader=yaml.FullLoader) with self.updatelock: self.status[\"state\"] =", "def getstatus(self): with self.updatelock: return self.st...
[ "on the left side if (i < 31) { // CATCH: for last", "1 bit. Then, if the last digit of input n is 1, we", "result |= n & 1 n >>= 1 return result class TestMethods(unittest.TestCase): def", "n as an unsigned value public int reverseBits(int n) { n = ((n", "0000_0000_0000_0000_0000_0000_0000_0001 = 0000_0000...
[ "following line *must* be the last in the module, exactly as formatted: __version__", "The following line *must* be the last in the module, exactly as formatted:", "*must* be the last in the module, exactly as formatted: __version__ = \"0.16.1\"", "line *must* be the last in the module, exactly as formatted: ...
[ "comma_pattern = re.compile('\\d+(,\\d+)*') def pages_args_to_array(pages_str): groups = range_pattern.search(pages_str) if groups: start = int(groups.group(1))", "else: raise Exception('pages should be like 1,2,3 or 1-3, but was {}' .format(pages_str))", "file1.pdf 1-3 file2.pdf 3,4,10 file1.pdf 50\" assert(le...
[ "in the number of detected vanishing points. Returns: Integer, positive when there are", "set() total_error = 0 for distance, gt_vp, dt_vp in point_pair_dists: if gt_vp in", "= 180 - abs(abs(gt_angle - dt_angle) - 180) point_pair_dists.append((angle_diff, gt_vp, dt_vp)) point_pair_dists =", "180) point_pair_d...
[ "type=int, default=2) parser.add_argument('--gamma', type=float, default=0.99) parser.add_argument('--seed', '-s', type=int, default=4) parser.add_argument('--cpu', type=int, default=4) parser.add_argument('--steps',", "from spinup.algos.pytorch.ppo.ppo import ppo from spinup.utils.run_utils import setup_logger_k...
[ "f() g.next() \"\"\" in d g = d['g'] assert g.send(42) == 42 def", "g = f() \"\"\" in d g = d['g'] assert g.next() == 1", "{} exec \"\"\" def f(): try: yield finally: f.x = 42 \"\"\".strip() in", "1 def test_generator2(self): def f(): yield 1 g = f() assert g.next() ==", "== [1] def test_generator5(self): d...
[ "chance to disconnect from # the hypervisors. disconnect_all() close_virtconns() # The underlying library", "guest system', ) subparser.add_argument( 'new_hostname', help='New hostname', ) subparser.add_argument( '--offline', action='store_true', help='Shutdown VM,", "taking our chance to disconnect from # the ...
[ "Abilene,_Texas\" assert test_dataset[0].text_b == \"\" assert test_dataset[0].tgt_text == \"Abilene, Texas is served by", "assert len(test_dataset) == 4928 assert test_dataset[0].text_a == \" | Abilene_Regional_Airport : cityServed :", "dataset_name = \"webnlg_2017\" dataset_path = os.path.join(base_path, data...
[ "15 FILE_CASE_MISMATCH = 16 FILE_DUPLICATED = 17 FILE_UNKNOWN_ERROR = 0x0FFF OPTION_UNKNOWN = 0x1000", "file type\", FILE_CASE_MISMATCH : \"File name case mismatch\", FILE_DUPLICATED : \"Duplicated file found\",", "0x3002 FORMAT_UNKNOWN_ERROR = 0x3FFF RESOURCE_NOT_AVAILABLE = 0x4000 RESOURCE_ALLOCATE_FAILURE = ...
[ "for path in self.data])) cats.sort() self.labels = torch.LongTensor([cats.index(path.split(\"/\")[3]) for path in self.data]) self.preprocessor", "idx.tolist() if len(self.encoded_data) == 0: return self.preprocessor(Image.open(self.data[idx]).convert('RGB')), self.labels[idx] return self.encoded_data[idx], self...
[ "mixbox import entities, fields import cybox import cybox.bindings.cybox_common as common_binding class LocationFactory(entities.EntityFactory): @classmethod", "The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. from", "def to_dict(self): d = super(Location, self).to_dict() if sel...
[ "clip_right = get_clip(rec.cigartuples[-1]) if clip_right is not None: softclips.append([clip_right, False, is_first_read]) if i", "else None clip_left = get_clip(rec.cigartuples[0]) if clip_left is not None: softclips.append([clip_left, True, is_first_read])", "#!/usr/bin/env python import sys import numpy as ...
[ "django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('rss_feeder_api', '0002_feed_subtitle'), ] operations = [ migrations.AlterModelOptions(", "'verbose_name_plural': 'entries'}, ), migrations.AlterModelOptions( name='feed', options={'ordering': ('-updated_at',), 'verbose_name': 'Feed',...
[ "[b])') # Start model definition. num_filters_in = 16 num_res_blocks = int((depth - 2)", "number of filters kernel_size (int): Conv2D square kernel dimensions strides (int): Conv2D square", "x = Activation(activation)(x) else: if batch_normalization: x = BatchNormalization()(x) if activation is not", "classif...
[ "defined!\") try: recursion_limit = int(sys.argv[2]) except IndexError: recursion_limit = 0 if recursion_limit >", "'images': [], 'id': dump(subj), }}) if pred == FHKB.Sex: node['data'][dump(pred)] = dump(obj) elif", "?pred ?obj . } ORDER BY ?person\"\"\") for rel in RELS_OF_INTEREST: pred =", "= 0 if recursi...
[ "Unless required by applicable law or agreed to in writing, software # distributed", "super().default_config() # If jwt_config has been defined (eg via @override_config), don't replace it.", "the template. channel = self.make_request(\"GET\", cas_ticket_url) # Test that the response is HTML.", "Signature has ...
[ "''' parser = argparse.ArgumentParser() parser.add_argument('-p', '--pickup', default='pantry', help='Start waypoint') parser.add_argument('-d', '--dropoff', default='hardware_2', help='Finish", "argparse.ArgumentParser() parser.add_argument('-p', '--pickup', default='pantry', help='Start waypoint') parser.add_ar...
[ "# so long as these are infrequent we're doing well log.warning( f\"{route.endpoint} Has", "if not 300 > response.status >= 200: await self._raise_exception(response, route, result) log.debug( f\"{route.endpoint}", "this gets a BucketLock for this route. # If this endpoint has been", "for {result.get('retry_a...
[ "app development configuration class \"\"\" ENV = \"development\" DEBUG = True SQLALCHEMY_TRACK_MODIFICATIONS =", "\"development\" DEBUG = True SQLALCHEMY_TRACK_MODIFICATIONS = True class ProductionConfig(Config): DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS", "for the user auth api JWT_SECRET_KEY = environ.get...
[ "# Standard wallet SEED_PREFIX_SW = '100' # Segwit wallet SEED_PREFIX_2FA = '101' #", "== '2fa': return SEED_PREFIX_2FA elif seed_type == '2fa_segwit': return SEED_PREFIX_2FA_SW raise Exception(f\"unknown seed_type:", "SEED_PREFIX_SW elif seed_type == '2fa': return SEED_PREFIX_2FA elif seed_type == '2fa_segwit'...
[ "(j + 0.5) / steps_x # unit center x,y cy = (i +", "/ 4) for k in range(len(self._steps))] def _create_prior(self, cx, cy, k): raise NotImplementedError", "TBWriter def vis(func): \"\"\"tensorboard visualization if has writer as input\"\"\" def wrapper(*args, **kw):", "type(None)): image = np.ones((self.image...
[ "and the following # disclaimer in the documentation and/or other materials provided with", "SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT", ": mostCommonValue = value maxCount = count return mostCommonValue combiners = { \"fileSystem:owner\"", "[] leafPathString...
[ "Migration(migrations.Migration): dependencies = [ ('reo', '0117_financialmodel_generator_fuel_escalation_pct'), ('reo', '0120_auto_20210927_2046'), ('reo', '0121_auto_20211012_0305') ] operations =", "on 2021-10-01 18:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('r...
[ "reverse = True) event.selectedTaus.sort(key = lambda l : l.pt(), reverse = True) event.otherTaus.sort(key", "= False tau.idDecayMode = tau.tauID(\"decayModeFinding\") tau.idDecayModeNewDMs = tau.tauID(\"decayModeFindingNewDMs\") if hasattr(self.cfg_ana, 'inclusive_decayModeID') and self.cfg_ana.inclusive_decayMo...
[ "= 5 if(f == 2): return 1 if not (f & 1): return", "i, N) == a): break plainText2File = open(\"plaintext2.txt\", \"w+\") plainText2File.write(str(i)) plainText2File.close() plain2File =", "str(N)) privateKeyFile.close() def encrypt(plaintext, publickeytxt): try: open(publickeytxt, \"r\") except FileNotFoundErro...
[ "module_dir + 'data_envo/envo.obo' self.path = path # --------------------------- In this section --------------------------- #", "\"\"\"A object that gives you access to the graph (network with nodes and", "# goatools # orange_network # pygraphviz # networkx @property_cached def orange_obo(self): \"\"\"The ont...
[ "based on the routing rules. :type service_bus_topics: list[~azure.mgmt.iothub.v2019_11_04.models.RoutingServiceBusTopicEndpointProperties] :param event_hubs: The list of", "True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display',", "'type': 'str'}, 'endpoint_names': {'k...
[ "'path': '/v1/traces', 'method': 'GET', 'is_getall': True }, { 'path': '/v1/traces/%s' % (trace_model.id), 'method':", "return 403 status code (body=%s)' % (endpoint['method'], endpoint['path'], response.body) self.assertEqual(response.status_code, http_client.FORBIDDEN, msg) #", "}, # Timers { 'path': '/v1/tim...
[ "-c myabtest', shell=True) wait_for_rollout(\"myabtest-myabtest-41de5b8\") wait_for_rollout(\"myabtest-myabtest-df66c5c\") r = initial_rest_request() r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST) res =", "mymodel --image seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oaut...
[]
[ "null=True) class Genre(models.Model): name = models.CharField(max_length=50) class Nation(models.Model): name = models.CharField(max_length=50) demonym =", "models.ForeignKey('Author') genres = models.ManyToManyField('Genre') class Author(models.Model): name = models.CharField(max_length=50) nationality = models...
[ "height*width]) k = tf.cast(height*width/dropblock_size**2, tf.int32) topk, _ = tf.math.top_k(cam, k=k) # [N, 1,", "= tf.divide(grads, tf.sqrt(tf.reduce_mean(tf.square(grads), reduction_indices=[2,3], keepdims=True)) + tf.constant(1e-5)) # weights = tf.reduce_mean(norm_grads, reduction_indices=[2,3]) #", "width...
[ "batcher processes def create_gym_env(env_name): return gym.make(env_name) def create_env(n_envs, env_name=None, max_episode_steps=None, seed=None): envs =", "seed) def create_agent(model, n_actions=1): return RecurrentAgent(model=model, n_actions=n_actions) class Experiment(A2C): def __init__(self, config, creat...
[ "gesamt_entity_count(): #Gesamtzahl der GND-Entitäten with open(f\"{path}/../stats/gnd_entity_count.csv\", \"r\") as f: entities = f'{int(f.read()):,}' return", "f'{uniques:,}' #Durchschnittliche Anzahl an GND-Verknüpfungen pro DNB-Titeldatensatz with open(f\"{path}/../stats/title_gnd_mean.csv\", \"r\") as f: mea...
[ "Class for all excpetions used in following scripts - geocoder.py - geocoder_input.py \"\"\"", "geocoder.py - geocoder_input.py \"\"\" class OverlappingGeographyError(Exception): def __init__(self, message): self.message = message #", "__init__(self, message): self.message = message # msg: geodataframe has over...
[ "sys.exit() elif(i.decode(\"utf-8\") == \"put yap\"): cevap = s_soket.recvfrom(4096) if(cevap[0].decode(\"utf-8\") == \"mevcut\"): dosyaIsmi, istemciAdres", "(kopya)\" + \".txt\" dosyaYeni = open(yeniAd, \"wb\") dosyaYeni.write(dosyaIcerigi[0]) dosyaYeni.close() print(\"\\nPUT islemi basariyla gerceklesti..\")", ...
[ "e.g. ${get_variables()} project_meta = load_project_meta(test_path) variables = parse_data(raw_variables, {}, project_meta.functions) return variables else:", "sort_dict_by_custom_order def convert_variables( raw_variables: Union[Dict, List, Text], test_path: Text ) -> Dict[Text, Any]:", "item in request.node....
[ "points, with basic Chaco panning and zooming. Interacting with the plot: - Left-mouse-drag", "the plot. - Mouse wheel up and down zooms the plot in and", "orientation = \"vertical\"), resizable=True, title=title ) def _plot_default(self): return _create_plot_component() demo = Demo()", "zoom = ZoomTool(compo...
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "KIND, either express or implied. # See the License for the specific language", "governing permissions and # limitations under the License. import ...
[ "random class Mutation: def __init__(self, chrom_mut_chance, gen_mut_chance): self.chrom_mut_chance = chrom_mut_chance self.gen_mut_chance = gen_mut_chance", "range(len(chrom)), round(self.gen_mut_chance * len(chrom))) for gt in genes_to_mutate: chrom[gt] = int(not bool(chrom[gt])) return", "chrom in chroms_to_...
[ "occurrences of each letter are:\") displayCounts(counts) def createList(): \"\"\"Create a list of characters.\"\"\"", "list return chars def displayList(chars): \"\"\"Display the list of characters.\"\"\" # Display the", "in the list, count it for i in range(len(chars)): counts[ord(chars[i]) - ord('a')] +=", ...
[ "API:: from ddtrace import config, patch patch(vertica=True) config.vertica['service_name'] = 'my-vertica-database' To configure the", "instrumented with ``patch_all``, or when using the ``ls-trace-run`` command. Vertica is instrumented on", "\"\"\" from ...utils.importlib import require_modules required_module...
[ "cases = [ '', \"http://not.in.a.link.tag/\", '<link rel=\"openid.server\" href=\"not.in.html.or.head\" />', ] def __init__(self, data):", "= [ '', \"http://not.in.a.link.tag/\", '<link rel=\"openid.server\" href=\"not.in.html.or.head\" />', ] def __init__(self, data): datadriven.DataDrivenTestCase.__init__(self,...
[ "EMAIL_HOST_USER = get_env_var('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = get_env_var('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL", "TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_director...
[ "states = [] g.attr('node', shape='ellipse') for column_name in column_names: if column_name[:6] == 'state_':", "pandas as pd import argparse import json try: from graphviz import Digraph except:", "if df[column_name].min() < 0 and df[column_name].max() <= 0: g.edge(state, parts[0]) elif df[column_name].min() >...
[ "None : break labelname = IndexLabel[MonthFileList.index(fileName)] df = df.rename(columns={'time': labelname }) if MonthFileList.index(fileName)", "import relativedelta from pprint import pprint import base.ColorPrint as CPrint import command.voice_log.Config_Main as", ": data += guild_item.members continue # ...
[ "n, m: (int(end.split(\".\")[n]) - int(start.split(\".\")[n])) * m return calc(0, 256 * 256 *", "256 * 256 * 256) + calc(1, 256 * 256) + calc(2, 256)", "end): calc = lambda n, m: (int(end.split(\".\")[n]) - int(start.split(\".\")[n])) * m return calc(0,", "* m return calc(0, 256 * 256 * 256) + calc(1, 256 *",...
[ "'adm3', 'adm_scale0', 'adm_scale1', 'adm_scale2', 'adm_scale3', ] ADM2_CONSTANT = 0 ADM_SCALE_CONSTANT = 0 def", "the log file. quality_w, quality_h = asset.quality_width_height ref_scores_mtx = None with YuvReader(filepath=asset.ref_workfile_path, width=quality_w,", "log_file_path = self._get_log_file_path(as...
[]
[ "from dao.models import PanAccounts from cfg import PAN_SERVICE, MASTER_ACCOUNT_ID class BaseService: def __init__(self):", "import PanAccounts from cfg import PAN_SERVICE, MASTER_ACCOUNT_ID class BaseService: def __init__(self): self.default_tz =", "from dao.dao import DataDao import pytz from dao.models impor...
[ "equal d_k self.d_k = d_model // nhead self.nhead = nhead self.linear_layers = nn.ModuleList([nn.Linear(d_model,", "for _ in range(3)]) self.output_linear = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(p=dropout) def forward(self,", "projections in batch from d_model => h x d_k query, key, value =", ...
[ "\"pns\", system, pn) \"\"\" READ FILES AND CONVERT TO XES \"\"\" traces =", "\"naive\": print(\"**** \", str(system), \" Job \", str(job), \" on PN \", str(pn_file),", "FILES AND CONVERT TO XES \"\"\" traces = readFile(train_file,gen_file, unique=True) convertToCsv(traces=traces, to_path=csv_file) time.sleep(1...
[ "cdll lib = cdll.LoadLibrary(\"../target/release/libembed.dylib\") #=> for Mac #lib = cdll.LoadLibrary(\"../target/release/libembed.so\") #=> for Linux", "lib = cdll.LoadLibrary(\"../target/release/libembed.dylib\") #=> for Mac #lib = cdll.LoadLibrary(\"../target/release/libembed.so\") #=> for Linux lib.process()...
[ "} def __init__(self): super(ImageClient, self).__init__() self.model_package = importlib.import_module(\"huaweicloudsdkimage.v1.model\") self.preset_headers = {'User-Agent': 'HuaweiCloud-SDK-Python'} @classmethod", "request): \"\"\"名人识别 分析并识别图片中包含的政治人物、明星及网红人物,返回人物信息及人脸坐标。 :param RunCelebrityRecognitionRequest r...
[ "- 1, 'Dual Certificate Value'] return abs(abs(value) - 1) else: raise ValueError('Stopping strategy", "None: new_positions = np.hstack([self.old_iterand['positions'], self.new_ind]) if self.step_size == 'optimal': gamma = np.dot(self.data_fidelity.gradient(iterand), iterand)", "Function']) / \\ self.diagnostic...
[ "for s,p,o in g1.triples((None, None, None)): g.addN([(s,p,o,g1)]) for s,p,o in g2.triples((None, None, None)):", "class TestTrixSerialize(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testSerialize(self): s1 = URIRef('store:1')", "r1 = URIRef('resource:1') r2 = URIRef('resource:2') lab...
[ "= dbupgrade.DBUpgradeTools('projectdata', drop=True) if __name__ == \"__main__\": updatelib_inst = updatelib.UpdateLib(project_dbupgrade) checkout_version = raw_input('Revert", "example, 2.1 -->') if checkout_version != 'trunk': try: map((lambda x:int(x)),checkout_version.split('.')[:2]) except: print \"valid", ...
[ "= prepare_data(data_set_path) retain_reg = LogisticRegression( C=C_param, penalty='l1', solver='liblinear', fit_intercept=True) retain_reg.fit(X, y) c_ext =", "from sklearn.linear_model import LogisticRegression from fightchurn.listings.chap8.listing_8_2_logistic_regression import prepare_data, save_regression_m...
[ "# clustering = ClassicalClustering(cfg.get('clustering')['classical']) clustering.load() #%% [markdown] # ## Visualisation des clusters #%%", "plt.figure(1, figsize=(12, 7)) plt.scatter(clustering.pca_reduction[:, 0], clustering.pca_reduction[:, 1], c = clustering.kmeans_labels) #%% [markdown] #", "images #%% ...
[ "except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(log_folder):", ">2.5 if exc.errno == errno.EEXIST and os.path.isdir(log_folder): pass else: raise # setup configuration", "'%(message).180s', datefmt='%Y-%m-%d %H:%M:%S') format_error = \\ logging.Formatter( '%(asctime)s %(leve...
[ "np.sqrt(np.mean((oos_ice.mean(axis=1) -true_ATE)**2)) < rmse_tolerance def test_model_pred_oos_shapes(self): num_obs = 1000 y, x, t =", "np.ones(num_obs_2).reshape(-1, 1)], axis=1) assert np.mean(test_1 == test_1_values) == 1 assert np.mean(test_2 == test_2_values)", "y.shape[1]) assert uplift_model.predict_ic...
[ "== 1 self.assertEqual(y0, 1) x1 = 100 y1 = increment(x1) #y1 == 101", "#TODO \"\"\" def test_increment(self): x0 = 0 y0 = increment(x0) #y0 == 1", "increment class ExampleTest(unittest.TestCase): \"\"\" #TODO \"\"\" def test_increment(self): x0 = 0 y0 =", "ExampleTest(unittest.TestCase): \"\"\" #TODO \"\"\" ...
[ "else: first_user_form = None auth_form = AuthenticationForm() if DEMO_ENABLED.get() and not 'admin' in", "= False userprofile.last_activity = datetime.now() userprofile.save() msg = 'Successful login for user: %s'", "KIND, either express or implied. # See the License for the specific language", "Unless requi...
[ "name self.follow_list = follow_list self.intention = intention self.lane = lane def __eq__(self, other):", "def get_name(self): return self.name def set_name(self, name): self.name = name def get_follow_list(self): return", "follow_list def get_intention(self): return self.intention def set_intention(self, int...
[ "sheet else: args['gid'] = gid params = parse.urlencode(args) return parse.urlunparse( (parts.scheme, parts.netloc, path,", "from collections import OrderedDict from moz_sql_parser import parse as parse_sql import pyparsing import", "'headers' in qs: headers = int(qs['headers'][-1]) if 'gid' in qs: gid = qs['gi...
[ "= [xs, ys, (xs + w), (ys + h)] return torch.stack(b, dim=-1) def", "[] iscrowd = [] area = [] for ann in segments: if len(ann[\"bbox\"])", "torch.tensor(boxes, dtype=torch.int64) labels = torch.tensor(labels, dtype=torch.int64) iscrowd = torch.tensor(iscrowd) area = torch.tensor(area) boxes", "labels = [] is...
[ "return index if array[index] == item: return index else: return linear_search_recursive(array, item, index", "middle - 1 return None def binary_search_recursive(array, item, left=None, right=None): \"\"\"Time Complexity: O(log*n)", "- 1 middle = left + (right - left) // 2 if left", "+ (right - left) // 2 if ...
[ "c): cursor.execute('''SELECT concept, location FROM memory WHERE concept =?''', (c,)) user = cursor.fetchone()", "# Robbie memory class. Collection of concepts class memoryClass(): def __init__(self): self.concepts =", "Collection of concepts class memoryClass(): def __init__(self): self.concepts = {} self.per...
[ "array input and out-of-range colors. The second subplot illustrates the use of BoundaryNorm", "0.0) # to make the bad region transparent. This is the default. #", "# to make the bad region transparent. This is the default. # If", "difference of Gaussians # Set up a colormap: palette = cm.gray palette.set_ove...
[ "Field from typing import List, Dict from datetime import datetime class Authenticate(BaseModel): access_token:", "validator, Field from typing import List, Dict from datetime import datetime class Authenticate(BaseModel):", "from pydantic import BaseModel, validator, Field from typing import List, Dict from da...
[ "message.channel.typing(): chosen_sub = random.choice(self.subreddits) r = requests.get(f\"https://api.reddit.com/r/{chosen_sub}/top.json?sort=top&t=day&limit=500\", headers={'User-agent': 'Super Bot 9000'}) r =", "random.choice(self.subreddits) r = requests.get(f\"https://api.reddit.com/r/{chosen_sub}/top.json?s...
[ "# Get Registry MultiSZ multi_sz = cli.get_reg_multi_sz(r'HKLM:\\SYSTEM\\CurrentControlSet\\control\\SecurePipeServers\\winreg\\allowedExactPaths', 'Machine') # Output Lines self.output =", "rec_multi_sz.lower(): self.is_compliant = False return self.is_compliant def fix(self, cli): cli.powershell(r\"New-Item -pa...
[ "<reponame>dzzhvks94vd2/mikan class MikanException(Exception): \"\"\"Generic Mikan exception\"\"\" class ConversionError(MikanException, ValueError): \"\"\"Cannot convert a string\"\"\"" ]
[ "auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.Passwor...
[ "relative_to=CONF_RELATIVE, version=None): conf = get_local_path(host, container, conf_path, version) return generate_edit_link(conf) def show_local_conf_diff(host, container,", "version=None): if version is None: version = find_latest_version(host, container, conf_path) return generate_local_path(host, conf_path...
[ "for substitutions. Resource: https://en.wikipedia.org/wiki/Edit_distance For example, getting from \"intention\" to \"execution\" is a", "m+1): D[0,j] = j for i in range(1, n+1): for j in range(1,", "For example, getting from \"intention\" to \"execution\" is a cost of 8. minimum_edit_distance(\"intention\",",...
[ "[] vcf_records[new_record.CHROM].append(new_record) for vcf_list in vcf_records.values(): vcf_list.sort(key=attrgetter(\"POS\")) with open(outfile, \"w\") as f: print(\"##fileformat=VCFv4.2\",", "new_record = vcf_record.VcfRecord( \"\\t\".join( [ variant.qry_name, str(variant.qry_start), \".\", query_seqs[varian...
[ "import asdict, dataclass from typing import Any, Dict, List, Type @dataclass(frozen=True) class StatsBaseModel:", "[ 'Pull requests:', '--------------', 'Open Closed Old', f'{str(self.open_count).ljust(8)}{str(self.closed_count).ljust(8)}{str(self.old_count).ljust(8)}' ] @dataclass(frozen=True) class IssueStats(...
[ "end(self): end_datetime = get_end(self.filter_args.get(\"end\")) if not end_datetime: return None if _has_no_time_info(end_datetime): end_datetime =", "datetime.datetime.min.replace(tzinfo=pytz.utc) max_datetime = datetime.datetime.max.replace(tzinfo=pytz.utc) def get_start(start_date_str): if not start_date_str...
[ "= len(featmap_sizes) multi_level_anchors = [] for i in range(num_levels): anchors = anchor_generators[i].grid_anchors(featmap_sizes[i], self.anchor_strides[i])", "super(RpnLossInput, self).__init__() def forward(self, x): \"\"\"Get cls score.\"\"\" cls_scores = x[2][0] bbox_preds =", "label.float(), weight, re...