text stringlengths 1 1.04M | language stringclasses 25 values |
|---|---|
NEW YORK -Stock indexes rose around the globe on Thursday, with the S&P 500 climbing more than 1% led by sharp gains in technology shares, while U. S. Treasury yields fell after a weaker-than-expected U. S. business activity reading.
The Philadelphia Federal Reserve Bank said its business activity index fell to 31. 5 from 50. 2 in April, its highest pace in nearly half a century. The reading was shy of economists' expectations of 43. 0, a Reuters poll found, and cast doubt on how fast the economy can continue to heat up.
Cryptocurrencies bounced back from their recent sharp drop, but were well off the day's highs by afternoon New York time, as U. S. regulators signaled greater oversight for the sector.
Bitcoin was most recently up about 8% at $40,035 after some of its prominent backers reiterated their support for the digital currency, having plummeted to 54% below its record high, hit just over a month ago.
Smaller rival ether gained about 14% to $2,782. On Wednesday, it fell 22. 8%, its biggest daily fall since March 2020.
Investors are also still digesting minutes from the Fed's meeting last month, which showed a number of officials thought that if the recovery holds up it might be appropriate to "begin discussing a plan for adjusting the pace of asset purchases. "
Other data on Thursday showed the number of Americans filing new claims for unemployment benefits dropped further below 500,000 last week, but jobless rolls swelled in early May, which could temper expectations for an acceleration in employment growth this month.
The S&P 500 technology index ended up 1. 9%.
The Dow Jones Industrial Average rose 188. 11 points, or 0. 55%, to 34,084. 15, the S&P 500 gained 43. 44 points, or 1. 06%, to 4,159. 12 and the Nasdaq Composite added 236. 00 points, or 1. 77%, to 13,535. 74.
The pan-European STOXX 600 index rose 1. 27% and MSCI's gauge of stocks across the globe gained 0. 95%.
The yield on benchmark 10-year Treasury notes fell 4. 3 basis points to 1. 640%.
Market expectations of a further rise in inflation would need evidence of the economy moving past full employment very, very rapidly, said Steven Ricchiuto, U. S. chief economist at Mizuho Securities USA LLC.
"We've probably already reached the peak level of economic activity, and that probably happened in March and April," Ricchiuto added.
In the foreign exchange market, the dollar lost ground and was hovering near multi-month lows.
Late in New York, the dollar index fell 0. 491%, with the euro down 0. 01% to $1. 2225.
The bounces in cryptocurrencies came after crypto backers such as Ark Invest's Cathie Wood and Tesla's Elon Musk indicated their support on Wednesday.
Concerns over tighter regulation in China and unease over the extent of leveraged positions in the cryptocurrency world had caused this week's big selloff.
Outages at several major trading platforms during the maelstrom, which also set ether tumbling nearly 50%, did little to inspire confidence.
SPACs - special purpose vehicles set up and listed to buy up other firms - experienced huge growth last year, as did the ARK innovation fund that focuses on tech companies.
Oil prices dropped more than 2% after diplomats said progress was made toward a deal to lift U. S. sanctions on Iran. Brent crude fell $1. 55, or 2. 3%, to settle at $65. 11 a barrel. West Texas Intermediate crude ended $1. 31, or 2. 1%, lower at $62. 05 a barrel. Both contracts fell around 3% in the previous session.
Spot gold was nearly flat. | english |
The probe is related to the purchase of 275 bigha land allegedly by the company in the Kolayat area in Bikaner. The probe agency had registered a criminal case of money laundering in 2016 on the basis of FIRs filed by the state police after the local tehsildar had made a complaint.
The Rajasthan high court on Thursday extended the interim protection from arrest to businessman Robert Vadra till January 28 in an alleged money laundering case related to a land scam in Bikaner.
On Monday, an application by the Enforcement Directorate (ED) was scheduled to be heard in the high court, where ED has sought the custodial interrogation of Vadra, but the court could not take up the case for hearing due to the paucity of time.
Vadra is the son-in-law of Congress president Sonia Gandhi. On January 21, 2019, the court asked Vadra, a partner in Sky Light Hospitality, and his mother Maureen Vadra, to appear before ED for questioning. The court of Justice Dr Pushpendra Singh Bhati has fixed January 28 as the next date of hearing in the case, and granted Vadra and his mother interim protection from arrest till then. ED has registered an enforcement case information report (ECIR) in the alleged Bikaner land scam. In connection with the case, on December 1, 2018, it summoned Sky Light Hospitality’s partners, including Robert Vadra, for questioning, but the firm on December 18, 2018 approached the Rajasthan HC against the ED move.
The probe is related to the purchase of 275 bigha land allegedly by the company in the Kolayat area in Bikaner. The probe agency had registered a criminal case of money laundering in 2016 on the basis of FIRs filed by the state police after the local tehsildar had made a complaint. | english |
{
"id": 56969,
"name": "Darwin win7 vs Firefox Fix",
"description": "This fixes the Firefox navigation, bookmark, and find toolbar height bug caused by the Darwin VS.\r\n\r\nSee theme here: http://nitnerolf.deviantart.com/gallery/#/d41xl7c",
"user": {
"id": 124991,
"name": "newscripter",
"email": "<PASSWORD>acted",
"paypal_email": null,
"homepage": null,
"about": null,
"license": null
},
"updated": "2011-11-26T22:28:54.000Z",
"weekly_install_count": 0,
"total_install_count": 138,
"rating": null,
"after_screenshot_name": "https://userstyles.org/style_screenshots/56969_after.png?r=1517184361",
"obsoleting_style_id": null,
"obsoleting_style_name": null,
"obsolete": 0,
"admin_delete_reason_id": null,
"obsoletion_message": null,
"screenshots": null,
"license": null,
"created": "2011-11-26T22:19:57.000Z",
"category": "app",
"raw_subcategory": "browser",
"subcategory": "browser",
"additional_info": null,
"style_tags": [],
"css": "@namespace url(http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul);\r\n\r\n/* Fix Navigation Toolbar height and align buttons */\r\n#nav-bar *{-moz-appearance:none!important;}\r\n\r\n/* Fix Find Toolbar height */\r\n#FindToolbar *{-moz-appearance:none!important;}\r\n\r\n/* Fix Bookmarks Toolbar height */\r\n#PersonalToolbar *{-moz-appearance:none!important;}",
"discussions": [],
"discussionsCount": 0,
"commentsCount": 0,
"userjs_url": null,
"style_settings": []
} | json |
<filename>litterbox/fabric/dataset_record.py
# Copyright (C) 2016 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# ==============================================================================
# Based on original Work Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
from abc import ABCMeta
from abc import abstractmethod
from .dataset import Dataset
from .dataset import FLAGS
class DatasetRecord(Dataset):
"""A simple class for handling data sets."""
__metaclass__ = ABCMeta
def __init__(self, name, subset):
super(DatasetRecord, self).__init__(name, subset, is_record=True)
def data_files(self):
"""Returns a python list of all (sharded) data subset files.
Returns:
python list of all (sharded) data set files.
Raises:
ValueError: if there are not data_files matching the subset.
"""
tf_record_pattern = os.path.join(FLAGS.data_dir, '%s-*' % self.subset)
data_files = tf.gfile.Glob(tf_record_pattern)
if not data_files:
print('No files found for dataset %s/%s at %s' %
(self.name, self.subset, FLAGS.data_dir))
exit(-1)
return data_files
def reader(self):
"""Return a reader for a single entry from the data set.
See io_ops.py for details of Reader class.
Returns:
Reader object that reads the data set.
"""
return tf.TFRecordReader()
| python |
SEO (Search Engine Optimization) is an industry with no shortage of controversy due to theories, rumors, and reputational woes. While many such theories and rumors are either bogus or untested, there are select ones that pique my interest from time-to-time and get me thinking a little. Now, I'm generally not one for conspiracy theories or prematurely buying into rumors prior to establishing some sort of credibility or ROI, but what's life without a bit of controversy? I'm going all-in here with publicly shouting a prospective implementation rumored to be considered by Google at some point when it comes to ranking outbound links from sites.
Please bear in mind that this is ultimately a rumor! At that, the only people who should really be upset if it happens are comment spammers (the people I would wager 99% of you out there despise)! Additionally, I have this rumor recorded on a digital voice recorder from the presentation it was first mentioned during, so if people try to take me down to the mat over this, I've got the proof. :)
Cutting right to the chase, Google is rumored to be considering placing more emphasis on the title tag of a page containing outbound links than on the anchor text used for those links. What does that mean? Well, the way things currently work is that a link's anchor text is kind of the holy grail for value to get out of a link. In other words, if you link to my site using anchor text like "click here," that's not going to be as valuable to me as if you link to my site using anchor text like "search engine optimization." Indeed, one always prefers a keyword that's relevant to their site be used as anchor text in a link pointing to their site from another, but that's easy to exploit. To help Google and Webmasters out, the "nofollow" attribute was created in part to help deter spammers from running amok and leaving comments about toasters and "making money fast" on blog posts about puppies and kittens. But it's still not enough because people still do it. (To note, "nofollow" is ultimately about not passing value to a site, regardless of if it's linked in a comment or within a post).
So, what would paying attention to a page's title do? Well, for one, Google would be looking at the page and saying, "what's this page about according to its title?" From there, they can compare it to the content on the page or any number of factors, really, but if Google is going to be comparing a title tag to the anchor text of an outbound blog comment link, that would put even more of a damper on the value one would hope to achieve from leaving a link in a blog comment. If Google is considering this as a ranking metric (and if they haven't already implemented it), it will be one more reason to seek out contextually relevant pages to build links on whether it's via comments, guest blog posts, or otherwise. Not to mention, the intitle:operator would probably start seeing more love while searching for keyword-related pages/blogs.
Now, though I think it's a great idea for even further devaluing links within comment spam on pages, there are some scenarios where such a metric might prove difficult to successfully implement. To start, there's always the likelihood of someone having a title tag that's generic or a template default. Maybe they have a blog post about kittens but their title tags says, "Place Your Title Here!" Or, maybe a blog's plug-in breaks and it takes title tags down with it. All the same, maybe an e-commerce site has product pages that allow product reviews to be written from individuals and the title tags of those product pages are totally generic. In all of those cases, putting a hindrance on links contained in comments is something I think makes sense... but what about other links on the page? Is this rumor solely pertaining to blog comments? That is one point left unclear as per when I heard this rumor.
In closing, I'd like to provide some historicity to this rumor. I personally heard it first-hand from an individual who attended Matt Cutts' PubCon 2010 presentation. This rumor was said to be something Matt mentioned personally. I later established that it must have been during a private conversation at some point before or after his presentation -- not during it.
After I tweeted what I'd heard (there was no request by this particular individual to not repeat this, so I jumped on Twitter to write what I had just heard), there was a quick-but-small wave of excitement and controversy stirred up that ultimately ended with Matt Cutts responding quite sternly, denying that he ever said such a thing. Maybe he did or maybe he didn't, but that's all part of the intrigue of this rumor to me. I'm personally under the impression that this was an "oops!" moment where something was said that shouldn't have been, but that's only because I personally think this sounds like a really good idea to help devalue links in blog comments. And because of that, it's my personal favorite SEO rumor from 2010!
What are your thoughts on the rumor above? Are there any particular ramifications you can think of based on such an implementation? Additionally, did you hear any SEO rumors in 2010 that piqued your interest? Feel free to add to the conversation if so!
| english |
<filename>src/structural/flyweight/Bullet.java
package structural.flyweight;
public final class Bullet {
private final String bulletSize;
private final String bulletWeight;
public Bullet(String bulletSize, String bulletWeight) {
this.bulletSize = bulletSize;
this.bulletWeight = bulletWeight;
}
public String getBulletSize() {
return bulletSize;
}
public String getBulletWeight() {
return bulletWeight;
}
}
| java |
<filename>ionic/www/js/controllers/game.js
angular.module('app.controllers')
.controller('GameCtrl', ['$scope', function($scope) {
console.log('GameCtrl initialized');
}])
| javascript |
<filename>tasks/physical_switch_create.json
{
"description": "Create a physical switch settings.",
"input_method": "stdin",
"supports_noop": false,
"remote": true,
"parameters":{
"connections":{
"description": "Supported connections for a physical switch.",
"type": "Array[Struct[{address => Optional[String[1,255]], connect_method => Optional[Enum['SSH','SNMPv2c']], Optional[port] => Optional[Integer[0,65535]], Optional[snmp_community_string] => Optional[String[0,128]], Optional[ssh_password] => Optional[String[0,128]], Optional[username] => Optional[String[0,128]], }]]"
},
"name":{
"description": "Name of a physical switch.",
"type": "String[1,128]"
},
"purpose":{
"description": "Physical switch purpose in network. Possible purposes are: * Data_and_Management - Physical switch for all data and management networks. * Management_Only - Physical switch for management network only.",
"type": "Enum['Data_and_Management','Management_Only']"
}},
"files": [
"powerstore/lib/puppet/util/task_helper.rb",
"powerstore/lib/puppet/transport/powerstore.rb",
"powerstore/lib/puppet/transport/schema/powerstore.rb"
]
}
| json |
{"pos":"proper","translits":{"wə·’aš·nāh":{"jos.15.33|3":["and Zorah、","and Ashnah、",null],"jos.15.43|1":["and Jiphtah、","and Ashnah、","and Nezib、"]}},"meanings":{"ashnah":2},"meaningsCount":1,"occurences":2} | json |
{
"name": "Home Assistant Add-on: Schedy UI",
"url": "https://github.com/alemuro/hassio-schedy-ui",
"maintainer": "<NAME> <<EMAIL>>"
}
| json |
{"name":"Higher Colleges of Technology – Dubai Men's College","alt_name":null,"country":"United Arab Emirates","state":null,"address":{"street":"PO Box 15825","city":"Dubai","province":null,"postal_code":null},"contact":{"telephone":"+971(4) 326-0333","website":"http:\/\/dbm.hct.ac.ae","email":null,"fax":"+971(4) 326-0303"},"funding":"Public","languages":null,"academic_year":null,"accrediting_agency":"Council for Academic Accreditation (CAA) of the UAE Ministry of Higher Education"}
| json |
/*
* Copyright 2011-2014 <NAME>. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.repository.util;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import java.util.ArrayList;
import java.util.List;
final class MultiValueGetterImpl implements ValueGetter<Value[], List<?>> {
private final ValueGetter<Value, ?> singleValueGetter;
public MultiValueGetterImpl(ValueGetter<Value, ?> singleValueGetter) {
this.singleValueGetter = singleValueGetter;
}
@Override
public List<?> getValue(Value[] values) throws RepositoryException {
if (values != null && values.length > 0) {
final List<Object> result = new ArrayList<>(values.length);
for (Value each : values) {
result.add(singleValueGetter.getValue(each));
}
return result;
} else {
return null;
}
}
}
| java |
<reponame>jesshaw/node-sample-project<filename>proxy/index.js
var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
proxy.on('error', function(err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
var server = require('http').createServer(function(req, res) {
var host = req.headers.host,
ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
switch (host) {
case 'miaowang.xyz':
case 'www.miaowang.xyz':
proxy.web(req, res, {
target: 'http://localhost:3000'
});
break;
case 'weixin.miaowang.xyz':
proxy.web(req, res, {
target: 'http://localhost:3001'
});
break;
case 'blog.miaowang.xyz':
proxy.web(req, res, {
target: 'http://www.cnblogs.com/jes_shaw/'
});
break;
case 'sanfor.com.cn':
case 'www.sanfor.com.cn':
proxy.web(req, res, {
target: 'http://localhost:3000'
});
break;
case 'weixin.sanfor.com.cn':
proxy.web(req, res, {
target: 'http://localhost:3001'
});
break;
case 'api.sanfor.com.cn':
proxy.web(req, res, {
target: 'http://localhost:4001'
});
break;
case 'demo.sanfor.com.cn':
proxy.web(req, res, {
target: 'http://localhost:4002'
});
break;
default:
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Welcome to my server!');
}
});
console.log("listening on port 80");
server.listen(80);
| javascript |
Tesla unveiled the new Model 3 tonight, and it looks damn cool. But before anyone had seen one lone hubcap, Tesla had already raked in $115 million in pre-order deposits, thanks to 115,000 people pre-ordering the Model 3.
It says a lot about Tesla’s brand (and the allure of maybe-supervillain Elon Musk) that the mere promise of a new car was enough to get the dollars rolling in. But whichever way you cut it, 115,000 $1,000 pre-orders in 24 hours for a car that no-one had seen, touched or driven is slightly absurd. Crazy pre-order lines, cult-like belief in brands, and a slightly crazy CEO? Tesla is officially the Apple of electric cars.
| english |
<filename>client/src/app/site/agenda/components/topic-detail/topic-detail.component.ts
import { Component } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Title, DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { MatSnackBar } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { BaseViewComponent } from 'app/site/base/base-view';
import { PromptService } from 'app/core/ui-services/prompt.service';
import { TopicRepositoryService } from 'app/core/repositories/agenda/topic-repository.service';
import { ViewTopic } from '../../models/view-topic';
import { OperatorService } from 'app/core/core-services/operator.service';
import { BehaviorSubject } from 'rxjs';
import { itemVisibilityChoices } from 'app/shared/models/agenda/item';
import { CreateTopic } from '../../models/create-topic';
import { Topic } from 'app/shared/models/topics/topic';
import { ViewMediafile } from 'app/site/mediafiles/models/view-mediafile';
import { ViewItem } from '../../models/view-item';
import { MediafileRepositoryService } from 'app/core/repositories/mediafiles/mediafile-repository.service';
import { ItemRepositoryService } from 'app/core/repositories/agenda/item-repository.service';
/**
* Detail page for topics.
*/
@Component({
selector: 'os-topic-detail',
templateUrl: './topic-detail.component.html',
styleUrls: ['./topic-detail.component.scss']
})
export class TopicDetailComponent extends BaseViewComponent {
/**
* Determine if the topic is in edit mode
*/
public editTopic: boolean;
/**
* Determine is created
*/
public newTopic: boolean;
/**
* Holds the current view topic
*/
public topic: ViewTopic;
/**
* Topic form
*/
public topicForm: FormGroup;
/**
* Subject for mediafiles
*/
public mediafilesObserver: BehaviorSubject<ViewMediafile[]>;
/**
* Subject for agenda items
*/
public itemObserver: BehaviorSubject<ViewItem[]>;
/**
* Determine visibility states for the agenda that will be created implicitly
*/
public itemVisibility = itemVisibilityChoices;
/**
* Constructor for the topic detail page.
*
* @param title Setting the browsers title
* @param matSnackBar display errors and other messages
* @param translate Handles translations
* @param route Angulars ActivatedRoute
* @param router Angulars Router
* @param formBuilder Angulars FormBuilder
* @param repo The topic repository
* @param promptService Allows warning before deletion attempts
* @param operator The current user
* @param DS Data Store
*/
public constructor(
title: Title,
matSnackBar: MatSnackBar,
protected translate: TranslateService,
private route: ActivatedRoute,
private router: Router,
private formBuilder: FormBuilder,
private repo: TopicRepositoryService,
private promptService: PromptService,
private operator: OperatorService,
private mediafileRepo: MediafileRepositoryService,
private itemRepo: ItemRepositoryService,
private sanitizer: DomSanitizer
) {
super(title, translate, matSnackBar);
this.getTopicByUrl();
this.createForm();
this.mediafilesObserver = this.mediafileRepo.getViewModelListBehaviorSubject();
this.itemObserver = this.itemRepo.getViewModelListBehaviorSubject();
}
/**
* Set the edit mode to the given Status
*
* @param mode
*/
public setEditMode(mode: boolean): void {
this.editTopic = mode;
if (mode) {
this.patchForm();
}
if (!mode && this.newTopic) {
this.router.navigate(['./agenda/']);
}
}
/**
* Save a new topic as agenda item
*/
public async saveTopic(): Promise<void> {
if (this.newTopic && this.topicForm.valid) {
if (!this.topicForm.value.agenda_parent_id) {
delete this.topicForm.value.agenda_parent_id;
}
await this.repo.create(new CreateTopic(this.topicForm.value));
this.router.navigate([`/agenda/`]);
} else {
this.setEditMode(false);
await this.repo.update(this.topicForm.value, this.topic);
}
}
/**
* Setup the form to create or alter the topic
*/
public createForm(): void {
this.topicForm = this.formBuilder.group({
agenda_type: [],
agenda_parent_id: [],
attachments_id: [[]],
text: [''],
title: ['', Validators.required]
});
this.topicForm.get('agenda_type').setValue(1);
}
/**
* Overwrite form Values with values from the topic
*/
public patchForm(): void {
const topicPatch = {};
Object.keys(this.topicForm.controls).forEach(ctrl => {
topicPatch[ctrl] = this.topic[ctrl];
});
this.topicForm.patchValue(topicPatch);
}
/**
* Determine whether a new topic should be created or an existing one should
* be loaded using the ID from the URL
*/
public getTopicByUrl(): void {
if (this.route.snapshot.url[1] && this.route.snapshot.url[1].path === 'new') {
// creates a new topic
this.newTopic = true;
this.editTopic = true;
this.topic = new ViewTopic(new Topic());
} else {
// load existing topic
this.route.params.subscribe(params => {
this.loadTopic(params.id);
});
}
}
/**
* Loads a top from the repository
*
* @param id the id of the required topic
*/
public loadTopic(id: number): void {
this.repo.getViewModelObservable(id).subscribe(newViewTopic => {
// repo sometimes delivers undefined values
// also ensures edition cannot be interrupted by autoupdate
if (newViewTopic && !this.editTopic) {
this.topic = newViewTopic;
// personalInfoForm is undefined during 'new' and directly after reloading
if (this.topicForm) {
this.patchForm();
}
}
});
}
/**
* Create the absolute path to the corresponding list of speakers
*
* @returns the link to the list of speakers as string
*/
public getSpeakerLink(): string {
if (!this.newTopic && this.topic) {
const item = this.topic.getAgendaItem();
if (item) {
return `/agenda/${item.id}/speakers`;
}
}
}
/**
* Handler for the delete button. Uses the PromptService
*/
public async onDeleteButton(): Promise<void> {
const title = this.translate.instant('Are you sure you want to delete this entry?');
const content = this.topic.title;
if (await this.promptService.open(title, content)) {
await this.repo.delete(this.topic).then(null, this.raiseError);
this.router.navigate(['/agenda']);
}
}
/**
* Checks if the operator is allowed to perform one of the given actions
*
* @param action the desired action
* @returns true if the operator has the correct permissions, false of not
*/
public isAllowed(action: string): boolean {
switch (action) {
case 'see':
return this.operator.hasPerms('agenda.can_see');
case 'edit':
return this.operator.hasPerms('agenda.can_manage');
case 'default':
return false;
}
}
/**
* clicking Shift and Enter will save automatically
* Hitting escape while in topicForm should cancel editing
*
* @param event has the code
*/
public onKeyDown(event: KeyboardEvent): void {
if (event.key === 'Enter' && event.shiftKey) {
this.saveTopic();
}
if (event.key === 'Escape') {
this.setEditMode(false);
}
}
/**
* Function to sanitize text.
* Necessary to render styles etc. correctly.
*
* @param text which will be sanitized.
*
* @returns safeHtml which can be displayed whithout loss.
*/
public sanitizedText(text: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(text);
}
}
| typescript |
<gh_stars>1-10
'use strict';
var assert = require('assert');
var File = require('vinyl');
var gulpDomProcessor = require('../');
var configLoader = require('./config/config-loader');
var invokedPath;
var load = configLoader.load;
configLoader.load = function(path) {
invokedPath = path;
return load(path);
};
describe('load function', function() {
it('should be invoked with file path', function(done) {
var fakeFile = new File({
path: 'FAKE_PATH',
contents: new Buffer([])
});
var processor = gulpDomProcessor(configLoader);
processor.write(fakeFile);
processor.once('data', function() {
assert.equal('FAKE_PATH', invokedPath);
done();
});
});
});
| javascript |
"""Utilities for approximating gradients."""
import numpy as np
from utils.misc import process_inputs
from utils.simrunners import SimulationRunner
def local_linear_gradients(X, f, p=None, weights=None):
"""Estimate a collection of gradients from input/output pairs.
Given a set of input/output pairs, choose subsets of neighboring points and
build a local linear model for each subset. The gradients of these local
linear models comprise estimates of sampled gradients.
Parameters
----------
X : ndarray
M-by-m matrix that contains the m-dimensional inputs
f : ndarray
M-by-1 matrix that contains scalar outputs
p : int, optional
how many nearest neighbors to use when constructing the local linear
model (default 1)
weights : ndarray, optional
M-by-1 matrix that contains the weights for each observation (default
None)
Returns
-------
df : ndarray
M-by-m matrix that contains estimated partial derivatives approximated
by the local linear models
Notes
-----
If `p` is not specified, the default value is floor(1.7*m).
"""
X, M, m = process_inputs(X)
if M<=m: raise Exception('Not enough samples for local linear models.')
if p is None:
p = int(np.minimum(np.floor(1.7*m), M))
elif not isinstance(p, int):
raise TypeError('p must be an integer.')
if p < m+1 or p > M:
raise Exception('p must be between m+1 and M')
if weights is None:
weights = np.ones((M, 1)) / M
MM = np.minimum(int(np.ceil(10*m*np.log(m))), M-1)
df = np.zeros((MM, m))
for i in range(MM):
ii = np.random.randint(M)
x = X[ii,:]
D2 = np.sum((X - x)**2, axis=1)
ind = np.argsort(D2)
ind = ind[D2 != 0]
A = np.hstack((np.ones((p,1)), X[ind[:p],:])) * np.sqrt(weights[ii])
b = f[ind[:p]] * np.sqrt(weights[ii])
u = np.linalg.lstsq(A, b)[0]
df[i,:] = u[1:].T
return df
def finite_difference_gradients(X, fun, h=1e-6):
"""Compute finite difference gradients with a given interface.
Parameters
----------
X : ndarray
M-by-m matrix that contains the points to estimate the gradients with
finite differences
fun : function
function that returns the simulation's quantity of interest given inputs
h : float, optional
the finite difference step size (default 1e-6)
Returns
-------
df : ndarray
M-by-m matrix that contains estimated partial derivatives approximated
by finite differences
"""
X, M, m = process_inputs(X)
# points to run simulations including the perturbed inputs
XX = np.kron(np.ones((m+1, 1)),X) + \
h*np.kron(np.vstack((np.zeros((1, m)), np.eye(m))), np.ones((M, 1)))
# run the simulation
if isinstance(fun, SimulationRunner):
F = fun.run(XX)
else:
F = SimulationRunner(fun).run(XX)
df = (F[M:].reshape((m, M)).transpose() - F[:M]) / h
return df.reshape((M,m))
| python |
$(document).ready(function () {
"use strict";
$('[data-toggle="tooltip"]').tooltip();
var bookingCalendar;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
bookingCalendar = jQuery('#calendar').fullCalendar({
//Random default events
header: {
left: 'prev',
center: 'title',
right: 'next'
},
firstDay: 1,
handleWindowResize: true,
fixedWeekCount: false,
editable: false,
droppable: false,
eventLimit: 3,
displayEventTime: false,
viewRender: function (view, element) {
//Last parameter is used to manage calender start and end dates
// 1 for render view as start and end date
//2 for month start and end date
refresh_calendar_overview(view.start.format('YYYY-MM-DD'), view.end.format('YYYY-MM-DD'), view.intervalStart.format('YYYY-MM-DD'), view.intervalEnd.format('YYYY-MM-DD'), 2);
},
eventClick: function (event, jsEvent, view) {
show_calender_event_details_overview(event.data);
},
// timezone: 'UTC'
});
function refresh_calendar_overview(start_render_view, end_render_view, start_month, end_month, render_view_status) {
jQuery.ajax({
url: '/admin/calendar',
type: 'POST',
data: {start_render_view: start_render_view, end_render_view: end_render_view, start_month: start_month, end_month: end_month, render_view_status: render_view_status},
success: function (response) {
bookingCalendar.fullCalendar('renderEvents', response);
},
error: function (xhr, textStatus, errorThrown) {
}
});
}
function show_calender_event_details_overview(data) {
jQuery.ajax({
type: "POST",
url: '/admin/calendar_event_details',
data: {data: data},
success: function (response) {
jQuery('#view_calender_event .modal-content').html(response);
jQuery('#view_calender_event').modal('show');
},
error: function (xhr, textStatus, errorThrown) {
}
});
}
}
);
| javascript |
The U. S. Food and Drug Administration (FDA) on Tuesday released comparative performance data for more than 55 COVID-19 diagnostic tests.
While the data alone isn’t strong enough to rationalize authorization or "other regulatory action" for any given test, the FDA said the data can better inform health care providers, labs and patients on which tests they decide to use.
The data show the tests’ Limit of Detection (LoD). The lower the number, the better, because it suggests the test can detect a lower amount of viral material in a sample and therefore signals a more sensitive test.
As of Sept. 10, the FDA contacted developers of 176 authorized assays for shipping information to send a standardized sample panel provided by the health agency. Of the available data for around 60 tests so far, the LoDs ranged from 540,000 NDU/mL for Quidel Corporation’s Lyra Direct SARS-CoV-2 Assay, to as low as 180 NDU/mL for PerkinElmer’s coronavirus nucleic acid detection kit. NDU refers to nucleic acid-based amplification tests (NAAT) detectable units (NDU).
The FDA previously developed a reference panel to assess diagnostic devices for the Zika virus.
In the case of SARS-CoV-2, officials said the panel has “one heat-inactivated SARS-CoV-2 strain and one heat-inactivated MERS-CoV strain in cell culture media” to confirm the determined LoD for the virus causing COVID-19 and to assess cross-reactivity for the latter.
The panel has five tubes, T1 to T5; T1 has the SARS-CoV-2 strain, while the rest of the tubes have blinded samples. “Although the FDA knows the concentration, the developer testing the samples does not,” officials explained.
While the data is readily available for nearly 60 tests at the moment, several tests may be of particular interest, like those of Abbott Molecular's RealTime SARS-CoV-2 assay, Centers for Disease Control and Prevention' (CDC) 2019-nCoV Real-Time RT-PCR Diagnostic Panel or Eli Lilly and Company's Lilly SARS-CoV-2 Assay, which returned LoD values of 5,400, 18,000 and 18,000 NDU/mL, respectively. | english |
<filename>assets/css/basic.css
* {
margin: 0;
padding: 0;
font-family: 'Baloo 2', cursive;
}
body {
background: white;
}
html {
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
}
a {
text-decoration: none;
}
.menu-btn {
position: fixed;
top: 20px;
right: 40px;
color: #f00658;
font-size: 30px;
display: none;
cursor: pointer;
}
.nav {
position: fixed;
height: 80px;
width: 100%;
border-bottom: 1px solid #ddd;
background: white;
z-index: 999;
}
.nav .container {
display: table;
width: 1000px;
height: fit-content;
margin: 0 auto;
}
.menu-item {
float: left;
width: fit-content;
height: 79px;
line-height: 79px;
margin: 0 20px;
font-size: 18px;
color: #f00658;
text-decoration-color: #f00658;
cursor: pointer;
white-space: nowrap;
}
.brand {
float: left;
width: fit-content;
height: 79px;
line-height: 79px;
margin: 0 20px;
font-size: 18px;
color: #777;
cursor: pointer;
}
.right {
float: right;
}
.menu-item:hover .bot-border {
width: 100%;
}
.bot-border {
width: 0;
height: 1px;
background: #f00658;
transition: 0.4s;
transform: scaleX(1.2);
}
@media (max-width: 1080px) {
.nav .container {
width: calc(100% - 80px);
margin: 0 40px;
}
}
@media (max-width: 700px) {
.nav .container {
width: 100%;
margin: 0;
}
.brand {
margin-left: 40px;
}
.menu {
width: 100%;
margin: 0;
display: none;
border-top: 1px solid #ddd;
box-shadow: 0 1px 0px #f0065870;
height: fit-content;
}
.menu-item {
margin: 0;
text-align: center;
width: 100%;
background: white;
}
.menu-btn {
display: block;
}
.show {
display: table;
}
}
@media (max-width: 500px) {
.menu-btn {
position: fixed;
top: 20px;
right: 20px;
}
.brand {
margin-left: 20px;
}
}
| css |
<reponame>CurtinHIVE/oldperth.github.io
{
"706295f-a": {
"width": 396,
"thumb_url": "http://oldnyc-assets.nypl.org/thumb/706295f-a.jpg",
"image_url": "http://oldnyc-assets.nypl.org/600px/706295f-a.jpg",
"title": "",
"date": "",
"text": "30-50 Plaza Street, east side, as seen across clearing from St. John's Place. No. 50 is in the foreground, and at the N.E. corner of Butler Place.\n\nAugust 29, 1930\n\nP.L. Sperr.",
"folder": "Plaza Street & St. Johns Place, Brooklyn, NY",
"height": 600,
"original_title": "Brooklyn: Plaza Street - St. Johns Place",
"years": [
""
]
}
} | json |
Bollywood actors Bipasha Basu and Karan Singh Grover are all set to welcome their first child. Bipasha took to Instagram to announce the news.
"A new time, a new phase, a new light adds another unique shade to our prism of life. Making us a little more whole than we used to be. We began this life individually and then we met each other and from then we were two. Too much love for only two, seemed a little unfair for us to see. . . so soon, we who once were two will now become three. A creation manifested by our love, our baby will join us soon and add to our glee. Thank you all, for your unconditional love, your prayers and good wishes as they are and will always be a part of us. Thank you for being a part of our lives and manifesting with us another beautiful life, our baby. Durga Durga", the actor wrote.
Bipasha also added pictures from a recent photoshoot. Bipasha and Karan got married on April 2016 as per Bengali traditions. They later hosted a reception for the film industry, which was attended by several Bollywood stars. | english |
Despite being identified as a diplomatic speaker. veteran actor Kamal Haasan has many times made candid observations about the state of affairs of various fields. The latest comes about his own field that is cinema.
In his latest interview to a leading Tamil weekly,while answering a question about why grand films on historical themes have become a rarity in Tamil cinema, Kamal said those things require a lot of preparations whereas here (in Kollywood) everything is like fast food.
Kamal said that he was not sure whether the young actors who take part in practice sessions for star night events and Celebrity Cricket League tournaments will be ready for rehearsals for their films. He also felt that hesitating to rehearse for films that fetch them income that was ten times more than what they earn through star nights and cricket is like committing betrayal to profession.
Follow us on Google News and stay updated with the latest! | english |
Summer season in Maharashtra is hot, yet this spot remains crowded with ardent roamers. Beginning from the month of March and extending till May, the temperature here hovers between 22°C-39°C. Along with the scorching heat of the sun, the state also experiences frequent thunderstorms. Despite of the hot climate, this spot has a lot to offer to keen explorers. Watch the sun setting at its palm-fringed beaches like Velas, Ganapatipule, Shrivardhan, Diveagar, Vengurla and Kihim. Wake up to the sunrise from behind the green carpeted mountains of Lonavala. If this isn’t enough, romanticize the Konkan Coast and relax and unwind yourself.
Inquisitive souls can travel past the remnants of the ancient forts of Murud Janjira, Raigad and Pratapgad. Iconic historical monuments like Ajanta Caves and Ellora Cave Temples are also not to be missed. Malvan, Amboli, Kashid, Lonavala, and Khandala are extremely captivating tourist destinations in Maharashtra that you can plan a visit to during summers. Ratnagiri, Malshej Ghat, Alibagh, Bhigwan Birding Site, Tadoba National Park, and Nashik Wineries &Vineyards are few other best summer travel places.
Are you an adventure freak? If yes, you can head off to some of the most fascinating summer treks in and around the state. Buckle up your shoes and hit the trails to Rajmachi, Lohagad, Tikona or Ratangad fort. These summer treks will open up to the wondrous nature and will also enchant you completely. Maharashtra one of the most encapsulating travel destinations in India, and it is also a hub of all round festivity. Host to numerous cultural, music, art, historic fairs and festivals, this state is the ideal place for merriment.
Melt in Maharashtra’s diverse culture by celebrating some of the most delightful festivals here. Nag Panchami, Gudhi Padwa, Narali Pourinma, Ganesh Chathurthi and Ellora Festivals are few of the unique festivals you can be a part of. Traveling in summer to this exotic travel destination, will be truly wonderful.
| english |
THE MUMBAI police helped a city-based businessman find a bag containing Rs 42 lakh cash that he forgot in a taxi while travelling from south Mumbai to Ghatkopar on Monday. It took the police two days to trace the taxi driver who had the bag.
An officer said that earlier this week, 38-year-old businessman Alpesh Laapsiya had complained to the Pant Nagar police station in Ghatkopar (east) about his lost bag. He informed the police that he forgot his bag containing Rs 42 lakh in a taxi in which he was travelling from Gulalwadi to Ghatkopar late Monday night. Based on his complaint, the police launched a probe.
Police scanned multiple CCTV cameras installed along the Eastern Freeway which the taxi used to drop him to Ghatkopar. However, they did not find any clue about the cab. Later they checked the cameras installed at Wadi Bunder signal where they spotted the cab. The police then used the taxi number and with the help of an e-challan machine, they got all the details about the vehicle, said an officer from the Pant Nagar police station. | english |
/**
* @license
* MyFonts Webfont Build ID 3192754, 2016-03-26T13:38:29-0400
*
* The fonts listed in this notice are subject to the End User License
* Agreement(s) entered into by the website owner. All other parties are
* explicitly restricted from using the Licensed Webfonts(s).
*
* You may obtain a valid license at the URLs below.
*
* Webfont: MuseoSans-700 by exljbris
* URL: http://www.myfonts.com/fonts/exljbris/museo-sans/700/
* Copyright: Copyright (c) 2008 by <NAME>. All rights reserved.
*
* Webfont: MuseoSans-500 by exljbris
* URL: http://www.myfonts.com/fonts/exljbris/museo-sans/500/
* Copyright: Copyright (c) 2008 by <NAME>. All rights reserved.
*
* Webfont: MuseoSans-100 by exljbris
* URL: http://www.myfonts.com/fonts/exljbris/museo-sans/100/
* Copyright: Copyright (c) 2008 by <NAME>. All rights reserved.
*
* Webfont: MuseoSlab-700 by exljbris
* URL: http://www.myfonts.com/fonts/exljbris/museo-slab/700/
* Copyright: Copyright (c) 2009 by <NAME>. All rights reserved.
*
* Webfont: MuseoSlab-300 by exljbris
* URL: http://www.myfonts.com/fonts/exljbris/museo-slab/300/
* Copyright: Copyright (c) 2009 by <NAME>. All rights reserved.
*
*
* License: http://www.myfonts.com/viewlicense?type=web&buildid=3192754
* Licensed pageviews: 500,000
*
* © 2016 MyFonts Inc
*/
/* @import must be at top of file, otherwise CSS will not work */
@font-face {
font-family: 'MuseoSans-700';
src: url('../webfonts/30B7B2_0_0.eot');
src: url('../webfonts/30B7B2_0_0.eot?#iefix') format('embedded-opentype'), url('../webfonts/30B7B2_0_0.woff2') format('woff2'), url('../webfonts/30B7B2_0_0.woff') format('woff'), url('../webfonts/30B7B2_0_0.ttf') format('truetype');
}
@font-face {
font-family: 'MuseoSans-500';
src: url('../webfonts/30B7B2_1_0.eot');
src: url('../webfonts/30B7B2_1_0.eot?#iefix') format('embedded-opentype'), url('../webfonts/30B7B2_1_0.woff2') format('woff2'), url('../webfonts/30B7B2_1_0.woff') format('woff'), url('../webfonts/30B7B2_1_0.ttf') format('truetype');
}
@font-face {
font-family: 'MuseoSans-100';
src: url('../webfonts/30B7B2_2_0.eot');
src: url('../webfonts/30B7B2_2_0.eot?#iefix') format('embedded-opentype'), url('../webfonts/30B7B2_2_0.woff2') format('woff2'), url('../webfonts/30B7B2_2_0.woff') format('woff'), url('../webfonts/30B7B2_2_0.ttf') format('truetype');
}
@font-face {
font-family: 'MuseoSlab-700';
src: url('../webfonts/30B7B2_3_0.eot');
src: url('../webfonts/30B7B2_3_0.eot?#iefix') format('embedded-opentype'), url('../webfonts/30B7B2_3_0.woff2') format('woff2'), url('../webfonts/30B7B2_3_0.woff') format('woff'), url('../webfonts/30B7B2_3_0.ttf') format('truetype');
}
@font-face {
font-family: 'MuseoSlab-300';
src: url('../webfonts/30B7B2_4_0.eot');
src: url('../webfonts/30B7B2_4_0.eot?#iefix') format('embedded-opentype'), url('../webfonts/30B7B2_4_0.woff2') format('woff2'), url('../webfonts/30B7B2_4_0.woff') format('woff'), url('../webfonts/30B7B2_4_0.ttf') format('truetype');
}
| css |
http://data.doremus.org/artist/f482df1a-9990-3708-8950-674bad8c4289
http://data.doremus.org/artist/98b8624b-589b-3239-9f08-be364eb20d42
http://data.doremus.org/artist/825e5fb4-4639-3c1d-b34c-5dbafaf55168
http://data.doremus.org/artist/ded35c7d-c496-3c17-8773-439fb62f60a8
http://data.doremus.org/artist/f146b700-a150-3e31-a67d-70a2d41ca53f
http://data.doremus.org/artist/3d8f2317-0f4b-3fd2-8ae1-7acabb780562
http://data.doremus.org/artist/1d6e7231-f178-322c-aecc-3b3a8d80e8aa
http://data.doremus.org/artist/dbbf7388-6b43-39d7-943e-a6ad55daa146 | json |
<filename>res/affected-clients-experiment/questions/mongoose@5.0.0/r2mongoose-precision.json
{
"[26a]index.js_CallExpression_25:13:25:69MaybeExplicitQuestionMatch": {
"questionText": "[26a] index.js, CallExpression at 25:13:25:69: Is it NOT exploited that the result of connect was a MongooseThenable?",
"answer": "Yes",
"patternId": "26a",
"fileName": "index.js",
"lineNumber": 25,
"columnNumber": 13
},
"[26a]index.js_CallExpression_25:13:25:69TransformQuestion": {
"questionText": "[26a] index.js, CallExpression at 25:13:25:69: Is the option useMongoClient enabled?",
"answer": "No",
"patternId": "26a",
"fileName": "index.js",
"lineNumber": 25,
"columnNumber": 13
}
} | json |
There is growing anticipation for GTA The Trilogy Definitive Edition, but some expectations need to be set.
Remember, these are not remakes. They are going to be remastered. While it does overhaul the combat system, it falls in line with current GTA titles. Rockstar isn't going to redefine the series here. Fans should set reasonable expectations for GTA The Trilogy Definitive Edition.
It's easy to get carried away. Anticipation has been building up for several months now. Rockstar even managed to surprise everybody with an early release date. However, players should ground themselves in reality. This article will go over this state of mind in detail.
Fans have every right to be disappointed if they don't get what they want. GTA The Trilogy Definitive Edition is no different in that regard. However, players should know what to expect ahead of time. Otherwise, they would be let down by unrealistic expectations.
After months of speculation, Rockstar finally confirmed they were making GTA The Trilogy Definitive Edition. Right off the bat, they made it clear what it was going to be. These classic games were going to maintain their original look. Leakers backed up these statements.
Some fans were very disappointed by Rockstar's direction. A few of them wanted visual upgrades similar to GTA 5. Of course, this was never going to happen. Rockstar wanted to keep the "look and feel of the originals. " Otherwise, it would look way too similar to GTA Online.
GTA The Trilogy Definitive Edition requires its own identity. Ultra-realistic graphics will probably be reserved for GTA 6.
These classic games feature a ton of cut features. For example, GTA San Andreas was meant to have a skateboard. It would be nice for Rockstar to implement them. Unfortunately, this is very unlikely.
In their original press release, Rockstar made no mention of the removed content. It would've been cool to bring these features back. However, the company is mainly concerned with capturing the original feel. Fans should not expect to see Darkel in GTA 3.
GTA The Trilogy Definitive Edition is not a remake. If it were, then perhaps Rockstar would've added these features. It would be interesting to see what these games could've looked like. Rockstar was very ambitious.
Liberty City Stories and Vice City Stories are often forgotten about. Their sales numbers never quite reached the main games. Beyond a few mobile ports, Rockstar hasn't done much with the prequels.
There is demand for GTA 3 and GTA Vice City. That's why fans got GTA The Trilogy Definitive Edition. However, the same cannot be said for the prequels. Their fanbase is decidedly smaller.
Rockstar would need a financial incentive to remaster those games. As it stands, the prequels lack the legacy of the classic titles. It's unlikely they will be remastered in the same manner as GTA The Trilogy Definitive Edition.
Note: This article reflects the writer's personal views. | english |
import { Nav, Footer, Meta, Download } from 'components';
import Button from 'components/Button';
import Image from 'next/image';
import meta from 'config/metas/home.json';
import { scroller } from 'react-scroll';
import { Users, Globe, Key } from 'react-feather';
import Fade from 'react-reveal/Fade';
import Flip from 'react-reveal/Flip';
import Zoom from 'react-reveal/Zoom';
import useTranslation from 'next-translate/useTranslation';
import { H1, H2, H3, H4, P } from 'components/Text';
import Box from 'components/Box';
import Flex from 'components/Flex';
import styled from 'styled-components';
function goto(_target = '', offset = 0): void {
scroller.scrollTo(_target, {
duration: 1500,
delay: 100,
smooth: true,
offset,
});
}
export function getStaticProps() {
return { props: {} };
}
function Home() {
const { t, lang } = useTranslation();
return (
<div id="home">
<Meta
title={meta[lang].title}
locale={meta[lang].locale}
meta={meta[lang].meta}
link={meta[lang].link}
/>
<Nav />
<Box position="relative" width="100%">
<Box
position="relative"
minHeight={['unset', 'unset', 'unset', 600]}
background="linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.55))"
>
<Box
maxWidth={['90%', '90%', '90%', 960]}
m="0 auto"
pt={[0, 0, 0, 120, 120]}
>
<Image
src="/assets/bg.jpg"
layout="fill"
alt="background"
objectFit="cover"
className="header-bg"
/>
<Box width="100%" pt={[100, 80, 80, 80]}>
<Fade up duration={800} delay={500}>
<H1
fontSize={[30, 30, 40, 54]}
letterSpacing={2}
textShadow="0 2px 24px rgba(0, 0, 0, 0.55)"
mb={15}
>
{t('landing:HEADER.TITLE')}
</H1>
</Fade>
<Fade up duration={800} delay={1000}>
<H2
fontWeight="normal"
textShadow="0 2px 24px rgba(0, 0, 0, 0.55)"
lineHeight="1.14"
letterSpacing={1.3}
fontSize={[18, 18, 24, 28]}
>
{t('landing:HEADER.SUBTITLE')}
</H2>
</Fade>
</Box>
<Box pb={[40, 40, 40, 0]} mt={40}>
<Zoom duration={800} delay={1500} center>
<Button onClick={() => goto('download')}>
{t('landing:DOWNLOAD')}
</Button>
</Zoom>
</Box>
</Box>
</Box>
</Box>
<Box as="section" width="100%" pt={70} pb={90} background="#f5f8fd">
<Box maxWidth={['90%', '90%', '90%', 960]} m="0 auto">
<Fade duration={800} delay={500}>
<H2
textAlign="center"
color="#545454"
mb={35}
textShadow="0 2px 24px rgba(0, 0, 0, 0.12)"
fontSize={[32, 32, 38, 45]}
>
{t('landing:BENEFITS.TITLE')}
</H2>
</Fade>
<Zoom duration={800} delay={1000}>
<hr />
</Zoom>
<Flex
flexDirection={['column', 'column', 'column', 'row', 'row']}
justifyContent={[
'center',
'center',
'center',
'space-between',
'space-between',
]}
mt={50}
>
<Flip left duration={800}>
<Card>
<Users size={48} color="#6DC7B0" />
<H4 fontSize={24} color="#545454" mt={15} mb={20}>
{t('landing:BENEFITS.LIST.0.TITLE')}
</H4>
<P
fontSize={16}
lineHeight="1.65"
letterSpacing={0.8}
color="#625957"
>
{t('landing:BENEFITS.LIST.0.DESC')}
</P>
</Card>
</Flip>
<Flip left duration={800} delay={300}>
<Card>
<Globe size={48} color="#6DC7B0" />
<H4 fontSize={24} color="#545454" mt={15} mb={20}>
{t('landing:BENEFITS.LIST.1.TITLE')}
</H4>
<P
fontSize={16}
lineHeight="1.65"
letterSpacing={0.8}
color="#625957"
>
{t('landing:BENEFITS.LIST.1.DESC')}
</P>
</Card>
</Flip>
<Flip left duration={800} delay={600}>
<Card>
<Key size={48} color="#6DC7B0" />
<H4 fontSize={24} color="#545454" mt={15} mb={20}>
{t('landing:BENEFITS.LIST.2.TITLE')}
</H4>
<P
fontSize={16}
lineHeight="1.65"
letterSpacing={0.8}
color="#625957"
>
{t('landing:BENEFITS.LIST.2.DESC')}
</P>
</Card>
</Flip>
</Flex>
</Box>
</Box>
<Box as="section" width="100%" py={40}>
<Box maxWidth={['90%', '90%', '90%', 960]} m="0 auto">
<Box mt={30}>
<Fade duration={800} delay={600}>
<H2
textAlign="center"
color="#545454"
mb={35}
textShadow="0 2px 24px rgba(0, 0, 0, 0.12)"
fontSize={[32, 32, 38, 45]}
>
{t('landing:EXPLORE.TITLE')}
</H2>
</Fade>
<Zoom duration={800} delay={900}>
<hr />
</Zoom>
</Box>
<Flex
mt={30}
flexDirection={['column-reverse', 'column-reverse', 'row']}
justifyContent="space-between"
alignItems="center"
pt={[30, 30, 0]}
>
<Box width={['100%', '100%', '45%']}>
<Fade up duration={800} delay={600}>
<Image
src="/assets/search.svg"
alt="search"
width={432}
height={216}
className="section-img"
/>
</Fade>
</Box>
<Box
width={['100%', '100%', '50%']}
p={[0, 0, 35]}
mb={[30, 30, 0]}
>
<Fade up duration={800} delay={600}>
<H3
fontSize={[22, 28, 36]}
color="#545454"
mb={18}
textShadow="0 2px 24px rgba(0, 0, 0, 0.12)"
letterSpacing="unset"
>
{t('landing:EXPLORE.LIST.0.TITLE')}
</H3>
<P fontSize={20} color="#625957" lineHeight="1.65">
{t('landing:EXPLORE.LIST.0.DESC')}
</P>
</Fade>
</Box>
</Flex>
<Flex
mt={30}
flexDirection={['column', 'column', 'row']}
justifyContent="space-between"
alignItems="center"
pt={[30, 30, 0]}
>
<Box
width={['100%', '100%', '50%']}
p={[0, 0, 35]}
mb={[30, 30, 0]}
>
<Fade up duration={800} delay={600}>
<H3
fontSize={[22, 28, 36]}
color="#545454"
mb={18}
textShadow="0 2px 24px rgba(0, 0, 0, 0.12)"
letterSpacing="unset"
>
{t('landing:EXPLORE.LIST.1.TITLE')}
</H3>
<P fontSize={20} color="#625957" lineHeight="1.65">
{t('landing:EXPLORE.LIST.1.DESC')}
</P>
</Fade>
</Box>
<Box width={['100%', '100%', '45%']}>
<Fade up duration={800} delay={600}>
<Image
src="/assets/dayoff.svg"
alt="dayoff"
width={432}
height={216}
className="section-img"
/>
</Fade>
</Box>
</Flex>
<Flex
mt={30}
flexDirection={['column-reverse', 'column-reverse', 'row']}
justifyContent="space-between"
alignItems="center"
pt={[30, 30, 0]}
>
<Box width={['100%', '100%', '45%']}>
<Fade up duration={800} delay={600}>
<Image
src="/assets/home.svg"
alt="home"
width={432}
height={216}
className="section-img"
/>
</Fade>
</Box>
<Box
width={['100%', '100%', '50%']}
p={[0, 0, 35]}
mb={[30, 30, 0]}
>
<Fade up duration={800} delay={600}>
<H3
fontSize={[22, 28, 36]}
color="#545454"
mb={18}
textShadow="0 2px 24px rgba(0, 0, 0, 0.12)"
letterSpacing="unset"
>
{t('landing:EXPLORE.LIST.2.TITLE')}
</H3>
<P fontSize={20} color="#625957" lineHeight="1.65">
{t('landing:EXPLORE.LIST.2.DESC')}
</P>
</Fade>
</Box>
</Flex>
</Box>
</Box>
<Download />
<Footer />
</div>
);
}
const Card = styled.div`
display: flex;
flex-direction: column;
min-height: 360px;
height: 100%;
border-radius: 10px;
background-color: rgba(255, 255, 255, 0.95);
box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.08);
transition: 0.4s;
max-width: 280px;
padding: 25px;
&:hover {
transform: translateY(-10px);
box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.35);
}
@media screen and (max-width: 1024px) {
max-width: unset;
min-height: unset;
height: 100%;
width: 100%;
margin-bottom: 25px;
}
`;
export default Home;
| typescript |
Social media is ablaze with postings emphasising how important mothers are in our lives. People express their love for their moms and share their wishes.
Digital Desk: The world a child can see, a finger that makes them learn to walk, a warm hug that makes all stress and worries aside, these powers are only within one person whom one should cherish with great love, care and respect, Happy Mothers Day to the mother's worldwide.
As a result, on Mother's Day, social media is ablaze with postings emphasising how important mothers are in our lives. People express their love for their moms and share their wishes for them on numerous channels, particularly Twitter.
A Short Brief about Mother Teresa :
Mother Mary Teresa Bojaxhiu, born at Anjez Gonxhe Bojaxhiu, Albanian, on August 26th August 1910, was an Albanian-Indian Roman Catholic nun and missionary venerated in the Catholic Church as Saint Teresa of Calcutta.
Mother Teresa was born in Skopje (formerly Üsküp, now the capital of North Macedonia), which was now part of the Ottoman Empire's Kosovo Vilayet. After eighteen years in Skopje, she travelled to Ireland and eventually to India, where she spent the rest of her life.
Her Contribution:
Mother Teresa was known throughout her lifetime as the Catholic nun who dedicated her life to caring for the poor and dying in Calcutta's slums.
From one of Mother Teresa's famous quotes- "We know only too well that what we are doing is nothing more than a drop in the ocean. But if the drop were not there, the ocean would be missing something. "
Did you Know these facts?
St. Teresa of Avila, a sixteenth-century Spanish nun, inspired her (Mother Teresa) to choose the name "Teresa. "
Mother Teresa received the inaugural Pope John XXIII Peace Prize from Pope Paul VI in 1971.
The Jawaharlal Nehru Award for International Understanding was given to her by the Indian government.
She was awarded the Nobel Peace Prize in 1979. These honours were accepted on behalf of the underprivileged by Mother Teresa.
Mother Teresa was declared a saint on September 4, 2016.
She established the Missionaries of Charity, a Catholic nuns' organisation committed to assisting the needy.
Mother Teresa was also named "The Saint of the Gutters" by the people.
On August 22, 1952, Mother Teresa inaugurated Nirmal Hriday ("Place of the Immaculate Heart"), a sanatorium for the dying.
How many of you know why she was called "Mother Teresa"?
As she made her final occupation of vows to a life of poverty, chastity, and obedience on May 24, 1937. As was customary for Loreto nuns, she was named "Mother" and became known as Mother Teresa.
Mother Teresa left the world on September 5 1997. Her great deeds are still remembered.
Wasn't she a great mother? Mothers are strong mentally and physically; vow to your mothers to love and protect them. | english |
Layer by layer, the secrecy that shrouds international money flows involving Indians has been unpeeled — beginning with the Offshore Leaks in 2013, Swiss Leaks in 2015, Panama Papers in 2016, and Paradise Papers in 2017, in a series of investigations by The Indian Express. Now comes the FinCEN Files.
The newspaper’s latest, beginning today, examines Indian connections in a cache of over 2000 secret documents — so secret banks aren’t even allowed to confirm they exist — which have been red-flagged to the top US financial watchdog, the Treasury Department’s Financial Crimes Enforcement Network (FinCEN) for suspected money laundering, terrorism, drug dealing or financial fraud.
These documents, called Suspicious Activity Reports or SARs, which constitute the FinCEN Files, are not evidence of illegality. They reflect views by watchdogs within banks, known as compliance officers, reporting past transactions that bore hallmarks of financial crime, or that involved clients with high-risk pofiles or past run-ins with the law.
In effect, they are crucial red flags raised by banks that point law-enforcement agencies to further investigation. (See explained). Indeed, the Department of Justice in the US has launched investigations and secured convictions in cases that are related to SARs.
The Indian Express, along with 109 media organisations in 88 countries, including Le Monde(France), Asahi Shimbun(Japan), Suddeutsche Zeitung(Germany), Aftenposten(Norway), NBC (US), BBC, and the Australian Broadcasting Corporation, teamed up with the International Consortium of Investigative Journalists (ICIJ) and BuzzFeed News to trace the Indian entities and banks named in these SARs filed with FinCEN between 1999 and 2017.
More than eight of every ten of these SARs were filed by: Deutsche Bank, Bank of New York Mellon (BNYM); Standard Chartered Bank, Citibank and JP Morgan Chase. The total value of transactions covered in these SARs: $ 2 trillion.
The SARs provide a rare peek into how businessmen, politicians and their companies utilise banking channels around the world to move their wealth across borders or to tax havens to avoid taxation or detection.
Over three months, The Indian Express investigated all the SARs with an India trail, further looking into those already under scrutiny in India for alleged financial irregularities. Indeed, a key finding is that in many cases the very fact that individuals and companies are being probed by Indian agencies is part of the SAR flagged to FinCEN.
Thus, transactions of Indian entities named in scams such as the 2G scam; the Augusta Westland scandal; the Rolls Royce bribery case and the Aircel-Maxis case besides those involved in other corruption and duty-evasion cases have all been hot-listed with the FinCEN.
Significantly, these cases are also being investigated by agencies like the Central Bureau of Investigation; the Enforcement Directorate and the Directorate of Revenue Intelligence.
The Indian Express investigation has revealed transactions of a range of individuals and companies: a jailed art and antique smuggler; a global diamond firm owned by Indian-born citizens named in several offshore leaks; a premier healthcare and hospitality group; a bankrupt steel firm; a luxury car dealer who allegedly duped several high net worth individuals; a multinational Indian conglomerate; a sponsor of the Indian Premier League (IPL) team; an alleged hawala dealer who became the reason for a massive fight within the Enforcement Directorate (ED) and a key financier of an Indian underworld don, among others.
In a majority of cases, domestic branches of Indian banks have been utilised to receive or remit the funds; in some cases, bank accounts with foreign branches of Indian banks, too, have been used to carry out these transactions.
As many as 44 Indian banks figure in the FinCEN Files primarily because they are “correspondent banks” to the foreign banks which have filed these SARs. Key in this list are Punjab National Bank, Kotak Mahindra, HDFC Bank, Canara Bank, IndusInd Bank and Bank of Baroda, among others.
There are a total of 3,201 transactions which have been listed as ‘’suspicious’’ in nature and these add to $1. 53 billion – but this is only those where complete Indian addresses linked to different entities (senders, banks, beneficiaries) are available. These are attached as spreadsheets in each SAR.
Over and above, are thousands of other transactions, also linked to Indian entities where senders or beneficiaries have addresses in foreign jurisdictions. These are contained in the SARs themselves.
Among the major global revelations, the investigation traced a Rhode Island drug dealer’s dollars to a chemist’s lab in Wuhan, China; explored scandals that crippled economies in Africa and Eastern Europe; tracked tomb raiders who looted ancient Buddhist artefacts that were sold to New York galleries; surveyed Venezuelan tycoons who siphoned money from public housing and hospitals; and scrutinized the Middle East’s largest gold refinery, the subject of a sprawling, never-revealed, US money-laundering probe.
Dozens of political figures who feature in the documents include Paul Manafort, the former Donald Trump campaign manager who was convicted of fraud and tax evasion.
JPMorgan processed more than $50 million over a decade between Manafort and his associates’ shell companies — at least $6. 5 million of that over 14 months after he resigned from the campaign amid charges of money laundering spawning from his ties to Russian-connected Ukrainian officials.
Earlier this month, anticipating this investigative series, FinCEN issued a statement in New York that “the unauthorized disclosure of SARs is a crime that can impact the national security of the United States, compromise law enforcement investigations, and threaten the safety and security of the institutions and individuals who file such reports. ” FinCEN said it had referred this to the US Department of Justice and the US Department of the Treasury’s Office of Inspector General. | english |
<reponame>YRainbbbb/myiced<filename>src/rectangle.rs
use crate::Point;
/// 一个普通的矩形
#[derive(Debug, PartialEq,Eq, Clone, Copy)]
pub struct Rectangle<T> {
/// 左上角坐标的X值
pub x: T,
/// 左上角坐标的Y值
pub y: T,
/// 矩形的宽带
pub width: T,
/// 矩形的高度
pub height: T,
}
impl Rectangle<f32> {
/// 给定['点']如果在['矩形']内,返回true
///
/// ['点']:type.point.html
/// ['矩形']:struct.Rectangle.html
pub fn contains(&self, point:Point) -> bool {
self.x <= point.x
&& point.x <= self.x + self.width
&& self.y <= point.y
&& point.y <= self.y + self.height
}
} | rust |
<filename>styles/menu.css<gh_stars>0
@import "main.css";
.menu {
width: 20%;
}
.menu-list {
list-style: none;
padding-inline-start: 0;
}
.menu-list-item {
padding: 5px;
}
.menu-list-icon {
background-color: var(--blue-300);
padding: 10px;
border-radius: 10px;
margin-right: 10px;
}
.hideOn {
display: none;
}
.hideOff {
display: block;
}
.nav-hamburguer-container {
display: none;
}
.nav-hamburguer-close {
display: none;
}
@media (min-width:426px) and (max-width: 768px) {
.menu {
display: none;
}
.menu-list-ham {
list-style: none;
padding-inline-start: 0;
}
.nav-hamburguer-container {
display: block;
}
.hamburguer-menu {
position: fixed;
right: 30px;
top: 100px;
width: 250px;
padding-left: 1em;
transition: transform 0.2s;
z-index: 500;
background-color: var(--blue-300);
}
}
@media (max-width:425px) {
.menu {
display: none;
}
.menu-list-ham {
list-style: none;
padding-inline-start: 0;
}
.nav-hamburguer-container {
display: block;
}
.hamburguer-menu {
position: fixed;
right: 30px;
top: 100px;
width: 250px;
padding-left: 1em;
transition: transform 0.2s;
z-index: 500;
background-color: var(--blue-300);
}
} | css |
<filename>data/airports/ktm.json
{
"id": "ktm",
"name": "<NAME>",
"city": "Kathmandu",
"country": "Nepal",
"description": "Opened as an airfield in 1949, Tribhuvan International is named after <NAME>, former King of Nepal. Its airport code comes from its home city of *K*a*t*h*m*andu.",
"imageCredit": "<NAME>",
"imageCreditLink": "https://www.flickr.com/photos/jaygalvin/"
} | json |
While a new stage of a coronavirus restrictions kicked off in Iran on Saturday, President Hassan Rouhani unveiled plans for a leap in the number of COVID-19 rapid tests.
Iran’s Ministry of Interior has proposed holding the next year’s presidential election in two days considering the coronavirus restrictions, an official said.
The death toll from COVID-19 in Iran has surpassed 44,000, while nearly 600,000 positive cases have recovered from the disease so far, the Health Ministry said.
The spokesman for Iran’s Foreign Ministry says the United States is responsible for multiple terrorist blasts that rocked the densely populated parts of Afghanistan’s capital with one hitting the Iranian embassy in Kabul.
The Iranian government has launched a comprehensive cash handout scheme covering 30 million people for the next four months amid a fresh round of nationwide restrictions on economic activity which are meant to curb the spread of the coronavirus.
A senior Russian diplomat says the so-called ‘maximum pressure’ policy pursued by the United States against Iran has failed to fulfill Washington's demand to target the country's economy and has only led to humanitarian sufferings.
Multiple blasts have rocked the densely populated parts of Kabul and left a number of civilian casualties, with one hitting the Iranian Embassy in the Afghan capital.
Iran says attempts by “devil’s advocate” Rudy Giuliani to defend anti-Iran terrorism have failed and the personal attorney to US President Donald Trump “is melting down, literally,” shortly after images of the American figure showing sweat darkened by what appears to be his hair dye running down his face during a presser were widely ridiculed.
Iran’s Foreign Ministry Spokesman Saeed Khatibzadeh on Friday called on France, Germany, Britain to, instead of playing a blame game against Tehran, fully implement their commitments under the 2015 nuclear deal. | english |
#ifndef WORLD_HPP
#define WORLD_HPP
#include "Core/System.hpp"
#include "Components/BodyComponent.hpp"
#include "Math/Vector4.hpp"
#include "Graphics/VertexObject.hpp"
namespace dm {
class TileMap {
public:
TileMap() : TileMap(50, 50) {}
TileMap(const int& width, const int& height)
: m_width(width), m_height(height) {
m_tiles.resize(width * height * 2);
}
~TileMap() {}
Tile& operator()(const int& x, const int& y) {
return m_tiles[(x + m_width) + ((y + m_height) * m_width)];
}
Tile& operator()(const Vec2i position) {
return (*this)(position.x, position.y);
}
private:
int m_width;
int m_height;
std::vector<Tile> m_tiles;
};
class World : public System {
public:
World() : m_map(320, 320) {}
~World() {}
void render(const GameState&) {}
void update(GameState&);
bool move(BodyComponent& body, int x, int y);
void set_position(BodyComponent& body, int x, int y);
Vec3f real_position(Vec2i position, Vec3f size);
void component_added(const uint32_t component_type, Entity e);
TileMap& map() { return m_map; }
private:
TileMap m_map;
};
dm_internal_register_type(World)
} /* namespace dm */
#endif /* end of include guard: WORLD_HPP */
| cpp |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fas';
var iconName = 'alarm-clock';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f34e';
var svgPathData = 'M512 96c0 27.8-11.8 52.8-30.7 70.3C450.8 109.9 399 65.2 335 44.4 352.1 17.7 382 0 416 0c53 0 96 43 96 96zM177 44.4C159.9 17.7 130 0 96 0 43 0 0 43 0 96c0 27.8 11.8 52.8 30.7 70.3C61.2 109.9 113 65.2 177 44.4zm323.3 455.9c-15.7 15.7-41 15.6-56.6 0l-42.1-42.1c-39.2 33.5-90 53.8-145.6 53.8s-106.5-20.3-145.6-53.8l-42.1 42.1c-15.7 15.7-41 15.6-56.6 0-15.6-15.6-15.6-40.9 0-56.6l47.9-47.9C42 363.8 32 327.1 32 288 32 164.3 132.3 64 256 64s224 100.3 224 224c0 39.1-10 75.8-27.6 107.8l47.9 47.9c15.6 15.6 15.6 41 0 56.6zM346.9 324.1l-54.9-40V162.7c0-6.6-5.4-12-12-12h-48c-6.6 0-12 5.4-12 12v152c0 3.8 1.8 7.5 4.9 9.7l79.7 57.9c5.4 3.9 12.9 2.7 16.8-2.6l28.2-38.8c3.9-5.4 2.7-12.9-2.7-16.8z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faAlarmClock = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | javascript |
<filename>resources/ru/russian-state-social-university.json
{"name":"Russian State Social University","alt_name":"Rossijskij Gosudarstvennyj Sotsial'nyj Universitet","country":"Russia","state":null,"address":{"street":"ul. Vel'gel'ma Pika, 4\/1","city":"Moskva","province":null,"postal_code":"129226"},"contact":{"telephone":"+7(495) 187-60-25","website":"http:\/\/www.rgsu.net","email":"<EMAIL>; <EMAIL>","fax":"+7(495) 783-71-25"},"funding":"Public","languages":null,"academic_year":null,"accrediting_agency":null}
| json |
<reponame>loiane/intershop-pwa
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from '@angular/core';
import { Observable, ReplaySubject, Subject } from 'rxjs';
import { filter, startWith, take, takeUntil } from 'rxjs/operators';
import { ShoppingFacade } from 'ish-core/facades/shopping.facade';
import { Category } from 'ish-core/models/category/category.model';
import { ProductVariationHelper } from 'ish-core/models/product-variation/product-variation.helper';
import { VariationOptionGroup } from 'ish-core/models/product-variation/variation-option-group.model';
import { VariationSelection } from 'ish-core/models/product-variation/variation-selection.model';
import { ProductView, VariationProductView } from 'ish-core/models/product-view/product-view.model';
import { ProductCompletenessLevel, ProductHelper } from 'ish-core/models/product/product.model';
import { ProductRowComponentConfiguration } from 'ish-shared/components/product/product-row/product-row.component';
import { ProductTileComponentConfiguration } from 'ish-shared/components/product/product-tile/product-tile.component';
export type ProductItemContainerConfiguration = ProductTileComponentConfiguration &
ProductRowComponentConfiguration & { displayType: 'tile' | 'row' };
export const DEFAULT_CONFIGURATION: Readonly<ProductItemContainerConfiguration> = {
readOnly: false,
allowZeroQuantity: false,
quantityLabel: ' ',
displayName: true,
displayDescription: true,
displaySKU: true,
displayInventory: true,
displayQuantity: true,
displayPrice: true,
displayPromotions: true,
displayVariations: true,
displayShipment: false,
displayAddToBasket: true,
displayAddToWishlist: true,
displayAddToOrderTemplate: true,
displayAddToCompare: true,
displayAddToQuote: true,
displayType: 'tile',
};
/**
* The Product Item Container Component fetches the product data for a given product sku
* and renders the product either as 'tile' or 'row'.
* The 'tile' rendering is the default if no value is provided for the displayType.
*
* @example
* <ish-product-item [productSku]="product.sku"></ish-product-item>
*/
@Component({
selector: 'ish-product-item',
templateUrl: './product-item.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductItemComponent implements OnInit, OnChanges, OnDestroy {
private static REQUIRED_COMPLETENESS_LEVEL = ProductCompletenessLevel.List;
/**
* The Product SKU to render a product item for.
*/
@Input() productSku: string;
@Output() productSkuChange = new EventEmitter<string>();
/**
* The quantity which should be set for this. Default is minOrderQuantity.
*/
@Input() quantity: number;
@Output() quantityChange = new EventEmitter<number>();
/**
* The optional Category context.
*/
@Input() category?: Category;
/**
* configuration
*/
@Input() configuration: ProductItemContainerConfiguration = DEFAULT_CONFIGURATION;
product$: Observable<ProductView>;
loading$: Observable<boolean>;
productVariationOptions$: Observable<VariationOptionGroup[]>;
isInCompareList$: Observable<boolean>;
private sku$ = new ReplaySubject<string>(1);
private destroy$ = new Subject();
constructor(private shoppingFacade: ShoppingFacade) {}
ngOnDestroy() {
this.destroy$.next();
}
// tslint:disable:initialize-observables-in-declaration
ngOnInit() {
this.productSkuChange.pipe(startWith(this.productSku), takeUntil(this.destroy$)).subscribe(this.sku$);
this.product$ = this.shoppingFacade.product$(this.sku$, ProductItemComponent.REQUIRED_COMPLETENESS_LEVEL);
this.loading$ = this.shoppingFacade.productNotReady$(this.sku$, ProductItemComponent.REQUIRED_COMPLETENESS_LEVEL);
this.productVariationOptions$ = this.shoppingFacade.productVariationOptions$(this.sku$);
this.isInCompareList$ = this.shoppingFacade.inCompareProducts$(this.sku$);
}
ngOnChanges(changes: SimpleChanges) {
this.mergeConfiguration(changes);
}
private mergeConfiguration(changes: SimpleChanges) {
if (changes.configuration && changes.configuration.firstChange) {
const oldConfig = this.configuration || {};
// tslint:disable-next-line:no-assignement-to-inputs
this.configuration = { ...DEFAULT_CONFIGURATION, ...oldConfig };
}
}
toggleCompare() {
this.sku$.pipe(take(1)).subscribe(sku => this.shoppingFacade.toggleProductCompare(sku));
}
addToBasket(quantity: number) {
this.sku$.pipe(take(1)).subscribe(sku => this.shoppingFacade.addProductToBasket(sku, quantity));
}
replaceVariation(event: { selection: VariationSelection; changedAttribute?: string }) {
this.product$
.pipe(
take(1),
filter<VariationProductView>(product => ProductHelper.isVariationProduct(product))
)
.subscribe(product => {
const { sku } = ProductVariationHelper.findPossibleVariationForSelection(
event.selection,
product,
event.changedAttribute
);
this.productSkuChange.emit(sku);
});
}
get isTile() {
return !!this.configuration && this.configuration.displayType === 'tile';
}
get isRow() {
return !this.isTile;
}
}
| typescript |
<gh_stars>0
{
"name": "DNA Library",
"description": "A sample that contains a pool of DNA molecules with many unique sequences",
"field_types": [
{
"name": "Oligo Pool",
"part": null,
"array": false,
"routing": null,
"ftype": "sample",
"choices": null,
"required": false
}
]
} | json |
<gh_stars>0
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package model
import (
"fmt"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
vpa_types "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/poc.autoscaling.k8s.io/v1alpha1"
"k8s.io/autoscaler/vertical-pod-autoscaler/recommender/util"
)
// ContainerMergePolicy contorls how MergeContainerState cobines samples.
type ContainerMergePolicy bool
const (
// SupportedCheckpointVersion is the tag of the supported version of serialized checkpoints.
SupportedCheckpointVersion = "v1"
// MergeForRecommendation means that all samples are combined during MergeContainerState call.
MergeForRecommendation ContainerMergePolicy = true
// MergeForCheckpoint controls that MergeContainerState call will omit last peak memory
// sample if it would result in positive feedback loop during crash loop.
MergeForCheckpoint ContainerMergePolicy = false
)
// AggregateContainerState holds input signals aggregated from a set of containers.
// It can be used as an input to compute the recommendation.
type AggregateContainerState struct {
AggregateCPUUsage util.Histogram
AggregateMemoryPeaks util.Histogram
FirstSampleStart time.Time
LastSampleStart time.Time
TotalSamplesCount int
}
// MergeContainerState merges the state of an individual container into AggregateContainerState.
func (a *AggregateContainerState) MergeContainerState(container *ContainerState,
mergePolicy ContainerMergePolicy, now time.Time) {
a.AggregateCPUUsage.Merge(container.CPUUsage)
memoryPeaks := container.MemoryUsagePeaks.Contents()
peakTime := container.WindowEnd
for i := len(memoryPeaks) - 1; i >= 0; i-- {
if mergePolicy == MergeForRecommendation || peakTime.Before(now) {
a.AggregateMemoryPeaks.AddSample(float64(memoryPeaks[i]), 1.0, peakTime)
}
peakTime = peakTime.Add(-MemoryAggregationInterval)
}
// Note: we look at CPU samples to calculate the total lifespan and sample count.
if a.FirstSampleStart.IsZero() || (!container.FirstCPUSampleStart.IsZero() && container.FirstCPUSampleStart.Before(a.FirstSampleStart)) {
a.FirstSampleStart = container.FirstCPUSampleStart
}
if container.LastCPUSampleStart.After(a.LastSampleStart) {
a.LastSampleStart = container.LastCPUSampleStart
}
a.TotalSamplesCount += container.CPUSamplesCount
}
// NewAggregateContainerState returns a new, empty AggregateContainerState.
func NewAggregateContainerState() *AggregateContainerState {
return &AggregateContainerState{
AggregateCPUUsage: util.NewDecayingHistogram(CPUHistogramOptions, CPUHistogramDecayHalfLife),
AggregateMemoryPeaks: util.NewDecayingHistogram(MemoryHistogramOptions, MemoryHistogramDecayHalfLife),
}
}
// SaveToCheckpoint serializes AggregateContainerState as VerticalPodAutoscalerCheckpointStatus.
// The serialization may result in loss of precission of the histograms.
func (a *AggregateContainerState) SaveToCheckpoint() (*vpa_types.VerticalPodAutoscalerCheckpointStatus, error) {
memory, err := a.AggregateMemoryPeaks.SaveToChekpoint()
if err != nil {
return nil, err
}
cpu, err := a.AggregateCPUUsage.SaveToChekpoint()
if err != nil {
return nil, err
}
return &vpa_types.VerticalPodAutoscalerCheckpointStatus{
FirstSampleStart: metav1.NewTime(a.FirstSampleStart),
LastSampleStart: metav1.NewTime(a.LastSampleStart),
TotalSamplesCount: a.TotalSamplesCount,
MemoryHistogram: *memory,
CPUHistogram: *cpu,
Version: SupportedCheckpointVersion,
}, nil
}
// LoadFromCheckpoint deserializes data from VerticalPodAutoscalerCheckpointStatus
// into the AggregateContainerState.
func (a *AggregateContainerState) LoadFromCheckpoint(checkpoint *vpa_types.VerticalPodAutoscalerCheckpointStatus) error {
if checkpoint.Version != SupportedCheckpointVersion {
return fmt.Errorf("Unssuported checkpoint version %s", checkpoint.Version)
}
a.TotalSamplesCount = checkpoint.TotalSamplesCount
a.FirstSampleStart = checkpoint.FirstSampleStart.Time
a.LastSampleStart = checkpoint.LastSampleStart.Time
err := a.AggregateMemoryPeaks.LoadFromCheckpoint(&checkpoint.MemoryHistogram)
if err != nil {
return err
}
err = a.AggregateCPUUsage.LoadFromCheckpoint(&checkpoint.CPUHistogram)
if err != nil {
return err
}
return nil
}
// DeepCopy returns a copy of the AggregateContainerState
func (a *AggregateContainerState) DeepCopy() *AggregateContainerState {
copy := NewAggregateContainerState()
copy.TotalSamplesCount = a.TotalSamplesCount
copy.FirstSampleStart = a.FirstSampleStart
copy.LastSampleStart = a.FirstSampleStart
copy.AggregateCPUUsage.Merge(a.AggregateCPUUsage)
copy.AggregateMemoryPeaks.Merge(a.AggregateMemoryPeaks)
return copy
}
// BuildAggregateContainerStateMap takes a set of pods and groups their containers by name.
// If checkpoint data is available it is incorporated into AggregateContainerState
func BuildAggregateContainerStateMap(vpa *Vpa, mergePolicy ContainerMergePolicy, now time.Time) map[string]*AggregateContainerState {
aggregateContainerStateMap := make(map[string]*AggregateContainerState)
for k, v := range vpa.ContainerCheckpoints {
aggregateContainerStateMap[k] = v.DeepCopy()
}
for _, pod := range vpa.Pods {
for containerName, container := range pod.Containers {
aggregateContainerState, isInitialized := aggregateContainerStateMap[containerName]
if !isInitialized {
aggregateContainerState = NewAggregateContainerState()
aggregateContainerStateMap[containerName] = aggregateContainerState
}
aggregateContainerState.MergeContainerState(container, mergePolicy, now)
}
}
return aggregateContainerStateMap
}
| go |
{"title": "Blogs as a collective war diary.", "fields": ["social media", "plural", "topic model", "pronoun", "collective identity"], "abstract": "Disaster-related research in human-centered computing has typically focused on the shorter-term, emergency period of a disaster event, whereas effects of some crises are long-term, lasting years. Social media archived on the Internet provides researchers the opportunity to examine societal reactions to a disaster over time. In this paper we examine how blogs written during a protracted conflict might reflect a collective view of the event. The sheer amount of data originating from the Internet about a significant event poses a challenge to researchers; we employ topic modeling and pronoun analysis as methods to analyze such large-scale data. First, we discovered that blog war topics temporally tracked the actual, measurable violence in the society suggesting that blog content can be an indicator of the health or state of the affected population. We also found that people exhibited a collective identity when they blogged about war, as evidenced by a higher use of first-person plural pronouns compared to blogging on other topics. Blogging about daily life decreased as violence in the society increased; when violence waned, there was a resurgence of daily life topics, potentially illustrating how a society returns to normalcy.", "citation": "Citations (29)", "departments": ["University of California, Irvine", "University of Colorado Boulder", "University of Colorado Boulder", "University of Colorado Boulder", "University of California, Irvine"], "authors": ["<NAME>.....http://dblp.org/pers/hd/m/Mark:Gloria", "<NAME>.....http://dblp.org/pers/hd/b/Bagdouri:Mossaab", "<NAME>.....http://dblp.org/pers/hd/p/Palen:Leysia", "<NAME>.....http://dblp.org/pers/hd/m/Martin:James_H=", "Ban Al-Ani.....http://dblp.org/pers/hd/a/Al=Ani:Ban", "<NAME>.....http://dblp.org/pers/hd/a/Anderson:Kenneth_Mark"], "conf": "cscw", "year": "2012", "pages": 10} | json |
A transporting tale set around the shifting power dynamics of viciously aggressive investors who enter a nation to maraud lt’s resources and will stop at nothing to make money. A stunning meditation on human nature and survival instincts, this novel poses intense moral questions. Discover a world of love and deception as it weaves through the extraordinary world of magical realism.
|Tale of Five Crocodiles (Tale Of Five Crocodiles)
|Saravanan Chandran (Saravanan Chandran)
|Zero Degree Publications (zero degree publishing)
| english |
#/*
# * Copyright (C) 2017 - This file is part of libecc project
# *
# * Authors:
# * <NAME> <<EMAIL>>
# * <NAME> <<EMAIL>>
# * <NAME> <<EMAIL>>
# *
# * Contributors:
# * <NAME> <<EMAIL>>
# * <NAME> <<EMAIL>>
# *
# * This software is licensed under a dual BSD and GPL v2 license.
# * See LICENSE file at the root folder of the project.
# */
import struct
keccak_rc = [
0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008
]
keccak_rot = [
[ 0, 36, 3, 41, 18 ],
[ 1, 44, 10, 45, 2 ],
[ 62, 6, 43, 15, 61 ],
[ 28, 55, 25, 21, 56 ],
[ 27, 20, 39, 8, 14 ],
]
# Keccak function
def keccak_rotl(x, l):
return (((x << l) ^ (x >> (64 - l))) & (2**64-1))
def keccakround(bytestate, rc):
# Import little endian state
state = [0] * 25
for i in range(0, 25):
(state[i],) = struct.unpack('<Q', ''.join(bytestate[(8*i):(8*i)+8]))
# Proceed with the KECCAK core
bcd = [0] * 25
# Theta
for i in range(0, 5):
bcd[i] = state[i] ^ state[i + (5*1)] ^ state[i + (5*2)] ^ state[i + (5*3)] ^ state[i + (5*4)]
for i in range(0, 5):
tmp = bcd[(i+4)%5] ^ keccak_rotl(bcd[(i+1)%5], 1)
for j in range(0, 5):
state[i + (5 * j)] = state[i + (5 * j)] ^ tmp
# Rho and Pi
for i in range(0, 5):
for j in range(0, 5):
bcd[j + (5*(((2*i)+(3*j)) % 5))] = keccak_rotl(state[i + (5*j)], keccak_rot[i][j])
# Chi
for i in range(0, 5):
for j in range(0, 5):
state[i + (5*j)] = bcd[i + (5*j)] ^ (~bcd[((i+1)%5) + (5*j)] & bcd[((i+2)%5) + (5*j)])
# Iota
state[0] = state[0] ^ keccak_rc[rc]
# Pack the output state
output = [0] * (25 * 8)
for i in range(0, 25):
output[(8*i):(8*i)+1] = struct.pack('<Q', state[i])
return output
def keccakf(bytestate):
for rnd in range(0, 24):
bytestate = keccakround(bytestate, rnd)
return bytestate
# SHA-3 context class
class Sha3_ctx(object):
def __init__(self, digest_size):
self.digest_size = digest_size / 8
self.block_size = (25*8) - (2 * (digest_size / 8))
self.idx = 0
self.state = [chr(0)] * (25 * 8)
def digest_size(self):
return self.digest_size
def block_size(self):
return self.block_size
def update(self, message):
for i in range(0, len(message)):
self.state[self.idx] = chr(ord(self.state[self.idx]) ^ ord(message[i]))
self.idx = self.idx + 1
if (self.idx == self.block_size):
self.state = keccakf(self.state)
self.idx = 0
def digest(self):
self.state[self.idx] = chr(ord(self.state[self.idx]) ^ 0x06)
self.state[self.block_size - 1] = chr(ord(self.state[self.block_size - 1]) ^ 0x80)
self.state = keccakf(self.state)
return ''.join(self.state[:self.digest_size])
| python |
package integration
import (
"github.com/nuodb/nuodb-helm-charts/v3/test/testlib"
"github.com/stretchr/testify/assert"
"testing"
)
func TestRegistryEntryUnmarshal(t *testing.T) {
s := (
`nuodb:
image:
registry: local
repository: master
tag: latest
`)
err, object := testlib.UnmarshalImageYAML(s)
assert.NoError(t, err)
assert.True(t, object.Nuodb.Image.Registry == "local")
assert.True(t, object.Nuodb.Image.Repository == "master")
assert.True(t, object.Nuodb.Image.Tag == "latest")
}
| go |
<reponame>33kk/uso-archive
{
"id": 92811,
"name": "New Vulpix theme",
"description": "Requested in my shop.",
"user": {
"id": 208760,
"name": "YandereDaizy[backup]",
"email": "redacted",
"paypal_email": null,
"homepage": null,
"about": null,
"license": "ccbync"
},
"updated": "2013-09-09T15:10:51.000Z",
"weekly_install_count": 0,
"total_install_count": 181,
"rating": null,
"after_screenshot_name": "https://userstyles.org/auto_style_screenshots/92811-after.png?r=1616573170",
"obsoleting_style_id": null,
"obsoleting_style_name": null,
"obsolete": 0,
"admin_delete_reason_id": null,
"obsoletion_message": null,
"screenshots": null,
"license": null,
"created": "2013-09-09T15:10:51.000Z",
"category": "site",
"raw_subcategory": "mycandylove",
"subcategory": "mycandylove",
"additional_info": null,
"style_tags": [],
"css": "@-moz-document domain(\"mycandylove.com\") {\r\n#container{\r\nbackground-image : url(http://images2.layoutsparks.com/1/125253/girly-red-white-design.jpg) !important ;\r\n}\r\n#container.connected #header { background-image : url(http://memberfiles.freewebs.com/82/46/100634682/photos/undefined/vulpix%20theme-1.png) !important ;\r\n}\r\n.idcard-member { background : url(http://memberfiles.freewebs.com/82/46/100634682/photos/undefined/vulpix%20card.gif) no-repeat !important ;\r\n}\r\n}\r\n\r\n@-moz-document regexp(\"http://www.mycandylove.com/profil/daizy106\") {\r\n.idcard-member { background : url(http://memberfiles.freewebs.com/82/46/100634682/photos/undefined/vulpix%20card.gif) no-repeat !important ;\r\n}\r\n}\r\n@-moz-document domain(\"mycandylove.com\") {\r\n\r\nbody {\r\n cursor:url(http://memberfiles.freewebs.com/82/46/100634682/photos/vulpix-sprite-i7.gif), crosshair !important;\r\n}\r\n\r\n}\r\n ",
"discussions": [],
"discussionsCount": 0,
"commentsCount": 0,
"userjs_url": "/styles/userjs/92811/new-vulpix-theme.user.js",
"style_settings": []
} | json |
---
title: "Single Board Computers"
weight: 55
---
| markdown |
<filename>chap4/main.cpp
#include <algorithm>
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include "grade.h"
#include "student_info.h"
using std::cin; using std::setprecision;
using std::cout; using std::sort;
using std::domain_error; using std::streamsize;
using std::endl; using std::string;
using std::max; using std::vector;
int main()
{
vector<Student_info> students;
Student_info record;
string::size_type maxlen = 0;
while( read(cin, record)){
maxlen = max(maxlen, record.name.size());
students.push_back(record);
}
//sort(students.begin(), students.end(), compare);
for(vector<Student_info>::iterator i = students.begin();
i!= students.end(); i++){
try {
double final_grade = grade(*i);
streamsize prec = cout.precision();
cout << i->name << string(maxlen + 1 - i->name.size(), ' ')
<< setprecision(5) << final_grade << endl;
cout.precision(prec);
}
catch(...){
cout << "there is error " << endl;
}
}
return 0;
}
| cpp |
import os
import numpy as np
import pandas as pd
from databroker.assets.handlers_base import HandlerBase
class APBBinFileHandler(HandlerBase):
"Read electrometer *.bin files"
def __init__(self, fpath):
# It's a text config file, which we don't store in the resources yet, parsing for now
fpath_txt = f"{os.path.splitext(fpath)[0]}.txt"
with open(fpath_txt, "r") as fp:
content = fp.readlines()
content = [x.strip() for x in content]
_ = int(content[0].split(":")[1])
# Gains = [int(x) for x in content[1].split(":")[1].split(",")]
# Offsets = [int(x) for x in content[2].split(":")[1].split(",")]
# FAdiv = float(content[3].split(":")[1])
# FArate = float(content[4].split(":")[1])
# trigger_timestamp = float(content[5].split(":")[1].strip().replace(",", "."))
raw_data = np.fromfile(fpath, dtype=np.int32)
columns = ["timestamp", "i0", "it", "ir", "iff", "aux1", "aux2", "aux3", "aux4"]
num_columns = len(columns) + 1 # TODO: figure out why 1
raw_data = raw_data.reshape((raw_data.size // num_columns, num_columns))
derived_data = np.zeros((raw_data.shape[0], raw_data.shape[1] - 1))
derived_data[:, 0] = (
raw_data[:, -2] + raw_data[:, -1] * 8.0051232 * 1e-9
) # Unix timestamp with nanoseconds
for i in range(num_columns - 2):
derived_data[:, i + 1] = raw_data[:, i] # ((raw_data[:, i] ) - Offsets[i]) / Gains[i]
self.df = pd.DataFrame(data=derived_data, columns=columns)
self.raw_data = raw_data
def __call__(self):
return self.df
| python |
<filename>src/main/resources/json/ULS2208.json
{"acadYear":"2019/2020","description":"Situated within a megadiverse biodiversity-hotspot, Singapore has drastically-reduced natural areas yet remains surprisingly species-rich. Combined with her colonial legacy, infrastructural capabilities and cultural biases, Singapore offers a unique situation for studying biodiversity. In this module, we study how Singapore’s biodiversity landscape as well as the motivations and methods for studying biodiversity have evolved across Singapore’s history. Retracing how prominent naturalists explored Singapore’s biodiversity in the past, we imagine how they would do it today using current techniques. This module has a strong fieldwork component, imbuing students with naturalist sensibilities which heightens their awareness of Singapore’s diverse but oft-neglected natural heritage.","title":"Biodiversity and Natural History in Singapore","department":"University Scholars Programme","faculty":"University Scholars Programme","workload":"2/4*-2/4*-2/4*-2/4*-6","moduleCredit":"4","moduleCode":"ULS2208","attributes":{"su":true},"semesterData":[{"semester":2,"timetable":[{"classNo":"01","startTime":"0800","endTime":"1200","weeks":[1,2,3,4,5,6,7,8,9,10,11,12,13],"venue":"USP-MC","day":"Tuesday","lessonType":"Seminar-Style Module Class","size":30}]}]}
| json |
import { KeyValue } from '@angular/common';
export class ProductModel {
engineTypeName: string;
categoryName: string;
constructor(
public id: string,
public code: string,
public modelName: string,
public modelCategory: number ,
public modelEngineType: number,
public customerRating: number,
public internalRating: number,
public modelPrice: number,
public description: string
) {
}
}
| typescript |
@import url("fonts.css");
body {
background-color: rgb(237, 247, 235);
color: black
}
h1 { /* per-page main title */
font-family: 'Cooper-Hewitt';
margin-top: 4rem;
font-size: 2.3rem;
font-weight: bold;
line-height: 1.2;
width: 90%;
/* a little nudge to make text visually lower than 4rem rule in left margin */
position: relative;
top: 6px;
}
h2, h3, h4, h5, h6, h7, h8 {
font-family: 'Cooper-Hewitt', sans-serif;
font-weight: 300;
font-size: 1.6rem;
color: #333;
margin-top: inherit;
margin-bottom: 1rem;
line-height: 1.25;
}
p {
max-width: 700px;
font-size: 16px;
line-height: 1.7;
font-family: Charter-Racket
}
.header {
padding: 10px 0;
position: relative;
background: rgb(150, 181, 143);
border-bottom: 1px solid #eaeaea;
}
.header h1{
float: left;
margin-top: -5px;
margin-bottom: -20px;
margin-left: 10px;
padding: 0;
font-size: 100%
}
.nav {
margin: 0 auto;
padding: 0 15px;
text-align: right;
}
.nav-logo {
float: left;
margin-top: -11px;
transition: transform 150ms ease-out;
}
.nav-logo:hover {
transform: scale(1.1);
}
.nav-logo img {
max-height: 40px;
width: auto;
}
.nav-links {
margin: 0;
padding: 0px;
}
.nav-links a {
font-size: 14px;
color: rgb(214, 240, 209);
font-family: 'Fira';
text-decoration: none;
font-weight: 900;
padding: 10px;
}
.nav-links a:hover {
color: #000000;
}
| css |
<filename>vendor/github.com/json-iterator/go/output_tests/struct/struct/empties/types.go
package test
type typeForTest struct {
F1 struct{}
F2 struct{}
F3 struct{}
}
| go |
html{
padding: 0;
margin: 0;
overflow-x: hidden !important;
}
.custom-shape-divider-bottom-1637170131 {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
overflow: hidden;
line-height: 0;
}
.custom-shape-divider-bottom-1637170131 svg {
position: relative;
display: block;
width: calc(100% + 1.3px);
height: 73px;
}
.custom-shape-divider-bottom-1637170131 .shape-fill {
fill: #FFFFFF;
}
/** For tablet devices **/
@media (min-width: 768px) and (max-width: 1023px) {
.custom-shape-divider-bottom-1637170131 svg {
width: calc(100% + 1.3px);
height: 93px;
}
}
/** For mobile devices **/
@media (max-width: 767px) {
.custom-shape-divider-bottom-1637170131 svg {
width: calc(100% + 1.3px);
height: 61px;
}
}
.btn.btn-lg{
padding: 0.5rem 1rem !important;
font-size: larger !important;
border-radius: 5px !important;
}
.btn-default{
background: #8a777782 !important;
}
.btn-primary{
background: #fbbf24 !important;
}
.sweet-alert.showSweetAlert > h2{
font-size: xx-large !important;
}
.sweet-alert.showSweetAlert > p.lead {
font-size: larger !important;
padding: 1.5rem 1rem !important;
}
div label input {
margin-right:100px;
}
body {
font-family:sans-serif;
}
| css |
{
"vorgangId": "8165",
"VORGANG": {
"WAHLPERIODE": "16",
"VORGANGSTYP": "Ansprache/Erklärung/Mitteilung",
"TITEL": "Worte des Gedenkens an den früheren Bundestagspräsidenten Dr. <NAME> und an den früheren Bundesratspräsidenten <NAME> (G-SIG: 16021091)",
"AKTUELLER_STAND": "",
"SIGNATUR": "",
"GESTA_ORDNUNGSNUMMER": "",
"PLENUM": {
"PLPR_KLARTEXT": "Ansprache",
"PLPR_HERAUSGEBER": "BR",
"PLPR_NUMMER": "825",
"PLPR_SEITEN": "261A - 261B",
"PLPR_LINK": "http://dipbt.bundestag.de:80/dip21/brp/825.pdf#P.261"
},
"EU_DOK_NR": "",
"SCHLAGWORT": {
"_fundstelle": "true",
"__cdata": "Bundesrat: Gedenken"
},
"ABSTRAKT": "Würdigung der Verdienste des früheren Bundestagspräsidenten Dr. <NAME> und des früheren Hessischen Ministerpräsidenten und Bundesratspräsidenten <NAME>\r\n \r\n"
},
"VORGANGSABLAUF": {
"VORGANGSPOSITION": {
"ZUORDNUNG": "BR",
"URHEBER": "Ansprache",
"FUNDSTELLE": "22.09.2006 - BR-Plenarprotokoll 825, S. 261A - 261B",
"FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/brp/825.pdf#P.261",
"PERSOENLICHER_URHEBER": {
"VORNAME": "<NAME>",
"NACHNAME": "Carstensen",
"FUNKTION": "Bundesratspräs.",
"AKTIVITAETSART": "Rede",
"SEITE": "261A"
}
}
}
}
| json |
const path = require("path");
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const bookTemplate = path.resolve("src/templates/bookTemplate.js");
const {
data: {
allBook: { edges },
},
} = await graphql(`
{
allBook {
edges {
node {
id
}
}
}
}
`);
edges.forEach(book => {
createPage({
path: `/book/${book.node.id}`,
component: bookTemplate,
context: { bookId: book.node.id },
});
});
};
exports.onCreateWebpackConfig = ({ actions, stage }) => {
if (stage === "develop-html" || stage === "build-html") {
actions.setWebpackConfig({
resolve: {
mainFields: ["main"],
},
});
} else {
actions.setWebpackConfig({
resolve: {
mainFields: ["browser", "module", "main"],
},
});
}
};
| javascript |
why we need domicile certificate, what is its relation with the studies. Its a simple equation that if she clears NEET exam then she will get admission otherwise not , as simple as that and she is giving a valid reason for that for her education. But why will you take, you will take reservation people with poor marks and that leads to poor doctor.The position which we call as a doctor.
| english |
My Latest Still Life Painting Now Available On My Ebay Store!!
My Latest Still Life Painting Now Available On My Ebay Store!!
Greetings Everyone,
Now I would like to announce that my latest still life painting is now ready for purchase.
| english |
The Brothers of Italy party, which won the most votes in Italy’s national election, has its roots in the post-World War II neo-fascist Italian Social Movement.
Keeping the movement’s most potent symbol, the tricolor flame, Giorgia Meloni has taken Brothers of Italy from a fringe far-right group to Italy’s biggest party.
A century after Benito Mussolini’s 1922 March on Rome, which brought the fascist dictator to power, Meloni is poised to lead Italy’s first far-right-led government since World War II and become its first female premier.
HOW DID POST-FASCISM BEGIN IN ITALY?
The Italian Social Movement, or MSI, was founded in 1946 by Giorgio Almirante, a chief of staff in Mussolini’s last government. It drew fascist sympathizers and officials into its ranks following Italy’s role in the war, when it was allied with the Nazis and then liberated by the Allies.
The 1990s brought about a change under Gianfranco Fini, Almirante’s protege who nevertheless projected a new moderate face of the Italian right. When Fini ran for Rome mayor in 1993, he won a surprising 46. 9% of the vote — not enough to win but enough to establish him as a player. Within a year, Fini had renamed the MSI the National Alliance.
It was in those years that a young Meloni, who was raised by a single mother in a Rome working-class neighborhood, first joined the MSI’s youth branch and then went onto lead the youth branch of Fini’s National Alliance.
DOES THAT MEAN MELONI IS NEO-FASCIST?
Fini was dogged by the movement’s neo-fascist roots and his own assessment that Mussolini was the 20th century’s “greatest statesman. ” He disavowed that statement, and in 2003 visited the Yad Vashem Holocaust memorial in Israel. There, he described Italy’s racial laws, which restricted Jews’ rights, as part of the “absolute evil” of the war.
During the campaign, Meloni was forced to confront the issue head-on, after the Democrats warned that she represented a danger to democracy.
“The Italian right has handed fascism over to history for decades now, unambiguously condemning the suppression of democracy and the ignominious anti-Jewish laws,” she said in a campaign video.
HOW DID BROTHERS OF ITALY EMERGE?
Meloni, who proudly touts her roots as an MSI militant, has said the first spark of creating Brothers of Italy came after Berlusconi resigned as premier in 2011, forced out by a financial crisis over Italy’s soaring debt and his own legal problems.
Meloni refused to support Mario Monti, who was tapped by Italy’s president to try to form a technocratic government to reassure international financial markets. Meloni couldn’t stand what she believed was external pressure from European capitals to dictate internal Italian politics.
Meloni co-founded the party in 2012, naming it after the first words of the Italian national anthem. “A new party for an old tradition,” Meloni wrote.
As the leader of the only party in opposition during Mario Draghi’s 2021-2022 national unity government, her popularity soared, with Sunday’s election netting it 26%.
BUT WHAT ABOUT THE PARTY’S LOGO?
The party has at the center of its logo the red, white and green flame of the original MSI that remained when the movement became the National Alliance. While less obvious than the bundle of sticks, or fasces, that was the prominent symbol of Mussolini’s National Fascist Party, the tricolor flame is nevertheless a powerful image that ties the current party to its past.
“Political logos are a form of branding, no different than those aimed at consumers,” Rutgers University professor T. Corey Brennan said.
He recalled that when Almirante made his final MSI campaign pitch to voters in the 1948 election at Rome’s Spanish Steps, he put the party’s flame symbol on top of the obelisk and illuminated it with floodlights.
“You can make whatever you want out of a flame, but everybody understood that Almirante was making a deeply emotional appeal to keep the spirit of fascism alive,” he said.
HOW DO ITALIANS FEEL ABOUT IT?
In general, the party’s neo-fascist roots appear to be of more concern abroad than at home. Some historians explain that by noting a certain historical amnesia here and Italians’ general comfort living with the relics of fascism as evidence that Italy never really repudiated the Fascist Party and Mussolini in the same way Germany repudiated National Socialism and Hitler.
While Germany went through a long and painful process reckoning with its past, Italians have in many ways simply turned a willful blindness to their own.
Historian David Kertzer of Brown University notes that there are 67 institutes for the study of the Resistance to Fascism in Italy, and virtually no center for the study of Italian Fascism.
In addition, Mussolini-era architecture and symbols are everywhere: from the EUR neighborhood in southern Rome to the Olympic training center on the Tiber River, with its obelisk still bearing Mussolini’s name.
The Italian Constitution bars the reconstitution of the Fascist party, but far-right groups still display the fascist salute and there continues to be an acceptance of fascist symbols in daily life, said Brennan, the Rutgers professor.
DOES THAT MEAN ITALIANS SUPPORT FASCISM?
If history is any guide, one constant in recent Italian political elections is a vote for change, with a desire for something new seemingly overtaking traditional political ideology in big pendulum shifts, said Nathalie Tocci, director of the Rome-based Institute of International Affairs.
Tocci said the Brothers of Italy’s popularity in 2022 was evidence of this “violent” swing from left to right that is more about Italian dissatisfaction than any surge in neo-fascist or far-right sentiment.
“I would say the main reason why a big chunk of that — let’s say 25-30% — will vote for this party is simply because it’s the new kid on the block,” she said.
Meloni still speaks reverently about the MSI and Almirante, even if her rhetoric can change to suit her audience.
Back home on the campaign trail, she projected a much more moderate tone and appealed for unity in her victory speech Monday. | english |
NAIROBI, Kenya, Aug 26 – Thirteen officials from the Kenya Ports Authority and KRA have been charged with releasing containers without payment of customs duty worth Sh9 million.
The officials pleaded not guilty to the offence, which is said to have occurred between June 21 and 23 this year.
Mombasa Principal Magistrate Douglas Ogoti released them on a Sh300,000 bond or an alternative cash bail of Sh100,000 each, ahead of the hearing of the case on September 13.
They were arrested in the ongoing probe of tax evasion at the Port of Mombasa by a multi-agency team comprising Kenya Revenue Authority, KPA, National Intelligence Service and Directorate of Criminal Investigation.
The charges indicate that the officials failed to make entries of the containers in the KPA’s Simba Systems.
“Being public officers employed in a public body KPA abused office by failing to make entries into the samba system in respect of three containers thereby causing a revenue loss being customs import duty,” the charges read.
Two directors of a Container Freight Station were also charged with felony for refusing to pay customs duty fee for the three containers.
Senior KRA and KPA officials are accused of running cartels at the port involving smuggling of goods and drugs at the Port of Mombasa.
President Uhuru Kenyatta has directed the new KPA Managing Director to restore sanity at the port. | english |
BEIJING: China will impose sanctions on US companies including Boeing and Lockheed Martin for supplying weapons to rival Taiwan, a foreign ministry spokesman said Monday.Raytheon also will be affected, said the spokesman, Zhao Lijian.He gave no details of what penalties might be imposed or when.China and Taiwan split during a civil war in 1949 and have no diplomatic relations.Beijing claims the democratically led island as part of the communist mainland's territory and has threatened to invade."In order to safeguard national interests, China decided to impose sanctions on the American companies that were involved in arms sales to Taiwan," Zhao said at a regular news briefing.
| english |
{"parent":"fd8af7ce-b8f3-41af-8ceb-15c4e23a9657","pid":8010,"argv":["/home/travis/.nvm/versions/node/v10.19.0/bin/node","/tmp/shelljs_14c6cd55274ea7044cfd"],"execArgv":[],"cwd":"/home/travis/build/commitizen/cz-cli/test/.tmp/enduser-app","time":1586289996128,"ppid":8009,"coverageFilename":"/home/travis/build/commitizen/cz-cli/.nyc_output/834f0a67-5dba-4b4d-b4e9-352e15f3fe0f.json","externalId":"","uuid":"834f0a67-5dba-4b4d-b4e9-352e15f3fe0f","files":[]} | json |
{"title":"Daglicht","directShadow":"Schaduw tonen","notSupportedInHW":"Deze feature wordt niet ondersteund in deze browser.","unsupported":"De tool Daglicht wordt alleen ondersteund in SceneView.","datePattern":"d. MMMM yyyy","playDay":"Zon- en schaduwwerking over de dag animeren","playYear":"Zon- en schaduwwerking over het jaar animeren","pause":"Pauzeren","season":"Seizoen","spring":"Bron","summer":"Zomer","winter":"Winter","fall":"Herfst"} | json |
Kapittel 122En sang ved festreisene; av David.
Jeg gleder mig ved dem som sier til mig: Vi vil gå til Herrens hus.
2 Våre føtter står i dine porter, Jerusalem!
3 Jerusalem, du velbyggede, lik en by som er tett sammenføiet,
4 hvor stammene drar op, Herrens stammer, efter en lov for Israel, for å prise Herrens navn!
5 For der er stoler satt til dom, stoler for Davids hus.
6 Bed om fred for Jerusalem! La det gå dem vel som elsker dig!
7 Der være fred innen din voll, ro i dine saler!
8 For mine brødres og mine venners skyld vil jeg si: Fred være i dig!
9 For Herrens, vår Guds huses skyld vil jeg søke ditt beste.
| english |
This period is surely going to bring all the authority. A foreign connection will serve Mitchell Marsh well for a considerable duration, and they might just be the source of the extra unexpected income on the cards for Mitchell Marsh and power that Mitchell Marsh strive for. Keep up the tempo and believe in Mitchell Marsh's abilities, the period will see Mitchell Marsh off in a completely new position. Family atmosphere will be very supporting. A long distance travel will be rewarding. Mitchell Marsh will take interest in religion and perform charitable deeds.
The period will not be awfully beneficial to Mitchell Marsh. Mitchell Marsh might face problems related to money matters. Tuning with Mitchell Marsh's own people and Mitchell Marsh's relatives may get disturbed. Give proper attention to our day to day pursuits. This is not a perfect time for taking any risk regarding business matters as the chances of loss are very high during this period. Health ailment of Mitchell Marsh's parents can disturb Mitchell Marsh's peace of mind. Mitchell Marsh will not be able to fulfill Mitchell Marsh's family’s expectations.
Increase of income position and bank balances will improve. This is a good time to start new ventures. This transit indicates new friendships and relationships and gain through them. Previous work, as well as newly starting works will bring good and desired results, Mitchell Marsh's cherished desires will be fulfilled. Mitchell Marsh may get into new trade or get new contracts. Help from superiors or people in responsible or influential positions can be expected. Over all prosperity is also indicated in this period. Mitchell Marsh need to pay special attention to the relationship with Mitchell Marsh's life-partner and some caution is required there.
This is a period of mixed results for Mitchell Marsh. In this period Mitchell Marsh will suffer due to mental stress and strain. Mitchell Marsh may face problem in Mitchell Marsh's business partnerships. Financially the period is not so good. Journeys will not be fruitful. Risk taking tendencies could be curbed totally. Mitchell Marsh can get into conflicts with Mitchell Marsh's dear ones so better try to avoid these kinds of situations. However, this is not a good period for love and romance. Mitchell Marsh should be very careful in love and relationship as it can bring disrespect and loss of honor to Mitchell Marsh.
A visit to a holy place of Mitchell Marsh's interest is on the charts. Mitchell Marsh will, however, have a romantic and charismatic attitude, and this will help Mitchell Marsh maintain cordial relations with the ones Mitchell Marsh know and establish contacts with the ones Mitchell Marsh don’t. There is certain amount of wish fulfillment which generally means gains in dealings or promotions in the hierarchy of the organization Mitchell Marsh work for. Acqusition of a new vehicle or buying new land is on the cards. Overall, the period is very good.
This is the period for Mitchell Marsh to add some spice into Mitchell Marsh's romance life. This is an excellent period for Mitchell Marsh to get profits from Mitchell Marsh's contracts and agreements. This is the perfect time for Mitchell Marsh to enter into deals that will surely work in Mitchell Marsh's favor. There will be increase in income from business and other ventures and ries in position and status. Now Mitchell Marsh have enough prerequisites in order to fully harmonize this area of Mitchell Marsh's personal life. Mitchell Marsh will aquire vehicles and other comforts. This is the time for Mitchell Marsh to add status and position to Mitchell Marsh's family life. A marked increase in Mitchell Marsh's income is indicated.
This will prove to be a fantastic period for Mitchell Marsh. Mitchell Marsh will be very confident with Mitchell Marsh's thoughts and chance of getting promotion is highly recommended. There are chances of sudden travel which seems to be very fruitful. There will be happiness from siblings and from the opposite sex. This is also a good period for Mitchell Marsh's borthers. Thought of changing place or profession should be avoided.
Mitchell Marsh will get full co-operation from superiors or people in responsible or influential positions. Mitchell Marsh can make great progress professionally. Mitchell Marsh might have to shoulder important responsibilities both at the career and domestic fronts. There will be a good opportunity to come into contact with compatible persons in the course of Mitchell Marsh's official duties/ travels. Mitchell Marsh will be precious metals, gems and jewelry. Mitchell Marsh's children will require attention as they will be more vulnerable during this period.
New areas Mitchell Marsh explore this period could be loss generating as there could be steady rise in expenses which might not yield direct gains or any long term position. There may be trouble from the enemies and legal problems. Mitchell Marsh will be able to continue with existing line of work & remain low profile and stable in Mitchell Marsh's outlook. The outlook for gain should be short term only. Medium & long term projects are better started. There may be problem s related to Mitchell Marsh's eyes. Mitchell Marsh's friendship with the opposite sex will not be cordial plans of making quick money should be scrutinized first. There can be problem to Mitchell Marsh's girl friend/ boy friend.
What will you get in 250+ pages Colored Brihat Horoscope.
Are money matters a reason for the dark-circles under your eyes?
Is there any question or problem lingering.
Worried about your career? don't know what is.
AstroSage Yearbook is a channel to fulfill your dreams and destiny.
The CogniAstro Career Counselling Report is the most comprehensive report available on this topic.
Buy Genuine Gemstones at Best Prices.
Energised Yantras for You.
Original Rudraksha to Bless Your Way.
Bring Good Luck to your Place with Feng Shui.
Praise the Lord with Divine Energies of Mala.
Jadi (Tree Roots)
Keep Your Place Holy with Jadi.
| english |
<filename>Algorithm/coding_interviews/Java/Test18.java
/**
* Author: 王俊超
* Date: 2015-04-23
* Time: 19:06
* Declaration: All Rights Reserved !!!
*/
public class Test18 {
/**
* 二叉树的树结点
*/
public static class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
/**
* 输入两棵二叉树A和B,判断B是不是A的子结构。
* 该方法是在A树中找到一个与B树的根节点相等的元素的结点,
* 从这个相等的结点开始判断树B是不是树A的子结构,如果找到其的一个就返回,
* 否则直到所有的结点都找完为止。
*
* @param root1 树A的根结点
* @param root2 树B的根结点
* @return true:树B是树A的子结构,false:树B是不树A的子结构
*/
public static boolean hasSubtree(BinaryTreeNode root1, BinaryTreeNode root2) {
// 只要两个对象是同一个就返回true
// 【注意此处与书本上的不同,书本上的没有这一步】
if (root1 == root2) {
return true;
}
// 只要树B的根结点点为空就返回true
if (root2 == null) {
return true;
}
// 树B的根结点不为空,如果树A的根结点为空就返回false
if (root1 == null) {
return false;
}
// 记录匹配结果
boolean result = false;
// 如果结点的值相等就,调用匹配方法
if (root1.value == root2.value) {
result = match(root1, root2);
}
// 如果匹配就直接返回结果
if (result) {
return true;
}
// 如果不匹配就找树A的左子结点和右子结点进行判断
return hasSubtree(root1.left, root2) || hasSubtree(root1.right, root2);
}
/**
* 从树A根结点root1和树B根结点root2开始,一个一个元素进行判断,判断B是不是A的子结构
*
* @param root1 树A开始匹配的根结点
* @param root2 树B开始匹配的根结点
* @return 树B是树A的子结构,false:树B是不树A的子结构
*/
public static boolean match(BinaryTreeNode root1, BinaryTreeNode root2) {
// 只要两个对象是同一个就返回true
if (root1 == root2) {
return true;
}
// 只要树B的根结点点为空就返回true
if (root2 == null) {
return true;
}
// 树B的根结点不为空,如果树A的根结点为空就返回false
if (root1 == null) {
return false;
}
// 如果两个结点的值相等,则分别判断其左子结点和右子结点
if (root1.value == root2.value) {
return match(root1.left, root2.left) && match(root1.right, root2.right);
}
// 结点值不相等返回false
return false;
}
public static void main(String[] args) {
BinaryTreeNode root1 = new BinaryTreeNode();
root1.value = 8;
root1.right = new BinaryTreeNode();
root1.right.value = 7;
root1.left = new BinaryTreeNode();
root1.left.value = 8;
root1.left.left = new BinaryTreeNode();
root1.left.left.value = 9;
root1.left.right = new BinaryTreeNode();
root1.left.right.value = 2;
root1.left.right.left = new BinaryTreeNode();
root1.left.right.left.left = new BinaryTreeNode();
root1.left.right.left.left.value = 4;
root1.left.right.left.right = new BinaryTreeNode();
root1.left.right.left.right.value = 7;
BinaryTreeNode root2 = new BinaryTreeNode();
root2.value = 8;
root2.left = new BinaryTreeNode();
root2.left.value = 9;
root2.right = new BinaryTreeNode();
root2.right.value = 2;
System.out.println(hasSubtree(root1, root2));
System.out.println(hasSubtree(root2, root1));
System.out.println(hasSubtree(root1, root1.left));
System.out.println(hasSubtree(root1, null));
System.out.println(hasSubtree(null, root2));
System.out.println(hasSubtree(null, null));
}
}
| java |
<gh_stars>100-1000
/* ==UserStyle==
@name friends.nico用マストドンCSS
@namespace USO Archive
@author ln-north
@description `friends.nico用マストドンCSSを作りました<br>アンケートもいい感じに打てるようにしてみました<br>CWとアンケートは同時に打てないのは仕様です m(_ _)m`
@version 20171023.2.15
@license CC-BY-4.0
@preprocessor uso
==/UserStyle== */
@-moz-document domain("friends.nico") {
body {
font-family: 'Segoe UI', 'Avenir Next' !important;
font-weight: 500;
-webkit-font-smoothing: antialiased;
}
.columns-area {
flex-flow: row wrap;
position: relative;
}
/* drawer: 投稿フォームのやつ */
.drawer {
position: absolute;
bottom: 0;
left: 0;
order: 4;
width: 100%;
height: calc(80px + 24px);
padding: 0 !important;
overflow: visible;
z-index: 200;
}
.drawer__inner,
.drawer__pager {
overflow: visible;
}
.drawer > .drawer__header {
display: none;
}
.drawer > .search {
display: none;
}
.drawer > .drawer__pager {
display: flex;
flex-flow: row wrap;
height: 50%;
}
.drawer .drawer__inner {
display: flex;
flex-flow: row nowrap;
}
.drawer .nico-connect-account,
.drawer .announcements,
.drawer .favourite-tags,
.drawer .navigation-bar {
display: none;
}
/* compose-form: 投稿フォーム */
.drawer .compose-form {
display: flex;
flex-flow: row nowrap;
flex-grow: 1;
position: relative;
overflow: visible;
}
.compose-form > .compose-form__autosuggest-wrapper {
flex-grow: 1;
}
.compose-form .autosuggest-textarea__textarea {
border-radius: 4px;
box-sizing: border-box;
padding-right: 158px;
min-height: 80px;
}
.compose-form > div:first-child:not(.compose-form__autosuggest-wrapper) {
overflow: visible !important;
width: 100%;
height: 50px;
position: absolute;
top: -46px;
left: 0;
padding: 8px 10px;
background-color: #444b5d;
z-index: 200;
box-sizing: border-box;
}
.compose-form > .compose-form__autosuggest-wrapper > div:not(:first-child) {
display: none;
}
.compose-form .compose-form__modifiers {
display: none;
}
.compose-form .compose-form__modifiers + div:not(.compose-form__buttons-wrapper) {
overflow: visible !important;
width: 100%;
height: 50px !important;
position: absolute;
top: -46px;
left: 0;
padding: 8px 10px;
background-color: #444b5d;
z-index: 200;
box-sizing: border-box;
display: flex !important;
flex-flow: row nowrap;
}
.compose-form .enquete-input {
width: 25%;
box-sizing: border-box;
}
.compose-form .enquete-input + .enquete-input {
margin-left: 8px;
}
.compose-form .compose-form__buttons {
position: relative;
background: transparent;
padding: 0;
}
.compose-form .compose-form__upload-button,
.compose-form .privacy-dropdown,
.compose-form .text-icon-button,
.compose-form .compose-form__enquete-button,
.compose-form .compose-form__sensitive-button--visible {
position: absolute;
top: 4px;
width: 30px;
height: 30px;
box-sizing: border-box;
padding: 4px;
}
.compose-form .compose-form__sensitive-button--visible {
left: -158px;
}
.compose-form .compose-form__upload-button {
left: -128px;
}
.compose-form .privacy-dropdown {
left: -98px;
}
.compose-form .text-icon-button {
left: -68px;
}
.compose-form .compose-form__enquete-button {
left: -38px;
}
.compose-form .compose-form__publish {
position: relative;
}
.compose-form .character-counter__wrapper {
position: absolute;
bottom: 0;
left: 0;
transform: translateX(calc(-100% - 16px));
z-index: 1;
}
.compose-form .character-counter {
color: #606984;
font-size: 14px;
}
.compose-form .compose-form__publish-button-wrapper {
display: none;
}
/* columns-area: トゥートとかあるとこ */
.columns-area > .column {
display: none;
}
.columns-area > .column + .column {
display: flex;
}
.columns-area > .column:nth-child(2) {
order: 2;
}
.columns-area > .column:nth-child(3) {
order: 1;
}
.columns-area > .column:nth-child(3),
.columns-area > .column:nth-child(4) {
height: calc(100vh - 100px - 8px);
padding-bottom: 0;
}
/* LTL */
.columns-area > .column:nth-child(4) {
flex-grow: 1;
margin-left: 8px;
box-sizing: border-box;
}
/* 通知 */
.columns-area > .column:nth-child(3) {
flex-shrink: 0;
width: 360px;
margin-right: 8px;
}
} | css |
// Copyright 2017 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** \file
*
* Illustrates matrix factorization with parallel SGD. We first create factors and then a data matrix
* from these factors. This process ensures that we know the best factorization of the input.
* These matrices are distributed across a cluster. We then try to reconstruct the factors
* using PSGD.
*/
#include <iostream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/random/uniform_real.hpp>
#include <mf/matrix/io/generateDistributedMatrix.h>
#include <util/evaluation.h>
#include <mpi2/mpi2.h>
#include <mf/mf.h>
log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main"));
using namespace std;
using namespace mf;
using namespace mpi2;
using namespace rg;
using namespace boost::numeric::ublas;
// type of SGD
typedef UpdateTruncate<UpdateNzslL2> Update;
typedef RegularizeNone Regularize;
typedef SumLoss<NzslLoss, L2Loss> Loss;
typedef NzslLoss TestLoss;
int main(int argc, char* argv[]) {
using namespace boost::program_options;
// initialize mf library and mpi2
boost::mpi::communicator& world = mfInit(argc, argv);
mfStart();
if (world.rank() == 0)
{
#ifndef NDEBUG
LOG4CXX_WARN(logger, "Warning: Debug mode activated (runtimes may be slow).");
#endif
//data
mf_size_type epochs;
string inputSampleMatrixFile;
string inputMatrixFile;
string inputRowFacFile;
string inputColFacFile;
string outputRowFacFile;
string outputColFacFile;
string inputTestMatrixFile;
string traceFile,traceVar;
string shuffleStr;
double lambda = 50;
double eps0 = 0.01;
// parameters for distribution
int tasks;
options_description desc("Options");
desc.add_options()
("help", "produce help message")
("epochs", value<mf_size_type>(&epochs)->default_value(10), "number of epochs to run [10]")
("lambda", value<double>(&lambda)->default_value(50), "lambda")
("eps0", value<double>(&eps0)->default_value(0.01), "initial step size for BoldDriver")
("tasks-per-rank", value<int>(&tasks)->default_value(1), "number of concurrent tasks [1]")
("trace", value<string>(&traceFile)->default_value("trace.R"), "filename of trace [trace.R]")
("traceVar", value<string>(&traceVar)->default_value("trace"), "variable name for trace [traceVar]")
("input-file", value<string>(&inputMatrixFile), "input matrix")
("input-test-file", value<string>(&inputTestMatrixFile), "input test matrix")
("input-row-file", value<string>(&inputRowFacFile), "input initial row factor")
("input-col-file", value<string>(&inputColFacFile), "input initial column factor")
("output-row-file", value<string>(&outputRowFacFile), "output initial row factor")
("output-col-file", value<string>(&outputColFacFile), "output initial column factor")
("shuffle",value<string>(&shuffleStr)->default_value("seq"),"shuffle method eg seq, par, parAdd")
;
positional_options_description pdesc;
pdesc.add("input-file", 1);
pdesc.add("input-test-file", 2);
pdesc.add("input-sample-matrix-file", 3);
pdesc.add("input-row-file", 4);
pdesc.add("input-col-file", 5);
variables_map vm;
store(command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);
notify(vm);
if (vm.count("help") || vm.count("input-file")==0) {
cout << "psgd with L2 NoLock (Hogwild-style) [options] <input-file> " << endl << endl;
cout << desc << endl;
return 1;
}
LOG4CXX_INFO(logger, "Using " << tasks << " parallel tasks");
PsgdShuffle shuffle;
if (shuffleStr.compare("seq") == 0)
shuffle= PSGD_SHUFFLE_SEQ;
else if (shuffleStr.compare("par") == 0)
shuffle= PSGD_SHUFFLE_PARALLEL;
else
shuffle= PSGD_SHUFFLE_PARALLEL_ADDITIONAL_TASK;
LOG4CXX_INFO(logger, "Using " << shuffle);
// Read matrices
Random32 random;
// SparseMatrix v,vTest;
// DenseMatrix w;
// DenseMatrixCM h;
// readMatrix(inputMatrixFile,v);
// readMatrix(inputTestMatrixFile,vTest);
// readMatrix(inputRowFacFile,w);
// readMatrix(inputColFacFile,h);
Timer t;
t.start();
std::vector<DistributedSparseMatrix> dataVector=getDataMatrices<SparseMatrix>(inputMatrixFile,"V",true,
tasks, 1, 1, 1, true, false, &inputTestMatrixFile);
SparseMatrix& v = *mpi2::env().get<SparseMatrix>(dataVector[0].blocks()(0,0).var());
SparseMatrix& vTest = *mpi2::env().get<SparseMatrix>(dataVector[1].blocks()(0,0).var());
std::pair<DistributedDenseMatrix, DistributedDenseMatrixCM> factorsPair= getFactors(inputRowFacFile,
inputColFacFile, tasks, 1, 1, 1, true);
t.stop();
LOG4CXX_INFO(logger, "Total time for loading matrices: " << t);
DenseMatrix w = *mpi2::env().get<DenseMatrix>(factorsPair.first.blocks()(0,0).var());
DenseMatrixCM h = *mpi2::env().get<DenseMatrixCM>(factorsPair.second.blocks()(0,0).var());
// parameters for SGD
SgdOrder order = SGD_ORDER_WOR;
Update update = Update(UpdateNzslL2(lambda), -100, 100); // truncate for numerical stability
Regularize regularize;
Loss loss((NzslLoss()), L2Loss(lambda));
TestLoss testLoss;
BalanceType balanceType = BALANCE_NONE;
BalanceMethod balanceMethod = BALANCE_OPTIMAL;
// initialize the DSGD
PsgdRunner psgdRunner(random);
PsgdJob<Update,Regularize> psgdJob(v, w, h, update, regularize, order, tasks, shuffle);
BoldDriver decay(eps0);
Trace trace;
trace.addField("Loss", "L2");
trace.addField("Shuffle_method", shuffle);
trace.addField("input_file", inputMatrixFile);
trace.addField("sample_matrix", inputSampleMatrixFile);
trace.addField("tasks", tasks);
// print the test loss
FactorizationData<> testData(vTest, w, h);
LOG4CXX_INFO(logger, "Initial test loss: " << testLoss(testData));
// run HogwildSGD to try to reconstruct the original factors
t.start();
psgdRunner.run(psgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);
t.stop();
LOG4CXX_INFO(logger, "Total time: " << t);
// print the test loss
LOG4CXX_INFO(logger, "Final test loss: " << testLoss(testData));
// write trace to an R file
LOG4CXX_INFO(logger, "Writing trace to " << traceFile);
trace.toRfile(traceFile, traceVar);
// write computed factors to file
if (outputRowFacFile.length() > 0) {
LOG4CXX_INFO(logger, "Writing row factors to " << outputRowFacFile);
//DenseMatrix w0;
//unblock(dw, w0);
writeMatrix(outputRowFacFile, w);
}
if (outputColFacFile.length() > 0) {
LOG4CXX_INFO(logger, "Writing column factors to " << outputColFacFile);
//DenseMatrixCM h0;
//unblock(dh, h0);
writeMatrix(outputColFacFile, h);
}
}
mfStop();
mfFinalize();
return 0;
}
| cpp |
/**
* Copyright 2018-2020 Symlink GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { Response, NextFunction, Request } from "express";
import { CustomRestError } from "@symlinkde/eco-os-pk-api";
import { ProtectionController } from "./ProtectionController";
import { ITokenRequest } from "./ITokenRequest";
import { Log, LogLevel } from "@symlinkde/eco-os-pk-log";
import { serviceContainer, ECO_OS_PK_CORE_TYPES } from "@symlinkde/eco-os-pk-core";
import { PkCore, MsUser } from "@symlinkde/eco-os-pk-models";
const processRequestingPath = async (path: string): Promise<boolean> => {
const configClient: PkCore.IEcoConfigClient = serviceContainer.get<PkCore.IEcoConfigClient>(
ECO_OS_PK_CORE_TYPES.IEcoConfigClient,
);
const loadConf = await configClient.get("publicApiEndpoints");
const openRoutes: Array<string> = Object(loadConf.data.publicApiEndpoints);
if (path.split("/")[3] === "queue" || path.split("/")[3] === "docs" || path.split("/")[3] === "validation") {
return true;
}
const index = openRoutes.findIndex((entry: string) => entry === path);
if (index > -1) {
return true;
}
return false;
};
const processAuthenticationHeader = (req: Request): boolean => {
if (!req.headers.authorization) {
Log.log(`detect unauthorized request`, LogLevel.warning);
Log.log(req, LogLevel.warning);
return false;
}
if (req.headers.authorization.split(" ")[0] !== "Bearer" || req.headers.authorization.split(" ")[1] === undefined) {
Log.log(`detect unauthorized request`, LogLevel.warning);
Log.log(req, LogLevel.warning);
return false;
}
return true;
};
const processAuthenticationByToken = async (req: ITokenRequest, res: Response, next: NextFunction) => {
if (!req.headers.authorization) {
next(
new CustomRestError(
{
code: 401,
message: "access denied",
},
401,
),
);
return;
}
const protectionController: ProtectionController = ProtectionController.getInstance();
protectionController
.validateToken(req.headers.authorization.split(" ")[1])
.then((extractedToken) => {
req.decriptedToken = extractedToken;
next();
return;
})
.catch((err) => {
Log.log(err, LogLevel.error);
next(
new CustomRestError(
{
code: 401,
message: "access denied",
},
401,
),
);
return;
});
};
const protectionMiddelware = async (req: ITokenRequest, res: Response, next: NextFunction) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, Accept-Language, X-Captcha-Token, X-Captcha-Result, X-Req-Checksum, X-Language-Delimiter, X-Federation-Key, X-Federation-Checksum, X-Api-Key",
);
if ("OPTIONS" === req.method) {
next();
return;
}
if (await processRequestingPath(req.path)) {
next();
return;
}
if (!processAuthenticationHeader(req)) {
next(
new CustomRestError(
{
code: 401,
message: "access denied",
},
401,
),
);
return;
}
processAuthenticationByToken(req, res, next);
};
export { protectionMiddelware };
| typescript |
Spirited Vasco Sports Club, Goa, got the better of debutants Hindustan Aeronautics Limited by a solitary goal to stay in the title race in the Tata National Football League.
Satish Minz scored the all-important goal in the 20th round match in Bangalore on Friday.
Following a pass from Marcos Pereira on the left flank, Minz did well to head home in the 30th minute.
Wanderley Weis, hit the side bar and bounced back.
Vasco tried hard to increase their tally in the second session but without success.
The victory took Vasco's points tally to 37 while HAL remained on 25.
HAL's Sunil Kumar earned a yellow card.
| english |
<reponame>DGrifferty/Python
currency = {
'GDP' : 1.3,
'EUR' : 1.08,
'USD' : 1.0,
'AUD' : 0.66,
'JPY' : 0.0090
}
while True:
intialcur = str(input('Please Enter the currency you want to convert from\n: ')).upper()
while True:
if intialcur in currency:
break
else:
intialcur = str(input('Not in list. Please Enter the currency you want to convert from\n: ')).upper()
intialvalue = input('Please enter the amount of that currency\n: ')
while True:
try:
float(intialvalue)
break
except ValueError:
intialvalue = input('Not a number. Please enter the amount of that currency\n: ')
finalcur = str(input('Enter the currency you want to convert this to\n: ')).upper()
while True:
if finalcur in currency:
break
else:
finalcur = str(input('Not in list. Please Enter the currency you want to convert from\n: ')).upper()
finalvalue = (float(currency.get(str(intialcur))) * float(intialvalue)) / float(currency.get(str(finalcur)))
print(finalvalue)
decision = input('Would you like to convert more values?').lower()
if decision == 'no':
print('Goodbye')
exit()
elif decision != 'no' and decision != 'yes':
decision = input('Would you like to convert more values? Please enter yes or no\n: ').lower() | python |
//! # Smart Leds Trait
//!
//! Smart leds is a collection of crates to use smart leds on embedded devices with rust.
//!
//! Examples of smart leds include the popular WS2812 (also called Neopixel),
//! APA102 (DotStar) and other leds, which can be individually adressed.
//!
//! This crate is used as a common base, so that breaking changes which would
//! force all other crates to be updated, can be avoided.
//!
//! End users should use the [smart-leds](https://crates.io/crates/smart-leds)
//! crate, which contains various convenience functions.
#![no_std]
pub use {rgb::RGB, rgb::RGB16, rgb::RGB8, rgb::RGBA};
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct White<C>(pub C);
/// The RGBW Pixel
///
/// This is used for leds, that in addition to RGB leds also contain a white led
pub type RGBW<ComponentType, WhiteComponentType = ComponentType> =
RGBA<ComponentType, White<WhiteComponentType>>;
/// A trait that smart led drivers implement
///
/// The amount of time each iteration of `iterator` might take is undefined.
/// Drivers, where this might lead to issues, aren't expected to work in all cases.
pub trait SmartLedsWrite {
type Error;
type Color;
fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
where
T: Iterator<Item = I>,
I: Into<Self::Color>;
}
| rust |
<reponame>powerblossom/workcloud
from core.response import Response
from communities.tests import TestCase
class ReplyPermissionTest(TestCase):
def setUp(self):
self.create_user(is_staff=True)
def test_permission_reply_all(self):
self.create_forum()
self.create_thread()
thread_id = self.thread.id
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'name': 'tester',
'content': 'test'
}
)
assert (
response.status_code == Response.HTTP_201 and
self.data.get('thread').get('id') == thread_id and
self.data.get('reply_id') == 0 and
not self.data.get('user') and
self.data.get('name') == 'tester' and
self.data.get('content') == 'test' and
not self.data.get('is_deleted')
)
reply_id = self.data.get('id')
response = self.get(
'/api/communities/f/%d/replies/' % thread_id
)
assert (
response.status_code == Response.HTTP_200 and
len(self.data) == 1 and
self.data[0].get('name') == 'tester' and
self.data[0].get('content') == 'test'
)
response = self.patch(
'/api/communities/r/%d/' % reply_id,
{
'content': 'edit'
},
)
assert response.status_code == Response.HTTP_401
response = self.delete(
'/api/communities/r/%d/' % reply_id
)
assert response.status_code == Response.HTTP_401
response = self.patch(
'/api/communities/r/%d/' % reply_id,
{
'content': 'edit',
},
auth=True
)
assert response.status_code == Response.HTTP_200
response = self.delete(
'/api/communities/r/%d/' % reply_id,
auth=True
)
assert response.status_code == Response.HTTP_200
self.create_user(username='<EMAIL>')
response = self.patch(
'/api/communities/r/%d/' % reply_id,
{
'content': 'edit',
},
auth=True
)
assert response.status_code == Response.HTTP_404
response = self.delete(
'/api/communities/r/%d/' % reply_id,
auth=True
)
assert response.status_code == Response.HTTP_404
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'name': 'tester',
'content': 'test'
},
auth=True
)
assert (
response.status_code == Response.HTTP_201 and
self.data.get('thread').get('id') == thread_id and
self.data.get('reply_id') == 0 and
self.data.get('user').get('id') == self.user.id and
self.data.get('content') == 'test' and
not self.data.get('is_deleted')
)
response = self.get(
'/api/communities/f/%d/replies/' % thread_id
)
assert (
response.status_code == Response.HTTP_200 and
len(self.data) == 2
)
def test_permission_reply_member(self):
option = self.create_option(
permission_reply='member'
)
self.create_forum(option=option)
self.create_thread()
thread_id = self.thread.id
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'name': 'tester',
'content': 'test'
}
)
assert response.status_code == Response.HTTP_401
response = self.get(
'/api/communities/f/%d/replies/' % thread_id
)
assert response.status_code == Response.HTTP_200
self.create_user(username='<EMAIL>')
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'content': 'test'
},
auth=True
)
reply_id = self.data.get('id')
assert (
response.status_code == Response.HTTP_201 and
self.data.get('content') == 'test' and
self.data.get('user').get('username') == self.user.username
)
response = self.patch(
'/api/communities/r/%d/' % reply_id,
{
'content': 'edit',
},
auth=True
)
assert (
response.status_code == Response.HTTP_200 and
self.data.get('content') == 'edit'
)
response = self.delete(
'/api/communities/r/%d/' % reply_id,
auth=True
)
assert response.status_code == Response.HTTP_200
def test_permission_reply_staff(self):
option = self.create_option(
permission_reply='staff'
)
self.create_forum(option=option)
self.create_thread()
thread_id = self.thread.id
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'name': 'tester',
'content': 'test'
}
)
assert response.status_code == Response.HTTP_401
response = self.get(
'/api/communities/f/%d/replies/' % thread_id
)
assert response.status_code == Response.HTTP_200
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'content': 'test'
},
auth=True
)
assert response.status_code == Response.HTTP_201
reply_id = self.data.get('id')
response = self.patch(
'/api/communities/r/%d/' % reply_id,
{
'content': 'edit',
},
auth=True
)
assert (
response.status_code == Response.HTTP_200 and
self.data.get('content') == 'edit'
)
response = self.delete(
'/api/communities/r/%d/' % reply_id,
auth=True
)
assert response.status_code == Response.HTTP_200
self.create_user(username='<EMAIL>')
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'content': 'test'
},
auth=True
)
assert response.status_code == Response.HTTP_403
response = self.patch(
'/api/communities/r/%d/' % reply_id,
{
'content': 'edit',
},
auth=True
)
assert response.status_code == Response.HTTP_404
response = self.delete(
'/api/communities/r/%d/' % reply_id,
auth=True
)
assert response.status_code == Response.HTTP_404
def test_permission_thread_read_member(self):
option = self.create_option(
permission_read='member',
permission_reply='member'
)
self.create_forum(option=option)
self.create_thread()
thread_id = self.thread.id
response = self.get(
'/api/communities/f/%d/replies/' % thread_id
)
assert response.status_code == Response.HTTP_401
response = self.get(
'/api/communities/f/%d/replies/' % thread_id,
auth=True
)
assert response.status_code == Response.HTTP_200
self.create_user(username='<EMAIL>')
response = self.get(
'/api/communities/f/%d/replies/' % thread_id,
auth=True
)
assert response.status_code == Response.HTTP_200
def test_permission_thread_read_staff(self):
option = self.create_option(
permission_read='staff',
permission_reply='staff'
)
self.create_forum(option=option)
self.create_thread()
thread_id = self.thread.id
response = self.get(
'/api/communities/f/%d/replies/' % thread_id
)
assert response.status_code == Response.HTTP_401
response = self.get(
'/api/communities/f/%d/replies/' % thread_id,
auth=True
)
assert response.status_code == Response.HTTP_200
self.create_user(username='<EMAIL>')
response = self.get(
'/api/communities/f/%d/replies/' % thread_id,
auth=True
)
assert response.status_code == Response.HTTP_403
class ReplyModelTest(TestCase):
def setUp(self):
self.create_user(is_staff=True)
self.create_forum()
self.create_thread()
self.create_reply()
def test_nested_reply(self):
response = self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'content': 'test'
},
auth=True
)
assert (
response.status_code == Response.HTTP_201 and
self.data.get('reply_id') == 0
)
reply_id = self.data.get('id')
response = self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'reply_id': reply_id,
'content': 'test'
},
auth=True
)
assert (
response.status_code == Response.HTTP_201 and
self.data.get('reply_id') == reply_id
)
response = self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'reply_id': self.data.get('id'),
'content': 'test'
},
auth=True
)
assert (
response.status_code == Response.HTTP_201 and
self.data.get('reply_id') == reply_id
)
def test_reply_edit_delete(self):
response = self.patch(
'/api/communities/r/%d/' % self.reply.id,
{
'content': 'bow wow'
},
auth=True
)
assert (
response.status_code == Response.HTTP_200 and
self.data.get('content') == 'bow wow' and
self.data.get('reply_id') == 0 and
not self.data.get('name')
)
response = self.patch(
'/api/communities/r/%d/' % self.reply.id,
{
'reply_id': self.reply.id,
'name': 'dog',
'content': 'meow'
},
auth=True
)
assert (
response.status_code == Response.HTTP_200 and
self.data.get('content') == 'meow' and
self.data.get('reply_id') == 0 and
not self.data.get('name')
)
response = self.delete(
'/api/communities/r/%d/' % self.reply.id,
auth=True
)
assert response.status_code == Response.HTTP_200
self.get(
'/api/communities/f/%d/replies/' % self.thread.id,
auth=True
)
assert (
len(self.data) == 1 and
self.data[0].get('is_deleted')
)
def test_reply_to_invalid_id(self):
thread_id = int(self.thread.id) + 1
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'content': 'test'
},
auth=True
)
assert response.status_code == Response.HTTP_404
reply_id = int(self.reply.id) + 1
response = self.post(
'/api/communities/f/%d/reply/' % thread_id,
{
'reply_id': reply_id,
'content': 'test'
},
auth=True
)
assert response.status_code == Response.HTTP_404
class ReplyListTest(TestCase):
def setUp(self):
self.create_user(is_staff=True)
self.create_forum()
self.create_thread()
def test_reply_list(self):
self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'content': '1'
},
auth=True
)
reply_id = self.data.get('id')
self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'content': '4'
},
auth=True
)
self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'reply_id': reply_id,
'content': '2'
},
auth=True
)
nested_reply_id = self.data.get('id')
self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'content': '5'
},
auth=True
)
self.post(
'/api/communities/f/%d/reply/' % self.thread.id,
{
'reply_id': nested_reply_id,
'content': '3'
},
auth=True
)
self.get(
'/api/communities/f/%d/replies/' % self.thread.id,
auth=True
)
assert (
len(self.data) == 5 and
self.data[0].get('content') == '1' and
self.data[0].get('reply_id') == 0 and
self.data[1].get('content') == '2' and
self.data[1].get('reply_id') == reply_id and
self.data[2].get('content') == '3' and
self.data[2].get('reply_id') == reply_id and
self.data[3].get('content') == '4' and
self.data[3].get('reply_id') == 0 and
self.data[4].get('content') == '5' and
self.data[4].get('reply_id') == 0
)
| python |
import { Mjml, MjmlBody, MjmlBreakpoint, MjmlButton, MjmlHead, MjmlImage, MjmlPreview, MjmlTitle, MjmlWrapper } from 'mjml-react';
import React from 'react';
import { MailSection } from '../components/MailSection';
export const example = (
<Mjml>
<MjmlHead>
<MjmlBreakpoint width="768px" />
<MjmlTitle>My email</MjmlTitle>
<MjmlPreview>Last Minute Offer...</MjmlPreview>
</MjmlHead>
<MjmlBody width={500}>
<MjmlWrapper>
<MailSection backgroundColor="#efefef">
<MjmlImage src="https://static.wixstatic.com/media/5cb24728abef45dabebe7edc1d97ddd2.jpg" />
</MailSection>
<MailSection>
<MjmlButton
padding="20px"
backgroundColor="#346DB7"
href="https://www.daphnesmit.nl"
>
I like it!
</MjmlButton>
</MailSection>
</MjmlWrapper>
</MjmlBody>
</Mjml>
);
| typescript |
<reponame>ChilliCream/thor-docs<gh_stars>1-10
{
"docs": {
"Usage": ["installation", "dependencies"],
"Components": ["break", "column", "container", "row", "theme-provider"],
"Types": []
},
"examples": {
"Break": ["example-break"],
"Column": ["example-column-auto"]
}
} | json |
The bus accident in Kullu’s Sainj valley, which claimed the lives of 13 people, has once again cast the spotlight on the high incidence of road mishaps on Himachal Pradesh’s narrow roads.
As per official data, Himachal Pradesh has recorded the highest road fatalities among the three northern hill states, including Jammu and Kashmir and Uttarakhand, with an average of three deaths per day. Annually, around 3,000 people lose their lives in road mishaps in Himachal Pradesh, while 105 are killed in around 200 aciidents reported in the state per month.
Himachal also has a high road crash severity rate (the number of persons killed per 100 accidents) of nearly 40%, which is higher than the national rate of around 33%.
As per a survey conducted by the traffic, tourist and railways (TTR) wing of the Himachal Pradesh police, a total of 13,740 accidents took place in the state over last five years (2017-2021), in which around 5,503 people lost their lives.
Last year, the state recorded a total of 2,404 accidents, in which 1,053 people lost their lives. The highest road mishaps are reported in Jammu and Kashmir, but the severity rate for the UT is just 16%.
Around 3,634 fatalities were reported in the 22,000 road accidents reported in Jammu and Kashmir between 2017-2020. Among the three hill states, Uttarakhand has the highest severity ratio of nearly 64% among the three states. The state recorded 3,530 fatalities in about 5,464 road crashes in the corresponding period.
In the annual Road Accidents in India report published by the ministry of road transport and highways, Himachal is ranked 22nd in terms of accidents and 20th in terms of fatalities in the country.
Rash driving, speeding, dangerous overtaking, drugs and alcohol consumption, slippery and uneven road surfaces, suspected vehicle defects, adverse weather, non-provision of parapets and crash barriers on outer curves are to blame for the road mishaps. However, accounting for around 90% of all accidents, human error remains the primary cause for the accidents in the state.
Director general of police Sanjay Kundu said, “Mostly accidents take place due to human negligence and violations such as not wearing helmets and seat belts, drunk driving and speeding. Another reason is poor road engineering, no-crash barriers and poor pedestrian infrastructure. Inclement weather, leading to landslides and rockslides, area also among the major causes for the accidents,” said Kundu.
“Critical analysis of the road traffic accidents (RTAs) database for the last 5 years has been carried out to identify black spots, clusters, stretches, causes, timings and collision types for working out specific remedies,” the police chief said, adding that strict enforcement of traffic rules, rectification of black spots, erection of crash barriers, use of reflective clothing and patches by pedestrians are some of the measures being taken. | english |
<filename>extffox_rebuild/package.json
{"title":"ZMov extention","name":"zmov-ext","version":"1.0.5","id":"zmov-ext-x@westixy","description":"Add-on for the ZMov webapp that he work with local files.","main":"index.js","author":"Westixy","engines":{"firefox":">=38.0a1","fennec":">=38.0a1"},"license":"GPL3.0","keywords":["jetpack"]} | json |
Toyota Motors has agreed to pay an additional USD 32. 425 million in civil penalties as the result of two separate investigations into the Japanese auto-maker’s handling of auto recalls,US Transportation Secretary Ray LaHood announced on Monday.
Toyota will pay the maximum fines allowable under the law — USD 16. 375 million in one case and USD 16. 050 million in the other — in response to the Transportation Department’s assertion that it failed to comply with the requirements of the National Traffic and Motor Vehicle Safety Act for reporting safety defects to the National Highway Traffic Safety Administration (NHTSA),an official release said.
“Safety is our top priority and we take our responsibility to protect consumers seriously,” LaHood said.
The first investigation completed today resulted in a USD 16. 375 million fine over Toyota’s recall of nearly five million vehicles with accelerator pedals that could become entrapped by floor mats.
As an initial remedy,Toyota had recalled 55,000 all-weather floor mats on September 26,2007.
Subsequently,in October,2009,Toyota recalled 3. 8 million Toyota and Lexus vehicles over a similar problem.
This was expanded on January 27,2010,to include another 1. 1 million vehicles.
The second investigation completed today resulted in a USD 16. 050 million fine being imposed on the Japanese auto giant.
In that case,the National Highway Traffic Safety Administration (NHTSA) looked into whether Toyota properly notified the agency of a safety defect in several Toyota models that could result in a loss of steering control.
“Automakers are required to report any safety defects to NHTSA swiftly,and we expect them to do so,” said NHTSA Administrator David Strickland.
Toyota will pay the maximum in civil penalties for each of the two violations.
The maximum civil penalty established under the National Traffic and Motor Vehicle Safety Act is adjusted for inflation,and was set at USD 16. 050 million at the time of the steering relay rod recall in 2005.
In April,Toyota agreed to pay the maximum penalty of USD 16. 375 million in response to the department’s assertion that it failed to notify the NHTSA within five days of learning of the “sticky pedal” defect.
That brings the total civil penalties assessed for Toyota in 2010 to USD 48. 8 million,the Department of Transportation said. | english |
#!/usr/bin/python
#
# Copyright (C) 2005 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
# not this notice.
# (2) Reproduced in the COPYING file, and at:
# http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: <EMAIL>
# to discuss alternative licensing.
# -------------------------------------------------------------------------
import unittest
import sys; sys.path.append("../")
from Rationals import rational, limit
class Rationals_Tests(unittest.TestCase):
def test_Identities(self):
self.assertEqual( (1,1), rational(1.0))
self.assertEqual( (0,1), rational(0.0))
self.assertEqual( (-1,1), rational(-1.0))
def test_Integers(self):
self.assertEqual( (2,1), rational(2.0))
self.assertEqual( (-100,1), rational(-100.0))
def test_EasyFractions(self):
self.assertEqual( (1,2), rational(0.5))
self.assertEqual( (1,4), rational(0.25))
self.assertEqual( (-1,2), rational(-0.5))
def test_NastyFractions(self):
self.assertEqual( (1,3), rational(1.0/3))
self.assertEqual( (10,3), rational(3+1.0/3))
self.assertEqual( (-1,3), rational(-1.0/3))
self.assertEqual( (-10,3), rational(-3-1.0/3))
def test_OtherFractions(self):
self.assertEqual( (337,218), rational(337.0/218))
if __name__=="__main__":
unittest.main()
# RELEASE: MH, MPS
| python |
<gh_stars>1-10
{"meta":{"build_time":"2021-04-11T07:04:14.468Z","license":"CC-BY-4.0","version":"2.0-beta"},"data":{"date":"2021-01-05","state":"AR","meta":{"data_quality_grade":"A+","updated":"2021-01-05T05:00:00Z","tests":{"total_source":"totalTestsViral"}},"cases":{"total":238888,"confirmed":195930,"probable":42958},"tests":{"pcr":{"total":2104323,"pending":null,"encounters":{"total":null},"specimens":{"total":2104323,"positive":null,"negative":1908393},"people":{"total":null,"positive":238888,"negative":1908393}},"antibody":{"encounters":{"total":null,"positive":null,"negative":null},"people":{"total":null,"positive":null,"negative":null}},"antigen":{"encounters":{"total":null,"positive":null,"negative":null},"people":{"total":261928,"positive":50949,"negative":210979}}},"outcomes":{"recovered":210617,"hospitalized":{"total":11743,"currently":1323,"in_icu":{"total":null,"currently":426},"on_ventilator":{"total":1256,"currently":224}},"death":{"total":3836,"confirmed":3205,"probable":631}}}}
| json |
Anulom Vilom Pranayam Video: In the Anulom-Vilom Pranayama, the method of breathing and exhaling is repeated again and again. This pranayama is also called 'pulse purifier pranayama'. By doing Anulom-Vilom daily, all the nerves of the body remain healthy. People of all ages can do this pranayama. In old age, by doing Anulom-Vilom Pranayama Yoga, arthritis, joint pain and swelling etc. are eliminated.
- Spread the blankets or mats in a clean place and sit on them as per your convenience in Padmasana, Siddhasana, Swastikasana or Sukhasana.
- Then close the right pore of the nostril with the thumb of your right hand and fill the breath through the left nostril and then close the left nostril with two fingers next to the thumb.
- Then remove the thumb from the right nostril and exhale the breath.
- Now fill the breath inward from the right nostril and close the right nostril and open the left nostril and exhale the breath in 8 counts.
- Do this activity for the first 3 minutes and then gradually increase the practice for 10 minutes.
- It should not be practised for more than 10 minutes. Do this pranayama in the morning in the open air.
- It cures disorders of phlegm, bile etc. in the body. Lungs become powerful by doing Anulom-Vilom daily.
- This makes the pulse pure, which makes the body healthy, radiant and powerful.
- By doing this pranayama daily, the level of cholesterol in the body is reduced.
- By taking Anulom-Vilom, there is a lot of relief in the complaints of cold and asthma.
- Anulom-Anulom-Vilom gives strength to the heart.
- During this pranayama when we take a deep breath, the pure air removes the contaminated elements of our blood.
- Pureblood goes to all the organs of the body and provides nutrition to them.
- Anulom-Vilom Pranayam can be done by people of all age groups and its duration can be fixed according to convenience.
- Weak and anaemia patients should take some care in breathing and exhaling during this pranayama.
- Some people often start breathing and exhaling due to lack of time.
- Due to this, dust, smoke, bacteria and viruses spread in the atmosphere can cause many types of infections by reaching the respiratory tract.
- During pranayama, breathing speed should be so smooth.
- While doing pranayama, the sound of breath should not be heard by oneself. | english |
<filename>19/Schriftliche Frage/19-249237.json<gh_stars>10-100
{
"vorgangId": "249237",
"VORGANG": {
"WAHLPERIODE": "19",
"VORGANGSTYP": "Schriftliche Frage",
"TITEL": "Unterstützung des Reflexionspapiers der EU-Kommission \"Auf dem Weg zu einem nachhaltigen Europa\" ",
"AKTUELLER_STAND": "Beantwortet",
"SIGNATUR": "",
"GESTA_ORDNUNGSNUMMER": "",
"WICHTIGE_DRUCKSACHE": {
"DRS_HERAUSGEBER": "BT",
"DRS_NUMMER": "19/10041",
"DRS_TYP": "Schriftliche Fragen",
"DRS_LINK": "http://dipbt.bundestag.de:80/dip21/btd/19/100/1910041.pdf"
},
"EU_DOK_NR": "",
"SCHLAGWORT": [
"Europäische Kommission",
{
"_fundstelle": "true",
"__cdata": "Europäische Union"
},
"Klimaschutz",
{
"_fundstelle": "true",
"__cdata": "Nachhaltige Entwicklung"
},
"Vereinte Nationen"
],
"ABSTRAKT": "Originaltext der Frage(n): \r\n \r\nWelches Szenario bzw. welche Aspekte aus den drei Szenarien (bitte benennen) aus dem Reflexionspapier der EU-Kommission \"Auf dem Weg zu einem nachhaltigen Europa\" (https://ec.europa.eu/commission/sites/beta-political/files/rp_ sustainable_europe_de_web_0102.pdf) unterstützt die Bundesregierung, und welche Verhandlungsziele für die Umsetzung der Agenda 2030 der Vereinten Nationen auf europäischer Ebene hat die Bundesregierung für das Abschlussdokument des informellen Gipfels von Sibiu am 9. Mai 2019? "
},
"VORGANGSABLAUF": {
"VORGANGSPOSITION": {
"ZUORDNUNG": "BT",
"URHEBER": "Schriftliche Frage/Schriftliche Antwort ",
"FUNDSTELLE": "10.05.2019 - BT-Drucksache 19/10041, Nr. 126",
"FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/19/100/1910041.pdf",
"PERSOENLICHER_URHEBER": [
{
"VORNAME": "Gerhard",
"NACHNAME": "Zickenheiner",
"FUNKTION": "MdB",
"FRAKTION": "BÜNDNIS 90/DIE GRÜNEN",
"AKTIVITAETSART": "Frage"
},
{
"VORNAME": "Rita",
"NACHNAME": "Schwarzelühr-Sutter",
"FUNKTION": "Parl. Staatssekr.",
"RESSORT": "Bundesministerium für Umwelt, Naturschutz und nukleare Sicherheit",
"AKTIVITAETSART": "Antwort"
}
]
}
}
}
| json |
<gh_stars>0
import './notification-badge.css';
declare const _default: {
"iconAttentionBell": "pf-icon-attention-bell",
"iconBell": "pf-icon-bell",
"modifiers": {
"read": "pf-m-read",
"unread": "pf-m-unread",
"attention": "pf-m-attention"
},
"notificationBadge": "pf-c-notification-badge",
"notificationBadgeCount": "pf-c-notification-badge__count"
};
export default _default; | typescript |
From the very first moment he crossed into the Water Kingdom, Ezra held an aversion for it. The vibrant blues and whites were a stark contrast to the fiery hues of his homeland, and the pervasive dampness grated on his senses. The humid air made it feel as if he were in a perpetual state of dehydration. He couldn't fathom why his superiors had chosen this destination. In his view, the Water Kingdom held little of value for the Fire Kingdom's interests. Nevertheless, orders were orders, and this mission ranked as a top priority for Ezra. The objective? To get close to Aurelia Cobres by any means necessary and extract whatever information he could obtain, then promptly transmit it back to his superiors.
He stepped off from the platform and concealed his inner discomfort as he entered the water. Thankfully, he had heeded advice and equipped himself with waterproof boots. The hall would have been unbearably uncomfortable without them. Raising his gaze from the water's surface, he spotted his mark, she was pretty he noted absentmindedly. The pictures he'd been given during briefing didn't do her proper justice.
Summoning a confident smile, he approached the lady and gracefully bowed. "Lady Cobres, I'm delighted to have the honor of finding you so early in the day," he declared, straightening his posture. "I am Ezra Avass, a diplomat representing the Fire Kingdom."
Aurelia smiled a genuine smile, thrilled she wouldn't have to fake absolutely everything in this encounter. He seemed amiable and kind, and this eased her mind. Her own briefing was merely of his existence—she got no further guidance, information, or assistance—but she was used to it. She realized that this would be a longer mission, as they needed to form a relationship, and desperately hoped her target would be pleasant. For the moment, it seemed be would be.
Her superiors had suggested a romantic development later on, as the only form of guidance they gave. She wasn't sure at first, but now she entirely embraced the idea as a possibility if it got that far. Ezra had an attractive boyish-ness to him that she found endearing; his dark, shaggy hair falling in his face, almond-shaped brown eyes bright and warm. skin a bit of a warmer tan than her own. She'd done nothing like this, forcing a relationship, but she trusted herself to do it. She knew she'd manage it fine, as she always did.
"Welcome to our Kingdom," she replied, eyes on his, smile mirroring his confident one with a very slight tilt of her head. "I am sure it isn't quite as pleasant as your own, for obvious reasons!" she acknowledged, laughing, a gentle, tinkling sound that seemed to escape her with no problem. She was able to force the most sincere laughs, but just as her smile wasn't forced or fake, her laugh also wasn't. She stepped forward to stand a close but respectful distance from him, hand outstretched to shake his. "It is indeed a pleasure to meet you. I hope your stay is pleasing, Ambassador Avass. Do feel entirely free to call me Aurelia," she added, smiling never wavering, nor her eyes.
Ezra's heart skipped a beat as Aurelia greeted him with a genuine smile, instantly putting him at ease. Her amiable demeanor was a welcome relief, suggesting that this mission might be even smoother than he had anticipated. Getting close to Aurelia seemed like it would be a breeze for him and after that gathering the necessary information afterwards seemed like it would pose little trouble, he was nearly certain.
Though he couldn't state it definitively, Ezra was confident this mission could potentially become one of his swiftest accomplishments yet, adding to his ever-growing list of successes. It was a pity, for he sensed a certain connection between them, speculating that there could have been a deeper bond if they were meeting under different circumstances, simply as two ordinary individuals.
Ezra chuckled softly, his laughter imbued with sincerity. "It is undeniably different, my lady, but I'm confident it'll grow on me with time," he remarked. Her laughter echoed enchantingly, like a delightful melody that complemented her overall pleasantness. Taking her hand and instead of a simple shake, he raised it gently and pressed his lips to the back. "The pleasure is all mine and please you must call me Ezra," he insisted with a warm and inviting smile. "If you happen to have some free time, would you kindly consider showing me around? This being my first visit, it would be rather unfortunate to become lost so early in my stay."
A careful calm swept through Aurelia, her senses that had built up since she became a spy warning her silently. It happened when she got too carried away, as if her mind sensed a looming doom and reminded her of her goal, not a personal want. She continued her cordial interaction but kept in mind the target of this meeting, wary and cautious all the while.
Well, she tried. When he kissed her hand, her heart jumped, but merely because she wasn't used to physical contact in her missions nor the respectful, gentle way he was treating her. Most men she did missions with were crude and hateful, hence the need for her mission, and even her superiors looked down on her occasionally. When there was a man for the mission, they were chosen over her. Even if she'd proved herself multiple times over, though she wasn't bitter; she knew her worth and assets. The way Ezra was handling their meeting had warm butterflies fluttering throughout her chest and settling in her tummy, and hope for success from this mission but also a peaceful outcome for their relationship flared in her soul.
She couldn't stop smiling, her cheeks aching from the effort although she smiled constantly, as her forced smiles were far different from this. "I'm here to help you all the way, Ezra, with settling in and a tour. I'd love to show you around," she said softly, after he ended the contact of his lips on her hand, the warmth fading to her dismay, though she kept his hand in hers for a few seconds more to turn and lead him to the staircase she'd just descended from. She let go when they reached it, not wanting to overstep her bounds, nodding for him to follow.
Ezra had been trained from a young age to be an expert in reading people, picking up on the subtle cues that other people might overlook. It was why he was so good at his job he possessed a deep understanding of how to influence and manipulate people. Interestingly, the current situation demanded none of these skills. Aurelia's pleasant and charming nature made it remarkably easy for Ezra to reciprocate in kind.
Her hand, warm and reassuring, lingered in his as she led him toward a stairwell within the grand hall.. The gentle splashes of water created a soothing symphony around them as they walked, a sound that Ezra oddly appreciated, finding it a fitting accompaniment to the beautiful girl beside him. The dampness seeping into the fabric of his pants was a minor inconvenience, one that he would address at a more opportune moment. For now, he was content to be led by Aurelia, eager to see where shed lead him.
Ezra offered a warm smile to Aurelia as they started to ascend the stairs. There was a fleeting twinge of disappointment when she released his hand, he quickly brushed it aside. "Well, thank you. If the Water Castle is as confusing as the Fire Castle, then I will need all the help I can get," he remarked lightly. Upon reaching the top of that particular set of stairs, he turned to face her. "So, where to first?" he inquired.
| english |
The Congress today slammed the government over a meeting between top election officials and the Prime Minister's Office, alleging that it was treating the Election Commission as its "subservient tool".
Congress general secretary and chief spokesperson Randeep Surjewala alleged that the government has fallen to a new low in destroying institutions in the country.
Citing reports, including one by news agency Press Trust of India, that a Law Ministry official had sought the presence of the Chief Election Commissioner and Election Commissioners at a meeting with the PM's Principal Secretary, the Congress leader said this "was unheard of in independent India".
"Cat is out of the bag! What was whispered till now is a fact. PMO summoning ECI was unheard of in independent India. Treating EC as a subservient tool is yet another low in Modi Government's record of destroying every institution," Mr Surjewala said on Twitter tagging an Indian Express news report in this regard.
What was whispered till now is a fact.
The reports said the Chief Election Commissioner had reservations on a note from a Law Ministry official that the Principal Secretary to Prime Minister, PK Mishra, will "chair a meeting" on a common electoral roll and "expects CEC" to be present, reported news agency Press Trust of India.
(Except for the headline, this story has not been edited by NDTV staff and is published from a syndicated feed. ) | english |
<filename>seedrandom/2.3.9.json<gh_stars>1-10
{"seedrandom.js":"<KEY>,"seedrandom.min.js":"<KEY>} | json |
import { GenesisBlockUtils, StaticNodeUtils } from '@celo/walletkit'
import BigNumber from 'bignumber.js'
import DeviceInfo from 'react-native-device-info'
import * as RNFS from 'react-native-fs'
import RNGeth from 'react-native-geth'
import config from 'src/geth/network-config'
import Logger from 'src/utils/Logger'
import FirebaseLogUploader from 'src/utils/LogUploader'
import { DEFAULT_TESTNET } from 'src/web3/testnets'
let gethLock = false
let gethInstance: typeof RNGeth | null = null
const currentNetworkName = DEFAULT_TESTNET
const currentConfig: any = config[currentNetworkName]
export const FailedToFetchStaticNodesError = new Error(
'Failed to fetch static nodes from Google storage'
)
export const FailedToFetchGenesisBlockError = new Error(
'Failed to fetch genesis block from Google storage'
)
// We are never going to run mobile node in full or fast mode.
enum SyncMode {
CELO_LATEST = 'celolatest',
LIGHT = 'light',
}
// Log levels correpond to the values defined in
// https://github.com/celo-org/geth/blob/master/log/logger.go#L21
enum LogLevel {
CRITICAL = 0,
ERROR = 1,
WARN = 2,
INFO = 3,
DEBUG = 4,
TRACE = 5,
}
// The logs will be uploaded only if they are larger than this size
const UPLOAD_SIZE_THRESHOLD = 10 * 1024 // 10 KB
enum ErrorType {
Unknown,
GethAlreadyRunning,
CorruptChainData,
}
async function createNewGeth(): Promise<typeof RNGeth> {
Logger.debug('Geth@newGeth', 'Configure and create new Geth')
const { nodeDir, syncMode } = currentConfig
const genesis: string = await readGenesisBlockFile(nodeDir)
const networkID: number = GenesisBlockUtils.getChainIdFromGenesis(genesis)
Logger.debug('Geth@newGeth', `Network ID is ${networkID}`)
const gethOptions: any = {
nodeDir,
networkID,
genesis,
syncMode,
useLightweightKDF: true,
}
// Setup Logging
const logFilePath = Logger.getGethLogFilePath()
// Upload logs first
await uploadLogs(logFilePath, Logger.getReactNativeLogsFilePath())
gethOptions.logFile = logFilePath
// Only log info and above to the log file.
// The logcat logging mode remains unchanged.
gethOptions.logFileLogLevel = LogLevel.INFO
Logger.debug('Geth@newGeth', 'Geth logs will be piped to ' + logFilePath)
return new RNGeth(gethOptions)
}
async function initGeth() {
Logger.info('Geth@init', 'Create a new Geth instance')
if (gethLock) {
Logger.warn('Geth@init', 'Geth create already in progress.')
return
}
gethLock = true
try {
if (gethInstance) {
Logger.debug('Geth@init', 'Geth already exists, trying to stop it.')
await stop()
}
if (!(await ensureGenesisBlockWritten())) {
throw FailedToFetchGenesisBlockError
}
if (!(await ensureStaticNodesInitialized())) {
throw FailedToFetchStaticNodesError
}
const geth = await createNewGeth()
try {
await geth.start()
gethInstance = geth
geth.subscribeNewHead()
} catch (e) {
const errorType = getGethErrorType(e)
if (errorType === ErrorType.GethAlreadyRunning) {
// Geth is already running, this is most likely RN restart.
Logger.info('Geth@init/startInstance', 'Geth start reported geth already running')
// Note: Unfortunately, RN-Geth doesn't currently support connecting to the
// already running geth instance, which we would need to subscribe to head updates.
// In the meantime, we need to force an app reset. See #3227
throw new Error('Geth already running, need to restart app')
} else if (errorType === ErrorType.CorruptChainData) {
Logger.warn('Geth@init/startInstance', 'Geth start reported chain data error')
attemptGethCorruptionFix(geth)
} else {
Logger.error('Geth@init/startInstance', 'Unexpected error starting geth', e)
throw e
}
}
} finally {
gethLock = false
}
}
export async function getGeth(): Promise<typeof gethInstance> {
Logger.debug('Geth@getGeth', 'Getting Geth Instance')
if (!gethInstance) {
await initGeth()
}
return gethInstance
}
async function ensureStaticNodesInitialized(): Promise<boolean> {
const { nodeDir } = currentConfig
if (await staticNodesAlreadyInitialized(nodeDir)) {
Logger.debug('Geth@maybeInitStaticNodes', 'static nodes already initialized')
return true
} else {
Logger.debug('Geth@maybeInitStaticNodes', 'initializing static nodes')
let enodes: string | null = null
try {
enodes = await StaticNodeUtils.getStaticNodesAsync(currentNetworkName)
} catch (error) {
Logger.error(
`Failed to get static nodes for network ${currentNetworkName},` +
`the node will not be able to sync with the network till restart`,
error
)
return false
}
if (enodes != null) {
await writeStaticNodes(nodeDir, enodes)
return true
}
return false
}
}
async function stop() {
try {
Logger.debug('Geth@stop', 'Stopping Geth')
await gethInstance.stop()
Logger.debug('Geth@stop', 'Geth stopped')
} catch (e) {
Logger.error('Geth@stop', 'Error stopping Geth', e)
throw e
}
}
async function ensureGenesisBlockWritten(): Promise<boolean> {
const { nodeDir } = currentConfig
if (await genesisBlockAlreadyWritten(nodeDir)) {
Logger.debug('Geth@ensureGenesisBlockWritten', 'genesis block already written')
return true
} else {
Logger.debug('Geth@ensureGenesisBlockWritten', 'writing genesis block')
let genesisBlock: string | null = null
try {
genesisBlock = await GenesisBlockUtils.getGenesisBlockAsync(currentNetworkName)
} catch (error) {
Logger.error(`Failed to get the genesis block for network ${currentNetworkName}.`, error)
return false
}
if (genesisBlock != null) {
await writeGenesisBlock(nodeDir, genesisBlock)
return true
}
return false
}
}
async function genesisBlockAlreadyWritten(nodeDir: string): Promise<boolean> {
const genesisBlockFile = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/genesis.json`
if (!(await RNFS.exists(genesisBlockFile))) {
return false
}
const fileStat: RNFS.StatResult = await RNFS.stat(genesisBlockFile)
return fileStat.isFile() && new BigNumber(fileStat.size, 10).isGreaterThan(0)
}
async function readGenesisBlockFile(nodeDir: string): Promise<string> {
const genesisBlockFile = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/genesis.json`
return RNFS.readFile(genesisBlockFile, { encoding: 'utf8' })
}
async function writeGenesisBlock(nodeDir: string, genesisBlock: string) {
Logger.debug(`writeGenesisBlock genesis block is: "${genesisBlock}"`)
const genesisBlockFile = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/genesis.json`
await RNFS.mkdir(`${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid`)
await RNFS.writeFile(genesisBlockFile, genesisBlock, 'utf8')
}
/**
* Returns true if the static nodes files in the Geth data dir has been initialized, false otherwise.
* @param nodeDir Geth data dir
*/
async function staticNodesAlreadyInitialized(nodeDir: string): Promise<boolean> {
const staticNodesFile = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/static-nodes.json`
if (!(await RNFS.exists(staticNodesFile))) {
return false
}
const fileStat: RNFS.StatResult = await RNFS.stat(staticNodesFile)
return fileStat.isFile() && new BigNumber(fileStat.size, 10).isGreaterThan(0)
}
async function writeStaticNodes(nodeDir: string, enodes: string) {
console.info(`writeStaticNodes enodes are "${enodes}"`)
const staticNodesFile = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/static-nodes.json`
await RNFS.mkdir(`${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/`)
await RNFS.writeFile(staticNodesFile, enodes, 'utf8')
}
async function attemptGethCorruptionFix(geth: any) {
const deleteChainDataResult = await deleteChainData()
const deleteGethLockResult = await deleteGethLockFile()
if (deleteChainDataResult && deleteGethLockResult) {
await geth.start()
gethInstance = geth
geth.subscribeNewHead()
} else {
throw new Error('Failed to fix Geth and restart')
}
}
export async function deleteChainData() {
Logger.debug('Geth@deleteChainData', 'Deleting chain data')
// Delete data for both the possible modes a mobile node could be running in.
const result1 = await deleteSingleChainData(SyncMode.CELO_LATEST)
const result2 = await deleteSingleChainData(SyncMode.LIGHT)
return result1 || result2
}
async function deleteSingleChainData(syncMode: SyncMode) {
const { nodeDir } = currentConfig
const chainDataDir = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/${syncMode}chaindata`
Logger.debug('Geth@deleteSingleChainData', `Going to delete ${chainDataDir}`)
return deleteFileIfExists(chainDataDir)
}
async function deleteGethLockFile() {
// Delete the .ipc file or the Geth will think that some other Geth node is using this datadir.
const { nodeDir } = currentConfig
const gethLockFile = `${RNFS.DocumentDirectoryPath}/${nodeDir}/GethDroid/LOCK`
Logger.info('Geth@deleteGethLockFile', `Deleting ${gethLockFile} for nodeDir ${nodeDir}`)
return deleteFileIfExists(gethLockFile)
}
async function deleteFileIfExists(path: string) {
try {
const gethLockFileExists = await RNFS.exists(path)
if (gethLockFileExists) {
Logger.debug('Geth@deleteFileIfExists', `Dir ${path} exists. Attempting to delete`)
await RNFS.unlink(path)
return true
} else {
Logger.debug('Geth@deleteFileIfExists', `Dir ${path} does not exist`)
return true
}
} catch (error) {
Logger.error('Geth@deleteFileIfExists', `Failed to delete ${path}`, error)
return false
}
}
// The only reason to upload both the logs simulatenously here is to have the same upload ID for both, so that,
// the developers can correlate them.
async function uploadLogs(gethLogFilePath: string, reactNativeLogFilePath: string) {
Logger.debug('Geth@uploadLogs', 'Attempting to upload geth logs')
try {
const bundleId = DeviceInfo.getBundleId()
const uploadPath = `${bundleId}/${DEFAULT_TESTNET}`
// Phone number might not be verified here but that does not matter for logging.
const phoneNumber = (await DeviceInfo.getPhoneNumber()) || 'unknown'
const timestamp = new Date().getTime()
const deviceId = DeviceInfo.getUniqueID()
const uploadId = `${timestamp}_${deviceId}`
const gethUploadFileName = `${phoneNumber}_${uploadId}_geth.txt`
const reactNativeUploadFileName = `${phoneNumber}_${uploadId}_rn.txt`
// Upload one if the other one is uploaded.
const [shouldUploadGeth, shouldUploadRN] = await Promise.all([
FirebaseLogUploader.shouldUpload(gethLogFilePath, UPLOAD_SIZE_THRESHOLD, true),
FirebaseLogUploader.shouldUpload(reactNativeLogFilePath, UPLOAD_SIZE_THRESHOLD, true),
])
// If either of them have to be uploaded then upload both.
// Noth that the Wi-Fi can switch to cellular between the time of check and
// the time of use but at this time that's an acceptable tradeoff.
if (shouldUploadGeth || shouldUploadRN) {
await Promise.all([
FirebaseLogUploader.upload(gethLogFilePath, uploadPath, gethUploadFileName),
FirebaseLogUploader.upload(reactNativeLogFilePath, uploadPath, reactNativeUploadFileName),
])
}
} catch (e) {
Logger.error('Geth@uploadLogs', 'Failed to upload logs', e)
}
}
function getGethErrorType(e: Error): ErrorType {
if (!e || !e.message) {
return ErrorType.Unknown
}
if (e.message.includes('datadir already used by another process')) {
return ErrorType.GethAlreadyRunning
}
if (e.message.includes('missing block number for head header hash')) {
return ErrorType.CorruptChainData
}
return ErrorType.Unknown
}
| typescript |
Assam chief minister Sarbananda Sonowal on Wednesday took part at the inauguration ceremony of volunteers’ camp for the forthcoming third Khelo India Youth Games at Sarusajai Sports Complex in Guwahati.
Sonowal urged the volunteers to perform their duties with utmost dedication and sincerity for smooth organisation of the Games.
Saying that Assam has got this great opportunity to hold this mega sports event which is the brainchild of Prime Minister Narendra Modi to make India a sports superpower, the chief minister called on the volunteers to extend hospitality to the players, officials, guardians coming to the event with the spirit of ‘Atithi Devo Bhava’.
They must also take up the responsibility to inform the visitors about the natural beauty and cultural heritage of Assam, he said.
Referring to Dr Bhupen Hazarika’s song ‘ei biswa ek krirangan’, Sonowal said that sports can create an environment of peace and development while strengthening the bond of unity and brotherhood among all sections.
The idea of ‘Ek Bharat Shresth Bharat’ would only be realized through sports, he said.
The chief minister also gave opportunity to the selected volunteers to express their feelings while encouraging them to work for making the games successful.
Joint executive officer of Khelo India Youth Games Dr M Angamutthu, member secretary of advisory committee for students and youth welfare Lakhya Konwar, CEO of third Khelo India Youth Games Avinash Joshi also spoke on the occasion where many dignitaries were present. | english |
{"_id":"brewery_Shipyard_Brewing_-_Portland","name":"<NAME>","address":["86 Newbury Street"],"city":"Portland","state":"Maine","code":"4101","country":"United States","phone":"1-800-789-0684","website":"http:\/\/www.shipyard.com\/","description":"Since 1994, Shipyard Brewing Company has been brewing fine quality products with a wide range of style profiles. We use only top quality ingredients and pride ourselves on the consistency and freshness of our products. All our beer is hand crafted from recipes developed by master brewer <NAME>, one of the most influential people in the craft brewing movement in North America. Shipyard is available in 35+ states around the country and markets for our freshly brewed, hand-crafted beers continue to expand.","geo":{"loc":["-70.2489","43.6619"],"accuracy":"RANGE_INTERPOLATED"},"updated":"2010-07-22 20:00:20"} | json |
<filename>packages/model/config-options.ts
import { VdConfirmInfo } from './request-options';
import { UseResult } from './use-result';
export interface VdConfigOptions {
message401?: string; //提示401消息
message403?: string; //提示403消息
showMessage401?: boolean; // 是否显示401消息
showMessage403?: boolean; // 是否显示403消息
systemErrorMessage?: string; // 全局异常提示消息
showErrorMessage: (message: string) => void; // 失败提示消息
showSuccessMessage: (message: string) => void; // 成功提示消息
handle401?: (message: string) => void; // 401处理
handle403?: (message: string) => void; // 403处理
handleConfirm?: (info: VdConfirmInfo) => Promise<any>; // 确认弹框
handleStartLoading?: () => void; // 开始执行loading
handleCloseLoading?: () => void;// 关闭执行loading
handleFormValidate?: ($refs: any, formNames: string[]) => boolean // 表单验证
handleHttpResult?: <T>(resBody: any) => UseResult<T>; // 处理正常请求返回值
}
| typescript |
<reponame>DOREMUS-ANR/recommender
http://data.doremus.org/expression/756904b2-d6eb-3cda-b281-4a20e0b77448
http://data.doremus.org/expression/7108cf87-e1e2-3934-b54e-5c14cd56be98
http://data.doremus.org/expression/0a1bdfe0-9e4e-33d9-8b5f-6bd488c929df
http://data.doremus.org/expression/4452b20e-1880-35ff-99bd-a7f706d1f100
http://data.doremus.org/expression/da00298a-5052-3f57-a4cd-7395452e0454
http://data.doremus.org/expression/0f027fa9-47dd-3311-ace4-e160f1b206ff
http://data.doremus.org/expression/1127e05c-d655-3e10-97db-c29334206b08
http://data.doremus.org/expression/7bca482f-9930-34bd-af12-6ac57830ae3e
http://data.doremus.org/expression/8d41e365-52c9-318e-92ac-06497adf5e7c
http://data.doremus.org/expression/28ba3ac4-23de-3f5c-9855-a0a75382196f
http://data.doremus.org/expression/ed379d4a-8e66-38e5-a889-ec8eadb79e3c
http://data.doremus.org/expression/a7535b33-02c0-3d2a-9dac-46220d387421
http://data.doremus.org/expression/0846e331-ee94-30a5-91a8-54ec596602ea
http://data.doremus.org/expression/45776150-b904-3a01-9257-4dbceceea565 | json |
<filename>agent/src/pt/com/broker/xml/SoapSerializer.java
package pt.com.broker.xml;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pt.com.broker.messaging.BrokerMessage;
public class SoapSerializer
{
private static final Logger log = LoggerFactory.getLogger(SoapSerializer.class);
public static void ToXml(SoapEnvelope soapEnv, OutputStream out)
{
try
{
IMarshallingContext mctx = JibxActors.getMarshallingContext();
mctx.marshalDocument(soapEnv, "UTF-8", null, out);
}
catch (JiBXException e)
{
if (soapEnv.body.notification != null)
{
BrokerMessage bmsg = soapEnv.body.notification.brokerMessage;
StringBuilder buf = new StringBuilder();
buf.append("\ncorrelationId: " + bmsg.correlationId);
buf.append("\ndestinationName: " + bmsg.destinationName);
buf.append("\nexpiration: " + bmsg.expiration);
buf.append("\nmessageId: " + bmsg.messageId);
buf.append("\npriority: " + bmsg.priority);
buf.append("\ntextPayload: " + bmsg.textPayload);
buf.append("\ntimestamp: " + bmsg.timestamp);
log.error("Unable to marshal soap envelope:" + buf.toString());
}
JibxActors.reload();
throw new RuntimeException(e);
}
}
public static SoapEnvelope FromXml(InputStream in)
{
try
{
IUnmarshallingContext uctx = JibxActors.getUnmarshallingContext();
Object o = uctx.unmarshalDocument(in, "UTF-8");
if (o instanceof SoapEnvelope)
return (SoapEnvelope) o;
else
return new SoapEnvelope();
}
catch (JiBXException e)
{
JibxActors.reload();
try
{
String invalidMessage = slurp(in);
log.error("\n" + invalidMessage + "\n");
}
catch (IOException ioe)
{
// ignore this exception
}
throw new RuntimeException(e);
}
}
private static String slurp(InputStream in) throws IOException
{
in.reset();
StringBuilder out = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;)
{
out.append(new String(b, 0, n));
}
return out.toString();
}
}
| java |
{
"general": {
"userConfigFileName": "reporterconfig.json",
"testRunSignature": "Auto created defect by Unified reporter v1.0"
},
"testrail": {
"gAuthEndPoint": "/auth/login/=",
"gListProjectsEndPoint": "/api/v2/get_projects",
"gListMileStones": "/api/v2/get_milestones",
"gListProjectSuites": "/api/v2/get_suites",
"gAddNewRun": "/api/v2/add_run",
"gAddResults": "/api/v2/add_results_for_cases",
"gGetCurrentUser": "/api/v2/get_user_by_email",
"gGetTestCase": "/api/v2/get_case",
"runReport": "/api/v2/run_report"
},
"jira": {
"gAuthEndPoint": "rest/auth/1/session",
"gCreateIssue": "rest/api/latest/issue/"
}
} | json |
{
"name": "maquete",
"version": "0.0.1",
"description": "Maquete simple and beautiful api documentation",
"main": "index.js",
"scripts": {
"start": "npm run widget-build && cd app; npm run start",
"first-run": "cd widget; npm install && cd ../ && cd app; npm install",
"clean-widget-build": "npm run clean-js-widget-build && npm run clean-css-widget-build",
"clean-js-widget-build": "rm -rf ./app/themes/whiteboard/source/js/lib/index.js && rm -rf ./app/themes/whiteboard/source/js/lib/index.js.map",
"clean-css-widget-build": "rm -rf ./app/themes/whiteboard/source/css/index.css && rm -rf ./app/themes/whiteboard/source/css/index.css.map",
"move-files": "npm run move-js-files && npm run move-css-files",
"move-js-files": "mv widget/dist/index.js app/themes/whiteboard/source/js/lib/. && mv widget/dist/index.js.map app/themes/whiteboard/source/js/lib/.",
"move-css-files": "mv widget/dist/*.css ./app/themes/whiteboard/source/css/.",
"widget-build": "npm run clean-widget-build && cd widget; npm run build && cd .. && npm run move-files"
},
"repository": {
"type": "git",
"url": "git+https://github.com/flpms/maquete.git"
},
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/flpms/maquete/issues"
},
"homepage": "https://github.com/flpms/maquete#readme"
}
| json |
<reponame>FFstats/FFstats.github.io<gh_stars>0
{"polyfill":["/polyfill-276a3aa7fa5c0ce61c6d.js"],"app":["/app-2237e4e5804e9928dc44.js"],"component---src-pages-gamerecords-js":["/component---src-pages-gamerecords-js-558e6e55cc68b7c82cc0.js"],"component---src-pages-headtohead-js":["/component---src-pages-headtohead-js-182352686446a3dd05fa.js"],"component---src-pages-index-js":["/component---src-pages-index-js-311a3cdc1dd852ef743d.js"],"component---src-pages-roadmap-js":["/component---src-pages-roadmap-js-c6ae60ea8ae9c8717931.js"],"component---src-pages-standings-js":["/component---src-pages-standings-js-757f5f6fe6885ed6f2f9.js"],"component---src-pages-support-js":["/component---src-pages-support-js-3808b971570819e94fd9.js"],"component---src-pages-teamrecords-js":["/component---src-pages-teamrecords-js-17649e0d53d51a306546.js"]} | json |
<gh_stars>0
// Copyright (c) 2017-2020 VMware, Inc. or its affiliates
// SPDX-License-Identifier: Apache-2.0
// +build tools
// The tools pseudo-package is used to explicitly record Go tool dependencies in
// a module-aware world. It replaces the dep "required" flow. Tools declared
// here can be installed into dev-bin/ using the depend-dev recipe in the
// top-level Makefile.
//
// See
//
// https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module
//
// for information.
package tools
import (
_ "github.com/golang/mock/mockgen"
_ "github.com/golang/protobuf/protoc-gen-go"
)
| go |
from collections import ChainMap
from collections.abc import Mapping, Iterable
from itertools import groupby
from operator import itemgetter
import numpy as np
from probability import RowKey
from probability import TableColumns
# from probability.core_1 import RowKey
# from probability.core_1 import TableColumns
def to_dict(groupby_index, value_index):
def make_dict(sorted_items):
# It groups the sorted item based on
# the element as groupby_index
# and then sum the values at value_index
return {
k: sum([item[value_index] for item in g2])
for k, g2 in groupby(sorted_items, key=itemgetter(groupby_index))
}
return make_dict
class Table(dict):
def __init__(self, rows, names=None, _internal_=False, _children_names_=None):
if _internal_:
# rows are dictionary for internal calls
key_values = rows
try:
self._row_sample_ = next(iter(rows))
except StopIteration:
# Rows are empty
super().__init__(key_values)
self._row_sample_ = None
self.names = names
if _children_names_ is None:
self.children_names = []
self.columns = TableColumns(
names=names, children_names=[], table=self
)
else:
self.children_names = _children_names_
self.columns = TableColumns(
names=names, children_names=_children_names_, table=self
)
return
else:
if isinstance(rows, Mapping):
key_values = [(RowKey(k), value) for k, value in rows.items()]
elif isinstance(rows, Iterable):
key_values = [(RowKey(k), value) for k, value in rows]
else:
raise ValueError("Table expect rows as Mapping/Iterable")
self._row_sample_ = key_values[0][0]
if names is None:
names = [f"X{i+1}" for i, _ in enumerate(self._row_sample_)]
if len(names) != len(self._row_sample_):
raise ValueError("The length of column names and columns are not the same.")
super().__init__(key_values)
self.names = names
value_sample = super().__getitem__(self._row_sample_)
if isinstance(value_sample, Table):
self.columns = TableColumns(
names=names, children_names=value_sample.names, table=self
)
self.children_names = value_sample.names
else:
if _children_names_ is None:
self.children_names = []
self.columns = TableColumns(names=names, children_names=[], table=self)
else:
self.children_names = _children_names_
self.columns = TableColumns(
names=names, children_names=_children_names_, table=self
)
def __missing__(self, key):
return None
def __getitem__(self, args):
"""Override the dict by converting the
comma separated arguments to RowKey
"""
# This is faster than isinstance
# We are sure there is not any inheritance
# to deal with
if type(args) is RowKey:
return super().__getitem__(args)
if self.columns.size == 1:
key = self.columns.to_key(args)
else:
key = self.columns.to_key(*args)
return super().__getitem__(key)
def _check_keys_consistencies_(self):
# We suppose each column is positioned
# in a fix place of the n-tuple.
# Therefore, the levels of the column can be
# found by iterating over each tuple's item
# Convert each features line to tuple
first_row_types = [type(item) for item in self._row_sample_]
for row in self.keys():
# compair length
if len(row) != self.columns.size:
raise ValueError("The length of the 'factors' are not consistence.")
# compair row's elements type
comparisions = [
isinstance(element, type_1)
for element, type_1 in zip(row, first_row_types)
]
if not all(comparisions):
raise ValueError("The types of the 'factors' are not consistence.")
def to_2d_array(self):
"""Convert the distribution ( or the self._counter's
key:value) to a 2D numpy array where the array
rows are [[(RV_1, RV_2, ..., RV_n, count)],[...
Returns:
numpy ndarray:
A 2D numpy array that the its last column
is the counts.
"""
return np.array([k + (v,) for k, v in self.items()], dtype=np.object)
def _product_(self, right):
"""Multiply two Tables.
Args:
right ([type]): [description]
Raises:
ValueError: [description]
Returns:
[type]: [description]
"""
if not isinstance(right, Table):
raise ValueError("The 'right' argument must be a Table.")
# Find common variables
# reorder commons based on their order in left_common_indices
commons = [
name for name in self.names if name in (set(self.names) & set(right.names))
]
# When there is no common variable, it is just a simple product
if len(commons) == 0:
names = np.r_[self.names, right.names]
return (
{
k1 + k2: v1 * v2
for k1, v1 in self.items()
for k2, v2 in right.items()
},
names,
)
# In the case that there is one or more common variables,
# the operation is similar to SQL inner join
# So, create a lookup for the left table, by using the
# common variables as key.
left_common_indices = [
i for i, name in enumerate(self.names) if name in commons
]
# the order in right must be the same as the left
# so we reorder the indices base on its left order
right_common_indices = [
i
for name in commons
for i, name2 in enumerate(right.names)
if name == name2
]
right_complement_indices = [
i for i, name in enumerate(right.names) if name not in commons
]
# Methods to split the keys
def l_comm(key):
return tuple([key[i] for i in left_common_indices])
def r_comm(key):
return tuple([key[i] for i in right_common_indices])
def r_comp(key):
return tuple([key[i] for i in right_complement_indices])
# left and right tables lookup
# left : (key:value) == (common_key: (left_key, left_value))
left_lookup = {}
for k, value in self.items():
comm = l_comm(k)
if comm in left_lookup:
left_lookup[comm] += [(k, value)]
else:
left_lookup[comm] = [(k, value)]
# right : (key:value) == (common_key: (right_compliment_key, right_value))
right_lookup = {}
for k, value in right.items():
comm = r_comm(k)
if comm in right_lookup:
right_lookup[comm] += [(r_comp(k), value)]
else:
right_lookup[comm] = [(r_comp(k), value)]
# The inner join happens over keys of two dictionaries (left_lookup and
# right_lookup).
prodcut_dict = {}
for comm, l_values in left_lookup.items():
if comm not in right_lookup:
continue
for left_key, left_value in l_values:
for right_comp, right_value in right_lookup[comm]:
# prodcut_dict values must be multiplied.
# prodcut_dict keys are the combination: (left, right_compliment).
prodcut_dict[left_key + right_comp] = left_value * right_value
# names are the combination of [left_names, right_compelements_names]
combined_names = np.r_[
self.names,
[name for name in right.names if name not in commons],
]
return (prodcut_dict, combined_names)
def marginal(self, *args, normalise=True):
"""Marginal of (group by) the Table over a set of columns.
P(X, Y, Z) -> P(X, Y) or P(X, Z) or P(Y, Z)
Args:
args (list):
List of column names to marginalised.
Raises:
ValueError:
Raises when one of the column names is
not defined.
Or raises when requested for all column names.
Returns:
Table: (rows, names).
"""
# check the validity of operation based on column names
if len(args) == self.columns.size:
raise ValueError("Cannot marginalize on all column names.")
# split columns to indices and comp_indices
columns_info = self.columns.split_columns(*args)
#
# Convert the key:values to 2D numpy array
# the array rows are (row, value)
arr = self.to_2d_array()
# filter the compliment columns
filtered_arr = np.c_[arr[:, columns_info.complimnet_indices], arr[:, -1]]
# split the 2d array's rows to a tuple of
# compliment columns (row[comp_indices])
# and count row[-1]
arr_gen = ((RowKey(row[:-1]), row[-1]) for row in filtered_arr)
# Before calling the groupby, we have to sort the generator
# by the tuple of compliment columns (index zero in itemgetter)
sorted_arr = sorted(arr_gen, key=itemgetter(0))
# since the values in each 'group' are
# (compliment columns, value)
# here we group by 'compliment columns' and apply
# the sum on the value. Then the dictionary of
# compliment columns:op_of_values
# is an acceptable argument for Table
grouped_arr = {
k: sum([item[1] for item in g])
for k, g in groupby(sorted_arr, key=itemgetter(0))
}
table = Table(grouped_arr, columns_info.complimnet_names, _internal_=True)
if normalise:
table.normalise()
return table
def condition_on(self, *args, normalise=True):
"""Creates the conditional based on
the provided names of columns.
P(X, Y) -> P(X | Y) or P(Y | X)
Args:
args (list):
List of names of provided random
variables.
Raises:
ValueError:
If the provided RV names do not exist
in the distribution.
Returns:
MultiTable
"""
if self.columns.size == 1:
raise ValueError("This is a single column Table and cannot condition on.")
if len(args) == self.columns.size:
raise ValueError("Cannot condition on all columns.")
# split columns to indices and comp_indices
columns_info = self.columns.split_columns(*args)
# Convert the key:value to 2D numpy array
# the array rows are (rows, value)
arr = self.to_2d_array()
# divide the 2d array's rows to a tuple of columns,
# (row[indices]), compliment columns (row[comp_indices])
# and values row[-1]
arr_gen = (
(
RowKey(row[columns_info.indices]),
RowKey(row[columns_info.complimnet_indices]),
row[-1],
)
for row in arr
)
# Before calling the groupby, we have to sort the generator
# by the tuple of columns (index zero in itemgetter)
# And since later we will call the group by on group,
# for each key we do the inner sort too (index one in itemgetter)
sorted_arr = sorted(arr_gen, key=itemgetter(0, 1))
# This method convert a group to a dictionary
def make_dict(group):
# since the values in 'group' argument are
# (columns, compliment columns, value)
# here we group by 'compliment columns' and sum
# the values.
return {
k: sum([item[2] for item in g2])
for k, g2 in groupby(group, key=itemgetter(1))
}
# For each group (belongs a unique values), we create
# a dictionary in a dictionary comprehension
grouped_arr = {
k: make_dict(g) for k, g in groupby(sorted_arr, key=itemgetter(0))
}
# The above dictionary is dictionary of dictionaries
# # the first set of names is for parent dictionary
# and the second set is for children
table = MultiTable(
{
key: Table(values, columns_info.complimnet_names, _internal_=True)
for key, values in grouped_arr.items()
},
columns_info.indices_names,
)
if normalise:
table.normalise()
return table
def reduce(self, **kwargs):
"""Reduce the Table by one or more columns.
P(X, Y) -> P(X = x, Y) or P(X, Y = y)
Args:
kwargs (dict):
A dictionary that its 'key' is the name
of the column and its 'value'
is the value that must be reduced by.
Raises:
ValueError:
If the provided names do not exist in the Table.
Returns:
[Table]: A reduce Table.
"""
# split columns to indices and comp_indices
columns = list(kwargs.keys())
if len(columns) == self.columns.size:
raise ValueError("Cannot reduce on all column names.")
columns_info = self.columns.split_columns(*columns)
values = np.array([value for _, value in kwargs.items()], dtype=np.object)
#
# Convert the key:values to 2D numpy array
# the array rows are (keys, value)
arr_counter = self.to_2d_array()
# filter the 2d array rows by provided values of the reduce
# conditioned_arr is a boolean one, and filtering happens
# in the second line
conditioned_arr = np.all(arr_counter[:, columns_info.indices] == values, axis=1)
sliced_arr = arr_counter[conditioned_arr, :]
# filter the 2d array columns (the compliment columns)
# plus the value column (which is the last column)
sliced_arr = sliced_arr[:, columns_info.complimnet_indices + [-1]]
# divide the 2d array's rows to a tuple of columns
# and value
# So, we make a generator that divide the rows to the tuple of
# columns (tuple(row[:-1]) and value (row[-1])
arr_gen = ((RowKey(row[:-1]), row[-1]) for row in sliced_arr)
# Before calling the groupby, we have to sort the generator
# by the tuple of column (index zero in itemgetter)
sorted_slice_arr = sorted(arr_gen, key=itemgetter(0))
# group by the filtered columns (compliment
# columns) and sum the value per key
# Note that the 'itemgetter' read the first index which
# is the tuple of compliment columns
return Table(
{
k: sum([item[1] for item in g])
for k, g in groupby(sorted_slice_arr, key=itemgetter(0))
},
columns_info.complimnet_names,
_internal_=True,
)
def get(self, *args, **kwargs):
key = self.columns.to_key(*args, **kwargs)
return super().__getitem__(key)
def to_table(self, sort=False, value_title=""):
arr = self.to_2d_array().astype("U")
arr_len = np.apply_along_axis(lambda row: [len(item) for item in row], 0, arr)
max_levels_len = np.max(arr_len[:, :-1], axis=0)
max_freq_len = max(np.max(arr_len[:, -1]), len(value_title))
def padding(max_len):
def str_padding(value):
return "".join([" "] * (max_len - len(str(value))))
return str_padding
r_padding = padding(max_freq_len)
if sort: # sort by values
items = reversed(sorted(self.items(), key=lambda item: item[1]))
else: # sort by keys
items = sorted(self.items())
rows = ""
header = ""
horizontal_line = ""
for i, name in enumerate(self.names):
header += f"|{name}{padding(max_levels_len[i])(name)}"
horizontal_line += "|" + "".join(["-"] * max_levels_len[i])
header += "|" + "".join([" "] * max_freq_len) + "|"
horizontal_line += "|" + "".join(["-"] * max_freq_len) + "|"
for k, value in items:
key_str = ""
for i, k_part in enumerate(k):
key_str += f"|{padding(max_levels_len[i])(k_part)}{k_part}"
freq_padding = r_padding(value)
rows += f"{key_str}|{value}{freq_padding}|\n"
return f"{header}\n{horizontal_line}\n{rows}"
def add(self, that):
"""Combines two FrequencyTable and return
a new one. All the frequencies are sum together.
This is not a mathematical sum.
"""
#############################################
# check the validity of operation based on column names
if not isinstance(that, Table):
raise ValueError("Table can only adds to Table.")
if self.columns.size != that.columns.size:
raise ValueError("Two adding Table do not have the same columns.")
if len(self.children_names) != len(that.children_names):
raise ValueError("Two adding Table do not have the same children columns.")
for i, name in enumerate(self.names):
if name != that.names[i]:
raise ValueError(
"Two adding Table do not have the same columns "
"(order must be the same too)."
)
for i, name in enumerate(self.children_names):
if name != that.children_names[i]:
raise ValueError(
"Two adding Table do not have the same children columns "
"(order must be the same too)."
)
#############################################
# Algorithm
#
def add_internal(this, that, names):
if that is not None:
for key in that.keys():
if key in this:
this[key] += that[key]
else:
this[key] = that[key]
return Table(this, names=names, _internal_=True)
############################################
# MultiTable handeling
if self.columns.is_multitable():
return Table(
{
k: add_internal(table.copy(), that[k], self.children_names)
for k, table in self.items()
},
self.names,
_internal_=True,
)
return add_internal(self.copy(), that, self.names)
def total(self):
if self.columns.is_multitable():
return {k: table.total() for k, table in self.items()}
return sum(self.values())
def normalise(self):
if self.columns.is_multitable():
for k, total in self.total().items():
if total == 0:
continue
table = self[k]
for k2 in table:
table[k2] /= total
else:
total = self.total()
if total != 0:
for k in self.keys():
self[k] /= total
def __mul__(self, right):
"""Multiplies a table with this one.
P(X, Y) * k -> P(X, Y)
P(X) * P(Y, Z) -> P(X, Y, Z)
Args:
right ([type]): [description]
Raises:
ValueError: [description]
Returns:
[type]: [description]
"""
if not isinstance(right, Table):
raise ValueError("The 'right' argument must be a 'Table'.")
(rows, names) = self._product_(right)
return Table(rows, names, _internal_=True)
def __rmul__(self, left):
"""Multiplies a table with this one.
k * P(X, Y) -> P(X, Y)
P(X) * P(Y, Z) -> P(X, Y, Z)
Args:
right ([type]): [description]
Raises:
ValueError: [description]
Returns:
[type]: [description]
"""
if not isinstance(left, Table):
raise ValueError("The 'right' argument must be a 'Table'.")
(rows, names) = left._product_(self)
return Table(rows, names, _internal_=True)
def __add__(self, right):
return self.add(right)
def prod_right(table, key2, value2):
# Product a table with kay and value
if value2 is None:
return {}
return {key1 + key2: value1 * value2 for key1, value1 in table.items()}
def prod_left(table, key2, value2):
# Product a table with kay and value
if value2 is None:
return {}
return {key2 + key1: value1 * value2 for key1, value1 in table.items()}
def multi_table_to_table_product(left, right, all_ordered_names):
"""Multiply two tables.
P(X, Y | Z) * P(Z) -> P(X, Y, Z)
P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W)
"""
# Case P(X, Y | Z) * P(Z) -> P(X, Y, Z)
if list(left.names) == list(right.names):
return Table(
ChainMap(
*[
prod_right(table, key2=k, value2=right[k])
for k, table in left.items()
]
),
left.columns.children_names + left.names,
_internal_=True,
)
# Case P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W)
for name in right.names:
if not left.columns:
raise ValueError(
f"Column name '{name}'in right table is not defined on "
"conditioned columns of the left Table (name mismatched)."
)
# e.g. P(X, Y | Z, W) * P(Z) : indices of [W]
indices = [i for i, name in enumerate(left.names) if name not in right.names]
# e.g. P(X, Y | Z, W) * P(Z) : indices of [Z]
compliment_indices = [i for i in range(left.columns.size) if i not in indices]
# e.g. P(X, Y | Z, W) * P(Z) : [W]
reduced_names = [left.names[i] for i in indices]
children_names = [
names for names in all_ordered_names if names not in reduced_names
]
def reduced_key(key):
# Method to split the keys
return {left.names[i]: key[i] for i in indices}
def compliment_key(key):
# Method to make a split key
return RowKey(*[key[i] for i in compliment_indices])
# Case: P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W)
if right.columns.size == len(indices):
return MultiTable(
ChainMap(
*[
prod_right(table, key2=k, value2=right[k])
for k, table in left.items()
]
),
reduced_names,
_children_names_=children_names,
)
return MultiTable(
{
compliment_key(k): table * right.reduce(**reduced_key(k))
for k, table in left.items()
},
reduced_names,
_children_names_=children_names,
)
def table_to_multi_table_product(left, right, all_ordered_names):
"""Multiply two tables.
P(Z) * P(X, Y | Z) -> P(Z, X, Y)
P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W)
"""
# Case P(Z) * P(X, Y | Z) -> P(Z, X, Y)
if list(left.names) == list(right.names):
return Table(
ChainMap(
*[
prod_left(table, key2=k, value2=left[k])
for k, table in right.items()
]
),
right.names + right.columns.children_names,
_internal_=True,
)
# Case P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W)
for name in left.names:
if not right.columns:
raise ValueError(
f"Column name '{name}'in left table is not defined on "
"conditioned columns of the right Table (name mismatched)."
)
# e.g. P(Z) * P(X, Y | Z, W) : indices of [W]
indices = [i for i, name in enumerate(right.names) if name not in left.names]
# e.g. P(Z) * P(X, Y | Z, W) : indices of [Z]
compliment_indices = [i for i in range(right.columns.size) if i not in indices]
# e.g. P(Z) * P(X, Y | Z, W) : [W]
reduced_names = [right.names[i] for i in indices]
children_names = [
names for names in all_ordered_names if names not in reduced_names
]
def reduced_key(key):
# Method to split the keys
return {right.names[i]: key[i] for i in indices}
def compliment_key(key):
# Method to make a split key
return RowKey(*[key[i] for i in compliment_indices])
# Case: P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W)
if left.columns.size == len(indices):
return MultiTable(
ChainMap(
*[
prod_left(table, key2=k, value2=left[k])
for k, table in right.items()
]
),
reduced_names,
_children_names_=children_names,
)
return MultiTable(
{
compliment_key(k): table * left.reduce(**reduced_key(k))
for k, table in right.items()
},
reduced_names,
_children_names_=children_names,
)
def multi_table_to_multi_table_product(table_main, table_side, all_ordered_names):
indices = [
i for i, name in enumerate(table_main.names) if name not in table_side.names
]
compliment_indices = [i for i in range(table_main.columns.size) if i not in indices]
reduced_names = [table_main.names[i] for i in compliment_indices]
children_names = [
names for names in all_ordered_names if names not in reduced_names
]
def reduced_key(key):
# Method to split the keys
return {table_main.names[i]: key[i] for i in indices}
def compliment_key(key):
# Method to split the keys
return RowKey(*[key[i] for i in compliment_indices])
if len(table_side.columns.children_names) == len(indices):
def prod2(key1, table1):
table_side_table2 = table_side[key1]
if table_side_table2 is None:
return {}
return {
compliment_key(key1): table1 * table2
for key2, table2 in table_side_table2
}
return MultiTable(
ChainMap(*[prod2(key1, table1) for key1, table1 in table_main.items()]),
reduced_names,
_children_names_=children_names,
)
return MultiTable(
{
compliment_key(key1): table1 * table2
for key1, table1 in table_main.items()
for key2, table2 in table_side.reduce(**reduced_key(key1))
},
reduced_names,
_children_names_=children_names,
)
def multi_table_product(left, right):
"""Multiply two tables.
P(X, Y | Z) * P(Z) -> P(X, Y , Z)
P(X, Y | Z, W) * P(Z) -> P(X, Y , Z | W)
P(X, Y | Z, U) * P(Z | U) -> P(X, Y , Z | U)
P(X, Y | Z, U, W) * P(Z | U, W) -> P(X, Y , Z | U, W)
in the case of two conditionals, the longer one defines
the order of variables
e.g.
P(X, Y | Z, U, W) * P(Z | W, U) -> P(X, Y , Z | U, W)
P(Z | W, U) * P(X, Y | Z, U, W) -> P(X, Y , Z | U, W)
Args:
left ([type]): [description]
right ([type]): [description]
Raises:
ValueError: [description]
Returns:
[type]: [description]
"""
# Cases:
# P(X, Y | Z) * P(Z) -> P(X, Y, Z)
# P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W)
if not isinstance(right, MultiTable):
if sorted(right.names) != sorted(left.names):
raise ValueError("The right names is" " not equal to conditionals of left.")
all_ordered_names = left.columns.children_names + right.columns.names
return multi_table_to_table_product(left, right, all_ordered_names)
# Cases:
# P(Z) * P(X, Y | Z) -> P(Z, X, Y)
# P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W)
if not isinstance(left, MultiTable):
if sorted(right.names) != sorted(left.names):
raise ValueError("The left names is" " not equal to conditionals of right.")
all_ordered_names = left.names + right.columns.children_names
return table_to_multi_table_product(left, right, all_ordered_names)
# Cases:
# P(X, Y | Z, U) * P(Z | U) -> P(X, Y, Z | U)
# P(X, Y | Z, U, W) * P(Z | U, W) -> P(X, Y, Z | U, W)
# P(X, Y, Z| U, W) * P(U | W) -> P(X, Y, Z, U | W
# P(X, Y, Z| U, V, W) * P(U, V | W) -> P(X, Y, Z, U, V | W)
def in_the_other(first, second):
for name in first:
if name not in second:
return False
return True
common_conditions = [name for name in left.names if name in right.names]
right_compliment_conditions = [
name for name in right.names if name not in common_conditions
]
left_compliment_conditions = [
name for name in left.names if name not in common_conditions
]
# To check the crossed cases
# e.g. P(X | Y) * P(Y | X)
# after removing common names on conditionals,
# one of them must remains conditionless
# e.g.
# 1) P(X, Y | Z, U) * P(Z | U)
# removes commons: P(X, Y | Z) * P(Z)
# 2) P(Z | U, W) * P(X, Y | Z, U, W)
# removes commons: P(Z) * P(X, Y | Z)
# 3) P(X | Y) * P(Y | X)
# remove commons fails
if len(right_compliment_conditions) == 0:
if not in_the_other(right.columns.children_names, left.names):
raise ValueError(
"Columns in right is not defined in conditional names of left."
)
all_ordered_names = left.columns.children_names + right.columns.children_names
return multi_table_to_multi_table_product(left, right, all_ordered_names)
elif len(left_compliment_conditions) == 0:
if not in_the_other(left.columns.children_names, right.names):
raise ValueError(
"Columns in left is not defined in conditional names of right."
)
all_ordered_names = left.columns.children_names + right.columns.children_names
return multi_table_to_multi_table_product(right, left, all_ordered_names)
else:
raise ValueError("Columns and conditional names mismatch.")
class MultiTable(Table):
def __init__(self, rows, names=None, _children_names_=None):
super().__init__(
rows, names, _internal_=True, _children_names_=_children_names_
)
def marginal(self, *args, normalise=True):
"""[summary]
P(X, Y | Z) -> P(X | Z) or P(Y | Z)
Args:
normalise (bool, optional): [description]. Defaults to True.
Raises:
ValueError: [description]
Returns:
MultiTable: [description]
"""
for name in args:
if name in self.names:
raise ValueError(f"Cannot marginalize on conditioned columns:'{name}'.")
table = Table(
{
k: table.marginal(*args, normalise=normalise)
for k, table in self.items()
},
self.names,
_internal_=True,
)
if normalise:
table.normalise()
return table
def condition_on(self, *args, normalise=True):
"""Creates the conditional based on
the provided names of columns.
P(X, Y | Z) -> P(X | Y, Z) or P(Y | X, Z)
Args:
args (list):
List of names of provided random
variables.
Raises:
ValueError:
If the provided RV names do not exist
in the distribution.
Returns:
(row, names)
"""
for name in args:
if name in self.names:
raise ValueError(f"Cannot condition on conditioned columns:'{name}'.")
conditioned_children = (
(k, table.condition_on(*args, normalise=normalise))
for k, table in self.items()
)
return MultiTable(
{
key2 + key1: table
for key1, key2_table in conditioned_children
for key2, table in key2_table.items()
},
# It results in: P(X, Y | Z) -> P(X | Y, Z)
# inversing the order turns it P(X, Y | Z) -> P(X | Z, Y)
# Maybe more controls is needed here
list(args) + self.names,
)
def reduce(self, **kwargs):
"""Reduce the Table by one or more columns.
P(X, Y | Z) -> P(X = x, Y | Z) or P(X, Y = y | Z)
Args:
kwargs (dict):
A dictionary that its 'key' is the name
of the column and its 'value'
is the value that must be reduced by.
Raises:
ValueError:
If the provided names do not exist in the Table.
Returns:
[Table]: A reduce Table.
"""
return MultiTable(
{k: table.reduce(**kwargs) for k, table in self.items()},
self.names,
)
def __mul__(self, right):
if not isinstance(right, Table):
raise ValueError("The 'right' argument must be a 'Table'.")
return multi_table_product(self, right)
def __rmul__(self, left):
if not isinstance(left, Table):
raise ValueError("The 'left' argument must be a 'Table'.")
return multi_table_product(left, self)
| python |
<filename>package.json<gh_stars>1-10
{
"name": "batch-notifications",
"version": "0.3.0",
"description": "NodeJS client wrapper for the Batch.com notifications server API",
"main": "./index.js",
"scripts": {
"lint": "eslint --quiet --cache --format codeframe .",
"lint:fix": "eslint --fix .",
"test": "NODE_ENV=test mocha",
"ci-coverage": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
"postversion": "git push && git push --tags"
},
"engines": {
"node": ">=6.x"
},
"repository": {
"type": "git",
"url": "https://github.com/nomadeducation/batch-notifications-node.git"
},
"keywords": [
"node",
"batch.com",
"notification",
"wrapper"
],
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/nomadeducation/batch-notifications-node/issues"
},
"homepage": "https://github.com/nomadeducation/batch-notifications-node#readme",
"dependencies": {
"ajv": "^5.0.1",
"axios": "^0.18.0",
"bunyan": "^1.8.12",
"lodash": "^4.17.5"
},
"devDependencies": {
"axios-mock-adapter": "^1.15.0",
"chai": "^3.5.0",
"coveralls": "^2.13.1",
"eslint": "^4.19.0",
"eslint-config-nomadeducation": "^1.1.2",
"istanbul": "^0.4.5",
"mocha": "^3.3.0"
}
}
| json |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Geotab SDK | Import HOS logs</title>
<link href="css/geotab.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<div class="container">
<nav>
<img src="http://www.geotab.com/webimages/header/geotablogo.png" alt="" />
<button id="help">Help</button>
<button id="signout">Sign out</button>
</nav>
<h1>Example: Import HOS logs</h1>
<h3>How to import a list of JSON HOS logs to MyGeotab</h3>
</div>
</header>
<div class="container bordered">
<div id="signin-content"></div>
<div id="example-content">
<form>
<h3>Import HOS logs</h3>
<p>
Use the text box below to import multiple HOS logs at a time. Place each device
on its own line as follows:
</p>
<div class="code">
<pre>{"dateTime":"2014-12-09T22:47:10.969Z","verifyDateTime":"2014-12-09T23:25:07.078Z","driver":{"id":"b41B4DC3B"},"id":"aHic5TSUoXEqVQagnbQmtpg","device":{"id":"b142"},"version":"000229ddc4f469b8","status":"ON"}</pre>
<pre>{"dateTime":"2014-12-10T15:13:22.646Z","verifyDateTime":"2014-12-10T23:35:26.300Z","driver":{"id":"b41B4DC3B"},"id":"aqwQdey20FEOPM9guvRs86Q","device":{"id":"b122"},"version":"00022c4707312d6f","status":"D"}</pre>
</div>
<p>
<textarea id="content" cols="80" rows="8"></textarea>
</p>
<button id="importLogs">Import logs</button>
<span id="result"></span>
</form>
</div>
</div>
<footer>
<div class="container footernotes">
<p>Source code provided as part of the <a href="https://helpdesk.geotab.com/forums" target="_blank">Geotab SDK</a>.</p>
<p>Last updated on 11/11/2013</p>
</div>
</footer>
<div id="help-content">
<h2>Help</h2>
<p>
<strong>Overview</strong><br />
This utility helps you import HOS logs to your account using a line list of JSON objects.
</p>
<p>
<strong>Work flow</strong><br />
TODO
</p>
<p>
<strong>Skill level</strong><br />
Intermediate
</p>
</div>
<script src="js/api.js"></script>
<script src="js/login.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("importLogs").addEventListener("click", function (event) {
event.preventDefault();
var content = document.getElementById("content").value;
var i;
if (content === "") {
alert("At least one log is required");
} else {
// Split up the lines one by one
var logs = content.split("\n");
// Reset the result display
document.getElementById("result").innerHTML = "";
// Build array of logs to multicall
var calls = [];
for (i = 0; i < logs.length; i++) {
if (logs[i].length == 0) continue;
var logJSON = JSON.parse(logs[i]);
//Only let the location.location exist
if (logJSON.location && logJSON.location.location) {
logJSON.location = {
location: logJSON.location.location
};
}
calls.push(["Add", {
typeName: "DutyStatusLog",
entity: logJSON
}]);
}
document.getElementById("result").innerHTML = "Importing started ... ";
api.multiCall(calls, function (results) {
console.log(results);
document.getElementById("result").innerHTML = "Importing finished";
}, function (error) {
console.log(error);
document.getElementById("result").innerHTML = "Error importing!";
});
}
});
});
</script>
</body>
</html>
| html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.