language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 8,971 | 3.0625 | 3 | [] | no_license | from enum import Enum
import json
import random
import sys
import time
# Support for PyInstaller --onefile. It creates an archive exe that
# unpacks to a temp directory. We need to convince all our file I/O
# to use that directoy as the application base dir. chdir is the
# easiest way, if we use relative paths for everything else.
if hasattr(sys, '_MEIPASS'):
os.chdir(sys._MEIPASS)
from prototype.entities.champion import Champion
from prototype.entities.cards.action import Action
from prototype.entities.cards.armour import Armour
from prototype.entities.cards.consumable import Consumable
from prototype.entities.cards.skill import Skill
from prototype.entities.cards.weapon import Weapon
class WhoseTurn(Enum):
PLAYER = 1
AI = 2
class Main:
# Main entry point!
def run(self):
self.whoseTurn = WhoseTurn.PLAYER
self.load_json_data()
self.pick_champions()
self.distribute_cards()
print("")
print("{0} (you) vs. {1}!".format(self.player.name, self.opponent.name))
self.print_player_stats()
def load_json_data(self):
# Load JSON data from files
with open('data/config.json') as data:
self.config = json.load(data)
with open('data/actions.json') as data:
actions = json.load(data)
with open('data/armour.json') as data:
armour = json.load(data)
with open('data/champions.json') as data:
champions = json.load(data)
with open('data/consumables.json') as data:
consumables = json.load(data)
with open('data/skills.json') as data:
skills = json.load(data)
with open('data/weapons.json') as data:
weapons = json.load(data)
# Construct classes
self.cards = []
for data in actions:
# Consumables show up several times because they're basic attacks.
self.cards.append(Action(data))
self.cards.append(Action(data))
self.cards.append(Action(data))
self.cards.append(Action(data))
for data in armour:
self.cards.append(Armour(data))
for data in consumables:
# Consumables show up several times because they're useful.
# Create copies, not references
self.cards.append(Consumable(data))
self.cards.append(Consumable(data))
self.cards.append(Consumable(data))
for data in skills:
self.cards.append(Skill(data))
for data in weapons:
self.cards.append(Weapon(data))
self.cards.append(Weapon(data))
# Populate class instances from said data
self.champions = []
for champ_data in champions:
weapon_data = Weapon.find(weapons, champ_data["weapon"])
armour_data = Armour.find(armour, champ_data["armour"])
c = Champion(champ_data["name"], champ_data["health"], weapon_data, armour_data)
self.champions.append(c)
def pick_champions(self):
self.player = self.champions[0]
index = random.randint(1, len(self.champions) - 1)
self.opponent = self.champions[index]
def distribute_cards(self):
random.shuffle(self.cards)
self._give_cards_to(self.player)
self._give_cards_to(self.opponent)
def _give_cards_to(self, player):
while len(player.deck) < self.config["deckSize"]:
player.deck.append(self.cards.pop())
while len(player.hand) < self.config["handSize"]:
self._draw_cards(player)
def print_player_stats(self):
while self.player.current_health > 0 and self.opponent.current_health > 0:
if self.whoseTurn == WhoseTurn.PLAYER:
Main.print_status_for(self.opponent, self.opponent.name)
Main.print_status_for(self.player, "You")
print("Your deck has {0} cards left.".format(len(self.player.deck)))
if len(self.player.deck) == 0 and len(self.player.hand) == 0:
print("You run out of cards! You abdicate! YOU LOSE!")
sys.exit(0)
print("")
print("You have {0} cards in your hand:".format(len(self.player.hand)))
if self.player.weapon != None:
print(" a) Attack with {0}".format(self.player.weapon.name))
i = 1
for card in self.player.hand:
print(" {0}) {1}".format(i, card.name))
i += 1
print("")
print("Play what card?")
input = sys.stdin.readline().lower().strip()
if input == "q" or input == "quit":
print("Bye!")
sys.exit(0)
elif input == "d" or input == "draw":
self._get_card(self.player)
self.whoseTurn = WhoseTurn.AI
time.sleep(0.5)
elif input == "a" or input == "attack":
Main._attack(self.player, self.opponent)
self.whoseTurn = WhoseTurn.AI
time.sleep(0.5)
else:
try:
card_number = int(input) - 1
if card_number >= 0 and card_number < len(self.player.hand):
card = self.player.hand[card_number]
took_action = Main.process_turn(self.player, self.opponent, card)
if took_action:
self._draw_cards(self.player)
self.whoseTurn = WhoseTurn.AI
time.sleep(0.5)
else:
print("Card number must be from 1-{0}.".format(len(self.player.hand)))
except ValueError:
print("That's not a number, mate. Enter the number of the card to use; type 'draw' to draw another card, 'a' or 'attack' to attack, or type 'quit' to quit.")
else:
if random.randint(1, 100) <= self.config["enemyAttackChance"]:
Main._attack(self.opponent, self.player)
else:
self._draw_cards(self.opponent)
if len(self.opponent.hand) > 0:
card = random.choice(self.opponent.hand)
Main.process_turn(self.opponent, self.player, card)
else:
print("{0} is out of cards! {0} abdicates! YOU WIN!".format(self.opponent.name))
sys.exit(0)
self.whoseTurn = WhoseTurn.PLAYER
time.sleep(0.5)
print("")
def _draw_cards(self, champion):
while len(champion.deck) > 0 and len(champion.hand) < self.config["handSize"]:
self._get_card(champion)
def _get_card(self, champion):
if len(champion.deck) > 0:
card = champion.deck.pop()
champion.hand.append(card)
if (champion == self.player):
print("You draw a {0} card".format(card.name))
else:
print("{0} draws a card".format(champion.name))
else:
print("{0}'s deck is empty!".format(champion.name))
@staticmethod
def process_turn(player, opponent, card):
took_action = card.apply(player, opponent)
if took_action:
player.hand.remove(card)
if player.bleeds_left > 0:
player.bleeds_left -= 1
player.get_hurt(1)
print("{0} bleeds for 1 damage!".format(player.name))
return took_action
@staticmethod
def print_status_for(player, name):
status = "{3}{4}: {0}/{1} health, {2} sp.".format(
player.current_health, player.total_health, player.skill_points, name,
" (bleeding)" if player.bleeds_left > 0 else "")
if player.weapon != None:
status = "{0} {1} +{2}/{3} durability".format(status, player.weapon.name, player.weapon.damage, player.weapon.durability)
if player.armour != None:
status = "{0} {1} +{2}/{3} durability".format(status, player.armour.name, player.armour.defense, player.armour.durability)
print(status)
@staticmethod
def _attack(attacker, target):
damage = (1 if attacker.weapon is None else attacker.weapon.damage) - (0 if target.armour is None else target.armour.defense)
print("{0} attacks {1} for {2} damage!".format(attacker.name, target.name, damage))
target.get_hurt(damage)
attacker.attacks()
Main().run() |
SQL | UTF-8 | 1,218 | 3.765625 | 4 | [] | no_license | drop table final_race_db;
drop table final_reason_db;
drop table final_gender_db;
drop table final_result_db;
drop table final_action_db;
create table final_reason_db (
stop_id int primary key,
reason_for_stop text,
reason_for_stopcode text,
reason_for_stop_detail text,
reason_for_stop_explanation text
);
create table final_gender_db (
stop_id int primary key,
gender text
);
create table final_result_db(
stop_id int primary key,
resultkey text,
result text
);
create table final_action_db (
stop_id int primary key,
action text
);
create table final_race_db (
stop_id int primary key,
race text
);
select final_race_db.stop_id, final_race_db.race, final_gender_db.gender, final_reason_db.reason_for_stop,
final_reason_db.reason_for_stopcode, final_reason_db.reason_for_stop_detail, final_reason_db.reason_for_stop_explanation,
final_action_db.action, final_result_db.resultkey, final_result_db.result
from final_race_db
join final_gender_db on final_gender_db.stop_id=final_race_db.stop_id
join final_reason_db on final_reason_db.stop_id=final_gender_db.stop_id
join final_action_db on final_action_db.stop_id=final_reason_db.stop_id
join final_result_db on final_result_db.stop_id=final_action_db.stop_id
|
TypeScript | UTF-8 | 552 | 2.609375 | 3 | [] | no_license | export class OverallRatingsForBook {
overallRating: number;
overallOriginalityRating: number;
overallWritingQualityRating: number;
overallPageTurnerRating: number;
constructor(overallRating: number, overallOriginalityRating: number, overallWritingQualityRating: number, overallPageTurnerRating: number) {
this.overallRating = overallRating;
this.overallOriginalityRating = overallOriginalityRating;
this.overallWritingQualityRating = overallWritingQualityRating;
this.overallPageTurnerRating = overallPageTurnerRating;
}
}
|
Python | UTF-8 | 651 | 3.609375 | 4 | [] | no_license | #打开调取文本文件
f1 = open("test.txt","r")
content= f1.read()
f1.close()
#删除文本文件所有符号
import string
translator = str.maketrans('', '', string.punctuation)
z=content.translate(translator)
#转为列表
a=z.split()
#用字典统计各个单词使用次数
#列表转为集合,去除重复项
set1=set(a)
#集合转为列表
b=list(set1)
#新建空字典
dir1={}
for x in range(len(b)):
dir1[b[x]]=0
for y in range(len(a)):
if b[x] ==a[y]:
dir1[b[x]]+=1
#按出现次数从大到小输出所有单词和次数
dir2=sorted(dir1.items(), key=lambda d:d[1], reverse = True)
print(dir2)
|
Rust | UTF-8 | 696 | 2.78125 | 3 | [] | no_license | use reqwest;
use std::thread;
use std::time::Duration;
#[allow(dead_code)] // Now the API is called from a free cron-job
pub async fn call_every_hour(addr: String, paths: Vec<&'static str>) {
let paths: Vec<_> = paths
.into_iter()
.map(|path| "http://".to_owned() + addr.as_str() + path)
.collect();
thread::sleep(Duration::from_secs(5));
loop {
for path in &paths {
println!("Starting Hourly Call");
let client = reqwest::Client::new();
let resp = client.get(path).send().await;
match resp {
Ok(_) => {}
Err(err) => println!("Error during hourly call: {:?}", err),
}
}
thread::sleep(Duration::from_secs(3600));
}
}
|
Java | UTF-8 | 737 | 1.664063 | 2 | [
"Apache-2.0"
] | permissive | package com.rbkmoney.newway.kafka;
import com.rbkmoney.newway.service.WalletService;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.boot.test.mock.mockito.MockBean;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.anyList;
public class WalletKafkaListenerTest extends AbstractKafkaTest {
@org.springframework.beans.factory.annotation.Value("${kafka.topics.wallet.id}")
public String topic;
@MockBean
WalletService walletService;
@Test
public void listenEmptyChanges() {
sendMessage(topic);
Mockito.verify(walletService, Mockito.timeout(TimeUnit.MINUTES.toMillis(1)).times(1))
.handleEvents(anyList());
}
}
|
C | UTF-8 | 2,486 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <lz4frame.h>
/*
* unframe-lz4
*
* example of using lz4's framing api
*
* on ubuntu, first install:
* sudo apt install liblz4-dev
*
*/
/* mmap file, placing its size in len and
* returning address or NULL on error.
* caller should munmap the buffer eventually.
*/
char *map(char *file, size_t *len) {
int fd = -1, rc = -1, sc;
char *buf = NULL;
struct stat s;
fd = open(file, O_RDONLY);
if (fd < 0) {
fprintf(stderr,"open: %s\n", strerror(errno));
goto done;
}
sc = fstat(fd, &s);
if (sc < 0) {
fprintf(stderr,"fstat: %s\n", strerror(errno));
goto done;
}
if (s.st_size == 0) {
fprintf(stderr,"error: mmap zero size file\n");
goto done;
}
buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (buf == MAP_FAILED) {
fprintf(stderr, "mmap: %s\n", strerror(errno));
buf = NULL;
goto done;
}
rc = 0;
*len = s.st_size;
done:
if (fd != -1) close(fd);
if (rc && buf) { munmap(buf, s.st_size); buf = NULL; }
return buf;
}
int main(int argc, char * argv[]) {
char *file, *buf=NULL, *cbuf=NULL, *c, out[512];
size_t len, nr, l, o;
int rc = -1;
if (argc < 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);
exit(-1);
}
file = argv[1];
buf = map(file, &len);
if (buf == NULL) goto done;
fprintf(stderr, "mapped %s: %zu bytes\n", file, len);
/* compressed buffer */
c = buf;
l = len;
/* decompression context */
LZ4F_decompressionContext_t context;
nr = LZ4F_createDecompressionContext(&context, LZ4F_VERSION);
if (LZ4F_isError(nr)) {
fprintf(stderr, "LZ4F_createDecompressoinContext: %s\n",
LZ4F_getErrorName(nr));
goto done;
}
do {
l = len - (c - buf); /* src bytes remaining */
o = sizeof(out); /* output bytes avail */
nr = LZ4F_decompress(context, out, &o, c, &l, NULL);
if (LZ4F_isError(nr)) {
fprintf(stderr, "LZ4F_decompress: %s\n",
LZ4F_getErrorName(nr));
goto done;
}
if (o) {
fprintf(stderr, "decompressed %zu bytes\n", o);
write(STDOUT_FILENO, out, o);
}
c += l; /* advance src position */
} while( nr != 0 );
rc = 0;
done:
LZ4F_freeDecompressionContext(context);
if (buf) munmap(buf, len);
if (cbuf) free(cbuf);
return rc;
}
|
Python | UTF-8 | 618 | 4.53125 | 5 | [] | no_license | import random
heads = 0
tails = 0
count = 0
# Initializes heads, tails and count at zero.
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("Heads!\n")
heads += 1
count +=1
# While the program hasn't reached 100, assign a random integer to COIN
# If coin is equal to 1, then print "heads". Increment and count by 1 each time.
# Otherwise (elif) the coin is equal to 2, then print "tails". Increment and count by 1 each time.
elif coin == 2:
print("Tails!\n")
tails += 1
count += 1
print("Heads:", heads)
print("Tails:", tails)
|
Markdown | UTF-8 | 2,169 | 3.53125 | 4 | [] | no_license | # 1. Introduction
## What is React
As per their [website](https://reactjs.org/) react is "A library for building user interfaces".
If we dig into that statment a little deeper we can say that React allows you to build complex user interfaces
from smaller isolated pieces of code called "components". These small pieces of code, components, are describing
what elements need to be rendered to the DOM. React also maintains any updates that need to be proccessed by state changes
but more about that later.
## Create React App
As per their [website](https://reactjs.org/docs/create-a-new-react-app.html) "an integrated toolchain".
Again if we dig a little deeper `create-react-app` basically just creates all the tooling boilerplate we need for a React app.
If we were doing it ourselves we would have to write all the configuration ourself. `create-react-app` abstracts this and gives us
a massive head start.
To set up a react app can run: `npx create-react-app my-app`
Then to start the application: `cd my-app` and then run `npm start`.
## ReactDOM
We mentioned previously that React manages updates and rendering of components to the DOM. This is nearly true. In fact the `react`
package itself can be considered more like the manager of all these components whereas ReactDOM is in charge of actually taking those
components and rendering them as DOM elements.
For example if you had this HTML
```html
<div id="root"></div>
```
And this JS
```js
const element = document.getElementById("#root");
ReactDOM.render("foo bar", element);
```
This would result in "foo bar" being rendered into `#root`. So we once this code runs we would end up with:
```html
<div id="root">foo bar</div>
```
ReactDOM can be described as providing an interop between the host environment (the DOM) and `react`. In fact there are other host environments
that we can use such as `react-native` which is used for IOS and Android apps or even `ink` which is used to create CLI tools. For the purpose
of getting to understand React we are going to focus on ReactDOM but we should at least know other host environment abstractions exist.
[Take me to part 02](http://localhost)
|
Java | UTF-8 | 2,265 | 2.640625 | 3 | [] | no_license | package com.mcmo.z.commonlibrary.permisson;
import java.util.ArrayList;
public class PermissionProcess {
protected String[] permissions;
protected PermissionCallback cb;
private String[] grantedPermissions;//已授权
private String[] deniedPermissions;//未授权
private String[] donotAskAgainPermissions;//选择了不再提示的权限,在权限申请回调里面能判断出来
private String[] needTipPermissions;//需要在申请前提示用户为什么要申请权限的权限
private String[] stringArray = new String[0];//用来做参数
protected PermissionProcess(String[] permissions, PermissionCallback cb) {
this.permissions = permissions;
this.cb = cb;
}
protected void setResult(ArrayList<String> grantedList, ArrayList<String> deniedList, ArrayList<String> donotAskAgainList, ArrayList<String> needTipList) {
grantedPermissions = getPermissionsArray(grantedList);
deniedPermissions = getPermissionsArray(deniedList);
donotAskAgainPermissions = getPermissionsArray(donotAskAgainList);
needTipPermissions = getPermissionsArray(needTipList);
}
private String[] getPermissionsArray(ArrayList<String> list) {
if (list == null) {
return new String[0];
} else {
return list.toArray(stringArray);
}
}
public String[] getGrantedPermissions() {
return grantedPermissions;
}
public String[] getDeniedPermissions() {
return deniedPermissions;
}
public String[] getDonotAskAgainPermissions() {
return donotAskAgainPermissions;
}
public String[] getNeedTipPermissions() {
return needTipPermissions;
}
/**
* 权限全部被允许
*
* @return
*/
public boolean isAllGranted() {
return deniedPermissions != null && deniedPermissions.length == 0;
}
/**
* 是否有选择了Do not ask again的权限
*
* @return
*/
public boolean needGuideToSettings() {
return donotAskAgainPermissions != null && donotAskAgainPermissions.length > 0;
}
public boolean needRationale() {
return needTipPermissions != null && needTipPermissions.length > 0;
}
}
|
Java | UTF-8 | 1,196 | 3.53125 | 4 | [] | no_license | package be.intecbrussel.eatables;
public class Magnum implements Eatable {
private MagnumType type;
//create constructors
public Magnum() {
}
public Magnum(MagnumType type) {
this.type = type;
}
//implement eat method for magni. prints the type you picked.
@Override
public void eat() {
System.out.println("Eating a " + getType() + " magnum");
}
public MagnumType getType() {
return type;
}
public enum MagnumType {
MILKCHOCOLATE("milk chocolate"),
WHITECHOCOLATE("white chocolate"),
BLACKCHOCOLATE("black chocolate"),
ALPINENUTS("alpine nuts"),
ROMANTICSTRAWBERRIES("romantic strawberries");
private String magnumName;
//create a constructor for magni so i can add a string to the types.
MagnumType(String magnumName) {
this.magnumName = magnumName;
}
@Override
public String toString() {
return magnumName;
}
//
// @Override
// public String toString() {
// return name().substring(0, 1).toUpperCase() + name().substring(1).toLowerCase();
// }
}
}
|
JavaScript | UTF-8 | 400 | 3.03125 | 3 | [] | no_license | // Extended goodie 'class'
Cell = function (game, x, y, cellx, celly) {
Phaser.Sprite.call(this, game, x, y, 'mazewall0');
this.cellx = cellx;
this.celly = celly;
this.exits = {north: true, east: true, south: true, west: true};
};
Cell.prototype = Object.create(Phaser.Sprite.prototype);
Cell.prototype.constructor = Cell;
Cell.prototype.update = function() {
}
|
Java | UTF-8 | 3,933 | 2.15625 | 2 | [
"MIT"
] | permissive | package com.example.testmvpapp.sections.main.personal;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.testmvpapp.Model.PersonalBean;
import com.example.testmvpapp.Model.PersonalItemBean;
import com.example.testmvpapp.R;
import com.example.testmvpapp.base.BasePresenter;
import com.example.testmvpapp.base.SimpleFragment;
import com.example.testmvpapp.sections.adapter.PersonalAdapter;
import com.example.testmvpapp.util.base.ToastUtils;
import com.example.testmvpapp.util.log.LatteLogger;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public class PersonalFragment extends SimpleFragment {
@BindView(R.id.rv_personal)
RecyclerView mPersonalRV;
private PersonalAdapter mPersonalAdapter;
@Override
protected Object getLayout() {
return R.layout.fragment_personal;
}
@Override
public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
setupRecyclerView();
}
private void setupRecyclerView() {
mPersonalRV.setLayoutManager(new LinearLayoutManager(getActivity()));
final PersonalItemBean itemBean = new PersonalItemBean();
itemBean.setId(0);
itemBean.setTitle("item");
// header 0 有两条
final PersonalBean section = new PersonalBean(true, "header");
section.setTitle("section");
final PersonalBean bean1 = new PersonalBean(itemBean);
final PersonalBean bean2 = new PersonalBean(itemBean);
// header 1 有一条
final PersonalBean section1 = new PersonalBean(true, "header");
section1.setTitle("section1");
final List<PersonalBean> datas = new ArrayList<>();
datas.add(section);
datas.add(bean1);
datas.add(bean2);
datas.add(section1);
datas.add(bean1);
mPersonalAdapter = new PersonalAdapter(R.layout.item_personal, R.layout.recycler_view_personal_section, datas);
// 添加header头
mPersonalAdapter.addHeaderView(getHeaderView(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ToastUtils.showToast("header 点击");
Intent intent = new Intent(getContext(), PersonalInfoActivity.class);
intent.putExtra("name", "123");
startActivity(intent);
LatteLogger.d("点击");
}
}));
mPersonalAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
PersonalBean item = (PersonalBean) adapter.getData().get(position);
LatteLogger.d("点击");
switch (view.getId()) {
case R.id.tv_title:
ToastUtils.showToast("点击");
break;
default:
break;
}
}
});
mPersonalRV.setAdapter(mPersonalAdapter);
}
/**
* 设置recycle的header头
*/
private View getHeaderView(View.OnClickListener listener) {
View view = getActivity().getLayoutInflater().inflate(R.layout.recycler_view_header_personal, null);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
view.setOnClickListener(listener);
return view;
}
}
|
Markdown | UTF-8 | 1,461 | 3.15625 | 3 | [
"MIT"
] | permissive | # nunjucks-markdown
A nunjuck extension that adds a markdown tag
## Install
``` bash
npm install marked --save
```
## Usage
Register the extension with nunjucks
``` js
var nunjucks = require('nunjucks'),
markdown = require('nunjucks-markdown');
var env = nunjucks.configure('views');
markdown.register(env);
```
Add markdown to your templates
```
{% markdown %}
Hello World
===========
# Do stuff
{% endmarkdown %}
```
You can also provide the markdown tag with a template to render
```
{% markdown "post.md" %}
```
_Note: This method doesn't require a closing tag_
As you would expect, you can add tags inside your markdown tag
```
{% markdown %}
{% include 'post1.md' %}
{% include 'post2.md' %}
{% endmarkdown %}
```
## Markdown Options
**Nunjucks-markdown** uses marked as its parser. Marked can be configured by passing in an options object to the register function.
``` js
var marked = require('marked');
markdown.register(env, {
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pendantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
```
For more information configuration options, checkout [marked](https://github.com/chjj/marked).
## Plans for the future
The last thing I really want to accomplish with this extension is to give the user the ability to specify
which markdown engine they want to use. I'll probably just set marked as the fallback if none is provided.
|
Swift | UTF-8 | 2,254 | 2.5625 | 3 | [] | no_license | //
// DetailTableViewController.swift
// PizzaMe
//
// Copyright © 2016 Charles Schwab & Co., Inc. All rights reserved.
//
import UIKit
class DetailTableViewController: UITableViewController {
private var viewModel: DetailViewModel?
func configureView() {
self.title = viewModel?.title
}
var detailItem: Restaurant? {
didSet {
if let detailItem = detailItem {
self.viewModel = DetailViewModel(restaurant: detailItem)
self.configureView()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
self.navigationController?.navigationBar.tintColor = UIColor.darkGray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel?.availableCells.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell
if let cellType = viewModel?.availableCells[indexPath.row] {
cell = tableView.dequeueReusableCell(withIdentifier: cellType.cellIdentifier, for: indexPath)
if let cell = cell as? DetailTableViewCell {
if let viewModel = viewModel?.cellViewModelFor(indexPath: indexPath) {
cell.configureWithViewModel(viewModel: viewModel)
}
}
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexPath)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let viewModel = viewModel?.cellViewModelFor(indexPath: indexPath), let action = viewModel.getAction() {
if let url = URL(string: action) {
UIApplication.shared.openURL(url)
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
JavaScript | UTF-8 | 1,476 | 2.6875 | 3 | [] | no_license | import React from 'react';
import { connect } from 'react-redux';
import { opToExpression, num1ToExpression, num2ToExpression } from '../actions/currentExpression';
import { addHistoryItem } from '../actions/history';
const numbers1 = [0, 1, 2, 3, 4];
const numbers2 = [5, 6, 7, 8, 9];
const operations = ['-', '+', '÷', '×','=',];
const Calculator = ({
expression,
operationToExpression,
number1ToExpression,
number2ToExpression,
addHistoryItem
}) => <fieldset className="calculator-body">
<legend>Calculator</legend>
<input disabled="true" value={expression} className="result"/>
<br />
{numbers1.map(num1 => <button onClick={() => number1ToExpression(num1)} key={num1}>{num1}</button>)}
<br />
{numbers2.map(num2 => <button onClick={() => number2ToExpression(num2)} key={num2}>{num2}</button>)}
<br />
{operations.map((op, index) => (
<button onClick={() => op === '=' ? addHistoryItem(expression) : operationToExpression(op)} key={index}>{op}</button>)
)}
</fieldset>;
const mapStateToProps = state => ({
expression: state.currentExpression,
});
const mapDispatchToProps = (dispatch) => ({
operationToExpression: op => dispatch(opToExpression(op)),
number1ToExpression: num1 => dispatch(num1ToExpression(num1)),
number1ToExpression: num2 => dispatch(num2ToExpression(num2)),
addHistoryItem: expr => dispatch(addHistoryItem(expr))
})
export default connect(mapStateToProps, mapDispatchToProps)( Calculator); |
Markdown | UTF-8 | 3,523 | 2.765625 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "In Defense of: Indiana Jones and the Kingdom of the Crystal Skull"
excerpt: "Pop Culture"
categories: popculture
comments: false
share: true
---

**This is the 6th installment of a 5,257 part series on the Spew: 'In Defense of:'. This series is meant to defend the helpless, the meek, and the bullied in our pop culture.**
When the fourth installment of the Indiana Jones series was announced to be released in 2008, it was met with great anticipation. I mean we all loved the first and third one, and even the second one had its moments. And we have been waiting since 1989 for a new adventure for Indy.
Then this Crystal Skull thing came out and laid a big turd in front of all of us.
Or did it??????
Yeah, unfortunately it did. It is clearly the worst of the tetrad of films in the series.
But it wasn't THAT bad.
Some of the criticisms I hear about it are sort of unfair. Granted, there are plenty of things to squawk about in this film. Shia LeBeouf's off-putting performance as Indiana Jones's kid, the fact that there was an Indiana Jones's son, the entire journey to South America (I had no idea where they where relative to other landmarks, like when they fell down that waterfall......and were the hell did those ants come from?), and the bad guys were simply....bad (I hate to see Galadriel with a Russian accent).
But again, it wasn't THAT bad.
One of the biggest criticisms is the fact there were aliens in it. Sort of a 'jumping the shark' argument. But I say 'WHOA' to that. I mean let's look a bit closer at Raiders of the Lost Ark. The Ark of the Covenant, when opened, released ghosts that melted the faces of onlookers. Remember that part in the Bible where Moses said 'don't open ye Ark of thy Covenant or else thee shalt not haveth a face after thine eyes lay upon thee ghosts of...' whatever....it's not in there!!! Just trust me on that. And when the Jones's boys found the Holy Grail, where in the world does it say that when drinking out of the wrong chalice, you age extremely poorly? Of course no where. And I won't even get into the 'grabbing of the heart' in Temple of Doom. Why are all of those acceptable yet aliens is soooooo out there?
Another critique is that when Indy is saved by being inside a refrigerator after an atomic blast. Yeah, that was dumb, but again not any more dumb than some of the previous shenanigans Spielberg introduced in the previous films (See 'melting faces' and 'grabbing heart through chest'). Having a bit of whimsy and fun is all part of the Indiana Jones experience, so some of these outlandish things that were torn apart is a bit unfair.
But the movie did sort of suck.
I know, I know, I am supposed to *defend* the movie in this post, and I don't think I am doing a very good job of this. But are you expecting me to die on that hill? The hill that says 'Crystal Skull is just as good as the other 3'? No way! Give me some credit here.
I just don't think this film ruins the entire Indiana Jones series, of should be completely ignored; defining Indiana Jones as a trilogy and NOT a quadrilogy. Sure, it was not as good, but we had the same director, the same lead actor, the lead heroine from Raiders, and overall the adventure is as ridiculous and fantaciful as any of the other installments.
I mean, it wasn't THAT bad, was it?
|
C++ | UTF-8 | 3,637 | 2.578125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | #include "UnitTest/UnitTest.h"
#include <rengine/file/File.h>
#include <algorithm>
using namespace std;
using namespace rengine;
std::string const test_filename("unit_test_data/xml_test.xml");
std::string const test_filename_unix(test_filename);
std::string const test_filename_windows("unit_test_data\\xml_test.xml");
//
// UnitTestFileFilename
//
UNITT_TEST_BEGIN_CLASS(UnitTestFileFilename)
virtual void run()
{
UNITT_FAIL_NOT_EQUAL(convertFileNameToUnixStyle(test_filename), test_filename_unix);
UNITT_FAIL_NOT_EQUAL(convertFileNameToWindowsStyle(test_filename), test_filename_windows);
UNITT_FAIL_NOT_EQUAL(convertFileNameToUnixStyle(test_filename_windows), test_filename_unix);
UNITT_FAIL_NOT_EQUAL(convertFileNameToWindowsStyle(test_filename_unix), test_filename_windows);
#if RENGINE_PLATFORM == RENGINE_PLATFORM_WIN32
UNITT_FAIL_IF( isFileNameNativeStyle(test_filename), "Filename should not be in native style" );
UNITT_FAIL_NOT_EQUAL(convertFileNameToNativeStyle(test_filename), test_filename_windows);
#else //RENGINE_PLATFORM != RENGINE_PLATFORM_WIN32
UNITT_FAIL_IF( !isFileNameNativeStyle(test_filename), "Filename should be in native style" );
UNITT_FAIL_NOT_EQUAL(convertFileNameToNativeStyle(test_filename), test_filename_unix);
#endif //RENGINE_PLATFORM != RENGINE_PLATFORM_WIN32
}
UNITT_TEST_END_CLASS(UnitTestFileFilename)
//
// UnitTestFilePath
//
UNITT_TEST_BEGIN_CLASS(UnitTestFilePath)
virtual void run()
{
UNITT_FAIL_NOT_EQUAL("unit_test_data", getFilePath(test_filename));
UNITT_FAIL_NOT_EQUAL("xml", getFileExtension(test_filename));
UNITT_FAIL_NOT_EQUAL("XmL", getFileExtension("unit_test_data/xmlss.XmL"));
UNITT_FAIL_NOT_EQUAL("xml", getLowerCaseFileExtension("unit_test_data/xmlss.XmL"));
UNITT_FAIL_NOT_EQUAL("xml_test.xml", getSimpleFileName(test_filename));
UNITT_FAIL_NOT_EQUAL("unit_test_data/xml_test", getNameLessExtension(test_filename));
UNITT_FAIL_NOT_EQUAL("xml_test", getStrippedName(test_filename));
}
UNITT_TEST_END_CLASS(UnitTestFilePath)
//
// UnitTestFileDirectory
//
UNITT_TEST_BEGIN_CLASS(UnitTestFileDirectory)
virtual void run()
{
std::string file_path = convertFileNameToNativeStyle("unit_test_data/File");
UNITT_ASSERT(fileType(file_path) == FileDirectory);
DirectoryContents contents = getDirectoryContents(file_path);
UNITT_FAIL_NOT_EQUAL(4 + 2, contents.size());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), ".") != contents.end());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), "..") != contents.end());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), "One") != contents.end());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), "Tw o") != contents.end());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), "one_text_file.txt") != contents.end());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), "another file.txt") != contents.end());
UNITT_ASSERT(fileType("unit_test_data/File/One") == FileDirectory);
UNITT_ASSERT(fileType("unit_test_data/File/Tw o") == FileDirectory);
UNITT_ASSERT(fileType("unit_test_data/File/one_text_file.txt") == FileRegular);
UNITT_ASSERT(fileType("unit_test_data/File/another file.txt") == FileRegular);
contents = find(file_path, EqualExtension("txt"));
UNITT_FAIL_NOT_EQUAL(2, contents.size());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), convertFileNameToNativeStyle("unit_test_data/File/one_text_file.txt")) != contents.end());
UNITT_ASSERT(std::find(contents.begin(), contents.end(), convertFileNameToNativeStyle("unit_test_data/File/another file.txt")) != contents.end());
}
UNITT_TEST_END_CLASS(UnitTestFileDirectory)
|
Java | UTF-8 | 242 | 2.09375 | 2 | [] | no_license | package runners;
import goalBasedProblems.models.State;
import java.util.ArrayList;
/**
* Created by emran on 11/10/16.
*/
public interface StateFoundListener extends SolveFinishedListener {
void pathFound(ArrayList<State> path);
}
|
C | UTF-8 | 3,588 | 3.75 | 4 | [] | no_license | /*
Worst Fit
Joshua Joseph
11/22/2015
*/
#include <stdio.h>
#include <time.h>
//worst fit
void worstFit(int numProcesses,int memSlot[10],int process[10],int numMemSlots) {
int i, j, k, fit, unallocated=0;
clock_t begin, end;
double execTime;
// Make a copy of the original memory slots
int origMemory[numMemSlots];
for(i=0; i<numMemSlots; i++) {
origMemory[i] = memSlot[i];
}
// Display the memory slots
printf("\nMemory Slots (and size): ");
for(i=0; i<numMemSlots; i++) {
printf("%d(%d)\t", i+1, memSlot[i]);
}
// Display the processes
printf("\n Processes (and size): ");
for(i=0; i<numProcesses; i++) {
printf("%d(%d)\t", i+1, process[i]);
}
printf("\n");
begin = clock(); // Get begin time
for(i = 0; i < numProcesses; i++) {
fit=0;
int bigOne=0;
for(j = 0; j < numMemSlots; j++) {
// If the current process fits, check for a bigger slot
if(process[i] <= memSlot[j]) {
bigOne=j; // Set bigOne variable to the current memory slot
// Check the rest of the memSlot array for a bigger memory slot
for(k = j; k < numMemSlots; k++) {
if(memSlot[bigOne] < memSlot[k]) {
bigOne = k;
}
}
// If the process is smaller than the slot size, allocate it and adjust the slot size
if(process[i] < memSlot[bigOne]) {
// Display where the process was allocated
printf("\nProcess %d (size %d) allocated to memory slot %d (size %d). New slot size: %d\n", i+1, process[i], j+1, memSlot[j], memSlot[j] - process[i]);
memSlot[j] -= process[i];
fit = 1; // The process successfully fit into a memory slot
break;
}
// If the process is the same size as the slot, allocate it and eliminate the slot
else if(process[i] == memSlot[bigOne]) {
// Display where the process was allocated
printf("\nProcess %d (size %d) allocated to memory slot %d (size %d). New slot size: %d\n", i+1, process[i], j+1, memSlot[j], memSlot[j] - process[i]);
// Remove the memory slot from the array
for(k=bigOne; k<numMemSlots-1; k++) {
memSlot[k] = memSlot[k + 1];
}
numMemSlots--; // Decrement the number of memory slots
fit = 1; // The process successfully fit into a memory slot
break;
} // End of else if statement
} // End of outermost if statement
} // End of inner for loop
// If there is no compatible memory slot for the process
if(fit == 0) {
printf("\n***Memory Slot Not Available for process %d (Size %d)\n",i+1,process[i]);
unallocated++; // Increment the number of unallocated processes
}
} // End of outer for loop
// Calculate the total execution time
end = clock(); // Get end time
execTime = (double)(end - begin) / CLOCKS_PER_SEC;
// Determine the number of unused memory slots
int unused=0, fragments=0;
for(i=0; i<numMemSlots; i++) {
if((origMemory[i] - memSlot[i]) == 0) {
unused++;
}
else if(origMemory[i] > memSlot[i]) {
fragments += origMemory[i] - memSlot[i];
}
}
// Display the results
printf("\n\n Time of Execution:\t%g microseconds", execTime*1000000);
printf("\nUnallocated Processes:\t%d", unallocated);
printf("\n Unused Memory Slots:\t%d", unused);
printf("\n Total Fragments:\t%d", fragments);
} // End of worstFit function
|
JavaScript | UTF-8 | 722 | 2.59375 | 3 | [] | no_license | $(document).ready(function(){
//只执行一次,完美解决重复调用AJAX问题
$("#get-k8s-ns").one("click",function () {
$.ajax({
async: true,
type:'get',
url:'/api/k8s/namespaces' ,
dataType:'json',
success:function (data){
var thishtml = ''
$.each(data,function(i,item){
thishtml = thishtml + '<li><a href="/home/k8s/namespace/' + item + '"><i class="fa fa-circle-o"></i>' + item + '</a></li>'
});
$("#k8s-ns-show").html(thishtml)
},
error:function(){
alert('inner error')
}
})
});
});
|
Shell | UTF-8 | 537 | 3.390625 | 3 | [] | no_license | #!/bin/sh
#!/bin/sh
ping_rst=0;
ping_site=192.168.157.186
ping_detect()
{
ping_act=`ping -c 1 $ping_site | grep "1 packets received"`
if [ "$ping_act" ]; then
ping_rst=1
else
ping_rst=0
fi
}
echo ""
echo ""
echo ""
echo "######### Start to boot Pico ########"
echo ""
echo ""
echo ""
gpio_task -b
#while [ $ping_rst -eq 0 ]
#do
# echo "Trying to ping $ping_site ..."
# ping_detect
# sleep 1
#done
#echo ""
#echo ""
#echo ""
#echo "######### Change GPIO6 to Tristate ########"
#echo ""
#echo ""
#echo ""
#gpio_task -p
|
C++ | UTF-8 | 602 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int H, W;
cin >> H >> W;
vector<vector<int>> A(H, vector<int>(W));
for (int h = 0; h < H; h++) {
for (int w = 0; w < W; w++) cin >> A[h][w];
}
int min_a = 999;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if (A[i][j] < min_a) {
min_a = A[i][j];
}
}
}
int res = 0;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
res += A[i][j] - min_a;
}
}
cout << res << endl;
} |
Java | GB18030 | 185 | 2.9375 | 3 | [
"MIT"
] | permissive | package day03;
//ѧ
public class Student {
String name;
int age;
public void study(String course){
System.out.println(name+"ѧϰ"+course);
}
}
|
JavaScript | UTF-8 | 307 | 2.640625 | 3 | [] | no_license | function roundTo(number, roundToValue) {
roundToValue = roundToValue || 1;
roundToValue = 1 / roundToValue;
return Math.round(number * roundToValue) / roundToValue;
}
function roundCurrency(value) {
return roundTo(value + 0.0001, 0.01);
}
export default {
roundTo,
roundCurrency
};
|
C# | UTF-8 | 946 | 3.15625 | 3 | [] | no_license | using System.Collections.Generic;
namespace Chess.Pieces
{
class Knight: ChessPieceRaw
{
public override string GetIcon()
{
return GetIconPrefix() + "knight.png";
}
public override IEnumerable<GridCell> PossibleMoves()
{
for (int i = 0; i <= 1; i++)
for (int j = 0; j <= 1; j++)
{
int s1 = i == 0 ? -1 : 1;
int s2 = j == 0 ? -1 : 1;
var tmp = new GridCell(2 * s1 + Cell.Row, s2 + Cell.Column);
if(IsValid(tmp)!=false)
yield return tmp;
tmp = new GridCell(s1 + Cell.Row, 2 * s2 + Cell.Column);
if (IsValid(tmp) != false)
yield return tmp;
}
}
public Knight(Team team, ChessPiece[,] board) : base(team, board)
{
}
}
}
|
Java | UTF-8 | 7,262 | 1.945313 | 2 | [] | no_license | package com.facebook.appevents.internal;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.android.billingclient.api.BillingClient;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.internal.FetchedAppSettings;
import com.facebook.internal.FetchedAppSettingsManager;
import com.facebook.internal.Validate;
import java.math.BigDecimal;
import java.util.Currency;
import org.json.JSONException;
import org.json.JSONObject;
public class AutomaticAnalyticsLogger {
private static final String TAG = AutomaticAnalyticsLogger.class.getCanonicalName();
private static final InternalAppEventsLogger internalAppEventsLogger = new InternalAppEventsLogger(FacebookSdk.getApplicationContext());
public static void logActivateAppEvent() {
Context applicationContext = FacebookSdk.getApplicationContext();
String applicationId = FacebookSdk.getApplicationId();
boolean autoLogAppEventsEnabled = FacebookSdk.getAutoLogAppEventsEnabled();
Validate.notNull(applicationContext, "context");
if (!autoLogAppEventsEnabled) {
return;
}
if (applicationContext instanceof Application) {
AppEventsLogger.activateApp((Application) applicationContext, applicationId);
} else {
Log.w(TAG, "Automatic logging of basic events will not happen, because FacebookSdk.getApplicationContext() returns object that is not instance of android.app.Application. Make sure you call FacebookSdk.sdkInitialize() from Application class and pass application context.");
}
}
public static void logActivityTimeSpentEvent(String str, long j) {
Context applicationContext = FacebookSdk.getApplicationContext();
String applicationId = FacebookSdk.getApplicationId();
Validate.notNull(applicationContext, "context");
FetchedAppSettings queryAppSettings = FetchedAppSettingsManager.queryAppSettings(applicationId, false);
if (queryAppSettings != null && queryAppSettings.getAutomaticLoggingEnabled() && j > 0) {
AppEventsLogger newLogger = AppEventsLogger.newLogger(applicationContext);
Bundle bundle = new Bundle(1);
bundle.putCharSequence(Constants.AA_TIME_SPENT_SCREEN_PARAMETER_NAME, str);
newLogger.logEvent(Constants.AA_TIME_SPENT_EVENT_NAME, (double) j, bundle);
}
}
public static void logPurchaseInapp(String str, String str2) {
PurchaseLoggingParameters purchaseLoggingParameters;
if (isImplicitPurchaseLoggingEnabled() && (purchaseLoggingParameters = getPurchaseLoggingParameters(str, str2)) != null) {
internalAppEventsLogger.logPurchaseImplicitlyInternal(purchaseLoggingParameters.purchaseAmount, purchaseLoggingParameters.currency, purchaseLoggingParameters.param);
}
}
public static void logPurchaseSubs(SubscriptionType subscriptionType, String str, String str2) {
String str3;
if (isImplicitPurchaseLoggingEnabled()) {
FacebookSdk.getApplicationId();
switch (subscriptionType) {
case RESTORE:
str3 = "SubscriptionRestore";
break;
case CANCEL:
str3 = "SubscriptionCancel";
break;
case HEARTBEAT:
str3 = "SubscriptionHeartbeat";
break;
case EXPIRE:
str3 = "SubscriptionExpire";
break;
case NEW:
logPurchaseInapp(str, str2);
return;
default:
return;
}
PurchaseLoggingParameters purchaseLoggingParameters = getPurchaseLoggingParameters(str, str2);
if (purchaseLoggingParameters != null) {
internalAppEventsLogger.logEventImplicitly(str3, purchaseLoggingParameters.purchaseAmount, purchaseLoggingParameters.currency, purchaseLoggingParameters.param);
}
}
}
public static boolean isImplicitPurchaseLoggingEnabled() {
FetchedAppSettings appSettingsWithoutQuery = FetchedAppSettingsManager.getAppSettingsWithoutQuery(FacebookSdk.getApplicationId());
return appSettingsWithoutQuery != null && FacebookSdk.getAutoLogAppEventsEnabled() && appSettingsWithoutQuery.getIAPAutomaticLoggingEnabled();
}
@Nullable
private static PurchaseLoggingParameters getPurchaseLoggingParameters(String str, String str2) {
try {
JSONObject jSONObject = new JSONObject(str);
JSONObject jSONObject2 = new JSONObject(str2);
Bundle bundle = new Bundle(1);
bundle.putCharSequence(Constants.IAP_PRODUCT_ID, jSONObject.getString("productId"));
bundle.putCharSequence(Constants.IAP_PURCHASE_TIME, jSONObject.getString("purchaseTime"));
bundle.putCharSequence(Constants.IAP_PURCHASE_TOKEN, jSONObject.getString("purchaseToken"));
bundle.putCharSequence(Constants.IAP_PACKAGE_NAME, jSONObject.optString("packageName"));
bundle.putCharSequence(Constants.IAP_PRODUCT_TITLE, jSONObject2.optString("title"));
bundle.putCharSequence(Constants.IAP_PRODUCT_DESCRIPTION, jSONObject2.optString("description"));
String optString = jSONObject2.optString("type");
bundle.putCharSequence(Constants.IAP_PRODUCT_TYPE, optString);
if (optString.equals(BillingClient.SkuType.SUBS)) {
bundle.putCharSequence(Constants.IAP_SUBSCRIPTION_AUTORENEWING, Boolean.toString(jSONObject.optBoolean("autoRenewing", false)));
bundle.putCharSequence(Constants.IAP_SUBSCRIPTION_PERIOD, jSONObject2.optString("subscriptionPeriod"));
bundle.putCharSequence(Constants.IAP_FREE_TRIAL_PERIOD, jSONObject2.optString("freeTrialPeriod"));
String optString2 = jSONObject2.optString("introductoryPriceCycles");
if (!optString2.isEmpty()) {
bundle.putCharSequence(Constants.IAP_INTRO_PRICE_AMOUNT_MICROS, jSONObject2.optString("introductoryPriceAmountMicros"));
bundle.putCharSequence(Constants.IAP_INTRO_PRICE_CYCLES, optString2);
}
}
double d = (double) jSONObject2.getLong("price_amount_micros");
Double.isNaN(d);
return new PurchaseLoggingParameters(new BigDecimal(d / 1000000.0d), Currency.getInstance(jSONObject2.getString("price_currency_code")), bundle);
} catch (JSONException e) {
Log.e(TAG, "Error parsing in-app subscription data.", e);
return null;
}
}
/* access modifiers changed from: private */
public static class PurchaseLoggingParameters {
Currency currency;
Bundle param;
BigDecimal purchaseAmount;
PurchaseLoggingParameters(BigDecimal bigDecimal, Currency currency2, Bundle bundle) {
this.purchaseAmount = bigDecimal;
this.currency = currency2;
this.param = bundle;
}
}
}
|
Go | UTF-8 | 1,256 | 3.03125 | 3 | [] | no_license | package discrete
import (
"math"
"code.google.com/p/liblundis/lmath/util/cont"
)
func Max(values []float64) (max float64, index int) {
max = values[0]
index = 0
for i, v := range values {
if v > max {
max = v
index = i
}
}
return max, index
}
func Min(values []float64) (min float64, index int) {
min = values[0]
index = 0
for i, v := range values {
if v < min {
min = v
index = i
}
}
return min, index
}
func VectorAbsDiff(x, y []float64) []float64 {
z := make([]float64, len(x))
for i := range x {
z[i] = math.Abs(x[i] - y[i])
}
return z
}
func Values(f cont.Function, x []float64) []float64 {
y := make([]float64, len(x))
for i, v := range x {
y[i] = f(v)
}
return y
}
func FindMaxDiff(x, y []float64) (max float64, index int) {
diff := VectorAbsDiff(x, y)
return Max(diff)
}
func Minus(x, y []float64) []float64 {
z := make([]float64, len(x))
for i := range z {
z[i] = x[i] - y[i]
}
return z
}
func Plus(x, y []float64) []float64 {
z := make([]float64, len(x))
for i := range z {
z[i] = x[i] + y[i]
}
return z
} |
JavaScript | UTF-8 | 587 | 3.046875 | 3 | [] | no_license | export function sym(...arg) {
const arrArgs = arg;
function compareArrays(arr1, arr2) {
const arr1red = arr1.reduce(function(collect, current) {
if (!arr2.includes(current) && !collect.includes(current)) {
collect.push(current);
}
return collect;
}, []);
const arr2red = arr2.reduce(function(collect, current) {
if (!arr1.includes(current) && !collect.includes(current)) {
collect.push(current);
}
return collect;
}, []);
return arr1red.concat(arr2red);
}
return arrArgs.reduce(compareArrays).sort();
}
|
Python | UTF-8 | 186 | 3.171875 | 3 | [] | no_license | numbers = sorted(map(int, open("numbers.txt").read().split(",")))
for i in range(len(numbers)):
if int(numbers[i]) != i+1:
print("number missing: %d" % (i+1))
break
|
JavaScript | UTF-8 | 3,964 | 2.65625 | 3 | [] | no_license | define(['instructionrow', 'valorregister', 'mapper'], function(InstructionRow, ValOrRegister, Mapper) {
var InstructionRowEntry = function(parent, instructionset, registers) {
this.instructionset = instructionset;
this.parent = parent;
this.registers = registers;
};
InstructionRowEntry.prototype = {
initElement: function () {
this.element = document.createElement("tr");
this.parent.appendChild(this.element);
this.labelCell = this.element.appendChild(document.createElement("td"));
this.labelInput = document.createElement("input");
this.labelInput.className = "entry_cell";
this.labelInput.setAttribute('type', 'number');
this.labelCell.appendChild(this.labelInput);
this.instructionCell = this.element.appendChild(document.createElement("td"));
this.instructionInput = document.createElement("select");
this.instructionInput.className = "select_cell";
var emptyopt = document.createElement("option");
emptyopt.setAttribute('value', "");
emptyopt.innerHTML = "--";
this.instructionInput.appendChild(emptyopt);
for (var instruction_id in Mapper) {
var opt = document.createElement("option");
opt.setAttribute("value", instruction_id);
opt.innerHTML = Mapper[instruction_id];
this.instructionInput.appendChild(opt);
}
this.instructionCell.appendChild(this.instructionInput);
this.firstArgCell = this.element.appendChild(document.createElement("td"));
this.firstArgInput = document.createElement("input");
this.firstArgInput.className = "entry_cell";
this.firstArgInput.setAttribute('type', 'number');
this.firstArgCell.appendChild(this.firstArgInput);
this.firstArgInputCheck = document.createElement("input");
this.firstArgInputCheck.className = "is_register";
this.firstArgInputCheck.setAttribute('type', 'checkbox');
this.firstArgCell.appendChild(this.firstArgInputCheck);
this.secondArgCell = this.element.appendChild(document.createElement("td"));
this.secondArgInput = document.createElement("input");
this.secondArgInput.className = "entry_cell";
this.secondArgInput.setAttribute('type', 'number');
this.secondArgCell.appendChild(this.secondArgInput);
this.secondArgInputCheck = document.createElement("input");
this.firstArgInputCheck.className = "is_register";
this.secondArgInputCheck.setAttribute('type', 'checkbox');
this.secondArgCell.appendChild(this.secondArgInputCheck);
},
asInstructionRow: function() {
var instSelect = this.instructionCell.querySelector('.select_cell'),
instruction = instSelect.options[instSelect.selectedIndex];
if (!instruction.value && !this.labelCell.querySelector('input').value) {
return false;
}
return new InstructionRow(
this.instructionset,
this.labelCell.querySelector('.entry_cell').value,
instruction.value,
new ValOrRegister(this.firstArgCell.querySelector('.entry_cell').value,
this.firstArgCell.querySelectorAll('input[type="checkbox"]:checked').length > 0,
this.registers),
new ValOrRegister(this.secondArgCell.querySelector('.entry_cell').value,
this.secondArgCell.querySelectorAll('input[type="checkbox"]:checked').length > 0,
this.registers));
}
};
return InstructionRowEntry;
});
|
Java | UTF-8 | 24,312 | 2.09375 | 2 | [] | no_license | package com.lwm.guesssong.ui;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.lwm.guesssong.R;
import com.lwm.guesssong.customUi.MyGridView;
import com.lwm.guesssong.data.Const;
import com.lwm.guesssong.model.Song;
import com.lwm.guesssong.model.WordButton;
import com.lwm.guesssong.oberserIf.IAlertDialogButtonListener;
import com.lwm.guesssong.oberserIf.IWordButtonOb;
import com.lwm.guesssong.util.MyPlayer;
import com.lwm.guesssong.util.SLog;
import com.lwm.guesssong.util.Util;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity implements IWordButtonOb{
//定义当前类的标记
public static final String TAG="MainActivity";
//定义当前答案的状态
public static final int ANSWER_RIGHT=1;
public static final int ANSWER_WRONG=2;
public static final int ANSWER_LACK=3;
//定义显示对话框的id
public static final int ID_DELETE_WORD=1;
public static final int ID_TIP_ANSWER=2;
public static final int ID_COIN_LACK=3;
//定义动画
//转盘旋转
private Animation mPanDiscAm;
private LinearInterpolator mPanDiscAmLin;
//拨杆进
private Animation mLeverInAm;
private LinearInterpolator mLeverInAmLin;
//拨杆出
private Animation mLeverOutAm;
private LinearInterpolator mLeverOutAmLin;
//定义界面组件
//播放按钮
private ImageButton mPlayButton;
//转盘
private ImageView mPanDisc;
//拨杆
private ImageView mLever;
//判断用户是否在播放
private boolean mIsRunning=false;
//文字框
//数据源(已选,待选)
private ArrayList<WordButton> mSelectedWords;
private ArrayList<WordButton> mAllWords;
//组件
private MyGridView mGridView;
private LinearLayout mSelectedLl;
//定义当前歌曲,当前歌曲的索引
private Song mCurrentSong;
private int mSongIndex=-1;
//过关显示组件
private View mPassGame;
//定义闪烁标志
private boolean mSpark=false;
//定义当前的金币数
private int mCurrentCoins=Const.INIT_COINS;
//定义显示金币的控件
private TextView mViewCoins;
//定义删除 提示组件
private ImageButton mViewDeleteWord;
private ImageButton mViewTipAnswer;
//定义当前关及其索引(过关弹出页)
private int mCurrentPassIndex;
private TextView mCurrentPass;
//定义当前关的歌曲名称
private TextView mCurrentPassSongName;
//定义下一题按钮
private ImageButton mNextPassButton;
//定义当前关(主页面)
private TextView mCurrentMainPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//hide the title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//初始化文字框组件
mGridView=(MyGridView)findViewById(R.id.gridview);
mSelectedLl=(LinearLayout)findViewById(R.id.word_select_container);
//GridView注册此接口
mGridView.registerIWordButtonOb(this);
//读取数据
int[] data=Util.readData(this);
mSongIndex=data[Const.INDEX_CURRENT_PASS];
mCurrentCoins=data[Const.INDEX_CURRENT_COINS];
//初始化金币控件,添加初始金币
mViewCoins=(TextView)findViewById(R.id.txt_bar_coins);
mViewCoins.setText(mCurrentCoins + "");
//初始化当前关(有问题)
mCurrentMainPass=(TextView)findViewById(R.id.current_level);
mCurrentMainPass.setText((mSongIndex+2) + "");
//初始化按钮
mPlayButton=(ImageButton)findViewById(R.id.btn_play_start);
mPanDisc=(ImageView)findViewById(R.id.imageView1);
mLever=(ImageView)findViewById(R.id.imageView2);
//为按钮添加点击事件
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//播放动画
hanlerPlay();
}
});
//初始化动画,定义动画监听
mPanDiscAm= AnimationUtils.loadAnimation(this, R.anim.rotate);
mPanDiscAmLin=new LinearInterpolator();
mPanDiscAm.setInterpolator(mPanDiscAmLin);
mPanDiscAm.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//转盘结束后 拨杆返回
mLever.startAnimation(mLeverOutAm);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mLeverInAm=AnimationUtils.loadAnimation(this,R.anim.rotate_45);
mLeverInAmLin=new LinearInterpolator();
mLeverInAm.setInterpolator(mLeverInAmLin);
//完成后停止在此位置
mLeverInAm.setFillAfter(true);
mLeverInAm.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//唱片开始
mPanDisc.startAnimation(mPanDiscAm);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mLeverOutAm=AnimationUtils.loadAnimation(this,R.anim.rotate_d_45);
mLeverOutAmLin=new LinearInterpolator();
mLeverOutAm.setInterpolator(mLeverOutAmLin);
mLeverOutAm.setFillAfter(true);
mLeverOutAm.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//结束后设置可见.结束标志置为false
mIsRunning=false;
mPlayButton.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
//更新数据
initGameData();
//控制删除按钮
handleDeleteButton();
//控制提示按钮
handleTipButton();
}
//点击事件触发后,开启动画
private void hanlerPlay(){
//拨杆不为空时候
if(mLever!=null){
if(!mIsRunning) {
//动画开启后,默认正在运行
mIsRunning=true;
//拨杆旋转,唱片准备旋转
mLever.startAnimation(mLeverInAm);
//设置按钮不可见
mPlayButton.setVisibility(View.INVISIBLE);
//开始播放音乐
MyPlayer.playSong(MainActivity.this, mCurrentSong.getFileName());
}
}
}
//实现接口方法
@Override
public void onClickWordButton(WordButton wordButton) {
onClickAllWords(wordButton);
int status=checkAnswer();
if(status==ANSWER_RIGHT){
//显示过关逻辑(如果通关了,就显示通关页面)
if(isPassThisGame()){
//最后一关时候,自动重置数据
Util.saveData(MainActivity.this,-1,Const.INIT_COINS);
//激活另一个通关Activity,
Util.aliveActivity(MainActivity.this,AllPassActivity.class);
}else{
//显示下一关
passView();
}
}else if(status==ANSWER_WRONG){
//错误答案闪烁
sparkWrongWords();
}else{
//答案不完整时候,显示答案为白色
for(int i=0;i<mSelectedWords.size();i++){
mSelectedWords.get(i).mCurrentButton.setTextColor(Color.WHITE);
}
}
}
//过关时候执行逻辑
private void passView(){
//过关显示过关界面可见
mPassGame=(View)findViewById(R.id.pass_view);
mPassGame.setVisibility(View.VISIBLE);
//停止未完成的动画(转盘不在转动)
mPanDisc.clearAnimation();
//停止歌曲
MyPlayer.stopSong(MainActivity.this);
//显示过关音效(金币掉落)
MyPlayer.playTone(MainActivity.this,MyPlayer.INDEX_COIN_TONE);
//显示当前关的索引
mCurrentPassIndex=mSongIndex;
mCurrentPass=(TextView)findViewById(R.id.txt_current_stage_pass);
mCurrentPass.setText((mCurrentPassIndex+1)+"");
//显示歌曲名称
mCurrentPassSongName=(TextView)findViewById(R.id.txt_current_song_name_pass);
String[] tmp=Const.SONG_RES[mSongIndex];
mCurrentPassSongName.setText(tmp[Const.INDEX_SONGNAME] + "");
//点击下一题按钮
mNextPassButton=(ImageButton)findViewById(R.id.btn_next);
mNextPassButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//关闭此页面,重新初始化页面
mPassGame.setVisibility(View.INVISIBLE);
//重新定义关数
mCurrentMainPass.setText((mCurrentPassIndex+2)+"");
initGameData();
}
});
}
//判断是否通关
private boolean isPassThisGame(){
return mCurrentPassIndex==Const.SONG_RES.length-2;
}
//检查答案
private int checkAnswer(){
//如果有一个为空,则答案不完整
for(int i=0;i<mSelectedWords.size();i++){
if(mSelectedWords.get(i).mCurrentWord.equals("")){
return ANSWER_LACK;
}
}
//判断所选答案是否与正确答案相同
StringBuffer sb=new StringBuffer();
for(int i=0;i<mSelectedWords.size();i++){
sb.append(mSelectedWords.get(i).mCurrentWord);
}
if(String.valueOf(sb).equals(mCurrentSong.getSongName())){
return ANSWER_RIGHT;
}else{
return ANSWER_WRONG;
}
}
//答案错误时闪烁(确保运行在ui线程中)
private void sparkWrongWords(){
TimerTask task=new TimerTask(){
// boolean mSpark=true;
int mSparkTimes=-1;
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
mSparkTimes++;
if(mSparkTimes>6){
return;
}
if(!mSpark){
for(int i=0;i<mSelectedWords.size();i++){
mSelectedWords.get(i).mCurrentButton.setTextColor(Color.RED);
mSpark=true;
}
}else {
for(int i=0;i<mSelectedWords.size();i++){
mSelectedWords.get(i).mCurrentButton.setTextColor(Color.WHITE);
mSpark=false;
}
}
}
});
}
};
Timer timer=new Timer();
timer.schedule(task,1,300);
}
//点击待选按钮效果
private void onClickAllWords(WordButton wordButton){
for(int i=0;i<mSelectedWords.size();i++){
if(mSelectedWords.get(i).mCurrentWord.equals("")){
//得到选中按钮的值,并记住当前值的索引
mSelectedWords.get(i).mCurrentButton.setText(wordButton.mCurrentWord);
mSelectedWords.get(i).mIsVisiable=true;
mSelectedWords.get(i).mCurrentWord=wordButton.mCurrentWord;
mSelectedWords.get(i).mIndex=wordButton.mIndex;
mSelectedWords.get(i).mCurrentButton.setEnabled(true);
//记录日志信息(当前点击按钮的索引)
SLog.d(TAG,wordButton.mIndex+"");
//点击按钮的值不可见,并设置按钮不可点击
wordButton.mIsVisiable=false;
wordButton.mCurrentButton.setVisibility(View.INVISIBLE);
//可见性
SLog.d(TAG, wordButton.mIsVisiable + "");
break;
}
}
}
@Override
protected void onPause() {
//暂停时候动画暂停,歌曲也暂停
mPanDisc.clearAnimation();
MyPlayer.stopSong(MainActivity.this);
//保存数据(如果是最后一关,不执行此逻辑)
if(!isPassThisGame()){
Util.saveData(MainActivity.this,mSongIndex-1,mCurrentCoins);
}
super.onPause();
}
//点击已选择框的效果
private void clearSelected(WordButton wordButton){
//设置按钮可见
mAllWords.get(wordButton.mIndex).mIsVisiable=true;
mAllWords.get(wordButton.mIndex).mCurrentButton.setVisibility(View.VISIBLE);
//可见性
SLog.d(TAG, wordButton.mIsVisiable + "");
//当前点击的按钮设置文本值为空
wordButton.mCurrentButton.setText("");
wordButton.mCurrentWord="";
wordButton.mIsVisiable=false;
wordButton.mCurrentButton.setEnabled(false);
}
//初始化游戏数据
private void initGameData(){
//初始化已选择框
mSelectedWords=initSelectedWords();
LayoutParams params=new LayoutParams(60,60);
//移除原先存在的View
mSelectedLl.removeAllViews();
for(int i=0;i<mSelectedWords.size();i++){
mSelectedLl.addView(mSelectedWords
.get(i).mCurrentButton,params);
}
//获取数据,更新数据
mAllWords=initAllWords();
mGridView.update(mAllWords);
//初始化就要播放歌曲
hanlerPlay();
}
//初始化文字框数据
private ArrayList<WordButton> initAllWords(){
char words[]=getAllWords();
String[] strWords=new String[MyGridView.WORD_COUNTS];
for(int i=0;i<words.length;i++){
strWords[i]=String.valueOf(words[i]);
}
ArrayList<WordButton> data=new ArrayList<WordButton>();
for(int i=0;i< MyGridView.WORD_COUNTS;i++){
WordButton wB=new WordButton();
wB.mCurrentWord=strWords[i];
data.add(wB);
}
return data;
}
//初始化已选框数据
private ArrayList<WordButton> initSelectedWords(){
//初始化当前歌曲
mCurrentSong=getCurrentSong(++mSongIndex);
ArrayList<WordButton> data=new ArrayList<WordButton>();
for(int i=0;i<mCurrentSong.getSongNameSize();i++){
View view= Util.getView(MainActivity.this,R.layout.word_button);
final WordButton wB=new WordButton();
wB.mCurrentButton=(Button)view.findViewById(R.id.item_btn);
wB.mCurrentButton.setTextColor(Color.WHITE);
wB.mCurrentButton.setText("");
wB.mIsVisiable=false;
wB.mCurrentButton.setBackgroundResource(R.mipmap.game_wordblank);
wB.mCurrentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearSelected(wB);
}
});
data.add(wB);
}
return data;
}
//创建当前歌曲对象
private Song getCurrentSong(int songIndex){
//判断选中哪一个歌曲
Song song=new Song();
String mCurrentSongInfo[]=Const.SONG_RES[songIndex];
song.setFileName(mCurrentSongInfo[Const.INDEX_FILENAME]);
song.setSongName(mCurrentSongInfo[Const.INDEX_SONGNAME]);
return song;
}
//生成初始化的24个汉字
private char[] getAllWords(){
Random random=new Random();
char allWords[]=new char[MyGridView.WORD_COUNTS];
char songNameCharArray[]=mCurrentSong.getSongNameCharArray(mCurrentSong.getSongName());
//生成歌曲名称
for(int i=0;i<mCurrentSong.getSongNameSize();i++){
allWords[i]=songNameCharArray[i];
}
//生成混淆的其他汉字
for(int i=songNameCharArray.length;
i<MyGridView.WORD_COUNTS;i++){
allWords[i]=Util.genChineseWord();
}
//打乱24个汉字数组的分布
for (int i = MyGridView.WORD_COUNTS - 1; i >= 0; i--) {
int index = random.nextInt(i + 1);
char buf = allWords[index];
allWords[index] = allWords[i];
allWords[i] = buf;
}
return allWords;
}
//删除一个单词
private void handleDeleteButton() {
mViewDeleteWord=(ImageButton)findViewById(R.id.btn_delete_word);
mViewDeleteWord.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
showDialogBaseId(ID_DELETE_WORD);
}
});
}
//提示一个单词
private void handleTipButton(){
mViewTipAnswer=(ImageButton)findViewById(R.id.btn_tip_word);
mViewTipAnswer.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
showDialogBaseId(ID_TIP_ANSWER);
}
});
}
//判断金币是否可删除
private boolean isDeleteCoin(int count){
boolean flag;
if (0 > (mCurrentCoins -count )) {
flag=false;
return flag;
} else {
mCurrentCoins = mCurrentCoins - count;
flag=true;
}
return flag;
}
//删除一个单词
private void deleteWord(){
boolean flag=isDeleteCoin(30);
if(flag) {
mViewCoins.setText(mCurrentCoins+"");
WordButton wB=findDeleteWord();
wB.mIsVisiable=false;
wB.mCurrentButton.setVisibility(View.INVISIBLE);
}else{
//金币余额不足时候提示
showDialogBaseId(ID_COIN_LACK);
}
}
//判断是否可增加一个提示
private void addTipAnswer() {
boolean mIsVoidSelect=isVoidSelect();
ALL:
if(mIsVoidSelect) {
for (int i = 0; i < mSelectedWords.size(); i++) {
if (mSelectedWords.get(i).mCurrentWord.length() == 0) {
//判断金币数量是否足够
boolean flag = isDeleteCoin(90);
//金币余额不足时候提示
if(!flag){
showDialogBaseId(ID_COIN_LACK);
break ALL;
}
if (flag) {
WordButton wB = findAnswerWord(i);
//原文字框消失不可见
wB.mIsVisiable = false;
wB.mCurrentButton.setVisibility(View.INVISIBLE);
//显示待选框数据
mSelectedWords.get(i).mCurrentButton.setText(wB.mCurrentWord);
mSelectedWords.get(i).mIndex = wB.mIndex;
mSelectedWords.get(i).mIsVisiable = true;
mSelectedWords.get(i).mCurrentWord = wB.mCurrentWord;
//减少金币
mViewCoins.setText(mCurrentCoins+"");
//如果待选框数据已满,判断答案是否正确
if(!isVoidSelect()){
onTipAnswerComplete();
}
break ALL;
}
}
}
}
}
//判断当前选择框是否有空位
private boolean isVoidSelect(){
boolean flag=false;
for(int i=0;i<mSelectedWords.size();i++){
if(mSelectedWords.get(i).mCurrentWord.length()==0){
flag=true;
}
}
return flag;
}
//找出一个要删除的单词
private WordButton findDeleteWord(){
Random random = new Random();
while(true){
int randomNum = random.nextInt(MyGridView.WORD_COUNTS);
if(mAllWords.get(randomNum)
.mIsVisiable&&(findIsAnswerWord(randomNum)==null)){
return mAllWords.get(randomNum);
}
}
}
//判断当前的词是否是答案
private WordButton findIsAnswerWord(int index){
WordButton buf;
for(int i=0;i<mCurrentSong.getSongName().length();i++) {
if (mAllWords.get(index).mCurrentWord
.equals(mCurrentSong.getSongNameCharArray(mCurrentSong.getSongName())[i] + "")) {
buf = mAllWords.get(i);
return buf;
}
}
return null;
}
//根据待选框的位置在AllWords中找到一个答案
private WordButton findAnswerWord(int index){
String mCurrentWord=mCurrentSong.getSongNameCharArray(mCurrentSong.getSongName())[index]+"";
WordButton mFindWord=null;
for(int i=0;i<MyGridView.WORD_COUNTS;i++){
if(mAllWords.get(i).mIsVisiable&&mAllWords
.get(i).mCurrentWord.equals(mCurrentWord)){
mFindWord=mAllWords.get(i);
}
}
return mFindWord;
}
//提示单词填充待选框时候,判断正确与否
private void onTipAnswerComplete(){
int status=checkAnswer();
if(status==ANSWER_RIGHT){
//显示过关逻辑
//过关显示过关界面可见
mPassGame=(View)findViewById(R.id.pass_view);
mPassGame.setVisibility(View.VISIBLE);
}else if(status==ANSWER_WRONG){
//错误答案闪烁
sparkWrongWords();
}
}
//删除单词对话框
private IAlertDialogButtonListener mOnClickDeleteWordButton=new IAlertDialogButtonListener() {
@Override
public void onclick() {
//确定删除单词
deleteWord();
}
};
//提示答案对话框
private IAlertDialogButtonListener mOnClickTipAnswerButton=new IAlertDialogButtonListener() {
@Override
public void onclick() {
//确定增加提示
addTipAnswer();
}
};
//金币不足对话框
private IAlertDialogButtonListener mCoinsIsLack=new IAlertDialogButtonListener() {
@Override
public void onclick() {
//
}
};
//根据id显示对话框
private void showDialogBaseId(int id){
switch (id){
case ID_DELETE_WORD:
//点击删除按钮
Util.showDialog(MainActivity.this,
"确定花掉30个金币去掉一个错误答案?",mOnClickDeleteWordButton);
break;
case ID_TIP_ANSWER:
//点击提示按钮
Util.showDialog(MainActivity.this,
"确定花掉90个金币获得一个文字提示?",mOnClickTipAnswerButton);
break;
case ID_COIN_LACK:
//金币不足时
Util.showDialog(MainActivity.this,
"金币不足,去商店购买?",mCoinsIsLack);
break;
}
}
}
|
Go | UTF-8 | 5,122 | 2.609375 | 3 | [] | no_license | package nqubits
import (
"github.com/waman/qwave/system"
"github.com/waman/qwave/system/nqubits/nbasis"
"github.com/waman/qwave/system/nqubits/nket"
"github.com/waman/qwave/system/nqubits/nop"
"github.com/waman/qwave/system/qubit"
"github.com/waman/qwave/system/qubit/basis"
"github.com/waman/qwave/system/qubit/ket"
"github.com/waman/qwave/system/qubit/op"
"log"
"math"
"math/cmplx"
"math/rand"
"sync"
)
func NewDense(qbtCount int, cs []complex128, isNormalized bool) MultiQubitSystem {
if !isNormalized { system.Normalize(cs) }
var _cs []complex128
if dim := system.Dim(qbtCount); len(cs) != dim {
_cs = make([]complex128, dim)
copy(_cs, cs)
} else {
_cs = system.CreateCopy(cs)
}
var mu sync.Mutex
return &denseMultiQubitSystem{qbtCount, &mu, _cs}
}
type denseMultiQubitSystem struct {
qubitCount int
mu *sync.Mutex
cs []complex128
}
func (nqbts *denseMultiQubitSystem) QubitCount() int {
return nqbts.qubitCount
}
func (nqbts *denseMultiQubitSystem) Dim() int {
return len(nqbts.cs)
}
func (nqbts *denseMultiQubitSystem) nstate() nket.NState {
return nket.NewWith(nqbts.qubitCount, &mutableDenseMetricVector{nqbts.cs})
}
func (nqbts *denseMultiQubitSystem) Observe(b nbasis.NBasis) nket.NState {
if b.QubitCount() != nqbts.qubitCount {
log.Panicf("The number of qubits is not match: MultiQubitSystem %d, NBasis %d",
nqbts.qubitCount, b.QubitCount())
}
nqbts.mu.Lock()
defer nqbts.mu.Unlock()
r := rand.Float64()
p := 0.0
current := nqbts.nstate()
for i, n := 0, nqbts.Dim()-1; i < n; i++ {
s := b.At(i)
p += s.Probability(current)
if r < p {
nqbts.cs = s.Coefficients()
return s
}
}
s := b.At(nqbts.Dim()-1)
nqbts.cs = s.Coefficients()
return s
}
func (nqbts *denseMultiQubitSystem) ObserveInStandardBasis() nket.NState {
return nqbts.Observe(nbasis.Standard(nqbts.qubitCount))
}
func (nqbts *denseMultiQubitSystem) iterateQubit(i int, f func(j, k int)) {
mask := 1 << uint(nqbts.qubitCount-i-1)
for j, n := 0, nqbts.Dim(); j < n; j++ {
if j&mask == 0 {
f(j, j+mask)
}
}
}
func (nqbts *denseMultiQubitSystem) ObserveQubit(i int, b *basis.Basis) *ket.State {
nqbts.mu.Lock()
defer nqbts.mu.Unlock()
cs := nqbts.cs
s := b.First()
m := s.OuterProduct(s)
p := 0.0
nqbts.iterateQubit(i, func(j, k int){
x, y := m.Apply(cs[j], cs[k])
xAbs, yAbs := cmplx.Abs(x), cmplx.Abs(y)
p += xAbs*xAbs + yAbs*yAbs
})
var nf complex128 // normaization factor
if r := rand.Float64(); r < p {
nf = complex(1.0/math.Sqrt(p), 0)
} else {
s = b.Second()
m = s.OuterProduct(s)
nf = complex(1.0/math.Sqrt(1-p), 0)
}
nqbts.iterateQubit(i, func(j, k int){
x, y := m.Apply(cs[j], cs[k])
cs[j], cs[k] = x*nf, y*nf
})
return s
}
func (nqbts *denseMultiQubitSystem) ObserveQubitInStandardBasis(i int) *ket.State {
nqbts.mu.Lock()
defer nqbts.mu.Unlock()
cs := nqbts.cs
p := 0.0
nqbts.iterateQubit(i, func(j, k int) {
amp := cmplx.Abs(cs[j])
p += amp * amp
})
if r := rand.Float64(); r < p {
nf := complex(1.0/math.Sqrt(p), 0)
nqbts.iterateQubit(i, func(j, k int) {
cs[j] = cs[j] * nf
cs[k] = 0
})
return ket.Zero()
} else {
nf := complex(1.0/math.Sqrt(1-p), 0)
nqbts.iterateQubit(i, func(j, k int) {
cs[j] = 0
cs[k] = cs[k] * nf
})
return ket.One()
}
}
func (nqbts *denseMultiQubitSystem) ObserveQubitInHadamardBasis(i int) *ket.State {
nqbts.mu.Lock()
defer nqbts.mu.Unlock()
cs := nqbts.cs
p := 0.0
nqbts.iterateQubit(i, func(j, k int) {
amp := cmplx.Abs(cs[j] + cs[k])
p += amp * amp / 2.0
})
if r := rand.Float64(); r < p {
nf := complex(1.0/(math.Sqrt(p)*2.0), 0)
nqbts.iterateQubit(i, func(j, k int) {
x := (cs[j] + cs[k]) * nf
cs[j] = x
cs[k] = x
})
return ket.Plus()
} else {
nf := complex(1.0/(math.Sqrt(1-p)*2.0), 0)
nqbts.iterateQubit(i, func(j, k int) {
x := (cs[j] - cs[k]) * nf
cs[j] = x
cs[k] = -x
})
return ket.Minus()
}
}
func (nqbts *denseMultiQubitSystem) Qubit(i int) qubit.Qubit {
return &qubitImpl{nqbts, i}
}
func (nqbts *denseMultiQubitSystem) Apply(u nop.Matrix) {
nqbts.mu.Lock()
defer nqbts.mu.Unlock()
nqbts.cs = u.Apply(nqbts.cs)
}
func (nqbts *denseMultiQubitSystem) ApplyToQubit(i int, u op.Matrix2x2) {
nqbts.mu.Lock()
defer nqbts.mu.Unlock()
cs := nqbts.cs
nqbts.iterateQubit(i, func(j, k int) {
cs[j], cs[k] = u.Apply(cs[j], cs[k])
})
}
//***** mutableDenseMetricVector *****
type mutableDenseMetricVector struct {
cs []complex128
}
func (m *mutableDenseMetricVector) Dim() int {
return len(m.cs)
}
// Note: This method DO NOT copy the slice
func (m *mutableDenseMetricVector) Coefficients() []complex128 {
return m.cs
}
func (m *mutableDenseMetricVector) CoefficientMap() map[int]complex128 {
return system.SliceToMap(m.cs)
}
func (m *mutableDenseMetricVector) At(i int) complex128 {
return m.cs[i]
}
func (m *mutableDenseMetricVector) InnerProduct(y nket.MetricVector) complex128 {
return nket.InnerProduct(m.cs, y)
}
func (m *mutableDenseMetricVector) OuterProduct(y nket.MetricVector) nop.Matrix {
return nket.OuterProduct(m.cs, y)
}
|
C++ | UTF-8 | 2,623 | 2.609375 | 3 | [] | no_license | #include "Adafruit_Sensor.h"
#include "Adafruit_LSM9DS0.h"
#include "Adafruit_Simple_AHRS.h"
#include "debug.h"
#include <SC_PlugIn.h>
#include <thread>
// written with reference to the chapter "Writing Unit Generator Plug-ins" in The SuperCollider Book
// and also http://doc.sccode.org/Guides/WritingUGens.html accessed March 2, 2015
struct AHRS : public Unit {
static const int ROLL = 0;
static const int PITCH = 1;
static const int HEADING = 2;
int channel = ROLL;
};
// PLUGIN INTERFACE
extern "C" {
void AHRS_Ctor(AHRS *unit);
void AHRS_next_k(AHRS *unit, int numSamples);
}
static InterfaceTable *ft;
PluginLoad(AHRS)
{
debug("PluginLoad")
ft = inTable;
DefineSimpleUnit(AHRS);
}
// PLUGIN IMPLEMENTATION
class AHRS_Singleton {
public:
static AHRS_Singleton* get() {
if (AHRS_Singleton::instance == nullptr) {
AHRS_Singleton::instance = new AHRS_Singleton();
AHRS_Singleton::thread = new std::thread(AHRS_Singleton::thready);
}
return AHRS_Singleton::instance;
}
static void thready() {
while (AHRS_Singleton::running) {
AHRS_Singleton::get()->update();
std::this_thread::yield();
}
}
static bool running;
void update() {
ahrs->getOrientation(&orientation);
}
float read(int which) {
switch (which) {
case AHRS::ROLL:
return orientation.roll;
case AHRS::PITCH:
return orientation.pitch;
case AHRS::HEADING:
default:
return orientation.heading;
}
}
private:
static AHRS_Singleton* instance;
static std::thread* thread;
Adafruit_LSM9DS0 lsm;
sensors_vec_t orientation;
Adafruit_Simple_AHRS* ahrs;
AHRS_Singleton() {
debug("AHRS_Singleton ctor")
lsm.begin();
ahrs = new Adafruit_Simple_AHRS(&lsm.getAccel(), &lsm.getMag());
orientation.roll = 0;
orientation.pitch = 0;
orientation.heading = 0;
}
~AHRS_Singleton() {
delete ahrs;
}
};
AHRS_Singleton* AHRS_Singleton::instance = nullptr;
std::thread* AHRS_Singleton::thread = nullptr;
bool AHRS_Singleton::running = true;
void AHRS_Ctor(AHRS *unit) {
debug("AHRS_Ctor");
unit->channel = static_cast<int>(IN0(0));
SETCALC(AHRS_next_k);
AHRS_next_k(unit, 1);
}
void AHRS_next_k(AHRS *unit, int numSamples) {
debug("AHRS_next_k");
float* out = OUT(0);
// TODO: this should probably be done differently
float value = AHRS_Singleton::get()->read(unit->channel);
for (int i = 0; i < numSamples ; i++) {
out[i] = value;
}
}
|
C++ | UTF-8 | 9,126 | 3.46875 | 3 | [] | no_license | /*
File: main
Author: Joseph Camacho
Created on December 12, 2016
Purpose: Project 2
*/
//System Libraries
#include <iostream> //Input/Output objects
#include <cstdlib> //Random
#include <ctime> //Time
#include <string> //String
using namespace std; //Name-space used in the System Library
//User Libraries
//Global Constants
//Function prototypes
void start(char, int, int, int);
void movepool(char, int, int, int, int, int, int, int);
void enemy(string, int, int);
void bars(string, int, int, int);
void fight(string, int, int, int, int, int, int, int, int);
void fight2(string, int, int, int, int);
char cond(int , int , int , char, char);
//Execution Begins Here!
int main(int argc, char** argv) {
//Declaration of Variables
char player; //class
int LP, AP, EP, nmy; //life points, Attack points, Energy points, enemy health
int Move1, Move2, Move3, DAM; //move1, move2, move3, enemy damage
int attack, att; //activation
int efc; //effect
string name;
char y, z;
//Input values
cout<<"-T.B.C. simulator--"<<endl;
cout<<"-Turn Based Combat-"<<endl;
cout<<"-------------------"<<endl;
cout<<"select class"<<endl;
cout<<"f=fighter"<<endl;
cout<<"t=thief"<<endl;
cout<<"w=wizard"<<endl;
start(player, LP, AP, EP);
cout<<"-------------------"<<endl;
enemy(name, nmy, DAM);
cout<<"-------------------"<<endl;
bars(name, LP, EP, nmy);
cout<<"-------------------"<<endl;
while (1){
movepool(player, LP, AP, EP, efc, Move1, Move2, Move3);
cout<<"-------------------"<<endl;
fight(name, attack, LP, AP, EP, nmy, Move1, Move2, Move3);
cout<<"-------------------"<<endl;
fight2(name, att, DAM, LP, nmy);
cout<<"-------------------"<<endl;
bars(name, LP, EP, nmy);
cout<<"-------------------"<<endl;
cond(nmy, LP, EP, y, z);
if(cond(nmy, LP, EP, y, z)=='y'){
cout<<"You win"<<endl;
break;
}
else if (cond(nmy, LP, EP, y, z)=='z'){
cout<<"You lose"<<endl;
break;
}
}
//Exit Program
return 0;
}
char cond(int nmy, int LP, int EP, char y, char z){
if (nmy<=0)
return 'y';
else if (LP<=0)
return 'z';
else if (EP<=0)
return 'z';
return '/';
}
void bars(string name, int LP, int EP, int nmy){
cout<<"you "<<name<<endl;
cout<<"LP: "<<LP<<" LP: "<<nmy<<endl;
cout<<"EP: "<<EP<<endl;
cout<<endl;
}
void fight2(string name, int att, int DAM, int LP, int nmy){
cout<<"The "<<name<<" attacks"<<endl;
int x;
srand(static_cast<unsigned int>(time(0)));
x=(rand()%5)+1;
if (x==1){
att=DAM;
if(att>=LP){
LP=att-LP;
}
else {
LP=LP-att;
}
cout<<"The "<<name<<" attacked"<<endl;
cout<<att<<" damage dealt"<<endl;
}
else if (x==2){
att=DAM*2;
if(att>=LP){
LP=att-LP;
}
else {
LP=LP-att;
}
cout<<"The "<<name<<" used Maul"<<endl;
cout<<att<<" damage dealt"<<endl;
}
else if (x==3){
att=DAM*0;
cout<<"The "<<name<<" missed"<<endl;
}
else if (x==4){
att=(DAM*.5)+DAM;
nmy=att+nmy;
cout<<"The "<<name<<" healed itself"<<endl;
cout<<att<<" damage dealt"<<endl;
}
else if (x==5){
att=DAM*.5;
if(att>=LP){
LP=att-LP;
}
else {
LP=LP-att;
}
cout<<"The "<<name<<"'s attack grazed"<<endl;
cout<<att<<" damage dealt"<<endl;
}
}
void fight(string name, int attack, int LP, int AP, int EP, int nmy, int Move1, int Move2, int Move3){
cout<<"your move"<<endl;
cin>>attack;
if (attack==1){
EP=EP-2;
Move1;
cout<<"you attack for "<<Move1<<" points of damage"<<endl;
if(nmy>=Move1){
nmy=nmy-Move1;
cout<<"The "<<name<<" takes "<<nmy-Move1<<" points of damage"<<endl;
}
else {
nmy=Move1-nmy;
cout<<"The "<<name<<" takes "<<Move1-nmy<<" points of damage"<<endl;
}
}
else if (attack==2){
EP=EP-3;
Move2;
cout<<"you attack for "<<Move2<<" points of damage"<<endl;
if(nmy>=Move2){
nmy=nmy-Move2;
cout<<"The "<<name<<" takes "<<nmy-Move2<<" points of damage"<<endl;
}
else {
nmy=Move2-nmy;
cout<<"The "<<name<<" takes "<<Move2-nmy<<" points of damage"<<endl;
}
}
else if (attack==3){
EP=EP+2;
LP=Move3+LP;
cout<<"you heal "<<Move3<<" points of health for "<<Move3+LP<<endl;
}
else if (attack>=4){
cout<<"you attack for "<<AP<<" points of damage"<<endl;
if(nmy>=AP){
nmy=nmy-AP;
cout<<"The "<<name<<" takes "<<nmy-AP<<" points of damage"<<endl;
}
else{
nmy=AP-nmy;
cout<<"The "<<name<<" takes "<<AP-nmy<<" points of damage"<<endl;
}
}
}
void enemy(string name, int nmy, int DAM){
int b; //calculate enemy health
int c; //calc enemy damage
int d; //name
srand(static_cast<unsigned int>(time(0)));
b=(rand()%5)+1;
nmy=b*10;
string Mig1 ="young";
string Mig2 ="small";
string Mig3 ="common";
string Mig4 ="giant";
string Mig5 ="ancient";
string Might;
if (b==1){
Might=Mig1;
}
else if (b==2){
Might=Mig2;
}
else if (b==3){
Might=Mig3;
}
else if (b==4){
Might=Mig4;
}
else if (b==5){
Might=Mig5;
}
srand(static_cast<unsigned int>(time(0)));
c=(rand()%3)+1;
DAM=c;
string Pow1 ="lesser";
string Pow2 ="Terrible";
string Pow3 ="dangerous";
string Pow4 ="malevolent";
string Pow5 ="Demonic";
string Power;
if (c=1){
Power=Pow1;
}
else if (c==2){
Power=Pow2;
}
else if (c==3){
Power=Pow3;
}
else if (c==4){
Power=Pow4;
}
else if (c==5){
Power=Pow5;
}
srand(static_cast<unsigned int>(time(0)));
d=(rand()%5)+1;
string Mon1 ="Slime";
string Mon2 ="Goblin";
string Mon3 ="Monster";
string Mon4 ="Dragon";
string Mon5 ="Evil";
if (d==1){
name=Mon1;
}
else if (d==2){
name=Mon2;
}
else if (d==3){
name=Mon3;
}
else if (d==4){
name=Mon4;
}
else if (d==5){
name=Mon5;
}
cout<<"prepare to fight a "<<Power<<" "<<Might<<" "<<name<<endl;
cout<<"LP: "<<nmy<<endl;
cout<<"AP: "<<DAM<<endl;
}
void movepool(char player, int LP, int AP, int EP, int efc, int Move1, int Move2, int Move3){
int a;
srand(static_cast<unsigned int>(time(0)));
a=(rand()%3)+1;
if(player=='f'){
cout<<"1: Power attack"<<endl;
Move1=AP*1.5;
cout<<"2: Heavy Bash"<<endl;
Move2=AP*LP;
cout<<"3: 2nd Wind"<<endl;
Move3=EP;
}
else if(player=='t'){
cout<<"1: critical strike"<<endl;
if (a=1){
efc=1;
}
else if (a=2){
efc=.5;
}
else if (a=3){
efc=1.5;
}
Move1=AP*efc;
cout<<"2: gamble"<<endl;
if (a>1){
Move2=AP*2;
}
else Move2=AP*0;
cout<<"3: Steal"<<endl;
if (a=1){
Move3=4;
}
else if (a=2){
Move3=-3;
}
else if (a=3){
Move3=0;
}
}
else if(player=='w'){
cout<<"1: Fireball"<<endl;
Move1=(AP*1.5);
cout<<"2: Shock"<<endl;
Move2=(AP*EP);
cout<<"3: Heal"<<endl;
Move3=3;
}
cout<<"4: Basic attack"<<endl;
}
void start(char player, int LP, int AP, int EP){
cin>>player;
switch(player){
case 'f':
case 'F':player='f';break;
case 't':
case 'T':player='t';break;
case 'w':
case 'W':player='w';break;
default: player='f';break;
}
//base stats = 20
if(player=='f'){
cout<<"you're the fighter"<<endl;
LP=10;
AP=5;
EP=5;
}
else if(player=='t'){
cout<<"you're the thief"<<endl;
LP=7;
AP=7;
EP=6;
}
else if(player=='w'){
cout<<"you're the wizard"<<endl;
LP=5;
AP=9;
EP=6;
}
}
|
C# | UTF-8 | 1,436 | 2.765625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
namespace Carnival.DBL
{
[Serializable]
public class ReadWriteFile
{
public static List<T> Read<T>()
{
List<T> list = new List<T>();
var type = list.GetType().GetTypeInfo().GenericTypeArguments[0];
string[] str = type.ToString().Split('.');
FileStream fs = new FileStream(@"C:\Users\Anshul\Downloads\Compressed\CarnivalCinemas\files\" + str[2] + ".txt", FileMode.Open);
XmlSerializer xmlserializerobj1 = new XmlSerializer(typeof(List<T>));
if (fs.Length > 1)
{
list = (List<T>)xmlserializerobj1.Deserialize(fs);
}
fs.Close();
return list;
}
public static void Write<T>(List<T> list)
{
var type = list.GetType().GetTypeInfo().GenericTypeArguments[0];
string[] str = type.ToString().Split('.');
FileStream fs1 = new FileStream(@"C:\Users\Anshul\Downloads\Compressed\CarnivalCinemas\files\" + str[2] + ".txt", FileMode.Create);
XmlSerializer xmlserializerobj = new XmlSerializer(typeof(List<T>));
xmlserializerobj.Serialize(fs1, list);
fs1.Close();
}
}
}
|
Java | UTF-8 | 441 | 1.914063 | 2 | [] | no_license | package vladyslav.shuhai.psyhology.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import vladyslav.shuhai.psyhology.entity.Admin;
import vladyslav.shuhai.psyhology.entity.User;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User,Long> {
Optional<User> findByEmail(String email);
boolean existsByEmail(String email);
}
|
Markdown | UTF-8 | 2,770 | 4.0625 | 4 | [
"Apache-2.0"
] | permissive | # 3.1.1. Numbers
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:
>>>
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5.0*6) / 4
5.0
>>> 8 / 5.0
1.6
The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. We will see more about numeric types later in the tutorial.
The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are. The remainder can be calculated with the % operator:
>>>
>>> 17 / 3 # int / int -> int
5
>>> 17 / 3.0 # int / float -> float
5.666666666666667
>>> 17 // 3.0 # explicit floor division discards the fractional part
5.0
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
With Python, it is possible to use the ** operator to calculate powers [1]:
>>>
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
>>>
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>>
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
>>>
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>>
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.
In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j). |
C# | UTF-8 | 612 | 2.546875 | 3 | [] | no_license | using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Transform player;
public Text scoreText;
public double answer;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (!isGrounded)
{
answer = answer + .01;
}
scoreText.text = answer.ToString("0");
}
}
|
Rust | UTF-8 | 10,146 | 2.828125 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ///Description, creation and opening of the shared memory structure used
///to communicate between the server and the app to profile. Note that
///I should have used MaybeUninit everywhere here, but I got really lazy...
use std::sync::atomic::{AtomicBool, Ordering, spin_loop_hint};
use std::thread::yield_now;
use std::path::PathBuf;
use std::ops::Deref;
use std::ops::DerefMut;
use shared_memory::{Shmem, ShmemConf, ShmemError};
#[cfg(feature = "server-mode")]
use serde::{Serialize, Deserialize};
pub const MAGIC: u32 = 0x1DC45EF1;
pub const PROTOCOL_VERSION: u32 = 0x00_01_0004; //Major_Minor_Patch
pub const NUM_ENTRIES: usize = 256;
pub const LOG_DATA_SIZE: usize = 8192;
pub const SHARED_STRING_MAX_SIZE: usize = 128;
pub type Time = f64; //Low precision time (seconds since program beginning)
pub type Duration = u64; //High precision time difference (nanoseconds)
pub type Color = u32; //24 bits, 0x00RRGGBB
#[derive(Default)]
struct SpinLock(AtomicBool);
impl SpinLock {
#[inline]
fn lock(&self) {
let mut i = 0;
while self.0.swap(true, Ordering::Acquire) {
match i {
0..=3 => {},
4..=15 => spin_loop_hint(),
_ => yield_now()
}
i += 1;
}
}
#[inline]
fn unlock(&self) {
self.0.store(false, Ordering::Release);
}
}
pub trait ShouldStopQuery {
fn should_stop_query(&self, t: f64, query_max: f64) -> bool;
}
#[derive(Copy, Clone)]
pub struct SharedString {
key: usize, //A number that uniquely identifies this zone's name string (typically, the string's address)
size: u8, //The length of this string, max 128 bytes
has_contents: bool, //False if this string has already been sent
contents: [u8; SHARED_STRING_MAX_SIZE] //If has_contents is true, the string's contents
}
impl SharedString {
pub fn set(&mut self, string: &'static str, copy_contents: bool) {
let raw = string.as_bytes();
assert!(raw.len() <= SHARED_STRING_MAX_SIZE, "SharedStrings are limited to {} bytes", SHARED_STRING_MAX_SIZE);
self.key = string.as_ptr() as usize;
if copy_contents {
self.size = raw.len() as u8;
unsafe {
std::ptr::copy_nonoverlapping(raw.as_ptr(), self.contents.as_mut_ptr(), raw.len());
}
self.has_contents = true;
} else {
self.has_contents = false;
}
}
pub fn set_special(&mut self, key: usize, contents: Option<(*const u8, usize)>) {
self.key = key;
if let Some((raw, sz)) = contents {
assert!(sz <= SHARED_STRING_MAX_SIZE, "SharedStrings are limited to {} bytes", SHARED_STRING_MAX_SIZE);
self.size = sz as u8;
unsafe {
std::ptr::copy_nonoverlapping(raw, self.contents.as_mut_ptr(), sz);
}
self.has_contents = true;
} else {
self.has_contents = false;
}
}
#[inline]
pub fn get_key(&self) -> usize {
self.key
}
#[inline]
pub fn make_str(&self) -> Option<&str> {
if self.has_contents {
Some(unsafe { std::str::from_utf8_unchecked(&self.contents[0..self.size as usize]) })
} else {
None
}
}
#[inline]
pub fn has_contents(&self) -> bool {
self.has_contents
}
}
#[derive(Copy, Clone)]
#[cfg_attr(feature = "server-mode", derive(Serialize, Deserialize))]
pub struct FrameData {
pub number: u64, //Frame number
pub end: Time, //Time when the frame ended
pub duration: Duration //Total frame time. start = end - duration if you convert the units first ;)
}
impl ShouldStopQuery for FrameData {
fn should_stop_query(&self, t: f64, query_max: f64) -> bool {
t - (self.duration as f64) * 1e-9 > query_max
}
}
#[derive(Copy, Clone)]
pub struct ZoneData {
pub uid: usize, //A number that uniquely identifies the zone
pub color: Color, //The color of the zone
pub end: Time, //Time when the zone ended
pub duration: Duration, //The execution time. start = end - duration if you convert the units first ;)
pub depth: u32, //Call stack depth
pub name: SharedString, //The name of the zone
pub thread: SharedString //Thread thread ID
}
#[derive(Copy, Clone)]
pub struct PlotData {
pub time: Time, //Time (X axis)
pub color: Color, //Color of the plot
pub value: f64, //Value to plot (Y axis)
pub name: SharedString //Plot name, which is also used as unique identifier
}
#[derive(Copy, Clone)]
pub struct HeapData {
pub time: Time, //Time at which the (de)allocation happened
pub addr: usize, //Address of the (de)allocated memory
pub size: usize, //Size of the (de)allocated memory
pub is_free: bool //True if the memory was deallocated, false otherwise
}
#[repr(packed)]
#[derive(Copy, Clone)]
pub struct LogEntryHeader {
pub time: Time, //Time at which the message was logged
pub color: Color, //Color of the message
pub length: usize //Amount of bytes contained in the string
}
pub struct Payload<T: Sized + Copy> {
lock: SpinLock, //A simple spin lock based on an AtomicBool
size: usize, //How many valid entries are available in `data`
data: [T; NUM_ENTRIES]
}
pub struct SharedMemoryData {
//Compatibility fields
pub magic: u32,
pub protocol_version: u32,
pub size_of_usize: u32,
//Useful data
pub frame_data: Payload<FrameData>,
pub zone_data: Payload<ZoneData>,
pub heap_data: Payload<HeapData>,
pub plot_data: Payload<PlotData>,
//Log data; different as it can contain Strings of variable size
log_data_lock: SpinLock, //A simple spin lock based on an AtomicBool
pub log_data_count: u32, //How many valid log messages are available in `log_data`
pub log_data: [u8; LOG_DATA_SIZE] //Array of LogEntryHeader followed by `header.length` bytes of log message
}
pub trait WriteInto<T> {
fn write_into(&self, target: &mut T);
}
impl<T: Copy> WriteInto<T> for T {
fn write_into(&self, target: &mut T) {
*target = *self;
}
}
impl<T: Sized + Copy> Payload<T> {
unsafe fn init(&mut self) {
self.lock.unlock(); //Hack to init
self.size = 0;
}
pub fn push<U: WriteInto<T>>(&mut self, entry: &U) -> bool {
let ret;
self.lock.lock();
if self.size < NUM_ENTRIES {
entry.write_into(&mut self.data[self.size]);
ret = true;
} else {
ret = false;
}
self.size += 1;
self.lock.unlock();
ret
}
pub unsafe fn retrieve_unchecked(&mut self, dst: *mut T) -> (usize, usize) {
self.lock.lock();
let (retrieved, lost) = if self.size <= NUM_ENTRIES {
(self.size, 0)
} else {
(NUM_ENTRIES, self.size - NUM_ENTRIES)
};
std::ptr::copy_nonoverlapping(self.data.as_ptr(), dst, retrieved);
self.size = 0;
self.lock.unlock();
(retrieved, lost)
}
pub fn retrieve(&mut self, dst: &mut [T]) -> (usize, usize) {
assert!(dst.len() >= NUM_ENTRIES, "destination slice has an unsufficient size");
unsafe {
self.retrieve_unchecked(dst.as_mut_ptr())
}
}
}
impl SharedMemoryData {
unsafe fn init(&mut self) {
self.magic = MAGIC;
self.protocol_version = PROTOCOL_VERSION;
self.size_of_usize = std::mem::size_of::<usize>() as u32;
self.frame_data.init();
self.zone_data.init();
self.heap_data.init();
self.plot_data.init();
self.log_data_lock.unlock(); //Init hack
self.log_data_count = 0;
}
}
pub struct SharedMemory {
data: *mut SharedMemoryData,
handle: Shmem
}
unsafe impl Send for SharedMemory {}
#[derive(Debug)]
pub enum SharedMemoryOpenError {
ShmemError(ShmemError),
BadMagic,
ProtocolMismatch,
PlatformMismatch
}
impl SharedMemory {
pub fn get_path() -> PathBuf {
let mut ret = super::get_data_dir();
ret.push("shmem");
ret
}
///Creates and maps the shared memory
///
///Note that the directory provided by `temporal_lens::get_data_dir()`
///must be created prior to calling this function, otherwise it will
///just fail.
pub fn create() -> Result<SharedMemory, ShmemError> {
let handle = ShmemConf::new()
.flink(Self::get_path().as_path())
.size(std::mem::size_of::<SharedMemoryData>())
.create()?;
let data = handle.as_ptr() as *mut SharedMemoryData;
unsafe {
(*data).init();
}
Ok(SharedMemory { data, handle })
}
pub fn open() -> Result<SharedMemory, SharedMemoryOpenError> {
let handle = ShmemConf::new()
.flink(Self::get_path().as_path())
.open().map_err(SharedMemoryOpenError::ShmemError)?;
let data = handle.as_ptr() as *mut SharedMemoryData;
let data_ref = unsafe { &mut *data };
if data_ref.magic != MAGIC {
Err(SharedMemoryOpenError::BadMagic)
} else if data_ref.protocol_version != PROTOCOL_VERSION {
Err(SharedMemoryOpenError::ProtocolMismatch)
} else if data_ref.size_of_usize != std::mem::size_of::<usize>() as u32 {
//Might happen if the lib was compiled for x86 and the server was compiled for x86_64
Err(SharedMemoryOpenError::PlatformMismatch)
} else {
Ok(SharedMemory { data, handle })
}
}
}
impl Deref for SharedMemory {
type Target = SharedMemoryData;
fn deref(&self) -> &SharedMemoryData {
unsafe {
&*self.data
}
}
}
impl DerefMut for SharedMemory {
fn deref_mut(&mut self) -> &mut SharedMemoryData {
unsafe {
&mut *self.data
}
}
}
|
PHP | UTF-8 | 1,796 | 3.046875 | 3 | [] | no_license | <?php
session_start();
//session_destroy();
mysql_connect('localhost', 'dig4530c_group04', 'dig4530cgroup04') or die (mysql_error());
mysql_select_db('dig4530c_group04') or die (mysql_error());
//If "ADD" is clicked
if(isset($_GET['add'])){
//Must prevent the user from adding more than we have in stock.
//To prevent sql injection make sure the value is number of type INT
$quantity = mysql_query('SELECT id, Stock FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while($quantity_row = mysql_fetch_assoc($quantity)){
//Loop through to get the quantity variable (Stock in products table)
//If the quantity in the database != to quantity already in the shopping cart
//we can add to cart
if($quantity_row['Stock']!=$_SESSION['cart_'.(int)$_GET['add']]){
//Use the id number we passed through our get variable, we concatinate it
//onto our cart session variable. Click add, id of product is 1, then cart_1
//session variable is made. Then increment for each added product.
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
}
}
//The function to grab and show all products (works fast for catalog.php)
function showProducts () {
$get = mysql_query('SELECT * FROM products WHERE Stock > 0 ');
if(mysql_num_rows($get)==0) {
echo "We currently have no products in stock. Sorry for the inconvenience.";
}
else{
//fetch an associative array for all products then display data in a paragraph
while($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.'<img src="'.$get_row['Product Image'].'" alt="Product Image" width="100" /> '.'<br />'.$get_row['Product Name'].'<br />'.$get_row['Description'].'<br /> $'.number_format($get_row['Price'], 2).'<br /><a href="cart2.php?add='.$get_row['id'].'">Add</a></p>';
}
}
}
?> |
C++ | UTF-8 | 2,998 | 3.625 | 4 | [] | no_license | #include <iostream>
using namespace std;
const char KEY_SAVE = 's';
const char KEY_PAY = 'p';
const char KEY_LIST = 'd';
const char KEY_QUIT = 'q';
class eCash {
private:
int Money;
string ID;
public:
eCash();
void login(string);
void logout();
void store(int m);
void pay(int m);
void display();
};
eCash::eCash() {
Money = 0;
}
void eCash::login(string id) {
ID = id;
FILE *file = fopen(ID.c_str(), "r");
if (file != NULL) {
fscanf(file, "%d", &Money);
cout << "eCash: 帳號開啟完成!" << endl << endl;
} else {
cout << "eCash: 帳號不存在, 第一次使用!" << endl << endl;
}
fclose(file);
}
void eCash::logout() {
FILE *file;
file = fopen(ID.c_str(), "w");
fprintf(file, "%d", Money);
fclose(file);
cout << "eCash: 帳號已登出, 已存檔!" << endl;
}
void eCash::store(int m) {
if (m < 0) {
cout << "eCash: 請輸入大於0的金額" << endl;
return;
}
cout << "eCash: 您存了" << m << "元" << endl;
Money = Money + m;
}
void eCash::pay(int m) {
if (m > Money) {
cout << "eCash: 您的錢不夠" << endl;
return;
}
if (m < 0) {
cout << "eCash: 請輸入大於0的金額" << endl;
return;
}
cout << "eCash: 您花了 " << m << "元" << endl;
Money -= m;
}
void eCash::display() {
cout << "eCash: 您尚有" << Money << "元" << endl;
}
char getInputCommand(string);
void handleeCashByCommand(eCash *, char);
int main() {
char command;
string ID;
eCash *eCasher = new eCash();
cout << "=== 歡迎使用eCash ===" << endl;
cout << "eCash: 請輸入您的帳號: ";
cin >> ID;
eCasher->login(ID);
do {
command = getInputCommand(ID);
handleeCashByCommand(eCasher, command);
} while (command != KEY_QUIT);
return 0;
}
char getInputCommand(string id) {
char command;
cout << id << "您好,請選擇項目:" << endl
<< "s: 儲值" << endl
<< "p: 消費" << endl
<< "d: 查詢餘額" << endl
<< "q: 離開" << endl
<< ">";
cin >> command;
return command;
}
void handleeCashByCommand(eCash *eCasher, char command) {
int money;
string anyKey;
switch (command) {
case KEY_SAVE: {
cout << "請輸入儲存金額:" << endl;
cin >> money;
eCasher->store(money);
break;
}
case KEY_PAY: {
cout << "請輸入消費金額:" << endl;
cin >> money;
eCasher->pay(money);
break;
}
case KEY_LIST: {
eCasher->display();
break;
}
case KEY_QUIT: {
eCasher->logout();
cout << "謝謝,ByeBye!" << endl;
break;
}
default: {
break;
}
}
system("pause");
system("cls");
}
|
Python | UTF-8 | 2,419 | 3.40625 | 3 | [
"Unlicense"
] | permissive | # -*- coding: utf-8 -*-
"""
Package: venn
Module: draw
This package provides functions for computing all sections of Venn diagrams.
Functionality for drawing the diagrams in SVG format is also provided. Input
can be sets or lists.
The length of the input, i.e., the number of individual sets/lists is arbitrary.
However, diagrmas can only be drawn up to length 5 - above that it gets too
confusing anyway.
Created on Mon Jun 15 15:34:04 2015
@author: kp14
"""
import sys
from jinja2 import Environment, PackageLoader
from . import compute
def draw(data, labels=None):
'''Draws Venn diagrams for data sets/lists.
At maximum, five sets/lists will be accepted. If not labels are provided,
uppercase letters will be used.
Args:
data (list): List of sets/lists.
labels (list): List of labels.
Returns:
SVG: Rendered Venn diagram.
'''
data_length = len(data)
if data_length > 5:
sys.exit('Too many sets/lists in data. Maximum is five.')
lbls = _create_label_dict(labels, data_length)
for key, val in compute.compute_sections(data, mode='length'):
key_string = _numerical_iterable2string(key)
lbls[key_string] = str(val)
env = Environment(loader=PackageLoader('venndy', 'templates'))
template = env.get_template('{}_set.svg'.format(str(data_length)))
return template.render(lbls)
def _create_label_dict(labels, data_length):
'''Create key-value pairs for filling in the SVG template on rendering.
Args:
labels (list): Lables for the datasets.
data_length (int): Number of data sets.
Returns:
dict: with labels
'''
default = 'ABCDE'
label_dict = {'A':None,
'B': None,
'C': None,
'D': None,
'E': None}
if labels:
if not len(labels) == data_length:
sys.exit('Incorrect number of labels for data set.')
else:
for k, v in zip(default, labels):
label_dict[k] = str(v)
else:
for lbl in default:
label_dict[lbl] = lbl
return label_dict
def _numerical_iterable2string(iterable):
'''Translate sequences like (0,1,0,0,1) to OIOOI.
Args:
iterable: iterable with sequence consisting of 0's and 1's
Returns:
str
'''
return ''.join(['I' if x else 'O' for x in iterable])
|
Python | UTF-8 | 300 | 2.953125 | 3 | [] | no_license | import random
import sys
number_of_input_entries = int(sys.argv[1])
max_number = int(sys.argv[2])
file_name = sys.argv[3]
inputFile = open(file_name, 'w')
for i in range(number_of_input_entries):
inputFile.write(str(random.randint(0, max_number))+"\n")
inputFile.close()
|
Java | UTF-8 | 9,048 | 2.953125 | 3 | [] | no_license | package controller;
import java.awt.EventQueue;
import java.util.EnumMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import marker.BreadCrumbs;
import marker.ForwardGeodesic;
import marker.Marker;
import util.Vector;
import development.Development;
public abstract class UserController implements Runnable {
/*********************************************************************************
* Timing Constants
*
* These constants define certain "timing constants" (in nanoseconds) that
* specify how often certain actions can be created. For example, if the user
* holds down the up arrow key for 2 seconds, the KEY_REPEAT_RATE variable
* explains how many "Forward" actions those 2 seconds translate to.
*********************************************************************************/
protected static final long KEY_REPEAT_DELAY = 1;//1;
protected static final long KEY_REPEAT_RATE = 90;//90
protected static long SLEEP_TIME = 10;
protected final int MAX_REPEAT_RATE = 100; // Hz
public boolean isPaused = false;
/*********************************************************************************
* This enumeration defines all of the different kinds of user input that we
* know how to process.
*********************************************************************************/
public static enum Action {
Right, Left, Forward, Back, A_Button, B_Button, start, L, R
}
/*********************************************************************************
* Data Structures
*
* We use actions ordered by the actionQueue to make changes to the model,
* through the reference "development."
*
* The "keyRepeatTimer" variable and "repeatingTasks" map are used to process
* certain repeating keystrokes (like holding down the up arrow) into a
* collection of discrete actions.
*********************************************************************************/
private Development development;
protected Marker source;
protected BlockingQueue<Action> actionQueue;
private BreadCrumbs crumbs;
private ForwardGeodesic geodesic;
protected Timer keyRepeatTimer;
private Map<Action, TimerTask> repeatingTasks;
/*********************************************************************************
* UserController
*
* This constructor builds a new UserController to control the input
* Development. From this development, we construct the data structures we use
* internally to process actions.
**********************************************************************************/
public UserController(Development dev, BreadCrumbs bc, ForwardGeodesic geo) {
development = dev;
actionQueue = new LinkedBlockingQueue<Action>();
geodesic = geo;
repeatingTasks = new EnumMap<Action, TimerTask>(Action.class);
keyRepeatTimer = new Timer("Button Repeat Timer");
crumbs = bc;
}
public UserController(){
development = null;
geodesic = null;
actionQueue = new LinkedBlockingQueue<Action>();
repeatingTasks = new EnumMap<Action, TimerTask>(Action.class);
keyRepeatTimer = new Timer("Button Repeat Timer");
}
/*********************************************************************************
* isRepeating
*
* This convenience method checks whether the input action is currently being
* monitored for repeating.
*********************************************************************************/
protected synchronized boolean isRepeating(Action m) {
return repeatingTasks.get(m) != null;
}
/*********************************************************************************
* startRepeating
*
* Given an input Action, this method is responsible for configuring our data
* structures to log repeating input from the keyboard. This means setting a
* timer to keep track of how long the input action has been taking place, and
* placing the corresponding events in the "actionQueue" for processing.
*********************************************************************************/
protected synchronized void startRepeatingAction(Action action) {
assert EventQueue.isDispatchThread();
if (isRepeating(action))
return;
long delay = KEY_REPEAT_DELAY;
int rate = (int) KEY_REPEAT_RATE;
if (rate >= MAX_REPEAT_RATE) {
rate = MAX_REPEAT_RATE;
}
long period = (long) (1000.0 / rate);
final Action repeatAction = action;
TimerTask tt = new TimerTask() {
public void run() {
switch (repeatAction) {
case Forward:
actionQueue.add(Action.Forward);
break;
case Back:
actionQueue.add(Action.Back);
break;
case Left:
actionQueue.add(Action.Left);
break;
case Right:
actionQueue.add(Action.Right);
break;
case A_Button:
actionQueue.add(Action.A_Button);
break;
case B_Button:
actionQueue.add(Action.B_Button);
break;
case start:
actionQueue.add(Action.start);
break;
case L:
actionQueue.add(Action.L);
}
// Attempt to make it more responsive to key-releases.
// Even if there are multiple this-tasks piled up (due to
// "scheduleAtFixedRate") we don't want this thread to take
// precedence over AWT thread.
Thread.yield();
}
};
repeatingTasks.put(action, tt);
keyRepeatTimer.scheduleAtFixedRate(tt, delay, period);
}
/*********************************************************************************
* stopRepeating
*
* As its name suggests, this method is called when we need to adjust our data
* structures (timers, etc.) to signal that a particular repeating action (a
* user holding down a key) has stopped.
*********************************************************************************/
protected synchronized void stopRepeatingAction(Action m) {
if (!isRepeating(m))
return;
repeatingTasks.get(m).cancel();
repeatingTasks.put(m, null);
}
/*********************************************************************************
* runNextAction
*
* Code that uses KeyboardController call this method in order to make a
* single "atomic" update to the model, based upon some user input. If there
* are user input actions sitting in the queue, this method takes the first
* one, processes it, and returns true (to indicate an update occurred). If no
* change takes place (due to lack of actions) then the method returns false.
*********************************************************************************/
public boolean runNextAction() {
if (actionQueue.isEmpty())
return false;
Action aa = actionQueue.poll();
switch (aa) {
case Forward:
if(development == null){
Vector dx = source.getPosition().getDirectionForward();
dx.normalize();
dx.scale(.01);
source.getPosition().move(dx);
}
else
development.translateSourcePoint(0.01, 0);
break;
case Back:
if(development == null){
Vector forward = source.getPosition().getDirectionForward();
forward.normalize();
Vector dx = new Vector(forward);
dx.scale(-.01);
source.getPosition().move(dx);
}
else
development.translateSourcePoint(-0.01, 0);
break;
case Left:
if(development == null){
source.getPosition().rotateOrientation(-.05);
}
else
development.rotate(-0.05);
break;
case Right:
if(development == null){
source.getPosition().rotateOrientation(.05);
}
else
development.rotate(0.05);
break;
case start:
isPaused = true;
break;
case A_Button:
if(crumbs != null )
crumbs.addMarker( development.getSource() );
break;
case B_Button:
if( geodesic != null )
geodesic.generateGeodesic( development.getSource() );
break;
}
return true;
}
/*********************************************************************************
* getNextAction
*
* Allows any class with a UserController object to get the next action in the
* queue. Allows the controller to be used for input in any setting (navigating
* menus for example) not only in running the development simulation.
*********************************************************************************/
public Action getNextAction(){
Action aa = actionQueue.poll();
return aa;
}
public Action seeNextAction(){
Action aa = actionQueue.peek();
return aa;
}
public void resetPausedFlag(){
isPaused = false;
}
public boolean isPaused(){
return isPaused;
}
public void clear() {
this.actionQueue.clear();
}
}
|
C++ | UTF-8 | 3,144 | 2.53125 | 3 | [] | no_license | #ifndef DATAEXTRACTOR_H
#define DATAEXTRACTOR_H
#include <QWidget>
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QWebPage>
////////////////////////////////////////////////////////////
// Class representing extractor which extracts data from
// HKL route services (www.omatlahdot.fi & www.reittiopas.fi)
//
// Purpose of this class is to populate and create new route
// objects from data. It seems that we need to do some kind
// of callback thing to extract data from HTTP response.
//
namespace bacra{
class DataExtractor : public QObject
{
Q_OBJECT
public:
DataExtractor(QObject *parent = 0);
~DataExtractor();
////////////////////////////////////////////////////////////
// Call this after constructor has been called. It loads
// jQuery.
//
void initialize();
////////////////////////////////////////////////////////////
// Call to HKL www.omatlahdot.fi service.
// HTTP GET call goes to following URL
// http://www.omatlahdot.fi/omatlahdot/web?
//
// Service uses following parameters:
//
// [stopid] = number of stop
// [Submit] = Hae
// [command] = quicksearch
// [view] = mobile
//
// param: stopId - number of stop
// return TODO
//
void servCallOmatLahdot(const QString &stopId);
////////////////////////////////////////////////////////////
// Call to HKL www.reittiopas.fi service.
//
//
void servCallReittiOpas(QString const &startStop, QString const &endStop);
signals:
void infoResponseReady(int);
void stopDataReceived(const QString &);
void invalidStopData();
public slots:
void testData(QString const &data);
private:
////////////////////////////////////////////////////////////
// Prevent copy constructing
//
DataExtractor(const DataExtractor&);
////////////////////////////////////////////////////////////
// Prevent default assignment
//
DataExtractor &operator = (const DataExtractor&);
////////////////////////////////////////////////////////////
// Loads given javascript to given variable
//
void loadScript(const QString &pathToScript, QString &loadTo);
QNetworkAccessManager *accessManager_;
QWebPage *page_;
QString jQuery_;
QString omatLahdotJS_;
QString reittiOpasJS_;
private slots:
void handleOmatLahdotResponse(QNetworkReply *reply);
void handleReittiopasResponse(QNetworkReply *reply);
};
}
#endif // DATAEXTRACTOR_H
|
C | UTF-8 | 792 | 3.15625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <limits.h>
/** read a line from stdin **/
char * gets(char *s)
{
/*
RETURN_SUCCESS(ARGUMENT(s));
RETURN_FAILURE(CONSTANT(NULL));
*/
return fgets(s, INT_MAX, stdin);
}
/***
does no bounds checking, is marked obsolete in ISO/IEC 9899:1999, and
has been removed from ISO/IEC 9899:2011. It is a security risk and should not be used.
The THIS() function reads a line of input from IDENTIFIER(stdin) into the array
ARGUMENT(s). Input characters are read until a newline or end-of-file is reached. The
newline will not be appended to ARGUMENT(s). A CHAR(\0) character will be written
after the last character read into the array.
If end-of-file is reached before any characters are read, the contents of ARGUMENT(s)
remain unchanged.
***/
/*
STDC(1,201112)
*/
|
Ruby | UTF-8 | 3,334 | 2.828125 | 3 | [
"MIT"
] | permissive | module Scribble
class Method
def initialize receiver, call, context
@receiver, @call, @context = receiver, call, context
end
class << self
attr_reader :method_name, :receiver_class, :signature
# Setup instance variables
def setup receiver_class, method_name, signature
raise "Method name needs to be a Symbol, got #{method_name.inspect}" unless method_name.is_a?(Symbol)
@receiver_class, @method_name, @signature = receiver_class, method_name, signature
end
# Insert method into a registry
def eql? other
receiver_class == other.receiver_class && method_name == other.method_name && signature == other.signature
end
def insert registry
raise "Duplicate method #{method_name} on #{receiver_class}" if registry.methods.any? { |method| eql? method }
raise "Method #{method_name} must be a #{'non-' if split?}split method" unless [nil, split?].include? registry.split?(method_name)
raise "Method #{method_name} must be a #{'non-' if block?}block method" unless [nil, block?].include? registry.block?(method_name)
registry.methods << self
end
# Setup method and insert into default registry
def register method_name, *signature, on: Template::Context
setup on, method_name, signature
insert Registry.instance
end
# Subclass, setup and insert into registry
def implement receiver_class, method_name, signature, registry, as: nil, to: nil, cast: nil, returns: nil, split: nil
Class.new(self) do
setup receiver_class, method_name, signature
raise "Received multiple implementation options for method" unless [as, to, cast, returns].compact.size <= 1
raise "Method option :as requires String, got #{as.inspect}" unless as.nil? || as.is_a?(String)
raise "Method option :to requires Proc, got #{to.inspect}" unless to.nil? || to.is_a?(Proc)
raise "Method option :cast must be 'to_boolean' or 'to_string'" unless [nil, 'to_boolean', 'to_string'].include? cast
raise "Method option :split must be true" unless [nil, true].include? split
# Redefine split?
define_singleton_method :split? do
true
end if split
# Implement method
send :define_method, method_name do |*args|
if to
@receiver.instance_exec *args, &to
elsif cast
registry.evaluate method_name, registry.send(cast, @receiver), args, @call, @context
elsif !returns.nil?
returns
else
@receiver.send (as || method_name), *args
end
end
end.insert registry
end
# Default split and block
def split?; false; end
def block?; false; end
# Arity
def min_arity
@min_arity ||= signature.reduce 0 do |min_arity, element|
element.is_a?(Array) ? min_arity : min_arity + 1
end
end
def max_arity
@max_arity ||= signature.reduce 0 do |max_arity, element|
if max_arity
element.is_a?(Array) ? element[1] && max_arity + element[1] : max_arity + 1
end
end
end
end
end
end
|
Markdown | UTF-8 | 2,554 | 2.59375 | 3 | [] | no_license | ---
title: 返校-Detention
catalog: true
author: DK
header-img: /img/home-bg.jpg
date: 2018-08-27 20:28:35
tags:
- Game
---
##### 序章
魏仲延视角:
游戏开篇是课堂上老师讲课,后来有个叫白国峰的向殷老师询问是否见过一张书单。
主角在课堂睡着了,醒来发现教室空无一人,黑板上写着“台风警报,请同学尽速返家”
通过主角反应,我们知道这个季节有台风是件不寻常的事。
主角后桌上有张纸条,是询问殷老师请假事宜,收录在周记本里
主角教室在2楼
左边第一间教室窗台拾取一张纸条:大榕树下的速写,
主角所在班级:二年仁班,二层只有两个班级
一楼,公告栏:检举匪谍公报
公告栏旁是老高住所、工具间
工具间取得:弯曲手柄、
工具间墙壁:金刚般若波罗蜜经
手摇柄打开铁卷门
左走水仙花下取得:旧照片
一楼最左:校长室
穿过礼堂离开学校
礼堂讲台上有个女生
礼堂库房拾取雨伞,通风口勾取白鹿项链
学校外桥断了,河里变成大量血水
女生是三年忠班的方芮欣
魏仲延去整理过夜装备,
切换到方芮欣视角,魏仲延倒吊在礼堂,取得魏仲延周记本,礼堂外小庙取得礼堂钥匙和一张魍魉图:”夜晚出入请小心,遇见魍魉莫害怕,屏住呼吸慢慢行“
回礼堂的路上遇到魍魉,礼堂储存室里拾得纸条,读书会:老师聚集学生私下教授管制书籍
校长室传来电话铃声。”方同学,我在辅导室等你。“
一二年级来工具间搬东西,会想起讨厌的事
二楼仁班,黑板“自求多福”,后门宣传栏取得“校内禁止博弈”,女厕取得“钳子””骰子“
镜子“忘记了,还是不愿想起来”
回去路上遇到魍魉,回到二年仁班,
钳子打开铁门,保健室门口,取得“魍魉脚尾饭”图。进入保健室,灯箱下取得卫生库房钥匙,获得脚尾饭,获得黄敏昌诊断书,神坛存档。
出门放置脚尾饭,吸引魍魉,屏息,用钥匙打开卫生库。
洗眼器获得骰子,铁箱获得松香水
回保健室获取脚尾饭,引开魍魉。
一楼用松香水喷洗门上的符咒,获取刀片,获取骰子,三颗骰子掷入盆内,获取点数623,获得割喉图
回到礼堂,割开魏仲延喉咙,用碗盛血,回到三楼,用血看清刻痕,周记本拓印,到一楼根据图示开锁上楼,
铁门内是辅导室,进去前到隔壁教室存档。 |
Java | UTF-8 | 3,664 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package org.apache.ojb.broker.prevayler.demo;
/* Copyright 2003-2005 The Apache Software Foundation
*
* 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 org.apache.ojb.broker.PersistenceBroker;
import org.apache.ojb.broker.PersistenceBrokerFactory;
import org.apache.ojb.broker.util.ui.AsciiSplash;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;
/**
* The tutorial application.
* @author Thomas Mahler
*/
public class Application
{
private Vector useCases;
private PersistenceBroker broker;
/**
* Application constructor comment.
*/
public Application()
{
broker = null;
try
{
broker = PersistenceBrokerFactory.defaultPersistenceBroker();
}
catch (Throwable t)
{
t.printStackTrace();
}
useCases = new Vector();
useCases.add(new UCListAllProducts(broker));
useCases.add(new UCEnterNewProduct(broker));
useCases.add(new UCEditProduct(broker));
useCases.add(new UCDeleteProduct(broker));
useCases.add(new UCQuitApplication(broker));
}
/**
* Disply available use cases.
*/
public void displayUseCases()
{
System.out.println();
for (int i = 0; i < useCases.size(); i++)
{
System.out.println("[" + i + "] " + ((UseCase) useCases.get(i)).getDescription());
}
}
/**
* Insert the method's description here.
* Creation date: (04.03.2001 10:40:25)
* @param args java.lang.String[]
*/
public static void main(String[] args)
{
Application app = new Application();
app.run();
}
/**
* read a single line from stdin and return as String
*/
private String readLine()
{
try
{
BufferedReader rin = new BufferedReader(new InputStreamReader(System.in));
return rin.readLine();
}
catch (Exception e)
{
return "";
}
}
/**
* the applications main loop.
*/
public void run()
{
System.out.println(AsciiSplash.getSplashArt());
System.out.println("Welcome to the OJB PB tutorial application");
System.out.println();
// never stop (there is a special use case to quit the application)
while (true)
{
try
{
// select a use case and perform it
UseCase uc = selectUseCase();
uc.apply();
}
catch (Throwable t)
{
broker.close();
System.out.println(t.getMessage());
}
}
}
/**
* select a use case.
*/
public UseCase selectUseCase()
{
displayUseCases();
System.out.println("type in number to select a use case");
String in = readLine();
int index = Integer.parseInt(in);
return (UseCase) useCases.get(index);
}
}
|
Python | UTF-8 | 82 | 2.734375 | 3 | [] | no_license | '''
One way to do it - one liner
'''
def mySqrt(self, x):
return int(x**0.5)
|
C# | UTF-8 | 8,046 | 2.828125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Schema;
namespace Revit.IFC.Common.Utility
{
/// <summary>
/// A Class that represent a node in the Ifc schema entity tree
/// </summary>
public class IfcSchemaEntityNode
{
IfcSchemaEntityNode superType = null;
IList<IfcSchemaEntityNode> subType = null;
public string Name { get; }
public bool isAbstract { get; set; }
public string PredefinedType { get; set; }
/// <summary>
/// Create the class with only the entityname
/// </summary>
/// <param name="nodeName">the entity name</param>
/// <param name="abstractEntity">optional: whether the entity is an abstract type (default is false)</param>
public IfcSchemaEntityNode(string nodeName, bool abstractEntity = false)
{
Name = nodeName;
isAbstract = abstractEntity;
}
/// <summary>
/// Create the class with the information about the parent (supertype)
/// </summary>
/// <param name="nodeName">the entity name</param>
/// <param name="parentNode">the supertype entity name</param>
/// <param name="abstractEntity">optional: whether the entity is an abstract type (default is false)</param>
public IfcSchemaEntityNode(string nodeName, IfcSchemaEntityNode parentNode, string predefTypeEnum, bool abstractEntity = false)
{
Name = nodeName;
isAbstract = abstractEntity;
if (parentNode != null)
superType = parentNode;
if (predefTypeEnum != null)
PredefinedType = predefTypeEnum;
}
/// <summary>
/// Add the subtype node into this node
/// </summary>
/// <param name="childNode">the subtype entity node</param>
public void AddChildNode(IfcSchemaEntityNode childNode)
{
if (childNode != null)
{
if (subType == null)
subType = new List<IfcSchemaEntityNode>();
subType.Add(childNode);
}
}
/// <summary>
/// Set the supertype node into this node
/// </summary>
/// <param name="parentNode">the supertype entity node</param>
public void SetParentNode(IfcSchemaEntityNode parentNode)
{
if (superType != null)
throw new System.Exception("parentNode cannot be null!");
if (superType == null)
if (parentNode != null)
superType = parentNode;
}
/// <summary>
/// get the supertype node of the this node
/// </summary>
/// <returns>the supertype entity node</returns>
public IfcSchemaEntityNode GetParent()
{
return superType;
}
/// <summary>
/// get the list of the subtypes entity nodes
/// </summary>
/// <returns>the list of subtype nodes</returns>
public IList<IfcSchemaEntityNode> GetChildren()
{
if (subType == null)
return new List<IfcSchemaEntityNode>();
return subType;
}
/// <summary>
/// Get all the subtype branch of this entity
/// </summary>
/// <returns>the list of all the subtype nodes</returns>
public IList<IfcSchemaEntityNode> GetAllDescendants()
{
List<IfcSchemaEntityNode> res = new List<IfcSchemaEntityNode>();
foreach (IfcSchemaEntityNode child in subType)
{
res.AddRange(child.GetAllDescendants());
}
return res;
}
/// <summary>
/// Get all the supertype line of this entity
/// </summary>
/// <returns>the list of supertype following the level order</returns>
public IList<IfcSchemaEntityNode> GetAllAncestors()
{
List<IfcSchemaEntityNode> res = new List<IfcSchemaEntityNode>();
IfcSchemaEntityNode node = this;
while (node.superType != null)
{
res.Add(superType);
node = superType;
}
return res;
}
/// <summary>
/// Test whether the supertTypeName is the valid supertype of this entity
/// </summary>
/// <param name="superTypeName">the name of the potential supertype</param>
/// <returns>true: is the valid supertype</returns>
public bool IsSubTypeOf(string superTypeName, bool strict = true)
{
bool res = false;
IfcSchemaEntityNode node = this;
while (node.superType != null)
{
if (strict)
{
if (superTypeName.Equals(node.superType.Name, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
else
{
if (superTypeName.Equals(node.superType.Name, StringComparison.InvariantCultureIgnoreCase)
|| superTypeName.Equals(node.Name, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
node = node.superType;
}
return res;
}
/// <summary>
/// Test whether the subtype name is the valid subtype of this entity
/// </summary>
/// <param name="subTypeName">the name of the potential subtype</param>
/// <returns>true: is the valid subtype</returns>
public bool IsSuperTypeOf(string subTypeName)
{
return CheckChildNode(subTypeName);
}
/// <summary>
/// Print the branch starting from this entity node. The print is formatted using tab indentation to represent the hierarchical level
/// </summary>
/// <param name="level">the level number</param>
/// <returns>the tree structure of the banch in a string</returns>
public string PrintBranch(int level = 0)
{
string res = string.Empty;
// Print itself first and then followed by each subtypes
IfcSchemaEntityNode node = this;
string abs = string.Empty;
if (node.isAbstract)
abs = " (ABS)";
res += "\n";
for (int i = 0; i < level; ++i)
res += "\t";
res += node.Name + abs;
if (node.subType == null)
return res;
foreach (IfcSchemaEntityNode sub in node.subType)
{
for (int i = 0; i < level; ++i)
res += "\t";
string br = sub.PrintBranch(level + 1);
if (!string.IsNullOrWhiteSpace(br))
res += br;
}
return res;
}
/// <summary>
/// Get the entities in the branch starting of this entity node in a set
/// </summary>
/// <returns>a set that contains all the subtype entity names</returns>
public HashSet<string> GetBranch()
{
HashSet<string> resSet = new HashSet<string>();
IfcSchemaEntityNode node = this;
resSet.Add(node.Name);
if (node.subType == null)
return resSet;
foreach (IfcSchemaEntityNode sub in node.subType)
{
HashSet<string> br = sub.GetBranch();
if (br.Count > 0)
resSet.UnionWith(br);
}
return resSet;
}
/// <summary>
/// Check whether an entityName is found in this entity and its subtypes
/// </summary>
/// <param name="entityName">the entity name to check</param>
/// <returns>true: the entityName is found in this entity or tits subtype</returns>
public bool CheckChildNode(string entityName)
{
IfcSchemaEntityNode node = this;
if (string.Compare(node.Name, entityName, ignoreCase: true) == 0)
return true;
if (node.subType == null)
return false;
foreach (IfcSchemaEntityNode sub in node.subType)
{
if (sub.CheckChildNode(entityName))
return true;
}
return false;
}
}
} |
Java | UTF-8 | 619 | 2.921875 | 3 | [] | no_license | package spring_framework.wideskills_com.lesson_08.xml;
public class MessageBean {
private String message;
public MessageBean()
{
System.out.println("Constructor of bean is called !! ");
}
public void init() throws Exception {
System.out.println("custom custom init method of bean is called !! ");
}
public void destroy() throws Exception {
System.out.println(" custom destroy method of bean is called !! ");
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
C# | UTF-8 | 1,600 | 2.8125 | 3 | [] | no_license | #region
using System;
using System.Diagnostics;
using System.IO;
using SQLite;
#endregion
namespace ProcessDashboard.DBWrapper
{
public class DbManager
{
private const string DbName = "pdash.db3";
private static DbManager _instance;
private static SQLiteConnection _db;
public ProjectWrapper Pw;
public TimeLogWrapper Tlw;
public TaskWrapper Tw;
// Private Constructor for Singleton Class.
private DbManager()
{
CreateConnection();
Pw = new ProjectWrapper(_db);
Tw = new TaskWrapper(_db);
Tlw = new TimeLogWrapper(_db);
//Create the table
Pw.CreateTable();
Tw.CreateTable();
Tlw.CreateTable();
}
public static DbManager GetInstance()
{
return _instance ?? (_instance = new DbManager());
}
//Create the Database
public static bool CreateDb()
{
try
{
CreateConnection();
Debug.WriteLine("DB Created");
return true;
}
catch (Exception e)
{
Debug.WriteLine("DB Creation failed : " + e.Message);
return false;
}
}
// Create the connection to the DB.
private static void CreateConnection()
{
var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DbName);
_db = new SQLiteConnection(dbPath);
}
}
} |
Java | UTF-8 | 5,285 | 2.1875 | 2 | [] | no_license | package com.kasun.userapp.inventory.controller;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.kasun.userapp.common.ServiceRequest;
import com.kasun.userapp.common.ServiceResponse;
import com.kasun.userapp.inventory.dto.InventoryAddParam;
import com.kasun.userapp.inventory.dto.InventorySearchCriteria;
import com.kasun.userapp.inventory.dto.Tenant;
import com.kasun.userapp.inventory.model.Inventory;
import com.kasun.userapp.inventory.service.InventoryService;
/**
* @author Kasun Kariyawasam
*
* Dec 21, 2014
*/
@Controller
@RequestMapping("/inventory")
public class InventoryController {
@Autowired
private InventoryService inventoryService;
private static final Logger log = LoggerFactory.getLogger(InventoryController.class);
@RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody String addInventory(@RequestBody InventoryAddParam inventoryAddParam) {
validate(inventoryAddParam);
System.out.println("Success " + inventoryAddParam.getName());
ServiceRequest<InventoryAddParam> serviceRequest = convertAddParamtoServiceRequest(inventoryAddParam);
inventoryService.addInventory(serviceRequest);
return "Inventory Added Succesfully";
}
@RequestMapping(value = "/delete", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody String deleteInventory(@RequestBody String inventoryId) {
ServiceRequest<String> serviceRequest = new ServiceRequest<>(
inventoryId);
inventoryService.deleteInventory(serviceRequest);
return "Inventory Deleted Succesfully";
}
@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String welcomePageTemp() {
log.debug("welcome");
return "inventory";
}
@RequestMapping(value = "/add_edit_view", method = RequestMethod.GET)
public String add_edit_view_page() {
log.debug("view/edit/add");
return "addViewEditInventory";
}
@RequestMapping(value = "/viewAll", method = RequestMethod.POST)
public @ResponseBody List<Inventory> viewInventory(@RequestBody Tenant tanent) {
List<Inventory> inventories = new ArrayList<>();
ServiceRequest<Tenant> serviceRequest = new ServiceRequest<>(tanent);
ServiceResponse<List<Inventory>> response = inventoryService.viewAllInventories(serviceRequest);
if (response.hasError()) {
throw new RuntimeException("Error in View All Inventories");
}
inventories = response.getPayload();
log.info("Inventory view all pass");
return inventories;
}
@RequestMapping(value = "/search", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody List<Inventory> searchInventory(@RequestBody InventorySearchCriteria searchCriteria) {
List<Inventory> inventories = new ArrayList<>();
ServiceRequest<InventorySearchCriteria> serchRequest = new ServiceRequest<InventorySearchCriteria>();
serchRequest.setPayload(searchCriteria);
ServiceResponse<List<Inventory>> response = inventoryService.searchInventory(serchRequest);
if (response.hasError()) {
throw new RuntimeException("Error in search...");
}
validateSearchResulit(response);
log.info("Inventory search pass");
inventories = response.getPayload();
return inventories;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody Inventory editInventory(@RequestBody Inventory inventory) {
ServiceRequest<Inventory> editRequest = new ServiceRequest<Inventory>(inventory);
ServiceResponse<Inventory> response = inventoryService.editInventory(editRequest);
if (response.hasError()) {
throw new RuntimeException("Error in Edition");
}
log.info("Inventory Edit pass");
return response.getPayload();
}
private ServiceRequest<InventoryAddParam> convertAddParamtoServiceRequest(InventoryAddParam inventoryAddParam) {
ServiceRequest<InventoryAddParam> request = new ServiceRequest<InventoryAddParam>();
request.setPayload(inventoryAddParam);
return request;
}
private void validateSearchResulit(ServiceResponse<List<Inventory>> response) {
}
private void validate(InventoryAddParam inventoryAddParam) {
if (inventoryAddParam == null) {
throw new RuntimeException("Add param can not be null");
}
if (inventoryAddParam.getInventoryId() == null
|| inventoryAddParam.getInventoryId().isEmpty()) {
throw new RuntimeException("Inventory id can not be null");
}
}
public void setInventoryService(InventoryService inventoryService) {
this.inventoryService = inventoryService;
}
}
|
Markdown | UTF-8 | 385 | 2.53125 | 3 | [] | no_license | # Fitness-Tracker
# Description
This is an application that allows a user to log and keep track of various exercises during a workout. This application uses MongoDB, Mongoose.js and Express.js.
[Fitness Tracker](https://calm-basin-11411.herokuapp.com/)



|
JavaScript | UTF-8 | 1,232 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | 'use strict';
import { VertexObjectDescriptor } from '../core';
class SpriteFactory {
constructor ( parentFactory = null ) {
this.registry = new Map;
this.parentFactory = parentFactory;
}
createDescriptor (name, ...args) {
if (this.getDescriptor(name)) {
throw new Error(`oops.. VertexObjectDescriptor '${name}' already exists!`);
}
let vod = new VertexObjectDescriptor(...args);
this.registry.set(name, vod);
return vod;
}
getDescriptor (descriptor = 'default') {
if (descriptor instanceof VertexObjectDescriptor) {
return descriptor;
} else {
let vod = this.registry.get(descriptor);
if (!vod && this.parentFactory) {
return this.parentFactory.getDescriptor(descriptor);
} else {
return vod;
}
}
}
createSprite (descriptor, ...args) {
let vod = this.getDescriptor(descriptor);
if (vod) {
return vod.create(...args);
}
}
createSubFactory () {
return new SpriteFactory(this);
}
}
export default (function () {
return new SpriteFactory;
})();
|
Markdown | UTF-8 | 694 | 2.78125 | 3 | [] | no_license | # penguin
Repo for a tutorial on setting up c++ project with cmake and ninja
Requirements:
CMake : https://cmake.org/
Ninja : https://ninja-build.org/
#### Steps to build the project:
1. Install **cmake **
1. On Mac OS, `brew install cmake`
2. Install the **ninja** build system
1. On Mac OS, `brew install ninja`
3. From the root directory of the project, run `mkdir -p build`
4. Go to newly created directory, `cd build`
5. Run the cmake command, `cmake -GNinja ..`
6. Run `ninja` to build the project
7. Run `./penguin` from build directory to run the project
8. Run `./test/penguin_test` from build directory to run the tests.
9. On changes, run `ninja` in the "build" directory.
|
Markdown | UTF-8 | 3,548 | 3.078125 | 3 | [] | no_license | ---
layout: post
title: "[Python] python으로 이미지 다루기 예제"
headline: Python15
modified: 2017-04-06
categories: Python_for_Everyone Elmo Python
comments: true
featured: true
---
# 1
냥냥이 그림 클래스 속 sum함수와 그냥 sum함수
``` python
from skimage import novice,data
class MyPic():
def __init__(self,filename):
self.pic = novice.open(data.data_dir + "/" + filename)
def threshold(self,p):
if p > 255:
return 255
else:
return int(p)
def show(self):
self.pic.show()
def sum(self):
(r,g,b,a) = (0,0,0,0)
for p in self.pic:
r += p.red
g += p.green
b += p.blue
a += p.alpha
return (r,g,b,a)
def grey(self):
for p in self.pic:
(r,g,b) = (p.red, p.green, p.blue)
grey = self.threshold((r + g + b)/3)
(p.red,p.green,p.blue)=(grey,grey,grey)
```
skimage.novice
skimage.data라는 모듈을 계속 부를때마다 이렇게 쓰는게 아니라
import 시키면 그냥 novice라고 사용할 수 있음
<br>
#### (a)
``` python
pic = MyPic("chelsea.png")
pic.show()
```
<img src="{{ site.url }}/images/elmo/py06b1.png" style="display: block; margin: auto;">
냥냥펀치!
<br>
#### (b)
``` python
pic = MyPic("chelsea.png")
print(pic.sum())
```
> (19980169, 15078438, 11743750, 34501500)
<br>
#### (c)
``` python
pic = MyPic("chelsea.png")
print(sum(pic.sum()))
```
> 81303857
<br>
#### (d)
``` python
pic = MyPic("chelsea.png")
pic.grey()
pic.show()
```
<img src="{{ site.url }}/images/elmo/py06b2.png" style="display: block; margin: auto;">
<br>
#### (e)
``` python
pic = MyPic("chelsea.png")
pic.grey()
print(pic.sum())
```
> (15554511, 15554511, 15554511, 34501500)
<br>
#### (f)
``` python
pic = MyPic("chelsea.png")
pic.grey()
print(sum(pic.sum()))
```
> 81165033
<br>
# 2
#### (a)
냥냥이를 반파랑 반빨강으로 만들 수 있도록 class MyPic을 수정해보자
``` python
from skimage import novice,data
class MyPic():
def __init__(self,filename):
self.pic = novice.open(data.data_dir + "/" + filename)
def threshold(self,p):
if p > 255:
return 255
else:
return int(p)
def show(self):
self.pic.show()
def bluered(self):
for y in range(self.pic.height):
for x in range(self.pic.width//2):
self.pic[x, y].blue=255
for x in range(self.pic.width//2):
self.pic[x + self.pic.width//2, y].red=255
```
```
pic = MyPic("chelsea.png")
pic.bluered()
pic.show()
```
<img src="{{ site.url }}/images/elmo/py06b3.png" style="display: block; margin: auto;">
<br>
<br>
#### (b)
세피아 효과를 줘보쟈
``` python
from skimage import novice,data
class MyPic():
def __init__(self,filename):
self.pic = novice.open(data.data_dir + "/" + filename)
def threshold(self,p):
if p > 255:
return 255
else:
return int(p)
def show(self):
self.pic.show()
def sepia(self):
for p in self.pic:
(r,g,b) = (p.red,p.green,p.blue)
p.red = self.threshold(r * .393 + g * .769 + b * .189)
p.green = self.threshold(r * .349 + g * .686 + b * .168)
p.blue = self.threshold(r * .272 + g * .534 + b * .131)
```
```
pic = MyPic("chelsea.png")
pic.sepia()
pic.show()
```
<img src="{{ site.url }}/images/elmo/py06b4.png" style="display: block; margin: auto;">
<br>
|
Java | UTF-8 | 597 | 3.28125 | 3 | [] | no_license | package WildFarm.animals;
import WildFarm.foods.Food;
import WildFarm.foods.Vegetable;
public class Tiger extends Felime {
public Tiger(String name, String type, double weight, String livingRegion) {
super(name, type, weight, livingRegion);
}
@Override
public void eat(Food food) {
if (food instanceof Vegetable) {
throw new IllegalArgumentException(
"Tigers are not eating that type of food!");
}
super.eat(food);
}
@Override
public void makeSound() {
System.out.println("ROAAR!!!");
}
}
|
Java | UTF-8 | 281 | 1.726563 | 2 | [] | no_license | package com.example.iga.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PagesController {
@GetMapping(value="/")
public String homepage(){
return "test";
}
}
|
Python | GB18030 | 1,919 | 2.890625 | 3 | [] | no_license | '''
@author: fightingliu
'''
import copy, numpy as np
from conv import mini_batch_size
from numpy import random
from astropy.units import nb
class Network(object):
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def fedforward(self, a):
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a) + b)
# ݶ
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):
if test_data:n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data)
mini_batches = [training_data[k:k + mini_batch_size]
for k in xrange(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print("Epoch{0}1/2{2}").format(j, self.evalutate(test_data), n_test)
else:
print("Epoch{0}complete").format(j)
def update_mini_batch(self,mini_batch,eta):
nabla_b=[np.zeros(b.shape) for b in self.biases]
nabla_w=[np.zeros(w.shape) for w in self.weights]
for x,y in mini_batch:
delta_nabla_b,delta_nabla_w=self.backprop(x,y)#÷㷨
nabla_b=[nb+dnb for nb,dnb in zip(nabla_b,delta_nabla_b)]
nabla_w=[nw+dnw for nw,dnw in zip(nabla_w,delta_nabla_w)]
self.weights=[w-(eta/len(mini_batch))*nw
for w ,nw in zip(self.weights,nabla_w)]
self.biases=[b-(eta/len(mini_batch))*nb
for b,nb in zip(self.biases,nabla_b)]
if __name__ == '__main__':
net = Network([2, 3, 1])
print(net)
|
Python | UTF-8 | 1,892 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python3
class CheckArgs(): #class that checks arguments and ultimately returns a validated set of arguments to the main program
def __init__(self):
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--variantPickleFile", help = "Input pickle of fused, sorted variants.", required = True)
parser.add_argument("-o", "--outputVariantFile", help = "Output file name", required = True)
rawArgs = parser.parse_args()
variantPickleFile = rawArgs.variantPickleFile
if not os.path.isfile(variantPickleFile):
raise FileNotFoundError("Unable to find input pickle file at %s" %variantPickleFile)
self.variantPickleFile = variantPickleFile
self.outputVariantFile = rawArgs.outputVariantFile
def makeOutputForOncotator(variantDict, delimiter = "\t"):
import variantDataHandler
variantList = list(variantDict.keys())
variantDataHandler.sortVariantDataTuples(variantList)
outputHeader = ["chr", "start", "end", "ref_allele", "alt_allele", "DNAcoverage", "Mut_DNA_Reads_Abs", "Mut_DNA_VAF", "NormalDNAcoverage"]
outputLines = []
outputLines.append(delimiter.join(outputHeader))
for variant in variantList:
if variantDict[variant].isIndel:
continue
outputLines.append(variantDict[variant].oncotatorInputLine(delimiter))
outputLines = "\n".join(outputLines)
return outputLines
if __name__ == '__main__':
args = CheckArgs()
import pickle
variantPickleFile = open(args.variantPickleFile, 'rb')
variantDict = pickle.load(variantPickleFile)
variantPickleFile.close()
fusedVariants = variantDict["fused"]["variants"]
outputFile = open(args.outputVariantFile, 'w')
outputFile.write(makeOutputForOncotator(fusedVariants))
outputFile.close()
quit()
|
Java | UTF-8 | 4,731 | 2.53125 | 3 | [] | no_license | package com.androidexample.chenn.androidclient.msgservice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by chenn on 2017/9/20.
*/
public class MsgSend {
private Handler handler;
private Socket client;
private OutputStream outStr = null;
private InputStream inStr = null;
private byte[] sndBytes;
public MsgSend(Handler handler, byte[] sndBytes){
this.handler = handler;
this.sndBytes = sndBytes;
}
private void send_err(String err){
Message msg = new Message();
Bundle b = new Bundle();
b.putString("content", err);
msg.what = Const.MSG_MAIN_ERR;
msg.setData(b);
handler.sendMessage(msg);
}
private void processReInfo(String info){
String type = "";
if (null == info){
//接收超时
type = "9999";
}else {
try {
info = info.replaceAll("[\u0000-\u001f]", "");
info = info.replaceAll("\n", "");
StringReader sr = new StringReader(info);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
type = doc.getElementsByTagName("type").item(0).getFirstChild().getNodeValue();
type = type.trim();
} catch (SAXException e) {
Log.i(Const.TAG,"sendCommand error:" + e.getMessage());
send_err("sendCommand error:" + e.getMessage());
} catch (ParserConfigurationException e) {
Log.i(Const.TAG,"sendCommand error:" + e.getMessage());
send_err("sendCommand error:" + e.getMessage());
} catch (IOException e) {
Log.i(Const.TAG,"sendCommand error:" + e.getMessage());
send_err("sendCommand error:" + e.getMessage());
}
}
if ("9999".equals(type)){
//处理传送失败
Log.i(Const.TAG,"传送失败");
send_err("传送失败");
}else{
Log.i(Const.TAG,"传送成功");
send_err("传送成功");
}
}
public void connect() throws IOException {
client = new Socket(Const.SERVER_IP, Const.SERVER_PORT);
outStr = client.getOutputStream();
inStr = client.getInputStream();
}
private class AnswerThread implements Runnable{
@Override
public void run() {
try{
//发送报文
outStr.write(sndBytes);
outStr.flush();
Log.i(Const.TAG,"msgsend:"+String.valueOf(sndBytes));
client.setSoTimeout(3000);
byte[] head = new byte[4];
//读四位包头
int number = inStr.read(head);
if (-1 < number){
//将四字节head转换为int类型
ByteBuffer bb = ByteBuffer.wrap(head);
int recvSize = bb.order(ByteOrder.BIG_ENDIAN).getInt();
byte[] info = new byte[recvSize];
number = inStr.read(info);
Log.i(Const.TAG,"msgsend return size:"+recvSize);
if (-1 < number){
//转换网络字节为string
String xmlinfo = Const.get_str_from_sockebytes(info);
Log.i(Const.TAG,"msgsend return info:"+xmlinfo);
processReInfo(xmlinfo);
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void start(){
try {
connect();
Thread tAnswer = new Thread(new AnswerThread());
tAnswer.start();
} catch (Exception e) {
Log.i(Const.TAG,"发送线程启动错误" + e);
send_err("发送线程启动错误"+e);
}
}
}
|
Java | UTF-8 | 304 | 1.640625 | 2 | [] | no_license | package ru.innovat.models.utils;
import lombok.*;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class Connect {
private int event_Id;
private int project_Id;
private int organization_Id;
private int typeEvent_id;
private int person_id;
private int role_id;
}
|
Markdown | UTF-8 | 1,315 | 3.0625 | 3 | [
"Apache-2.0"
] | permissive | ---
layout: default
title: xls2xlsx(xlsFile,xlsxFile)
parent: excel
tags: command excel xls xlsx
comments: true
---
### Description
This command converts an Excel file in XLS format (pre-2007 format) to the XLSX format (2007 and after). The target can
either be a fully qualified file name or a directory where the converted file should reside. If a directory is specified
as the`xlsxFile` then Nexial will derive at the target file name based on the source (i.e. `xlsFile`). For example,
```
excel | xls2xlsx(xlsFile,xlsxFile) | /path1/path2/myFile.xls | /path3/path4/
```
Nexial will convert `/path1/path2/myFile.xls` to `/path3/path4/myFile.xlsx`.
If `xlsxFile` resolves to an existing file, it will be overwritten during file conversion.
The source file will remain as is.
### Parameters
- **xlsFile** - the Excel file to convert; must be pre-2007 format (file ending with `.xls`)
- **xlsxFile** - the target Excel file for this conversion; assumes file saved with an `.xlsx` extension.
### Example
**Script**:<br/>
```
excel | xls2xlsx(xlsFile,xlsxFile) | /path1/path2/myFile.xls | /path3/path4/myNewFile.xlsx
```
**Output**:<br/>
The Excel file `/path1/path2/myFile.xls` is converted to `/path3/path4/myNewFile.xlsx`. The source file
`/path1/path2/myFile.xls` will remain as is.
### See Also
|
Python | UTF-8 | 8,750 | 2.71875 | 3 | [] | no_license | from filter import Filter
from GeoMetDemo import dumps as dumpWKT
from shapely import wkt
import numpy as np
import copy
from setting import INTERSECT_AREA_PARTION
class Cover:
"""
指定空间范围、时间范围和分辨率范围的最优影像覆盖分析
"""
items = []
def __init__(self, itemList):
self.items = itemList
def _round_coordinates(self, geomObj):
"""
对几何体点集的坐标进行四舍五入降低精度
"""
from shapely.geometry import shape, mapping
geomJSON = mapping(geomObj)
geomJSON['coordinates'] = np.round(np.array(geomJSON['coordinates'], dtype=float), 4)
return shape(geomJSON)
def _unionShapelyObjLists(self, shapelyObjList):
"""
将一个shapely对象列表进行union运算为一个整的shapely对象
:param list shapelyObjList shapely对象的列表
:return object unionObj 返回union的shapely对象
"""
# DEBUG 列表只有一个元素则直接返回
if len(shapelyObjList) == 1:
return shapelyObjList[0]
unionObj = shapelyObjList[0].union(shapelyObjList[1])
for i in range(2,len(shapelyObjList)):
unionObj = unionObj.union(shapelyObjList[i])
return unionObj
def makeCover(self):
"""
最优覆盖分析(初级)——利用系统云量
"""
f = Filter()
initGeom = f.wenchangGEOJSON
initGeom = wkt.loads(dumpWKT(initGeom))
initRes = 1000
initCloud = 1
initID = ''
initItem = {'id':initID, 'geom':initGeom, 'res': initRes, 'cloud':initCloud}
checkedItemList = []
checkedItemList.append(initItem)
uncheckedItems = self.items
# 遍历查询结果来填入查询区域的边界范围内
# 采用对每个api返回的查询结果item逐步进入的覆盖策略
### 这个地方相交查询可以用RTree来提高查询效率
# from rtree import index
# idx = index.Index()
for uncheckedItem in uncheckedItems:
uncheckedID = uncheckedItem['id']
uncheckedRes = uncheckedItem['properties']['pixel_resolution']
uncheckedCloud = uncheckedItem['properties']['cloud_cover']
uncheckedGeom = uncheckedItem['geometry']
uncheckedGeom = wkt.loads(dumpWKT(uncheckedGeom)) # 加载成shapely geometry对象
updatedCheckedList = []
print("Begin Checking " + uncheckedID + " ,Checked Item Now is {}".format(len(checkedItemList)))
for checkedItem in checkedItemList:
# DEBUG: 云量为0不再更新
if checkedItem['cloud'] == 0 or checkedItem['geom'].area < 1e-5:
# continue
# DEBUG
updatedCheckedList.append(checkedItem)
continue
# DEBUG:对所有多边形做buffer来避免拓扑错误,不论多边形大小
# checkedItem['geom'] = self._round_coordinates(checkedItem['geom'])
checkedItem['geom'] = checkedItem['geom'].buffer(1e-6)
try:
if checkedItem['geom'].intersects(uncheckedGeom):
intersectGeom = checkedItem['geom'].intersection(uncheckedGeom)
# DEBUG 如果待插入的item与存在的块相交面积太小,则不去急着更新块,因为这是碎块产生太多的根本原因
if intersectGeom.area / checkedItem['geom'].area < INTERSECT_AREA_PARTION:
updatedCheckedList.append(checkedItem)
continue
# 待插入数据与存在数据的象元尺寸相同
if uncheckedRes == checkedItem['res']:
if uncheckedCloud < checkedItem['cloud']:
intersectItem = {'id':uncheckedID, 'geom':intersectGeom, 'res': uncheckedRes, 'cloud':uncheckedCloud}
else:
# DEBUG:要拷贝,而不是赋值
intersectItem = copy.copy(checkedItem)
intersectItem['geom'] = intersectGeom
# 待插入数据的象元尺寸大于存在数据的象元尺寸
elif uncheckedRes > checkedItem['res']:
if uncheckedCloud - checkedItem['cloud'] < -0.2:
intersectItem = {'id':uncheckedID, 'geom':intersectGeom, 'res': uncheckedRes, 'cloud':uncheckedCloud}
else:
intersectItem = copy.copy(checkedItem)
intersectItem['geom'] = intersectGeom
# 待插入数据的象元尺寸小于存在数据的象元尺寸(分辨率更高)
else:
# 待插入数据云量不比存在数据高很多,就插入替换重叠区域
if uncheckedCloud - checkedItem['cloud'] <= 0.02:
intersectItem = {'id':uncheckedID, 'geom':intersectGeom, 'res': uncheckedRes, 'cloud':uncheckedCloud}
else:
intersectItem = copy.copy(checkedItem)
intersectItem['geom'] = intersectGeom
updatedCheckedList.append(intersectItem)
differenceGeom = checkedItem['geom'].difference(intersectGeom)
# 修复bug 添加差值区域为空的判断条件
# 如果重叠区域外还有未确认区域,就将未确认区域继续加入判断列表
if differenceGeom.area > 0.0:
DifferenceItem = {'id':checkedItem['id'], 'geom':differenceGeom, 'res': checkedItem['res'], 'cloud':checkedItem['cloud']}
updatedCheckedList.append(DifferenceItem)
else:
updatedCheckedList.append(checkedItem)
except Exception:
# DEBUG shapely.errors.PredicateError
# DEBUG 相交运算拓扑错误引发异常
# from geojsonio import display
# display(uncheckedGeom)
print("致命的GEOS错误!")
exit(0)
else:
pass
# # 按id合并checkedItemList的元素
# print("--Begin Merging Items by ID!")
# print("--Checked Item Now is {}".format(len(updatedCheckedList)))
# import pandas as pd
# mergedUpdatedCheckedList = [{'id': name, 'geom':self._unionShapelyObjLists([geom for geom in group.geom]), \
# 'res': group['res'].iloc[0], 'cloud': group.cloud.iloc[0]} \
# for name, group in pd.DataFrame(updatedCheckedList).groupby(['id'])]
# checkedItemList = []
# checkedItemList = mergedUpdatedCheckedList
# print("--End Merging Items by ID!" + " Checked Item Now is {}".format(len(checkedItemList)))
checkedItemList = updatedCheckedList
print("Begin Processing return Item List")
print("===后处理1:拆分复合多边形===")
# 将结果item中的multipolygon分解为polygon
splitItemList = []
for item in checkedItemList:
print(item['geom'].type)
if item['geom'].type == 'MultiPolygon':
for poly in item['geom']:
item_split = {'id':item['id'], 'geom':poly, 'res': item['res'], 'cloud':item['cloud']}
splitItemList.append(item_split)
elif item['geom'].type == 'Polygon':
splitItemList.append(item)
# 严谨的异常处理
else:
print("ERROR GEOMETRY TYPE THAT CANNOT HANDLE BY SPLIT")
for item in splitItemList:
print(item['geom'].type)
# print("===后处理2:按ID合并返回结果===")
# # 按id合并返回元素
# print("--splitItemList Now is {}".format(len(splitItemList)) + " ,Begin Merging Items by ID")
# import pandas as pd
# mergedSplitItemList = [{'id': name, 'geom':self._unionShapelyObjLists([geom for geom in group.geom]), \
# 'res': group['res'].iloc[0], 'cloud': group.cloud.iloc[0]} \
# for name, group in pd.DataFrame(splitItemList).groupby(['id'])]
print("End Processing return Item List")
return splitItemList
|
JavaScript | UTF-8 | 2,764 | 2.515625 | 3 | [
"MIT"
] | permissive | import React from "react";
import { Text, View, Button, ImageBackground} from 'react-native';
import styles from "../screens/styles/manage.js";
function changeState(i,ref)
{
if(i == 1)
{
if(ref.state.x1 === 0)ref.setState({x1: 1});
else ref.setState({x1: 0});
if(ref.state.y1 === 0)ref.setState({y1: 1});
else ref.setState({y1: 0});
}
else if(i == 0)
{
if(ref.state.x2 === 0)ref.setState({x2: 1});
else ref.setState({x2: 0});
if(ref.state.y2 === 0)ref.setState({y2: 1});
else ref.setState({y2: 0});
}
else
{
ref.setState({flag: true});
ref.setState({message: "Generation in progress"});
}
}
function makecard(i,ref)
{
if( i == 1)
{
const textlabels = ["Registration Closed", "Registration Open"];
const buttonlabels = ["Open", "End"];
return (
<View style={styles.BoxU}>
<View style={styles.Box}>
<Text style={styles.Text}>Registration</Text>
<Text style={styles.TextI}>{textlabels[ref.state.x1]}</Text>
<View style={styles.Button}>
<Button title= {buttonlabels[ref.state.y1]} onPress={async () => changeState(i,ref)}></Button>
</View>
</View>
</View>
);
}
else if( i == 0)
{
const textlabels = ["Event Started", " Event Ended"];
const buttonlabels = ["End", "Start"];
return (
<View style={styles.BoxU}>
<View style={styles.Box}>
<Text style={styles.Text}>Event</Text>
<Text style={styles.TextI}>{textlabels[ref.state.x2]}</Text>
<View style={styles.Button}>
<Button title= {buttonlabels[ref.state.y2]} onPress={async () => changeState(i,ref)}></Button>
</View>
</View>
</View>
);
}
else
{
return (
<View style={styles.BoxU}>
<View style={styles.Box}>
<Text style={styles.Text}>Certificate</Text>
<Text style={styles.TextI}>{ref.state.message}</Text>
<View style={styles.Button}>
<Button disabled={ref.state.flag} title= "Start" onPress={async () => changeState(i,ref)}></Button>
</View>
</View>
</View>
);
}
}
class manage extends React.Component
{
constructor(props){
super(props);
const { eventName } = this.props.route.params;
this.state = {
x1: 0,
y1: 0,
x2: 0,
y2: 0,
flag: false,
message: "Generate Certificate",
eventName: eventName
}
}
render() {
console.log(this.state.eventName);
return (
<View style={styles.Container}>
{makecard(0,this)}
{makecard(1,this)}
{makecard(2,this)}
</View>
);
}
}
export default manage;
|
Python | UTF-8 | 3,211 | 3.1875 | 3 | [] | no_license | #!/usr/bin/env python
# don't forget to "conda activate bgmp_py3" on the command line
import re
import matplotlib.pyplot as plt
FILE = "/home/afo/bgmp/Bi621/PS6/KMER49/contigs_49_cov_cutoff_500.fa"
KMER_LEN = 49
# mean depth coverage for contigs, must solve for C
# Ck = C * (L - K + 1) / L (original equation)
# Ck = k-mer coverage
# C = coverage
# L = length of reads
# K = k-mer length
# C = Ck * L / (L - K + 1) (modified equation)
# C = kmer_cov * phys_len / (kmer_len - KMER_LEN + 1)
with open(FILE, "r") as fh:
phys_len = []
kmer_cov = []
contig_num = 0
for line in fh:
line = line.strip() # python adds a new line and needs to be stripped
if line[0] == '>': # if the beginning of the line starts with a '>'
phys_len.append(re.findall("length_[0-9]+", line)[0][7:]) # findall grabs the specified line but needs to have more grabbed from it, hence specifying the first 7 characters, append to empty array
kmer_cov.append(re.findall("cov_[0-9]+\.[0-9]+", line)[0][4:])
for cov in range(len(kmer_cov)):
kmer_cov[cov] = float(kmer_cov[cov])
for index, value in enumerate(phys_len):
phys_len[index] = int(value) + KMER_LEN - 1 # the physical length is "strlen" (ie kmer_len) in the formula "kcnt = strlen" - k + 1"
contig_num += 1 # increment for contig length
max_contig = max(phys_len)
mean_contig = sum(phys_len) / len(phys_len)
mean_cov_depth = sum(kmer_cov) / len(kmer_cov)
total_phys = sum(phys_len)
num_contigs = len(phys_len)
# 5. Calculate the N50 value of your assembly.
# If the position in the entire contig length (item), as it's incremented (total)
# is greater than the sum of the entire physical length divided by 2 (L50),
# then the N50 requirement is perfected.
phys_len_sort = sorted(phys_len)
L50 = sum(phys_len_sort) / 2
total = 0
for item in phys_len_sort:
total += item
if total >= L50:
N50 = item
break
# 6. Calculate the distribution of contig lengths and bucket the contig lengths into groups of
# 100bp. So, all contigs with lengths between 0 and 99 would be in the 0 bucket, those
# with lengths between 100 and 199 would be in the 100 bucket, etc.
# 7. Print out the distribution.
# # Contig length Number of contigs in this category
# 0 0
# 100 5324
# 200 3345
# 300 1130
# ...
# Must do floor division and multiply by 100 to make the contigs 100, 200, 300, etc.
# I initialized a dictionary (bucket) and incremented with an if, else. Ben also
# showed me how to use the .update function to overwrite a dictionary.
bucket = {}
keys = []
values = []
for item in phys_len_sort:
x = (item // 100) * 100
if x in bucket:
bucket[x] += 1
else:
bucket[x] = 1
for key in bucket:
keys.append(key)
values.append(bucket[key])
print("# Contig length", "\t", "Number of contigs in this category")
for key in bucket:
print(str(key), "\t", str(bucket[key]))
plt.bar(keys, values, width=100)
plt.xlabel("# Contig length")
plt.ylabel("Number of contigs in this category")
plt.yscale("log")
plt.title("Contig Distribution, K-mer size 49, cc auto, min contig 500 bp")
plt.savefig("contigs_49_cov_cutoff_500.png")
|
Python | UTF-8 | 2,367 | 3.609375 | 4 | [] | no_license | # -*- encoding: utf-8 -*-
# Return all such possible sentences.
#
# For example, given
# s = "catsanddog",
# dict = ["cat", "cats", "and", "sand", "dog"].
#
# A solution is ["cats and dog", "cat sand dog"].
# 递归:超时
class Solution(object):
def wordBreak(self, s, wordDict):
# edge case
if len(s) == 0 or s == '':
return False
pos = 0
length = set([len(ele) for ele in wordDict])
res = []
temp = []
self.helper(s, wordDict, pos, length, res, temp)
return res
def helper(self,s, wordDict, pos,length,res,temp):
# for i in range(pos,len(s)):
if pos == len(s):
res.append(' '.join(temp[:]))
return
for le in length:
if pos+le <= len(s) and s[pos:pos+le] in wordDict:
temp.append(s[pos:pos+le])
self.helper(s, wordDict, pos+le, length,res,temp)
temp.pop()
class Solution_leet(object):
def wordBreak(self, s, wordDict):
# edge case
if len(s) == 0 or s == '':
return []
start = 0
hash = {}
length = set([len(ele) for ele in wordDict])
res = self.helper(s, wordDict, length, start, hash)
return [' '.join(temp[:]) for temp in res]
def helper(self, s, wordDict, length, start, hash):
if hash.has_key(start):
return hash[start]
res = []
for le in length:
if start + le <= len(s) and s[start:start + le] in wordDict:
list = self.helper(s, wordDict, length, start + le, hash)
if not (list == [] and start != len(s)):
for ele in list:
res.append([s[start:start + le]] + ele)
elif list == [] and start + le == len(s):
res.append([s[start:start + le]])
hash[start] = res
return res
if __name__ == '__main__':
# s = Solution_leet()
s = Solution_leet()
# x = "catsanddog"
# y = ["cat", "cats", "and", "sand", "dog"]
x = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
y = ["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"]
print s.wordBreak(x,y) |
C++ | UTF-8 | 677 | 2.65625 | 3 | [] | no_license | /******************************************************************************/
/*!
\file singletontemplate.h
\author Lee Sek Heng
\par email: 150629Z@mymail.nyp.edu.sg
\brief
A template for all classes that needs to be a singleton
*/
/******************************************************************************/
#ifndef SINGLETON_TEMPLATE_H
#define SINGLETON_TEMPLATE_H
#include "..\\Misc\\DetectMemoryLeak.h"
template<class Type>
class SingletonTemplate/*<Type>*/
{
public:
static Type &accessing() {
static Type Cant_touch_this;
return Cant_touch_this;
}
protected:
SingletonTemplate() {};
virtual ~SingletonTemplate() {};
};
#endif |
C++ | UTF-8 | 690 | 2.671875 | 3 | [] | no_license | #ifndef HEADER_BINARYKEYPAD
#define HEADER_BINARYKEYPAD
#include "Header.h"
class BinaryKeypad
{
public:
BinaryKeypad();
~BinaryKeypad();
// Mutators
void SetKeyValue(); // Calculates the value of the key pressed
void PauseUntilButtonPressed(); // Pauses until a button is pressed
void PauseUntilButtonReleased();// Pauses until a button is released
void ToggleSpecialChar(); // Toggles specialChar T/F
// Accessors
const int GetKeyValue(); // Returns value
const boolean GetSpecialChar(); // Returns specialChar
private:
int buttonArray[5];
int value;
boolean specialChar;
};
#endif
|
Java | UTF-8 | 5,380 | 2.5625 | 3 | [] | no_license | package com.zd.book.ui;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.wb.swt.SWTResourceManager;
import org.jdom.Element;
import com.zd.book.util.Weather;
public class ShowWeather {
protected Shell shell;
private Display display;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
ShowWeather window = new ShowWeather();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setFont(SWTResourceManager.getFont("楷体", 12, SWT.BOLD));
shell.setBackgroundImage(SWTResourceManager.getImage(ShowWeather.class, "/images/20091212_17370529145dbf1f8c8dCcqVWNv386KQ.jpg"));
shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION));
shell.setSize(367, 220);
shell.setLocation((display.getClientArea().width-shell.getSize().x), (display.getClientArea().height-shell.getSize().y));
shell.setImage(SWTResourceManager.getImage(ShowWeather.class, "/images/log.ico"));
shell.setText("今日天气");
shell.setLayout(null);
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
lblNewLabel.setBounds(0, 0, 351, 48);
List<Element> es = Weather.getWeather();
Map<String,Object>list =new HashMap<String,Object> ();
int count =0;
for(Element e:es){
count++;
list.put(String.valueOf(count),e.getText());
}
StringBuffer ti=new StringBuffer();
ti.append(String.valueOf(list.get("1"))+"\n");
ti.append(String.valueOf(list.get("5"))+"\n");
ti.append(String.valueOf(list.get("6"))+"\n");
lblNewLabel.setText(ti.toString());
Label label = new Label(shell, SWT.NONE);
label.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
label.setBounds(0, 48, 434, 24);
StringBuffer tis=new StringBuffer();
tis.append(String.valueOf(list.get("8"))+" ");
tis.append(String.valueOf(list.get("9"))+" ");
tis.append(String.valueOf(list.get("10"))+" ");
label.setText(tis.toString());
Label lblNewLabel_1 = new Label(shell, SWT.NONE);
lblNewLabel_1.setImage(SWTResourceManager.getImage(ShowWeather.class, "/weather/"+String.valueOf(list.get("11"))));
lblNewLabel_1.setBounds(25, 72, 20, 20);
Label lblNewLabel_2 = new Label(shell, SWT.NONE);
lblNewLabel_2.setImage(SWTResourceManager.getImage(ShowWeather.class, "/weather/"+String.valueOf(list.get("12"))));
lblNewLabel_2.setBounds(110, 72, 20, 20);
//下一天
Label label_1 = new Label(shell, SWT.NONE);
label_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
label_1.setBounds(0, 92, 351, 17);
StringBuffer tiss=new StringBuffer();
tiss.append(String.valueOf(list.get("13"))+" ");
tiss.append(String.valueOf(list.get("14"))+" ");
tiss.append(String.valueOf(list.get("15"))+" ");
label_1.setText(tiss.toString());
Label lblNewLabel_3 = new Label(shell, SWT.NONE);
lblNewLabel_3.setBounds(25, 109, 20, 20);
lblNewLabel_3.setImage(SWTResourceManager.getImage(ShowWeather.class, "/weather/"+String.valueOf(list.get("16"))));
Label lblNewLabel_4 = new Label(shell, SWT.NONE);
lblNewLabel_4.setBounds(110, 109, 20, 20);
lblNewLabel_4.setImage(SWTResourceManager.getImage(ShowWeather.class, "/weather/"+String.valueOf(list.get("17"))));
Label lblNewLabel_5 = new Label(shell, SWT.NONE);
lblNewLabel_5.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
lblNewLabel_5.setBounds(0, 129, 351, 17);
//下下天
StringBuffer tisss=new StringBuffer();
tisss.append(String.valueOf(list.get("18"))+" ");
tisss.append(String.valueOf(list.get("19"))+" ");
tisss.append(String.valueOf(list.get("20"))+" ");
lblNewLabel_5.setText(tisss.toString());
Label lblNewLabel_6 = new Label(shell, SWT.NONE);
lblNewLabel_6.setBounds(25, 146, 20, 20);
lblNewLabel_6.setImage(SWTResourceManager.getImage(ShowWeather.class, "/weather/"+String.valueOf(list.get("21"))));
Label lblNewLabel_7 = new Label(shell, SWT.NONE);
lblNewLabel_7.setBounds(110, 152, 20, 20);
lblNewLabel_7.setText("");
lblNewLabel_7.setImage(SWTResourceManager.getImage(ShowWeather.class, "/weather/"+String.valueOf(list.get("22"))));
over();
}
public void over(){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
display.syncExec(new Runnable(){
@Override
public void run() {
shell.dispose();
}
});
}
},10000);
}
}
|
Rust | UTF-8 | 1,875 | 2.515625 | 3 | [
"MIT"
] | permissive | use std::net;
use std::path::PathBuf;
use argh::FromArgs;
use nakamoto_client::Network;
use nakamoto_node::{logger, Domain};
#[derive(FromArgs)]
/// A Bitcoin light client.
pub struct Options {
/// connect to the specified peers only
#[argh(option)]
pub connect: Vec<net::SocketAddr>,
/// listen on one of these addresses for peer connections.
#[argh(option)]
pub listen: Vec<net::SocketAddr>,
/// use the bitcoin test network (default: false)
#[argh(switch)]
pub testnet: bool,
/// use the bitcoin signet network (default: false)
#[argh(switch)]
pub signet: bool,
/// only connect to IPv4 addresses (default: false)
#[argh(switch, short = '4')]
pub ipv4: bool,
/// only connect to IPv6 addresses (default: false)
#[argh(switch, short = '6')]
pub ipv6: bool,
/// log level (default: info)
#[argh(option, default = "log::Level::Info")]
pub log: log::Level,
/// root directory for nakamoto files (default: ~)
#[argh(option)]
pub root: Option<PathBuf>,
}
impl Options {
pub fn from_env() -> Self {
argh::from_env()
}
}
fn main() {
let opts = Options::from_env();
logger::init(opts.log).expect("initializing logger for the first time");
let network = if opts.testnet {
Network::Testnet
} else if opts.signet {
Network::Signet
} else {
Network::Mainnet
};
let domains = if opts.ipv4 && opts.ipv6 {
vec![Domain::IPV4, Domain::IPV6]
} else if opts.ipv4 {
vec![Domain::IPV4]
} else if opts.ipv6 {
vec![Domain::IPV6]
} else {
vec![Domain::IPV4, Domain::IPV6]
};
if let Err(e) = nakamoto_node::run(&opts.connect, &opts.listen, opts.root, &domains, network) {
log::error!(target: "node", "Exiting: {}", e);
std::process::exit(1);
}
}
|
C# | UTF-8 | 1,861 | 2.703125 | 3 | [
"MIT"
] | permissive | using AutoMapper;
using ECommerce.Domain.Entities;
using ECommerce.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Ecommerce.Application.Categories
{
public class CategoryService : ICategoryService
{
private readonly ICategoryRepository _categoryRepository;
private readonly IMapper _mapper;
public CategoryService(ICategoryRepository categoryRepository, IMapper mapper)
{
_categoryRepository = categoryRepository;
_mapper = mapper;
}
public Task Add(CategoryDto categoryDto)
{
return _categoryRepository.Add(_mapper.Map<Category>(categoryDto));
}
public async Task Delete(int id)
{
var result = await _categoryRepository.GetByIdAsync(id);
await _categoryRepository.Delete(result);
}
public async Task<List<CategoryDto>> Get(Expression<Func<CategoryDto,bool>> filter)
{
var dtoFilter = _mapper.Map<Expression<Func<Category, bool>>>(filter);
var result = await _categoryRepository.Get(dtoFilter);
return _mapper.Map<List<CategoryDto>>(result);
}
public async Task<List<CategoryDto>> GetAll()
{
var result = await _categoryRepository.GetAll();
return _mapper.Map<List<CategoryDto>>(result);
}
public async Task<CategoryDto> GetById(int id)
{
var result = await _categoryRepository.GetByIdAsync(id);
return _mapper.Map<CategoryDto>(result); ;
}
public Task Update(CategoryDto categoryDto)
{
return _categoryRepository.Update(_mapper.Map<Category>(categoryDto));
}
}
}
|
Python | UTF-8 | 422 | 2.796875 | 3 | [] | no_license | import re
from ..utils import format_next
entrance_regex = r"^G(\d):(\d+)-(\d+);([CRS]\d+)$"
def is_entrance(str):
return re.search(entrance_regex, str)
def generate_entrance(raw):
groups = re.search(entrance_regex, raw).groups()
return {
"type": "entrance",
"id": int(groups[0]),
"min": int(groups[1]),
"max": int(groups[2]),
"next": format_next(groups[3]),
}
|
Python | UTF-8 | 1,170 | 2.71875 | 3 | [] | no_license | import requests
import os
import time
os.system('clear')
print('\033[01;35mSeja Bem Vindo Consulta IP By:OdinModder ϟ')
print('\033[01;36m=========================================')
ip = input('\033[01;34m>>> ')
r = requests.get('http://ip-api.com/json/{}'.format(ip));data = r.json( )
print('\033[01;33mConsulta Realizada!!')
print( )
print("IP: {}".format(data['query']))
print("Status: {}".format(data['status']))
print("País: {}".format(data['country']))
print("Código_País: {}".format(data['countryCode']))
print("Código_Região: {}".format(data['region']))
print("Nome_Região: {}".format(data['regionName']))
print("Cidade: {}".format(data['city']))
print("Zip: {}".format(data['zip']))
print("Lat: {}".format(data['lat']))
print("Lon: {}".format(data['lon']))
print("TimeZone: {}".format(data['timezone']))
print("Isp: {}".format(data['isp']))
print("Org: {}".format(data['org']))
print("As: {}".format(data['as']))
print("\033[01;32mby:OdinModder ϟ\n")
back = str(input("\n\033[0mnova consulta?[\033[32mS\033[0m/\033[31mN\033[0m]: "))
while back == "s" or back == "S":
back = str(input("\n\033[0mnova consulta?[\033[32mS\033[0m/\033[31mN\033[0m]: ")) |
C++ | UTF-8 | 5,185 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long N, M, Q, grid[1010][1010];
long long sums[1010][1010];
int find(int x, int y) {
if (x <= N && y <= M)
return grid[x - 1][y - 1];
long long p = N, q = M;
while (p * 2 < x || q * 2 < y) p *= 2, q *= 2;
if (p < x && q < y)
return find(x - p, y - q);
else if (p < x)
return 1 - find(x - p, y);
else
return 1 - find(x, y - q);
}
pair<int, int> togn(int x, int y) {
int r = (x + N - 1) / N;
int c = (y + M - 1) / M;
return {r, c};
}
long long subSum(int x, int y) {
if (x == 1 && y == 1) return 1;
long long p = 1;
while (p * 2 <= x && p * 2 <= y) p *= 2;
if (p == 1) {
p = 1;
while (p * 2 < x || p * 2 < y) p *= 2;
long long ans = (x == 1 ? y - p : x - p) - subSum(x == 1 ? 1 : x - p, y == 1 ? 1 : y - p) + (p == 1 ? 1 : (p / 2));
return ans;
}
long long ans = 0;
if (x > p && y > p)
ans += subSum(x - p, y - p);
ans += p / 2 * p;
ans += p / 2 * (x - p);
ans += p / 2 * (y - p);
return ans;
}
long long sumRow(int y) {
return subSum(1, y);
}
long long matSum(int x1, int y1, int x2, int y2) {
long long ans = subSum(x2, y2);
if (y1 > 1)
ans -= subSum(x2, y1 - 1);
if (x1 > 1)
ans -= subSum(x1 - 1, y2);
if (x1 > 1 && y1 > 1)
ans += subSum(x1 - 1, y1 - 1);
return ans;
}
long long totSum(long long x, long long y) {
if (x == 0 || y == 0) return 0;
if (x <= N && y <= M)
return sums[x - 1][y - 1];
if (x <= N || y <= M) {
long long times = max(x / N, y / M);
long long pos = sumRow(times);
long long neg = times - pos;
long long psum = sums[min(N, x) - 1][min(M, y) - 1];
long long npsum = min(N, x) * min(M, y) - psum;
long long ans = pos * psum + neg * npsum;
if (x <= N) {
if (sumRow(times + 1) - pos)
ans += totSum(x, y - M * times);
else
ans += (y - M * times) * x - totSum(x, y - M * times);
}
else {
if (sumRow(times + 1) - pos)
ans += totSum(x - N * times, y);
else
ans += (x - N * times) * y - totSum(x - N * times, y);
}
return ans;
}
long long p = N, q = M;
while (p * 2 <= x && q * 2 <= y) p *= 2, q *= 2;
long long ans = 0;
// add full grids
long long times = 0;
if (x / N < y / M) times = y / q;
else times = x / p;
long long pos = sumRow(times);
long long neg = times - pos;
long long psum = sums[N - 1][M - 1] * (p / 2 * q) + (N * M - sums[N - 1][M - 1]) * (p / 2 * q);
ans += psum * pos + (p * q - psum) * neg;
// add bottom right corner
if (x / N < y / M) ans += totSum(x - p, y - q * times);
else ans += totSum(x - p * times, y - q);
// add sides
if (x / N < y / M) {
ans += sums[N - 1][(y - q * times) - 1];
psum = sums[(x - p) - 1][M - 1];
ans += neg * psum + ((x - p) * M - psum) * pos;
}
else {
ans += sums[(x - p * times) - 1][M - 1];
psum = sums[N - 1][(y - q) - 1];
ans += neg * psum + ((y - q) * N - psum) * pos;
}
return ans;
}
long long newSum(long long x, long long y) {
long long rows = x / N;
long long prowsum = totSum(N, y);
long long nprowsum = N * y - prowsum;
long long pos = 0;
if (rows)
pos = sumRow(rows);
long long neg = rows - pos;
long long ans = prowsum * pos + nprowsum * neg;
if (x - rows * N) {
if (sumRow(rows + 1) - pos)
ans += totSum(x - rows * N, y);
else
ans += (x - rows * N) * y - totSum(x - rows * N, y);
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
// input
cin >> N >> M >> Q;
for (int i = 0; i < N; i++) {
string tmp; cin >> tmp;
for (int j = 0; j < M; j++)
grid[i][j] = tmp[j] - '0';
}
// calculate submatrix sums
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (i == 0 && j == 0) sums[i][j] = grid[i][j];
else if (i == 0) sums[i][j] = grid[i][j] + sums[i][j - 1];
else if (j == 0) sums[i][j] = grid[i][j] + sums[i - 1][j];
else sums[i][j] = grid[i][j] + sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1];
}
}
/*
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
long long sum = 0;
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= j; b++) {
sum += find(a + 1, b + 1);
}
}
if (sum != newSum(i + 1, j + 1)) {
throw runtime_error("Foo!");
}
}
}
*/
for (int i = 0; i < Q; i++) {
int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;
long long ans = newSum(x2, y2);
if (x1 > 1) ans -= newSum(x1 - 1, y2);
if (y1 > 1) ans -= newSum(x2, y1 - 1);
if (x1 > 1 && y1 > 1) ans += newSum(x1 - 1, y1 - 1);
cout << ans << "\n";
}
return 0;
}
|
Markdown | UTF-8 | 1,437 | 2.9375 | 3 | [] | no_license | # Article 3
Les épreuves écrites d'admissibilité sont les suivantes :
1° Une composition portant sur un sujet d'ordre général relatif aux problèmes politiques, économiques, culturels et sociaux du monde contemporain permettant de vérifier les qualités de rédaction, d'analyse et de réflexion du candidat (durée : quatre heures ; coefficient 4) ;
2° Une épreuve constituée d'une série de dix à quinze questions à réponse courte, portant sur des éléments essentiels du droit public, des questions européennes, des finances publiques et de l'économie (durée : trois heures ; coefficient 5, dont coefficient 2,5 pour le droit public et les questions européennes et coefficient 2,5 pour les finances publiques et l'économie) ;
3° Une épreuve portant, au choix du candidat, sur l'une des matières suivantes, ce choix étant effectué au moment de l'inscription au concours (durée : trois heures ; coefficient 3) :
a) Droit civil ;
b) Droit du travail ;
c) Gestion des ressources humaines ;
d) Gestion comptable et financière des entreprises ;
e) Géographie humaine, économique et régionale en France et en Europe.
L'épreuve consiste en une note de synthèse, un cas pratique ou une explication de documents à partir d'un dossier documentaire de vingt-cinq pages au maximum.
Les programmes de la deuxième et de la troisième épreuve écrite d'admissibilité sont annexés au présent arrêté.
|
Java | UTF-8 | 1,074 | 3.0625 | 3 | [] | no_license | /*
* Copyright 2020. Androsaces. All rights reserved.
*/
package com.androsaces.javaessentials.issue252;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;
public class YearSpliterator implements Spliterator<LocalDate> {
private LocalDate date;
public YearSpliterator(LocalDate startDate) {
this.date = startDate;
}
@Override
public long estimateSize() {
return Long.MAX_VALUE;
}
@Override
public boolean tryAdvance(Consumer<? super LocalDate> action) {
Objects.requireNonNull(action);
action.accept(date);
date = date.minusYears(1);
return true;
}
@Override
public Spliterator<LocalDate> trySplit() {
return null;
}
@Override
public int characteristics() {
return DISTINCT | IMMUTABLE | NONNULL | ORDERED | SORTED;
}
@Override
public Comparator<? super LocalDate> getComparator() {
return Comparator.reverseOrder();
}
}
|
TypeScript | UTF-8 | 442 | 3.5 | 4 | [] | no_license | /**
* @param {string} str
* @param {number} precision
* @returns {string} trimmed string
* @example trimStringDecimals("0.12345", 2); // "0.12"
*/
export const trimStringDecimals = (str: string, precision: number) => {
if (!str || !str.includes(".")) {
return str;
}
const [integer, decimals] = str.split(".");
if (decimals.length <= precision) {
return str;
}
return `${integer}.${decimals.slice(0, precision)}`;
};
|
JavaScript | UTF-8 | 3,556 | 2.546875 | 3 | [
"MIT"
] | permissive | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserModel = require('./UserModel')
const validateShortName = require('../lib/validateShortName')
function toLower(v) {
return v.toLowerCase().split(' ').join('');
}
const MenuSchema = new Schema({
propietario: {
type: Schema.Types.ObjectId,
required: true,
ref: 'user',
validate: {
isAsync: true,
validator: function (v, cb) {
UserModel.findById(v, 'max_menus menus', function (err, usuario) {
if (err) {
cb(err, false)
} else {
/*if (usuario.Menus == undefined) {
cb(true)
} else */ if (!(usuario.Menus.length >= usuario.max_menus)) {
cb(true)
} else {
cb(null, false)
}
}
})
},
message: 'Usuario no es válido, o llegó a su límite de menus por crear.'
},
autopopulate: {
maxDepth: 1
}
},
Categorias: [{
type: Schema.Types.ObjectId,
required: false,
ref: 'categoria',
autopopulate: {
maxDepth: 1
}
}],
Platillos: [{
type: Schema.Types.ObjectId,
required: false,
ref: 'platillo',
autopopulate: {
maxDepth: 1
}
}],
/** Nombre del Menú */
nombre: {
type: String,
required: [true, 'Valor necesario: nombre']
},
/** Descricíón del menú */
descripcion: {
type: String,
required: false
},
/** Logo dl Menú */
logo: {
type: Schema.Types.Mixed,
required: false,
default: null
},
/** Imagen del Menu */
imagen: {
type: Schema.Types.Mixed,
required: false,
default: null
},
/** Datos de la URL corta
* Este dato se usará para la creación del la URL corta. La URL quedaría de esta forma.:
* https:/mevouapp.com/m/shortnametext
* No debe llevar carateres espaciales. Solo letras en minusculas y numeros
*
*/
shortname: {
type: String,
required: [true, "Valor Necesario: shortname"],
unique: true,
validate: {
validator: function (v) {
return validateShortName(v)
},
message: 'El valor shortname debe incluir solo números, letras minúsculas o punto.'
},
set: toLower
},
/** Color de Fondo del menú */
color_menu_fondo: {
type: String,
required: false,
default: '#FFFFFF'
},
color_menu_letra: {
type: String,
required: false,
default: '#000000'
},
color_plato_nombre_letra: {
type: String,
required: false,
default: '#FFFFFF'
},
color_plato_nombre_fondo: {
type: String,
required: false,
default: '#000000'
},
color_plato_desc_letra: {
type: String,
required: false,
default: '#000000'
},
color_plato_desc_fondo: {
type: String,
required: false,
default: '#FFFFFF'
},
}, {
strict: true
})
MenuSchema.pre('save', function(next){
this.shortname = String(this.shortname).toLowerCase()
next()
})
MenuSchema.post('save', function (doc) {
UserModel.findByIdAndUpdate(doc.propietario, {
$addToSet: {
Menus: doc._id
}
}, {
new: true
}, function (err, usuarioActualizado) {
if (err) {
console.log('Error el menú a al Usuario.', err)
} else {
console.log(`'Menu ${doc.nombre} : ${doc._id} Agregada con éxito al usuario: ${usuarioActualizado.username}:${usuarioActualizado._id}`)
}
})
})
MenuSchema.plugin(require('mongoose-autopopulate'))
const MenuModel = mongoose.model('menu', MenuSchema)
module.exports = MenuModel |
Java | UTF-8 | 1,305 | 2.359375 | 2 | [] | no_license | package dream.orientation.model;
import javax.persistence.Entity;
import java.io.Serializable;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.Version;
import java.lang.Override;
import dream.orientation.enumeration.originRegion;
import dream.orientation.lib.AbstractIdentif;
import dream.orientation.lib.Locality;
import javax.persistence.Enumerated;
@Entity
public class School extends AbstractIdentif
{
@Column(nullable = false)
private String name;
@Enumerated
private Locality locality;
@Column
private String type;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
@Override
public String toString()
{
String result = getClass().getSimpleName() + " ";
if (name != null && !name.trim().isEmpty())
result += "name: " + name;
if (locality != null)
result += ", locality: " + locality;
if (type != null && !type.trim().isEmpty())
result += ", type: " + type;
return result;
}
} |
Java | UTF-8 | 1,057 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package sample.weather;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by yasuhiro on 2015/01/24.
*/
@RestController
public class WeatherController {
private static final Logger logger = LoggerFactory.getLogger(WeatherController.class);
private static final Integer DAYS_WEEK = 7;
@Autowired
private OpenWeatherClient openWeatherClient;
@RequestMapping("/weather")
public Object weather( @RequestParam String city ) {
logger.info("weather requested : " + city);
return openWeatherClient.getCityWeather(city);
}
@RequestMapping("/forecast")
public Object forecast( @RequestParam String cityId ) {
logger.info("forecast requested : city={}, days={}", cityId, DAYS_WEEK);
return openWeatherClient.getForecastByCityId(cityId, DAYS_WEEK);
}
}
|
Ruby | UTF-8 | 1,738 | 2.609375 | 3 | [] | no_license | class Customer
attr_reader :id, :first_name, :last_name,
:created_at, :updated_at, :customer_repository, :fields
def initialize(input_data, customer_repository)
@id = input_data[0].to_i
@first_name = input_data[1]
@last_name = input_data[2]
@created_at = input_data[3]
@updated_at = input_data[4]
@customer_repository = customer_repository
@fields = [:id, :first_name, :last_name,
:created_at, :updated_at]
end
def invoices
@customer_repository.se.invoice_repository.find_all_by_customer_id(id)
end
def transactions
customer_transactions = []
invoices.each do |invoice|
transaction_repository = @customer_repository.se.transaction_repository
transaction = transaction_repository.find_all_by_invoice_id(invoice.id)
customer_transactions << transaction
end
end
def invoices
@customer_repository.se.invoice_repository.find_all_by_customer_id(id)
end
def transactions
customer_transactions = []
invoices.each do |invoice|
transaction_repository = @customer_repository.se.transaction_repository
transaction = transaction_repository.find_all_by_invoice_id(invoice.id)
customer_transactions << transaction
end
customer_transactions.flatten
end
def favorite_merchant
merchants = Hash.new(0)
invoices.each do |invoice|
if invoice.successful?
merchant_repository = customer_repository.se.merchant_repository
merchant = merchant_repository.find_by(:id, invoice.merchant_id)
merchants[merchant] += 1
end
end
return nil if merchants.empty?
merchants.sort_by{|merchant, count| count}.reverse[0][0]
end
end
|
Java | UTF-8 | 883 | 1.898438 | 2 | [] | no_license | package com.digihealth.sysMng.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.digihealth.common.formbean.SystemSearchFormBean;
import com.digihealth.sysMng.dao.BasUserDao;
import com.digihealth.sysMng.entity.BasUser;
@Service
public class BasUserService {
@Autowired
private BasUserDao basUserDao;
public BasUser selectByPrimaryKey(String userName) {
return basUserDao.selectByPrimaryKey(userName);
}
public BasUser verifyUser(BasUser user) {
return basUserDao.verifyUser(user);
}
public List<BasUser> getAllUser(SystemSearchFormBean formBean) {
return basUserDao.getAllUser(formBean);
}
public void updateByPrimaryKey(BasUser user) {
basUserDao.updateByPrimaryKey(user);
}
public int getTotalAllUser() {
return basUserDao.getTotalAllUser();
}
}
|
Java | UTF-8 | 256 | 1.578125 | 2 | [] | no_license | package com.serdariince.hrms.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import com.serdariince.hrms.entities.conretes.SystemAdmin;
public interface SystemAdminDao extends JpaRepository<SystemAdmin, Integer> {
}
|
Java | UTF-8 | 2,908 | 2.546875 | 3 | [] | no_license | package com.xt.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author 杨卫兵
* @version V1.00
* @date 2020/11/25 10:38
* @since V1.00
*/
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
if(ServletFileUpload.isMultipartContent(req)){
ServletFileUpload upload=new ServletFileUpload(
new DiskFileItemFactory()
);
try {
List<FileItem> items=upload.parseRequest(req);
for(int i=0;items!=null && i<items.size();i++){
FileItem item=items.get(i);
if(item.isFormField()){
if(item.getFieldName().equals("desc")) {
req.setAttribute("desc",
item.getString("UTF-8"));
}
}
else{
ServletContext ctx=getServletContext();
String path=ctx.getRealPath("/imgs");
File filePath=new File(path);
if(!filePath.exists()){
filePath.mkdirs();
}
File target=new File(filePath,item.getName());
item.write(target);
req.setAttribute("imgSrc","imgs/"+item.getName());
}
}
req.setAttribute("msg","ok");
} catch (Exception e) {
e.printStackTrace();
}
}
else{
req.setAttribute("msg","不是文件上传");
}
req.getRequestDispatcher("/WEB-INF/pages/result.jsp").forward(req,resp);
}
/**
* InputStream is=null;
* try{
* is=req.getInputStream();
* byte []bts=new byte[1000];
* int cnt=0;
* while((cnt=is.read(bts))!=-1){
* String str=new String(bts,0,cnt);
* System.out.print(str);
* }
* }
* catch (Exception ex){
* System.out.println(ex);
* }
* finally {
* is.close();
* }
*
*/
}
|
Java | UTF-8 | 2,106 | 2.71875 | 3 | [] | no_license | package org.serverwizard.reactor;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.util.Objects;
class TransformTest {
@DisplayName("Mono에서 map operator 사용법을 확인한다.")
@Test
void monoMapTest() {
StepVerifier.create(Mono.just(new User("serverwizard"))
.map(u -> new User(u.getName().toUpperCase())))
.expectNext(new User("SERVERWIZARD"))
.verifyComplete();
}
@DisplayName("Flux에서 map operator 사용법을 확인한다.")
@Test
void fluxMapTest() {
StepVerifier.create(Flux.just(new User("serverwizard"))
.map(u -> new User(u.getName().toUpperCase())))
.expectNext(new User("SERVERWIZARD"))
.verifyComplete();
}
@DisplayName("Flux에서 flatMap operator 사용법을 확인한다.")
@Test
void fluxFlatMapTest() {
StepVerifier.create(Flux.just(new User("serverwizard"), new User("jwh"))
.flatMap(u -> Flux.just(new User(u.getName().toUpperCase())))
.log())
.expectNext(new User("SERVERWIZARD"))
.expectNext(new User("JWH"))
.verifyComplete();
}
private class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
}
|
C | UTF-8 | 578 | 2.921875 | 3 | [] | no_license | void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
int numIndex1 = m - 1;
int numIndex2 = n - 1;
int tmp = m + n - 1;
while (numIndex1 >= 0 && numIndex2 >= 0) {
if (nums1[numIndex1] >= nums2[numIndex2]) {
nums1[tmp] = nums1[numIndex1];
tmp--;
numIndex1--;
} else {
nums1[tmp] = nums2[numIndex2];
tmp--;
numIndex2--;
}
}
while (numIndex2 >= 0) {
nums1[tmp] = nums2[numIndex2];
tmp--;
numIndex2--;
}
}
|
C# | UTF-8 | 578 | 2.5625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tehtävä04
{
class Program
{
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle(); // uusi ajoneuvo
// ajoneuvon tiedot kirjataan tässä
vehicle.Name = "Nissan GT-R";
vehicle.Tyres = "Pirelli P Zero, Front: 255/40ZR20 | Rear: 285/35ZR20";
vehicle.Speed = "315 km/h";
vehicle.PrintData();
// vehicle.tostring();
}
}
}
|
Python | UTF-8 | 137 | 3.859375 | 4 | [
"MIT"
] | permissive | def fibonacci(num):
return num if num <= 1 else fibonacci(num - 1) + fibonacci(num - 2)
for i in range(10):
print(fibonacci(i))
|
Python | UTF-8 | 876 | 3.375 | 3 | [] | no_license |
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
INF = int(1e9)
# 모든 vertex 쌍의 v1 -> v2 최단경로 담는 array
distance = [[INF]*(n+1) for _ in range(n+1)]
for i in range(1, n+1):
distance[i][i] = 0
# append edges
for _ in range(m):
a, b = map(int,input().split())
distance[a][b] = 1
distance[b][a] = 1
# apply floyd warshall algorithm
for k in range(1, n+1):
for i in range(1, n+1):
for j in range(1, n+1):
distance[i][j] = min(distance[i][j], distance[i][k]+distance[k][j])
min_val = INF
result = 0
for i in range(1, n+1):
bacon = 0
# 모든 vertices에 대해서
# i -> vertex 최단거리 합 구하기
for j in range(1, n+1):
bacon += distance[i][j]
# bacon 최솟값 구하기
if min_val > bacon:
result = i
min_val = bacon
print(result) |
C | UTF-8 | 1,704 | 3.78125 | 4 | [] | no_license | #include "vectores.h"
//// FUNCIONES PARA TRABAJAR CON VECTORES //////////////////////////////////
void imprimir_vector(float **v, size_t filas, size_t columnas){
size_t i, j;
for(i=0; i<filas; i++){
for(j=0; j<columnas; j++)
printf("% 7f\t", v[i][j]);
printf("\n");
}
}
void destruir_vector(float **v, size_t n){
for(size_t i = 0; i < n; i++)
free(v[i]);
free(v);
}
float **crear_vector(size_t n){
float **v = NULL;
size_t j;
v = malloc(n * sizeof(float *));
if(v == NULL){
return NULL;
}
for(j = 0; j < n; j++){
v[j] = malloc(COLUMNAS * sizeof(float));
if(v[j] == NULL){
destruir_vector(v, j);
return NULL;
}
}
return v;
}
void copiar_matriz_a_vector(const float m[][COLUMNAS], float **v, size_t n){
size_t i,j;
for(i = 0; i < n; i++){
for(j = 0; j < COLUMNAS; j++)
v[i][j] = m[i][j];
}
}
float **matriz_a_vector(const float m[][COLUMNAS], size_t n){
float **vector = NULL;
//Se uso la funcion de crear_vector porque al ingresar un vector nulo, el realloc funciona como un malloc.
if(!(vector = crear_vector(n)))
return NULL;
copiar_matriz_a_vector(m, vector, n);
return vector;
}
void copiar_valores_a_vector(float **v1, float **v2, size_t filas){
size_t i,j;
for(i = 0; i < filas; i++){
for(j = 0; j < COLUMNAS; j++)
v1[i][j] = v2[i][j];
}
}
void swap(float *v1,float *v2){
float aux = 0;
aux = *v1;
*v1 = *v2;
*v2 = aux;
}
void ordenar_v(float **v, size_t nn){
size_t i, cambios = 0;
do{
cambios = 0;
for (i = 0; i < nn-1; i++){
if(v[i][0] > v[i+1][0]){
swap(&v[i][0], &v[i+1][0]);
swap(&v[i][1], &v[i+1][1]);
cambios ++;
}
}
}while(cambios!=0);
}
|
Python | UTF-8 | 4,219 | 3.078125 | 3 | [] | no_license | """
This is a vanilla neural network, written from scratch by me. I adapted this from a series of blog posts on neural networks:
http://iamtrask.github.io/2015/07/12/basic-python-network/
You'll notice that this network is a generalization of the one found in the above blog post
How to use:
Example:
num_hidden_nodes = 5
X = np.array([[1,1],
[1,0],
[0,1],
[0,0]])
y = np.array([[0],[1],[1],[1]])
run_once(num_hidden_nodes,X,y)
The above example creates a neural network with 5 hidden nodes, X is the indepent variables, where is y the dependent variables.
Note these are matrices - meaning I'm assuming a multi-dimensional array
If you run this example from the command line:
python back_prop.py
it will run the the run once method.
"""
import numpy as np
import copy
from tools import *
from functools import partial
from hackthederivative import complex_step_finite_diff as deriv
import inspect
import functions
from functions import *
def create_connection(num_rows,num_cols):
return 2*np.random.random((num_rows,num_cols)) -1
def create_nn(input_data,output_data,num_hidden_layers):
nn = [{"name":"input data","connection":input_data}]
#input layer
input_syn = {"name":"input layer"}
input_syn["connection"] = create_connection(len(input_data[0]),len(input_data))
nn.append(input_syn)
#hidden layers
for i in xrange(num_hidden_layers):
syn = {"name":i}
syn["connection"] = create_connection(len(input_data),len(input_data))
nn.append(syn)
#output_layer
syn = {"name":"output layer"}
syn["connection"] = create_connection(len(output_data),len(output_data[0]))
nn.append(syn)
nn.append({"name":"output data","connection":output_data})
return nn
def forward_propagate(synapses,f):
layers = [synapses[0]["connection"]]
for ind,synapse in enumerate(synapses[:-1]):
if ind == 0: continue
layers.append(
f(np.dot(layers[ind-1],synapse["connection"]))
)
return layers
def back_propagate(layers,synapses,f):
df = partial(deriv,f)
errors = [synapses[-1]["connection"] - layers[-1]]
synapses_index = -1
layers_index = -1
errors_index = 0
deltas_index = 0
deltas = []
while len(layers) - abs(layers_index) > 0:
deltas.append(errors[errors_index]*df(layers[layers_index]))
synapses_index -= 1
layers_index -= 1
errors.append(deltas[deltas_index].dot(synapses[synapses_index]["connection"].T))
errors_index += 1
deltas_index += 1
synapses_index = -2
layers_index = -2
deltas_index = 0
while len(layers) - abs(layers_index) >= 0:
synapses[synapses_index]["connection"] += layers[layers_index].T.dot(deltas[deltas_index])
synapses_index -= 1
layers_index -= 1
deltas_index += 1
return synapses,errors[0]
def run_once(num_hidden_nodes,X,y,f):
np.random.seed(1)
errors = []
nn = create_nn(X,y,num_hidden_nodes)
for j in xrange(70000):
layers = forward_propagate(nn,f)
nn,error = back_propagate(layers,nn,f)
if j%10000 == 0:
errors.append(np.mean(np.abs(error)))
return errors
def get_functions():
dicter = globals()
x = [elem for elem in dir(functions) if not "__" in elem]
return {elem:dicter[elem] for elem in x}
if __name__ == '__main__':
funcs = get_functions()
#tune(11)
X = np.array([[1,1],[1,0],[0,1],[0,0]])
y = np.array([[0],[1],[1],[1]])
n = 10
funcs = get_functions()
for i in xrange(0,n):
for func_name in funcs.keys():
errors = run_once(i,X,y,funcs[func_name])
print funcs[func_name]
print "The minimum error for the this network was",min(errors)
print "The average error for the this network was",sum(errors)/float(len(errors))
# print inspect.getsourcelines(funcs[j])[0][-1].strip()
#inflection_points,num_inflection_points = find_inflection_points(errors)
#print "These were the inflection points for ",i
#print "There were",num_inflection_points,"in total"
|
Python | UTF-8 | 806 | 3.71875 | 4 | [] | no_license | # *args - словарь,*kwargs - список
def min(*args, **kwargs):
key = kwargs.get("key", None)
print(args)
return None
def max(*args, **kwargs):
key = kwargs.get("key", None)
print(len(args))
if args[0] is str:
print("args is string")
else:
"no"
maximum = args[0]
print(maximum)
for i in range(len(args)):
if (args[i] > maximum):
maximum = args[i]
return maximum
print(max("hello"))
# assert max(3, 2) == 3, "Simple case max"
# assert min(3, 2) == 2, "Simple case min"
# assert max([1, 2, 0, 3, 4]) == 4, "From a list"
# assert min("hello") == "e", "From string"
# assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items"
# assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
|
C++ | UTF-8 | 3,518 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstring>
#include <algorithm>
const int maxn = 100001, maxm = 10001;
int n, m, q, sqn, a[maxn], b[maxn], pos[maxn];
struct Block {
int pre, nxt;
int sta, len;
bool rev;
void access() {
if(rev) {
int *A = a + sta;
std::reverse(A, A + len);
rev = 0;
}
}
void sort() {
int *A = a + sta, *B = b + sta;
memcpy(B, A, len * sizeof(int));
std::sort(B, B + len);
}
int query(int L, int R, int val) {
access();
int *A = a + sta, ret = 0;
for( ; L < R; ret += A[L++] < val);
return ret;
}
int query(int val) {
int *B = b + sta;
return std::lower_bound(B, B + len, val) - B;
}
} f[maxm];
void update(int idx, int sta, int len) {
int *P = pos + sta;
for(int i = 0; i < len; ++i)
P[i] = idx;
}
void rebuild(bool fir = 0) { // f[0] (left) <-> ... <-> f[1] (right)
if(!fir) {
for(int i = f[0].nxt, idx = 0; i != 1; i = f[i].nxt) {
f[i].access();
memcpy(b + idx, a + f[i].sta, f[i].len * sizeof(int));
idx += f[i].len;
}
memcpy(a, b, n * sizeof(int));
}
m = 2;
f[0] = (Block){0, 1, 0, 0, 0};
f[1] = (Block){0, 1, n, 0, 0};
for(int i = 0; i < n; i += sqn) {
int sta = i, len = std::min(sqn, n - i);
f[m] = (Block){f[1].pre, 1, sta, len, 0};
f[f[1].pre].nxt = m;
f[1].pre = m;
update(m, sta, len);
f[m++].sort();
}
}
void split(int idx, int sz) {
f[m].pre = idx;
f[m].nxt = f[idx].nxt;
f[f[idx].nxt].pre = m;
f[idx].nxt = m;
f[idx].access();
f[m].sta = f[idx].sta + sz;
f[m].len = f[idx].len - sz;
update(m, f[m].sta, f[m].len);
f[idx].len = sz;
f[idx].sort();
f[m++].sort();
}
void align(int L, int R) {
int pL = pos[L];
if(f[pL].sta < L)
split(pL, L - f[pL].sta);
int pR = pos[R];
if(R - f[pR].sta + 1 < f[pR].len)
split(pR, R - f[pR].sta + 1);
}
void convert(int &L, int &R) { // order -> index
int cnt = 0;
bool fL = 0;
for(int i = f[0].nxt; i != 1; i = f[i].nxt) {
cnt += f[i].len;
if(!fL && L <= cnt) {
L = f[i].sta + f[i].len - 1 - (cnt - L);
fL = 1;
}
if(R <= cnt) {
R = f[i].sta + f[i].len - 1 - (cnt - R);
break;
}
}
}
int main() {
while(scanf("%d", &n) == 1) {
for(sqn = 1; sqn * sqn <= n << 2; ++sqn);
for(int i = 0; i < n; ++i)
scanf("%d", a + i);
rebuild(1);
scanf("%d", &q);
while(q--) {
char op[9];
scanf("%s", op);
if(op[0] == 'R') {
int L, R;
scanf("%d%d", &L, &R);
convert(L, R);
align(L, R);
for(int pL = pos[L], pR = f[pos[R]].nxt; pL != pR; pL = f[pL].pre) {
f[pL].rev = !f[pL].rev;
std::swap(f[pL].pre, f[pL].nxt);
}
std::swap(f[f[pos[L]].nxt].nxt, f[f[pos[R]].pre].pre);
std::swap(f[pos[L]].nxt, f[pos[R]].pre);
} else if(op[0] == 'S') {
int L1, R1, L2, R2;
scanf("%d%d%d%d", &L1, &R1, &L2, &R2);
convert(L1, R1);
convert(L2, R2);
align(L1, R1);
align(L2, R2);
std::swap(f[pos[L1]].pre, f[pos[L2]].pre);
std::swap(f[f[pos[L1]].pre].nxt, f[f[pos[L2]].pre].nxt);
std::swap(f[pos[R1]].nxt, f[pos[R2]].nxt);
std::swap(f[f[pos[R1]].nxt].pre, f[f[pos[R2]].nxt].pre);
} else { // op[0] == 'A'
int L, R, k;
scanf("%d%d%d", &L, &R, &k);
convert(L, R);
int ans, pL = pos[L], pR = pos[R];
if(pL == pR) {
ans = f[pL].query(L - f[pL].sta, R - f[pR].sta + 1, k);
} else {
ans = f[pL].query(L - f[pL].sta, f[pL].len, k) + f[pR].query(0, R - f[pR].sta + 1, k);
for(pL = f[pL].nxt; pL != pR; pL = f[pL].nxt)
ans += f[pL].query(k);
}
printf("%d\n", ans);
}
if(m > sqn * 2)
rebuild();
}
}
return 0;
}
|
PHP | UTF-8 | 4,708 | 2.921875 | 3 | [] | no_license | <?php
class User{
protected $userID;
protected $username;
protected $email;
protected $company;
protected $logo;
public $db;
public function __construct($db){
$this->db=$db;
}
public function setCompany($company){
$this->company = $company;
$_SESSION['company'] = $company;
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function getCompany(){
if(!empty($this->company)){
return $this->company;
}else if(isset($_SESSION['company'])){
return $_SESSION['company'];
}else{
return "WeichieProjects";
}
}
public function setLogo($logo){
$this->logo = $logo;
$_SESSION['logo'] = $logo;
}
public function getLogo(){
if(!empty($this->logo)){
return $this->logo;
}else{
return $_SESSION['logo'];
}
}
public function register($username, $email, $password){
$options = ['cost' => 12];
$password = password_hash($password, PASSWORD_DEFAULT, $options);
$query = "INSERT INTO users(username, email, password) VALUES ('".$this->db->real_escape_string($username)."','".$this->db->real_escape_string($email)."','".$this->db->real_escape_string($password)."');";
//bestaat gebruiker al?
$controle = "SELECT * FROM users WHERE email='".$this->db->real_escape_string($email)."'";
$qry = $this->db->query($controle);
$result = $qry->fetch_assoc();
if($qry->num_rows == 1){
echo '<div class="message error-msg">This email address is already in use...</div>';
}else{
if($this->db->query($query) === TRUE){
echo '<div class="message success-msg">Registration complete, you can now login to your account!</div>';
}else{
echo '<div class="message error-msg">Error: ' . $query . '<br>' . $conn->error;
}
}
}
public function login($email, $password){
$query = "SELECT * FROM users WHERE email = '".$this->db->real_escape_string($email)."'";
$qry = $this->db->query($query);
$result = $qry->fetch_assoc();
if($qry->num_rows == 1){
if(password_verify($password, $result['password'])){
$_SESSION['logged'] = true;
$_SESSION['user_id'] = $result['id'];
$_SESSION['company'] = $result['company'];
$this->setName($result['name']);
header('Location: index.php');
}else{
echo '<div class="message error-msg">Login failed, please try again.</div>';
}
}else{
echo '<div class="message error-msg">This email address does not exist. Please register your account first</div>';
}
}
public function updateUser($name, $username, $email, $company, $company_logo){
$query = "UPDATE users SET name='".$this->db->real_escape_string($name)."', username='".$this->db->real_escape_string($username)."', email='".$this->db->real_escape_string($email)."', company='".$this->db->real_escape_string($company)."', company_logo='".$this->db->real_escape_string($logo['name'])."' WHERE id='".$_SESSION['user_id']."';";
$controle = "SELECT id FROM users WHERE id=".$_SESSION['user_id']."";
$qry = $this->db->query($controle);
$result = $qry->fetch_assoc();
if($qry->num_rows == 1){
if($this->db->query($query)){
echo "Account is geupdate";
$this->setCompany($result['company']);
}else{
echo "Whoops, something went wrong...";
}
}
}
public function upload_logo($file){
if(!empty($file['name'])){
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$imgtype = $file['type'];
$ext = $this->getImageExtention($imgtype);
$target_path = "uploads/logo/".$file_name;
if(move_uploaded_file($temp_name, $target_path)){
$query = 'UPDATE users SET company_logo="'.$this->db->real_escape_string($file['name']).'" WHERE id="'.$_SESSION['user_id'].'"';
if($this->db->query($query)){
echo "Company logo updated!";
}else{
echo "Whoops, something went wrong... Please try again!";
}
}
}
}
public function getImageExtention($imagetype){
if(empty($imagetype)){
return false;
}else{
switch($imagetype){
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'iamge/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
}
public function isLogged(){
if($_SESSION['logged'] === TRUE){
$query = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."';";
$controle = "SELECT id FROM users WHERE id='".$_SESSION['user_id']."';";
$qry = $this->db->query($controle);
$result = $qry->fetch_assoc();
if($qru->num_rows == 1){
$this->setName($result['name']);
$this->setCompany($result['company']);
}
// get all info from database
}else{
}
}
public function logout(){
session_destroy();
header('Location:'.SITE_URL);
exit;
}
}
?> |
C# | UTF-8 | 1,521 | 2.984375 | 3 | [] | no_license | using System;
using System.Linq;
using System.Data.SqlClient;
using WpfApp.DAL.DataContext;
using WpfApp.DataProtocol;
using System.Collections.Generic;
namespace WpfApp.DAL
{
public class UsersService
{
public IEnumerable<User> Users
{
get
{
using (var db = new AppDbContext())
{
return db.Users.ToList();
}
}
}
public bool AddUser(User user)
{
var res = false;
using (var db = new AppDbContext())
{
db.Users.Add(user);
res = true;
db.SaveChanges();
}
return res;
}
public User GetUser(Credentials credentials)
{
User res = null;
using (var db = new AppDbContext())
{
var query = from user in db.Users
where user.Email.ToLower() == credentials.Email.ToLower() && credentials.Password == user.Password
select user;
var users = query.ToList();
if (users.Count == 1)
{
res = users.First();
}
else if (users.Count > 1)
{
throw new Exception("Critical error. You can't have two users with the same credentials.");
}
}
return res;
}
}
}
|
Java | UTF-8 | 14,448 | 1.96875 | 2 | [] | no_license | /*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.midp.midlet;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.midp.security.Permissions;
import com.sun.midp.security.SecurityToken;
/**
* This MIDletStateHandler is a synchronous class that simply forwards
* central AMS actions to a single MIDlet running in isolation.
* <p>
* The MIDletStateHandler is a singleton for the suite being run and
* is retrieved with getMIDletStateHandler(). This allow the
* MIDletStateHandler to be the anchor of trust internally for the MIDP API,
* restricted methods can obtain the MIDletStateHandler for a MIDlet suite
* inorder to check the properties and actions of a suite.
* Because of this, there MUST only be one a MIDlet suite per
* MIDletStateHandler.
* <p>
* The MIDlet methods are protected in the javax.microedition.midlet package
* so the MIDletStateHandler can not call them directly. The MIDletState
* object and
* MIDletTunnel subclass class allow the MIDletStateHandler to hold the state
* of the
* MIDlet and to invoke methods on it. The MIDletState instance is created
* by the MIDlet when it is constructed.
* <p>
* When a MIDlet changes its or requests to change its state to
* the MIDlet state listener is notified of the change,
* which in turn sends the notification onto the central AMS.
* <p>
* When a MIDlet state is changed by the central AMS there is no call to a
* listener, since this is synchronous handler.
*
* @see MIDlet
* @see MIDletPeer
* @see MIDletLoader
* @see MIDletStateHandler
*/
public class MIDletStateHandler {
/** The event handler of all MIDlets in an Isolate. */
private static MIDletStateHandler stateHandler;
/** The listener for the state of all MIDlets in an Isolate. */
private static MIDletStateListener listener;
/** Serializes the creation of MIDlets. */
private static Object midletLock = new Object();
/** New MIDlet peer waiting for the next MIDlet created to claim it. */
private static MIDletPeer newMidletPeer;
/**
* Gets the MIDletStateHandler that manages the lifecycle states of
* MIDlets running in an Isolate.
* <p>
* If the instance of the MIDletStateHandler has already been created
* it is returned. If not it is created.
* The instance becomes the MIDletStateHandler for this suite.
* <p>
* The fact that there is one handler per Isolate
* is a security feature. Also a security feature, is that
* getMIDletStateHandler is
* static, so API can find out what suite is calling, if in the future
* multiple suites can be run in the same VM, the MIDlet state handler
* for each suite
* should be loaded in a different classloader or have some other way
* having multiple instances of static class data.
*
* @return the MIDlet state handler for this Isolate
*/
public static synchronized MIDletStateHandler getMidletStateHandler() {
/*
* If the midlet state handler has not been created, create one now.
*/
if (stateHandler == null) {
/* This is the default scheduler class */
stateHandler = new MIDletStateHandler();
}
return stateHandler;
}
/**
* Called by the MIDlet constructor to a new MIDletPeer object.
*
* @param token security token for authorizing the caller
* @param m the MIDlet for which this state is being created;
* must not be <code>null</code>.
* @return the preallocated MIDletPeer for the MIDlet being constructed by
* {@link #createMIDlet}
*
* @exception SecurityException AMS permission is not granted and
* if is constructor is not being called in the context of
* <code>createMIDlet</code>.
*/
public static MIDletPeer newMIDletPeer(SecurityToken token, MIDlet m) {
token.checkIfPermissionAllowed(Permissions.MIDP);
synchronized (midletLock) {
MIDletPeer temp;
if (newMidletPeer == null) {
throw new SecurityException(
"MIDlet not constructed by createMIDlet.");
}
temp = newMidletPeer;
newMidletPeer = null;
temp.midlet = m;
return temp;
}
}
/** the current MIDlet suite. */
private MIDletSuite midletSuite;
/** loads the MIDlets from a suite's JAR in a VM specific way. */
private MIDletLoader midletLoader;
/** Forwards actions to the MIDlet. */
private MIDletPeer midlet;
/** True when a MIDlet is first being started. */
private boolean midletStarting;
/**
* True when a MIDlet has called notifyDestroyed during it initial
* startApp call.
*/
private boolean midletDestroyedDuringStart;
/**
* Construct a new MIDletStateHandler object.
*/
private MIDletStateHandler() {
}
/**
* Initializes MIDlet State Handler.
*
* @param token security token for initilaization
* @param theMIDletStateListener processes MIDlet states in a
* VM specific way
* @param theMidletLoader loads a MIDlet in a VM specific way
* @param thePlatformRequestHandler the platform request handler
*/
public void initMIDletStateHandler(
SecurityToken token,
MIDletStateListener theMIDletStateListener,
MIDletLoader theMidletLoader,
PlatformRequest thePlatformRequestHandler) {
token.checkIfPermissionAllowed(Permissions.AMS);
listener = theMIDletStateListener;
midletLoader = theMidletLoader;
MIDletPeer.initClass(this, thePlatformRequestHandler);
}
/**
* Loads and starts a given MIDlet in a suite.
* <p>
* MIDlets are created using their no-arg constructor. Once created
* a MIDlet is sequenced to the <code>ACTIVE</code> state.
* <p>
* If a Runtime exception occurs during <code>startApp</code> the
* MIDlet will be destroyed immediately. Its <code>destroyApp</code>
* will be called allowing the MIDlet to cleanup.
*
* @param aMidletSuite the current midlet suite
* @param classname name of MIDlet class
*
* @exception ClassNotFoundException if the MIDlet main class is
* not found
* @exception InstantiationException if the MIDlet can not be
* created
* @exception IllegalAccessException if the MIDlet is not
* permitted to perform a specific operation
* @exception IllegalStateException if a suite is already running
* @exception MIDletStateChangeException is thrown
* if the <code>MIDlet</code>
* cannot start now but might be able to start at a
* later time.
*/
public void startSuite(
MIDletSuite aMidletSuite, String classname)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, MIDletStateChangeException {
synchronized (midletLock) {
if (midletSuite != null) {
throw new IllegalStateException(
"There is already a MIDlet Suite running.");
}
midletSuite = aMidletSuite;
midletStarting = true;
midlet = createMIDlet(classname);
try {
midlet.startApp();
midletStarting = false;
if (midletDestroyedDuringStart) {
throw new MIDletStateChangeException();
}
} finally {
if (midletStarting) {
/*
* MIDlet did not start, don't stop the exception,
* if any case, just cleanup
*/
try {
midlet.destroyApp(true);
} catch (Throwable e) {
// Ignore
}
}
}
}
}
/**
* Forwards the startApp to the MIDlet.
*
* @exception <code>MIDletStateChangeException</code> is thrown if the
* <code>MIDlet</code> cannot start now but might be able
* to start at a later time.
*/
public void resumeApp() throws MIDletStateChangeException {
synchronized (midletLock) {
if (midlet == null) {
return;
}
midlet.startApp();
}
}
/**
* Forwards pauseApp to the MIDlet.
*/
public void pauseApp() {
synchronized (midletLock) {
if (midlet == null) {
return;
}
midlet.pauseApp();
}
}
/**
* Forwards destoryApp to the MIDlet.
*
* @param unconditional the flag to pass to destroy
*
* @exception <code>MIDletStateChangeException</code> is thrown
* if the <code>MIDlet</code>
* wishes to continue to execute (Not enter the <i>Destroyed</i>
* state).
*/
public void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
synchronized (midletLock) {
if (midlet == null) {
return;
}
midlet.destroyApp(unconditional);
}
}
/**
* Provides a object with a mechanism to retrieve
* <code>MIDletSuite</code> being run.
*
* @return MIDletSuite being run
*/
public MIDletSuite getMIDletSuite() {
return midletSuite;
}
/**
*
* Used by a <code>MIDletPeer</code> to notify the application management
* software that it has entered into the
* <i>DESTROYED</i> state. The application management software will not
* call the MIDlet's <code>destroyApp</code> method, and all resources
* held by the <code>MIDlet</code> will be considered eligible for
* reclamation.
* The <code>MIDlet</code> must have performed the same operations
* (clean up, releasing of resources etc.) it would have if the
* <code>MIDlet.destroyApp()</code> had been called.
*
*/
void midletDestroyed() {
if (midletStarting) {
midletDestroyedDuringStart = true;
} else {
listener.midletDestroyed(getMIDletSuite(),
midlet.getMIDlet().getClass().getName(), midlet.getMIDlet());
}
}
/**
* Used by a <code>MIDlet</code> to notify the application management
* software that it has entered into the <i>PAUSED</i> state.
* Invoking this method will
* have no effect if the <code>MIDlet</code> is destroyed,
* or if it has not yet been started. <p>
* It may be invoked by the <code>MIDlet</code> when it is in the
* <i>ACTIVE</i> state. <p>
*
* If a <code>MIDlet</code> calls <code>notifyPaused()</code>, in the
* future its <code>startApp()</code> method may be called make
* it active again, or its <code>destroyApp()</code> method may be
* called to request it to destroy itself.
*/
void midletPaused() {
if (!midletStarting) {
listener.midletPausedItself(getMIDletSuite(),
midlet.getMIDlet().getClass().getName());
}
}
/**
* Used by a <code>MIDlet</code> to notify the application management
* software that it is
* interested in entering the <i>ACTIVE</i> state. Calls to
* this method can be used by the application management software to
* determine which applications to move to the <i>ACTIVE</i> state.
* <p>
* When the application management software decides to activate this
* application it will call the <code>startApp</code> method.
* <p> The application is generally in the <i>PAUSED</i> state when this is
* called. Even in the paused state the application may handle
* asynchronous events such as timers or callbacks.
*/
void resumeRequest() {
listener.resumeRequest(getMIDletSuite(),
midlet.getMIDlet().getClass().getName());
}
/**
* Creates a MIDlet.
*
* @param classname name of MIDlet class
*
* @return newly created MIDlet
*
* @exception ClassNotFoundException if the MIDlet class is
* not found
* @exception InstantiationException if the MIDlet cannot be
* created
* @exception IllegalAccessException if the MIDlet is not
* permitted to perform a specific operation
*/
private MIDletPeer createMIDlet(String classname) throws
ClassNotFoundException, InstantiationException,
IllegalAccessException {
MIDletPeer result;
/*
* Just in case there is a hole we have not found.
* Make sure there is not a new MIDlet state already created.
*/
if (newMidletPeer != null) {
throw new SecurityException("Recursive MIDlet creation");
}
newMidletPeer = new MIDletPeer();
// if newInstance is sucessful newMidletPeer will be null
result = newMidletPeer;
try {
midletLoader.newInstance(getMIDletSuite(), classname);
} finally {
/* Make sure the creation window is closed. */
newMidletPeer = null;
}
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.