anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
def _get_action(self):
return self.__action | Getter method for action, mapped from YANG variable /input/mapping_record/action (enumeration) |
def days_since_last_checkin(self):
# TODO use local timezone
checkin_date = (self.last_checkin - datetime.timedelta(hours=5)).date()
today = datetime.date.today()
return (today - checkin_date).days | The number of full days since last checkin. We consider the current day to start from 5AM local time. Note that this can be more than 24 hours ago! |
def clone(self) -> "set_default":
return type(self)(self.value) | Create a clone of the sentinel. |
def student_view(self, context=None): # pylint: disable=W0613
# Load the HTML fragment from within the package and fill in the template
html_str = pkg_resources.resource_string(__name__,
"static/html/thumbs.html").decode('utf-8')
frag = Fragment... | Create a fragment used to display the XBlock to a student. `context` is a dictionary used to configure the display (unused) Returns a `Fragment` object specifying the HTML, CSS, and JavaScript to display. |
def level_time_average(start_levels, attack_style, attack_bonus, strength_bonus):
ticks_per_attack = 4 # Scimitar attack speed
max_hit, accuracy = get_max_hit_and_accuracy(
start_levels, attack_style, attack_bonus, strength_bonus)
if attack_style == Attack_Style.ATTACK:
start_exp = osrs... | Uses average damage to determine time (ticks) to level up attack or strength Enemy has 1 def and 0 def bonus Weapon is best available scimitar |
def run(sc, logger):
start = time.time()
# Spark SQL Context
sqlContext = sql.context.SQLContext(sc)
# 1) Practices - Small table so no need to partition it, could even broadcast across all executors
# Spark SQL JDBC Options: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html
prac... | Run spark job that will associate vendor's users (loaded from REST API) with our users (loaded from MySQL) |
def get_token(client_id, client_secret, username, password):
try:
if oauth2db.check_client(client_id, client_secret):
if oauth2db.check_user(username, password):
token, refresh = oauth2db.generate_token(client_id, username)
res = { "token": token }
excep... | Returns an OAuth2 authorization token or None in case of errors. This is the flow for nonweb clients. |
def tranBelong(tr, lst, t):
if tr.isReal():
cp = Trade()
cp.state = tr.state
cp.addTrans(tr.tranCol+lst, False)
else:
cp = tr
return cp.belong(t) | Determine if the transaction(t) belongs to trade(tr) without altering the tr |
def sequence_ingest(self,sequence):
data=self.data
counter=0
for item in data[sequence]:
datestring=item['specimenDate']
date=fetchdate(datestring)
row,created=DailyCases.objects.get_or_create(specimenDate=date,areacode=item['areaCode'])
row.areaname=item['areaName']
row.dailyLabConfirmedCases=... | ingest from a particular sequence |
def test_NaNall(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(
float('nan'), float('nan'), float('nan'), float('nan'))
self.assertEqual(str(e.exception), 'width must be an integer') | This function tests for all NaN values |
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request),
'groups': reverse('group-list', request=request),
'pools': reverse('pool-list', request=request),
}) | The entry endpoint of our API. |
def _bundle_from_response(data):
return Bundle(
uuid=UUID(data['uuid']),
title=data['title'],
description=data['description'],
slug=data['slug'],
# drafts: Convert from a dict of URLs to a dict of UUIDs:
drafts={draft_name: UUID(url.split('/')[-1]) for (draft_name, ur... | Given data about a Bundle returned by any blockstore REST API, convert it to a Bundle instance. |
def validate_n_digits_range(min_val: int, max_val: int, n: int = 4) -> bool:
def func(s: str):
return validate_n_digits(n)(s) and min_val <= int(s) <= max_val
return func | >>> validate_n_digits_range(1920, 2002)("2002") True >>> validate_n_digits_range(1920, 2002)("2003") False |
def token_required(func):
def func_wrapper(self, *args, **kwargs):
auth_token = self.request.headers.get('X-Auth-Token',
self.request.get('token', ''))
namespace = self.request.route_kwargs.get('namespace', '')
try:
token = base64.url... | Secures handlers with auth token taken from ndb |
def change(self, num):
if self.manhattan(self[0], self[num]) != 1:
raise RuntimeError(
"Numbers {} {} in positions {} {} can't change".format(0, num, self[0], self[num]))
z_i, z_j = self[0]
n_i, n_j = self[num]
self.pos_to_num[(z_i, z_j)] = num
self.... | function which change cells |
def optional(self) -> Optional[bool]:
return pulumi.get(self, "optional") | Specify whether the Secret or its key must be defined |
def create_ngram_set(self, input_list, ngram_value=2):
return set(zip(*[input_list[i:] for i in range(ngram_value)])) | Extract a set of ngrams from a list of integers. create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] |
def preprocess_dataset(dataset_path, SAMPLES_TO_CONSIDER: int, num_mfcc = 13, n_fft = 2048, hop_length = 512):
data = {
'mapping': [],
'labels': [],
'MFCCs': [],
'files': []
}
# loop through all sub-dirs
total_samples = 0
valid_samples = 0
for i, (di... | Extracts MFCCs from music dataset and saves them into a json file. |
def non_param_paired_ci(sample1, sample2, alpha):
n = len(sample1)
N = norm.ppf(1 - alpha/2)
diff_sample = sorted(list(map(operator.sub, sample2, sample1)))
averages = sorted([(s1+s2)/2 for i, s1 in enumerate(diff_sample)
for _, s2 in enumerate(diff_sample[i:])]... | Confidence interval for differences between the two samples. |
def get_release_files(tag_name, config) -> Tuple[List[ReleaseFile], Dict[str, SourceFile]]:
@retry_multi(5) # retry at most 5 times
def execute_request(path):
"""!
@brief Performs a GET request with the given path. To be used with Github's REST API.
@returns If successful, returns a .JS... | ! Brief Gets the binary and source files from the Github Release server [in] `tag_name` Git tag of the current release [in] `config` confi metadata set in main.py `List[ReleaseFile]` List of release files `Dict[str, SourceFile]` Dictionary of source files Sends an `HTTP GET` request to github using their REST API to re... |
def mfk(inp, db=None):
db_init(db)
inp = inp.lower()
m_regex = re.compile(r"marry\s([a-zA-Z0-9_]+\s|[a-zA-Z0-9_]+)").finditer(inp)
f_regex = re.compile(r"fuck\s([a-zA-Z0-9_]+\s|[a-zA-Z0-9_]+)").finditer(inp)
k_regex = re.compile(r"kill\s([a-zA-Z0-9_]+|[a-zA-Z0-9_]+\s)").finditer(inp)
if inp... | .mfk play Begin the game ||| [+/] Edit the mfk user list ||| marry fuck kill Give the verdict ||| score Retrieves the score of a user |
def __init__(self, numcols):
# Start by making a root cell
# This isn't part of the matrix, but it gives an entry point to the matrix
# root.right is the first column header, root.left is the last
# root.up and root.down just wrap around to itself
root = Column("root")
se... | Initialize the dancling links matrix with a given number of columns |
def get_pressurexlsb(self):
byte_list = self.i2c.readfrom_mem(
self.device_address,
self.REGISTER_PRESSUREXLSB,
1,
addrsize=8
)
val = 0
val = val << 8 | byte_list[0]
return val | Part 3 of Pressure |
def test_decrypt_key_default(self, settings):
settings.CHITON_ENCRYPTION_KEY = b'0' * 32
encrypted = encrypt('message')
assert decrypt(encrypted) == 'message'
settings.CHITON_ENCRYPTION_KEY = b'1' * 32
with pytest.raises(EncryptionError):
decrypt(encrypted) | It gets its default key from settings. |
def rectangle_circumference(a,b):
return (2*(a+b)) | Calculates total circumferences of a rectangle |
def do_POST(self):
self.do_GET() | emulate post request with get handler, we don't need the data |
def truncate(self):
self.population = self.population[:self.max_number_trees] | Truncates forest to maximum number of trees. |
def read_prn(file_name):
with open(file_name) as f:
f = MyIter(f)
try:
assert next(f).strip() == 'prn:13|'
assert next(f).strip() == 'subtype = MT2500'
assert next(f).strip() == 'Doc={MT2500:14|'
assert next(f).strip() == 'Film={12.1|'
fi... | Read a prn file. |
def get_leader_model_pdf(currentEmpl, employees):
lm = LeaderModel()
employee_actions = {}
legend = []
colors = {}
errors = {'noactions': []}
# numbered_actions = {}
for empl in employees:
if not currentEmpl.hasAccessTo(empl):
raise PermissionDenied()
actions ... | Create LeaderModel and send it as a PDF to the browser |
def __init__(self,db):
self._numFeatures = len(db.keys)
self._numEntries = len(db.entries)
numMissing = 0
if isinstance(db.entries[0],dict):
#already sparse database given as input
self.featureMatrix = None
self.featureDicts = [{} for i in range(self._... | Given a normal feature matrix, creates a transpose feature matrix, a list of discrete features, and a list of nonempty features for each id. If the dataset is dense, this uses a Numpy matrix to save on space. Otherwise, it uses a listofdicts structure. |
def pause_writing(self):
self._stream.pause_writing() | Pause writing callback from transport. |
def parent(self, n):
return None if n == 0 else (n - 1) // 2 | Returns parent of node at n; None if there isn't a parent |
def _verify_cas1(ticket, service):
params = {'ticket': ticket, 'service': service}
url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
urlencode(params))
page = urlopen(url)
try:
verified = page.readline().strip()
if verified == 'yes':
return page.readline(... | Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. |
def test_dimension_size_override(self, nt=100):
i, j, k = dimify('i j k')
a = TimeData(name='a', dimensions=(i, j, k))
one = symbol(name='one', dimensions=(i, j, k), value=1.)
op = Operator(Eq(a.forward, a + one))
# Test dimension override via the buffered dimenions
a.da... | Test explicit overrides for the leading time dimension |
def toconic(self):
res = __library__.MSK_XX_toconic(self.__nativep)
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg) | Inplace reformulation of a QCQP to a COP toconic(self) |
def sample3d(f, x_args, y_args):
x, x_min, x_max, x_n = None, None, None, None
y, y_min, y_max, y_n = None, None, None, None
try:
f = sympify(f)
except SympifyError:
raise ValueError("f could not be interpreted as a SymPy function")
try:
x, x_min, x_max, x_n = x_args
... | r""" Samples a 3d function f over specified intervals and returns three 2d arrays (X, Y, Z) suitable for plotting with matlab (matplotlib) syntax. See examples\mplot3d.py. f is a function of two variables, such as x2 + y2. x_args and y_args are intervals given in the form (var, min, max, n) |
def create_prod_git_repo(git_repo_name):
with cd(git_dir):
run("git init --bare %s.git && cd %s.git && git config http.receivepack true" %
(git_repo_name,git_repo_name)) | Creates a new git repo on the server (do not include the .git ending in git_repo_name) |
def traj_nslice (u,teq,tsample) :
# get the number of frames in the slice (http://stackoverflow.com/a/7223557)
traj_slice = u.trajectory[teq::tsample]
return sum(1 for _ in traj_slice) | Returns the number of frames in the trajectory in universe u, using teq as equilibration time and tsample as sampling time |
def find_approx(self, gamma):
if self.jumps != []:
# first we divide the jumps of the BSS into subarrays in each of which the subsequent jumps are closer to each other than \gamma
jump_seq_list = identify_jump_subseq(self.jumps, gamma)
# jumps will store all jumps of the proj... | Returns the projection of the BinaryStateSequences using DAG functionality |
def cam_to_world(cam_point, world_to_cam):
# cam_point = np.array([cam_pose[0], cam_pose[1], cam_pose[2]])
obj_vector = np.concatenate((cam_point, np.ones(1))).reshape((4, 1))
world_point = np.dot(world_to_cam, obj_vector)
world_point = [p[0] for p in world_point]
return world_point[0:3] | Convert from camera_frame to world_frame |
def describe_backup_dbs(
self,
request: dds_20151201_models.DescribeBackupDBsRequest,
) -> dds_20151201_models.DescribeBackupDBsResponse:
runtime = util_models.RuntimeOptions()
return self.describe_backup_dbs_with_options(request, runtime) | Precautions You can call the [CreateDBInstance](~~61763~~) operation to restore a database for an ApsaraDB for MongoDB instance. For more information, see [Restore one or more databases of an ApsaraDB for MongoDB instance](~~112274~~). |
def eval_model(device, model, sampler, loss_compute, logit_modifier_fxn, token_sampler,
print_every, max_len, user_items_df, max_name_len=15, ingr_map=None,
base_save_dir='', pad_ingr=None, ppx_only=False, **tensor_kwargs):
start = datetime.now()
results_dicts = []
# Extract ... | Run a single epoch |
def update_commitments(commitment=None, external_to_remove=None,
external_to_add=None):
c = {}
if os.path.isfile(PODLE_COMMIT_FILE):
with open(PODLE_COMMIT_FILE, "rb") as f:
try:
c = json.loads(f.read())
except ValueError:
pr... | Optionally add the commitment commitment to the list of 'used', and optionally remove the available external commitment whose key value is the utxo in external_to_remove, persist updated entries to disk. |
def unpack(run=0, seqno=0, iraw=0):
if iraw == 0 and run == 0:
print("Usage: osgprod_bind.unpack(iraw=<iraw>)")
print(" or: osgprod_bind.unpack(run=<run>, seqno=<seqno>)")
return 0
if iraw:
with db_connection() as conn:
with conn.cursor() as curs:
curs.execute("""SEL... | Looks up rawdata id iraw and unpacks the job output tarballs from all jobs that completed successfully into a new directory named iraw under the pwd. If iraw is not known, alternatively one can supply the run number and sequence number of the raw data input file. |
def init_column_headers(self):
col_headers = {1: "bid", 2: "tricks", 3: "score"}
for player in range(1, 5):
ent_player_name = tk.Entry(self.master, font='courier 10 bold', fg='blue',
borderwidth=2, relief="groove")
ent_player_name.grid(... | player names and bid / trick / score headers |
def run_all():
db = DBInterface()
year = Config.get_property("league_year")
session = Session(bind=db.engine)
scraper.scrape_all(db, session, year)
session.commit()
bets.predict_all(db, session)
session.commit()
session.close() | Run the entire NBA_bet project. |
def intersection(line1, line2):
rho1, theta1 = line1
rho2, theta2 = line2
A = np.array([
[np.cos(theta1), np.sin(theta1)],
[np.cos(theta2), np.sin(theta2)]
])
b = np.array([[rho1], [rho2]])
x0, y0 = np.linalg.solve(A, b)
x0, y0 = int(np.round(x0)), int(np.round(y0))
retur... | Finds the intersection of two lines given in Hesse normal form. Returns closest integer pixel locations. |
def event_hub_connection_string(self) -> Optional[str]:
return pulumi.get(self, "event_hub_connection_string") | (Personalization Only) The flag to enable statistics of Bing Search. |
def replay(method: Callable) -> None:
counter_key = method.__qualname__
i_keys = method.__qualname__ + ':inputs'
o_keys = method.__qualname__ + ':outputs'
this = method.__self__
counter = this.get_str(counter_key)
history = list(zip(this.get_list(i_keys),
this.get_list(o_... | Ouput log of actions taken on method |
def get_ytm_discount_data(self):
ytm=Bootstrapping.get_ytm_dict(self)
data = pd.DataFrame()
for i in ytm.keys():
data.loc[i / 2, 'Yield to maturity'] = ytm[i]
data.loc[i / 2, 'discount_rate'] = Bootstrapping.P_Tn(self,ytm[i], i)
return data | This funtion is to get the dataframe of yield to maturity and discount rate value. |
def start(self) -> None:
cb = self._callback
if cb is not None:
self._callback = None
propagate(from_=ensure_future(cb()), to=self._future) | Actually invoke the underlying function (but only if it hasn't been invoked already). |
def get_rest_list(request):
if request.method == "GET":
rest_list = Package.objects.order_by('-location')
serializer = PackageSerializer(rest_list, many=True)
return JsonResponse(serializer.data, safe=False) | Returns Json list of all Packages |
def set_logger(save=False, log_path=None):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if not logger.handlers:
if save:
# Logging to a file
file_handler = logging.FileHandler(log_path)
file_handler.setFormatter(logging.Formatter('%(asctime)s:%(leve... | Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`. |
def choose_mi_best(self, R):
population = np.empty([self.P.shape[0] + R.shape[0], 2*self.d + 1])
i = 0
for individual in np.vstack([self.P, R]):
population[i, 0] = -self.J(individual[0:self.d], self.nCEC)
population[i, 1:] = individual
i = i+1
sorted_... | Method creates new population by choosing mi best individuals from children and current population |
def inner_product(pattern_one, pattern_two):
return np.sum(np.multiply(pattern_one, pattern_two)) | Calculate the inner product of the two patterns as a vecter. |
def list_of_medias(args, sourcedir, recursive):
files = list_of_files(sourcedir, recursive)
return [_ for _ in files if is_media_within_dates(_, args.dates)] | Return the list of full paths for pictures and movies in source directory |
def classify(self, verbose=True, print_scores=False):
if verbose:
print("%s: Training model ..." % self.clf_name)
self.clf.fit(self.X_train, self.y_train)
if verbose:
print("%s: Calculating probablities ... " % self.clf_name)
y_proba = self.clf.predict_proba(self... | Conduct classification and calculate metrics |
def mptcp_connections(self, pkts):
count = 0
#MPTCP_Capable = 0x0
#MPTCP_CapableACK ---> successful handshake
print "======================================================================"
print "Successful Handshake --- Look for Ack packets with MPTCP option Header"
print """Token = connectionID = SHA1(key... | Identify distinct MPTCP Connections that reached Successful handshake Look for Ack packets with MPTCP option Header For each MPTCP connection report Receiver's token value which acts as the connectionID |
def _logits_to_predictions(self, logits):
key = prediction_key.PredictionKey.SCORES
with ops.name_scope(None, "predictions", (logits,)):
if self.logits_dimension == 1:
logits = array_ops.squeeze(logits, squeeze_dims=(1,), name=key)
return {key: logits} | Returns a dict of predictions. |
def import_outcome_group_global(request_ctx, id, source_outcome_group_id, **request_kwargs):
path = '/v1/global/outcome_groups/{id}/import'
payload = {
'source_outcome_group_id' : source_outcome_group_id,
}
url = request_ctx.base_api_url + path.format(id=id)
response = client.post(request_c... | Creates a new subgroup of the outcome group with the same title and description as the source group, then creates links in that new subgroup to the same outcomes that are linked in the source group. Recurses on the subgroups of the source group, importing them each in turn into the new subgroup. Allows you to copy orga... |
def _get_weight(self):
return self.__weight | Getter method for weight, mapped from YANG variable /input/LocatorRecord/weight (uint8) |
def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = pr... | First Python implementation method of the Levenshtein distance between strings |
def find_mle_by_grad_descent(initial_sensor_loc,
obj_loc, distance, lr=0.001, num_iters = 1000):
sensor_loc = initial_sensor_loc
# Your code: finish the gradient descent
return sensor_loc | Compute the gradient of the loglikelihood function for part f. |
def save_config_file(self):
with open(self.config_file_name, 'w',encoding='utf-8') as outfile:
json.dump(self._config, outfile,indent=2) | Saves the config file |
def DeleteSetting(appname, section, key):
settings = _OptionsDB(appname)
settings.delete(section, key) | Delete a setting in the central setting file |
def rSeqFile(FilePath):
f=open(FilePath, 'r')
#check if file open
if f.mode == 'r':
return(f.read()) | Read file returns read file as string |
def remove_stop_words(tokens, language):
if not remove_stop_words_activated or language.__eq__("Catalan"):
return tokens
output = []
stop = stopwords.words(language.lower())
for token in tokens:
if token not in stop:
output.append(token)
return output | Method to remove the stop words used in get_left_right_lists() This method does not work for Catalan language. |
def num_accepts_ge(self, max_len: int, bound: Sequence[Text] = ()) -> int:
_, num_accepted_eq, num_accepted_gt = self.num_accepts(max_len, bound)
return num_accepted_eq + num_accepted_gt | Returns the number of sequences >= bound with len() <= max_len accepted by this NFA. |
def test_06_dt_to_milliseconds_str(self):
dt = datetime.datetime.utcnow()
ts = utils.dt_to_milliseconds_str(dt)
self.assertIsInstance(ts, str) | Should return Python datetime object. |
def nullHeuristic(state, problem=None):
return 0 | A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. |
def rearrange_digits(input_list):
## Corner cases:
if len(input_list) == 0:
return [0, 0]
elif len(input_list) == 1:
return [input_list[0], 0]
# Sort an array using merge-sort
sorted_list = merge_sort(input_list)
# Create two empty array and pop largest number from an sorted_li... | Rearrange Array Elements so as to form two number such that their sum is maximum. |
def __init__(self, *args, **kwargs):
self.jsonp_callback = kwargs.pop('jsonp_callback', None)
super(JsonResponse, self).__init__(*args, **kwargs) | Supports an additional argument ``jsonp_callback``. If specified, the JSON serialized data string will be wrapped in parenthesis and prefixed by the value of ``jsonp_callback``. |
def plot_image_and_proj(image, title="", **kwargs):
fig = plt.figure()
gs = gridspec.GridSpec(3, 2, width_ratios=[3, 1], height_ratios=[0.2, 3, 1])
ax0 = plt.subplot(gs[1,0])
plt.title(title)
ims = plt.imshow(image, aspect="auto", **kwargs)
ax2 = plt.subplot(gs[2,0], sharex=ax0, )
plt.... | Plots an image and the projections (sums) of it on the x, y axes. |
def info(self, message):
if self.show_info:
print(message) | Print a message to the standard output, in case show_info is enabled. |
def _getCoordsFromRun(self, run_dict, bold=False):
run_dict = copy.deepcopy(run_dict)
run_dict = self._filterDictionaryBold(run_dict, bold=bold)
timeDictKey = ""
if "t" in run_dict:
timeDictKey = "t"
else:
for k in run_dict:
if k.startswith... | Find coordinates of a single run time, output and space dimensions. |
to check if the user is the owner of the lock. | def owner?(obj)
(self.id == RedisMutexer.config.redis.get(key(obj)).to_i)
end |
GET /spaceships/new GET /spaceships/new.json | def new
@spaceship = Spaceship.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @spaceship }
end
end |
Time complexity O(1) Space complexity O(1) | def get_first
return @head if @head.nil?
return @head.data
end |
:nodoc: Creates a new InstallerSet that will look for gems in +domain+. | def initialize(domain)
super()
@domain = domain
@f = Gem::SpecFetcher.fetcher
@always_install = []
@ignore_dependencies = false
@ignore_installed = false
@local = {}
@local_source = Gem::Source::Local.new
@remote_set = Gem::Resolver::BestSet.n... |
To render with the distance to | def setOrigin(origin)
@origin = origin
end |
POST /frontapp_support_sources POST /frontapp_support_sources.json | def create
@support_source = FrontappSupportSource.new(frontapp_support_source_params)
respond_to do |format|
if @support_source.save
format.html { redirect_to support_sources_path,
notice: 'Support source was successfully created.' }
format.json { render :show, status: :created... |
HELPER METHODS =========================================== The two drivers have slightly different ways of yielding hashes of results, so this method must be implemented to provide a uniform interface. | def each_hash(result) # :nodoc:
raise NotImplementedError
end |
get article table data from ga | def get_article_data(yesterday, view_id, domain_id, article_key)
date_range = @analytics::DateRange.new(start_date: yesterday, end_date: yesterday)
order_by = @analytics::OrderBy.new(field_name: 'ga:pageviews', sort_order: 'DESCENDING')
metric = @analytics::Metric.new(expression: 'ga:pageviews')
dimensions ... |
Checks that dependencies use requirements as we recommend. Warnings are issued when dependencies are openended or overly strict for semantic versioning. | def validate_dependencies # :nodoc:
warning_messages = []
@specification.dependencies.each do |dep|
prerelease_dep = dep.requirements_list.any? do |req|
Gem::Requirement.new(req).prerelease?
end
warning_messages << "prerelease dependency on #{dep} is not recommended" if
prer... |
Returns the name of the current directory. | def pwd
Dir.pwd
end |
sets the next unbonded node in nodes to node | def next=(node)
# you can only bond if it has unbonded sites
if !full?
nodes.each_index { |i|
if nodes.at(i) == nil
nodes[i] = node
break
end
}
return node
# unless it expands, in which case you can bond
elsif expands?
nodes << node
puts nodes
nodes.flatten!
... |
Subject can be set in your I18n file at config/locales/en.yml with the following lookup: en.user_mailer.password_reset.subject | def password_reset(user)
@user = user
@hostname = "http://creuroja.net"
@reset_password_link = "#{@hostname}#{edit_password_reset_path(@user.resettoken)}"
mail(to: @user.email, subject: 'Recuperació de contrasenya de Creu Roja a Catalunya')
end |
PATCH/PUT /organizations/1 PATCH/PUT /organizations/1.json | def update
respond_to do |format|
if @organization.update(organization_params)
format.html { redirect_to edit_admin_organization_path(@organization), notice: 'Organization was successfully updated.' }
format.json { head :no_content }
else
flash[:error] = "#{@organization.errors.f... |
Prepare the aggregation function for a model class and a field | def prepare(model, field_name = nil)
@model = model
@selection = Babik::Selection::Path::Factory.build(model, @aggregation_path)
@field_name = field_name || "#{self.table_alias}__#{SQL_OPERATION.downcase}"
self
end |
Set a term that is included for every chef_search call. | def chef_scope(field, term="*")
scopes = fetch(:chef_scopes) || []
scopes.delete_if { |scope| scope =~ /chef_environment/ }
set :chef_scopes, scopes << [field, term].join(":")
end |
forget user in persistent session | def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end |
POST /accession_location_entries POST /accession_location_entries.json | def create
@accession_location_entry = AccessionLocationEntry.new(params[:accession_location_entry])
respond_to do |format|
if @accession_location_entry.save
format.html { redirect_to @accession_location_entry, notice: 'Accession location entry was successfully created.' }
format.json { r... |
Constrain the distance between bob and anchor between min and max | def constrain_length(bob, minlen, maxlen)
dir = bob.location - @anchor
d = dir.mag
# Is it too short?
if d < minlen
dir.normalize!
dir *= minlen
# Reset location and stop from moving (not realistic physics)
bob.location = @anchor + dir
bob.velocity *= 0
elsif d > maxlen... |
Write a method that takes a positive integer, n, as an argument, and displays a right triangle whose sides each have n stars. The hypotenuse of the triangle (the diagonal side in the images below) should have one end at the lowerleft of the triangle, and the other end at the upperright. | def triangle(num)
spaces = num - 1
stars = 1
loop do
puts " "*spaces + "*"*stars
break if stars == num
spaces -= 1
stars += 1
end
end |
This method does the actual permalink escaping. | def escape(string)
result = ((translation_to && translation_from) ? Iconv.iconv(translation_to, translation_from, string) : string).to_s
result.gsub!(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics).
result.gsub!(/[^\w_ \-]+/i, '') # Remove unwanted chars.
result.gsu... |
Only allow a list of trusted parameters through. | def foo38_params
params.require(:foo38).permit(:foo1, :foo2, :foo3, :foo4, :foo5)
end |
PUT /crossword_puzzles/1 PUT /crossword_puzzles/1.json | def update
@crossword_puzzle = CrosswordPuzzle.find(params[:id])
respond_to do |format|
if @crossword_puzzle.update_attributes(params[:crossword_puzzle])
format.html { redirect_to edit_crossword_puzzle_path(@crossword_puzzle), notice: 'Puzzle saved!' }
format.json { head :no_content }
... |
Return the missing translation placeholder | def missing_translation_placeholder field
evaluate_localization_option!(:placeholder, field)
end |
PATCH/PUT /discussions/1 PATCH/PUT /discussions/1.json DELETE /discussions/1 DELETE /discussions/1.json | def destroy
@discussion.destroy
flash[:success] = "Discussion was successfully deleted."
redirect_to discussions_path
end |
author ahmed jihad called to show answer view for questionnaires finds the selected questionnaire Args : | def answer_show
@questionnaire = Questionnaire.find(params[:id])
answer = @questionnaire.answer_questionnaires.build
render 'answer_show'
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.