text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
using Gum.Wireframe; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gum.Managers { public class GraphicalUiElementManager { List<GraphicalUiElement> GraphicalUiElements; public GraphicalUiElementManager() { GraphicalUiElements = new List<GraphicalUiElement>(); } public void Add(GraphicalUiElement graphicalUiElement) { GraphicalUiElements.Add(graphicalUiElement); } public void Remove(GraphicalUiElement graphicalUiElement) { GraphicalUiElements.Remove(graphicalUiElement); } public void Activity() { var count = GraphicalUiElements.Count; for(int i = 0; i < count; i++) { GraphicalUiElements[i].AnimateSelf(); } } } }
{'content_hash': '81ffee6aebec92fe0d747f38bc6fc095', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 65, 'avg_line_length': 23.641025641025642, 'alnum_prop': 0.6117136659436009, 'repo_name': 'vchelaru/Gum', 'id': '199899c01915213cb4dc76e4101f3fbb2405b70e', 'size': '924', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Gum/Managers/GraphicalUiElementManager.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AutoIt', 'bytes': '898'}, {'name': 'C#', 'bytes': '4215189'}]}
import Dao from '../Dao/Dao' import {ACTIVE_ROUTE, NEXT_MARKER, ROUTE_IS_ACTIVE, ROUTE_SELECTED} from './Types' export const setRouteSelected = (route) => { let dao = new Dao() if(dao.selectedRouteKey !== route.key) { dao.listenAsSelectedRoute(route.key) } return { type: ROUTE_SELECTED, route } } export const setRouteActive = (route) => { let dao = new Dao() if(dao.activeRouteKey !== route.key) { dao.listenAsActiveRoute(route.key) } return { type: ACTIVE_ROUTE, route } } export const routeIsActive = (status) => { return { type: ROUTE_IS_ACTIVE, active: status } } export const setNextMarker = (marker) => { return { type: NEXT_MARKER, marker } }
{'content_hash': '8e8d61061e06ea4bec1f2d20b6080b81', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 82, 'avg_line_length': 18.13157894736842, 'alnum_prop': 0.6676342525399129, 'repo_name': 'EksyApp/eksy', 'id': '82482dd65548469db3049c2df55f918a6adf30fd', 'size': '689', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'EKSY/App/Actions/RouteActions.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '3857'}, {'name': 'JavaScript', 'bytes': '236364'}, {'name': 'Objective-C', 'bytes': '4887'}, {'name': 'Python', 'bytes': '1724'}, {'name': 'Ruby', 'bytes': '1944'}, {'name': 'Shell', 'bytes': '1085'}]}
(function(host) { function Matcher() { } function ValueMatcher(value) { this.value = value; } ValueMatcher.prototype = new Matcher(); ValueMatcher.prototype.matches = function(value) { return JSON.stringify(this.value) === JSON.stringify(value); }; ValueMatcher.prototype.toString = function() { return this.value ? ( (this.value instanceof Array) ? "[" + this.value.toString() + "]" : this.value.toString() ) : this.value; }; function TypeMatcher(type) { this.type = type; } TypeMatcher.prototype = new Matcher(); TypeMatcher.prototype.matches = function(value) { return this.type === typeof(value); }; TypeMatcher.prototype.toString = function() { return "'" + this.type + "'"; }; function InstanceOfMatcher(type) { this.type = type; } InstanceOfMatcher.prototype = new Matcher(); InstanceOfMatcher.prototype.matches = function(value) { return value instanceof this.type; }; InstanceOfMatcher.prototype.toString = function() { var typeCode = this.type.toString(); var match = typeCode.match(/^function\s+([^\(]*)?/); return "'" + (match ? match[1].toLowerCase() : this.type) + "'"; }; function NotMatcher(wrappedMatcher) { this.wrappedMatcher = wrappedMatcher; } NotMatcher.prototype = new Matcher(); NotMatcher.prototype.matches = function(value) { return !this.wrappedMatcher.matches(value); }; NotMatcher.prototype.toString = function() { return "'not " + this.wrappedMatcher.toString() + "'"; }; host.SimpleMocks.Matchers = { Number: new TypeMatcher("number"), String: new TypeMatcher("string"), Object: new TypeMatcher("object"), Boolean: new TypeMatcher("boolean"), Function: new TypeMatcher("function"), Array: new InstanceOfMatcher(Array), Null: new ValueMatcher(null), NonNull: new NotMatcher(new ValueMatcher(null)), Undefined: new ValueMatcher(undefined), NonUndefined: new NotMatcher(new ValueMatcher(undefined)), Matcher: Matcher, ValueMatcher: ValueMatcher }; })(this);
{'content_hash': '13eb9f0907492934c9346cd2e4039f47', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 68, 'avg_line_length': 26.30952380952381, 'alnum_prop': 0.6257918552036199, 'repo_name': 'antivanov/SimpleMocks', 'id': '5a0e2a446de6fe5ca65e496cc10b33146c81bd2c', 'size': '2210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Matchers.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '51105'}]}
module BrewSparkling module Action module Xcode class Devices < Base def call devices = gateway.devices if devices.empty? puts 'No deviecs' else devices.each do |device| puts "#{device.name}" end end end end end end end
{'content_hash': '439e7d45c950a7d31eb066a72da2a463', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 36, 'avg_line_length': 18.57894736842105, 'alnum_prop': 0.48441926345609065, 'repo_name': 'codefirst/homebrew-sparkling', 'id': '5c00f6cacafaff6a56f9f1b363c097af10f063f5', 'size': '353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/brew_sparkling/action/xcode/devices.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '43479'}, {'name': 'Makefile', 'bytes': '7397'}, {'name': 'Ruby', 'bytes': '221330'}, {'name': 'Shell', 'bytes': '3363'}]}
from bokeh.io import output_file, show from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.sampledata.periodic_table import elements from bokeh.transform import dodge, factor_cmap output_file("periodic.html") periods = ["I", "II", "III", "IV", "V", "VI", "VII"] groups = [str(x) for x in range(1, 19)] df = elements.copy() df["atomic mass"] = df["atomic mass"].astype(str) df["group"] = df["group"].astype(str) df["period"] = [periods[x-1] for x in df.period] df = df[df.group != "-"] df = df[df.symbol != "Lr"] df = df[df.symbol != "Lu"] cmap = { "alkali metal" : "#a6cee3", "alkaline earth metal" : "#1f78b4", "metal" : "#d93b43", "halogen" : "#999d9a", "metalloid" : "#e08d49", "noble gas" : "#eaeaea", "nonmetal" : "#f1d4Af", "transition metal" : "#599d7A", } source = ColumnDataSource(df) p = figure(plot_width=900, plot_height=500, title="Periodic Table (omitting LA and AC Series)", x_range=groups, y_range=list(reversed(periods)), toolbar_location=None, tools="hover") p.rect("group", "period", 0.95, 0.95, source=source, fill_alpha=0.6, legend="metal", color=factor_cmap('metal', palette=list(cmap.values()), factors=list(cmap.keys()))) text_props = {"source": source, "text_align": "left", "text_baseline": "middle"} x = dodge("group", -0.4, range=p.x_range) r = p.text(x=x, y="period", text="symbol", **text_props) r.glyph.text_font_style="bold" r = p.text(x=x, y=dodge("period", 0.3, range=p.y_range), text="atomic number", **text_props) r.glyph.text_font_size="8pt" r = p.text(x=x, y=dodge("period", -0.35, range=p.y_range), text="name", **text_props) r.glyph.text_font_size="5pt" r = p.text(x=x, y=dodge("period", -0.2, range=p.y_range), text="atomic mass", **text_props) r.glyph.text_font_size="5pt" p.text(x=["3", "3"], y=["VI", "VII"], text=["LA", "AC"], text_align="center", text_baseline="middle") p.hover.tooltips = [ ("Name", "@name"), ("Atomic number", "@{atomic number}"), ("Atomic mass", "@{atomic mass}"), ("Type", "@metal"), ("CPK color", "$color[hex, swatch]:CPK"), ("Electronic configuration", "@{electronic configuration}"), ] p.outline_line_color = None p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_standoff = 0 p.legend.orientation = "horizontal" p.legend.location ="top_center" show(p)
{'content_hash': '26956528d5acc8b4e0add0b822e9d663', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 101, 'avg_line_length': 33.62162162162162, 'alnum_prop': 0.6181672025723473, 'repo_name': 'timsnyder/bokeh', 'id': '8cffd49c0ef121d57af0cbaa02c1244a638d5a48', 'size': '2488', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'sphinx/source/docs/user_guide/examples/categorical_heatmap_periodic.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '1442'}, {'name': 'CSS', 'bytes': '24877'}, {'name': 'Dockerfile', 'bytes': '4099'}, {'name': 'HTML', 'bytes': '54062'}, {'name': 'JavaScript', 'bytes': '27797'}, {'name': 'Makefile', 'bytes': '886'}, {'name': 'PowerShell', 'bytes': '713'}, {'name': 'Python', 'bytes': '3827067'}, {'name': 'Roff', 'bytes': '495'}, {'name': 'Shell', 'bytes': '9953'}, {'name': 'TypeScript', 'bytes': '2145262'}]}
package com.codingbrothers.futurimages.domain; import javax.inject.Inject; import com.googlecode.objectify.Key; import com.googlecode.objectify.Ref; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Unindex; @Entity(name = "T") @Unindex // @Cache(expirationSeconds = 60) public class ImageTransformation extends BaseImage<Image> { private Transform transform; @Inject private ImageTransformation() {} public Transform getTransform() { return transform; } void setTransform(Transform transform) { this.transform = transform; } public boolean isPublic() { return true; // at the moment, ImageTransformation is always public } public static Builder Builder() { return Builder.create(); } public static class Builder { private final ImageTransformation imageTransformation; private Builder() { imageTransformation = new ImageTransformation(); } public Builder of(Key<Image> imageKey) { imageTransformation.parent = Ref.create(imageKey); return this; } public Builder with(Transform transform) { imageTransformation.transform = transform; return this; } public Builder setBlobKey(String blobKey) { this.imageTransformation.blobKey = blobKey; return this; } public Builder proto(ImageTransformation imageTransformation) { this.imageTransformation.parent = imageTransformation.parent; this.imageTransformation.id = imageTransformation.id; this.imageTransformation.p = imageTransformation.p; this.imageTransformation.c = imageTransformation.c; this.imageTransformation.blobKey = imageTransformation.blobKey; this.imageTransformation.transform = imageTransformation.transform; return this; } public ImageTransformation build() { return imageTransformation; } public static Builder create() { return new Builder(); } } }
{'content_hash': '30b26c62ca5003436f5c528b05931446', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 70, 'avg_line_length': 24.734177215189874, 'alnum_prop': 0.72978505629478, 'repo_name': 'CodingBrothers/futurimages', 'id': 'aa0c375babbb9328367abd5693c221c5a6fa5725', 'size': '1954', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/codingbrothers/futurimages/domain/ImageTransformation.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'API Blueprint', 'bytes': '47091'}, {'name': 'Java', 'bytes': '120426'}]}
package rss import ( "bytes" "encoding/xml" "fmt" "sort" "strings" "time" ) func parseRSS1(data []byte, read *db) (*Feed, error) { warnings := false feed := rss1_0Feed{} p := xml.NewDecoder(bytes.NewReader(data)) p.CharsetReader = charsetReader err := p.Decode(&feed) if err != nil { return nil, err } if feed.Channel == nil { return nil, fmt.Errorf("Error: no channel found in %q.", string(data)) } channel := feed.Channel out := new(Feed) out.Title = channel.Title out.Description = channel.Description out.Link = channel.Link out.Image = channel.Image.Image() if channel.MinsToLive != 0 { sort.Ints(channel.SkipHours) next := time.Now().Add(time.Duration(channel.MinsToLive) * time.Minute) for _, hour := range channel.SkipHours { if hour == next.Hour() { next.Add(time.Duration(60-next.Minute()) * time.Minute) } } trying := true for trying { trying = false for _, day := range channel.SkipDays { if strings.Title(day) == next.Weekday().String() { next.Add(time.Duration(24-next.Hour()) * time.Hour) trying = true break } } } out.Refresh = next } if out.Refresh.IsZero() { out.Refresh = time.Now().Add(10 * time.Minute) } if feed.Items == nil { return nil, fmt.Errorf("Error: no feeds found in %q.", string(data)) } out.Items = make([]*Item, 0, len(feed.Items)) out.ItemMap = make(map[string]struct{}) // Process items. for _, item := range feed.Items { if item.ID == "" { if item.Link == "" { if debug { fmt.Printf("[w] Item %q has no ID or link and will be ignored.\n", item.Title) fmt.Printf("[w] %#v\n", item) } warnings = true continue } item.ID = item.Link } // Skip items already known. if read.req <- item.ID; <-read.res { continue } next := new(Item) next.Title = item.Title next.Content = item.Content next.Link = item.Link if item.Date != "" { next.Date, err = parseTime(item.Date) if err != nil { return nil, err } } else if item.PubDate != "" { next.Date, err = parseTime(item.PubDate) if err != nil { return nil, err } } next.ID = item.ID next.Read = false if _, ok := out.ItemMap[next.ID]; ok { if debug { fmt.Printf("[w] Item %q has duplicate ID.\n", next.Title) fmt.Printf("[w] %#v\n", next) } warnings = true continue } out.Items = append(out.Items, next) out.ItemMap[next.ID] = struct{}{} out.Unread++ } if warnings && debug { fmt.Printf("[i] Encountered warnings:\n%s\n", data) } return out, nil } type rss1_0Feed struct { XMLName xml.Name `xml:"RDF"` Channel *rss1_0Channel `xml:"channel"` Items []rss1_0Item `xml:"item"` } type rss1_0Channel struct { XMLName xml.Name `xml:"channel"` Title string `xml:"title"` Description string `xml:"description"` Link string `xml:"link"` Image rss1_0Image `xml:"image"` MinsToLive int `xml:"ttl"` SkipHours []int `xml:"skipHours>hour"` SkipDays []string `xml:"skipDays>day"` } type rss1_0Item struct { XMLName xml.Name `xml:"item"` Title string `xml:"title"` Content string `xml:"description"` Link string `xml:"link"` PubDate string `xml:"pubDate"` Date string `xml:"date"` ID string `xml:"guid"` } type rss1_0Image struct { XMLName xml.Name `xml:"image"` Title string `xml:"title"` Url string `xml:"url"` Height int `xml:"height"` Width int `xml:"width"` } func (i *rss1_0Image) Image() *Image { out := new(Image) out.Title = i.Title out.Url = i.Url out.Height = uint32(i.Height) out.Width = uint32(i.Width) return out }
{'content_hash': '86ec4936f24a655e91ab2be846bfcc7c', 'timestamp': '', 'source': 'github', 'line_count': 167, 'max_line_length': 83, 'avg_line_length': 22.05389221556886, 'alnum_prop': 0.60657073038284, 'repo_name': 'LuckyBeaver/rss', 'id': '3622949aa7c893a6177adecab74371e95a76bf54', 'size': '3683', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rss 1.0.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Go', 'bytes': '25564'}]}
use tokio_tungstenite as tungstenite; use atomic_counter::AtomicCounter; use atomic_counter::RelaxedCounter; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use serde::Deserialize; use serde_json::json; use std::result::Result; use std::sync::Arc; use std::sync::RwLock; use std::time::Instant; use chrono::prelude::Utc; use tokio::sync::mpsc; use crate::core::santizer; // Type alias for msg_id pub type MsgId = Arc<RelaxedCounter>; #[derive(Debug)] enum Event { UserEvent(UserEvent), SystemControl(SystemControl), MessageControl(MessageControl), } #[derive(Debug, Deserialize)] #[serde(tag = "type")] #[serde(rename_all = "snake_case")] pub enum UserEvent { // These events are what plugins will care for: // // Slack messages // TODO: more involved here for now basics Message { subtype: Option<String>, hidden: Option<bool>, #[serde(rename = "channel")] channel_id: Option<String>, #[serde(rename = "user")] user_id: String, text: String, ts: String, thread_ts: Option<String>, }, // TODO: consider looking at slack_api for types to reuse here ReactionAdded { #[serde(rename = "user")] user_id: String, reaction: String, item_user: Option<String>, item: ReactionItem, event_ts: String, ts: String, }, ReactionRemoved { #[serde(rename = "user")] user_id: String, reaction: String, item_user: Option<String>, item: ReactionItem, event_ts: String, ts: String, }, } #[derive(Debug, Deserialize)] #[serde(tag = "type")] #[serde(rename_all = "snake_case")] pub enum ReactionItem { Message { #[serde(rename = "channel")] // I think this is mandatory? channel_id: String, ts: String, }, File { file: String, }, FileComment { file: String, file_comment: String, }, } #[derive(Debug, Deserialize)] #[serde(tag = "type")] #[serde(rename_all = "snake_case")] #[allow(dead_code)] enum SystemControl { // First message upon successful connection establishment Hello, // Client should reconnect after getting such message Goodbye, // Reply to Ping = { type: ping, id: num } Pong { reply_to: usize, timestamp: Option<i64> }, } #[derive(Debug, Deserialize)] #[serde(untagged)] #[allow(dead_code)] enum MessageControl { // Reply to message sent MessageSent { ok: bool, reply_to: usize, text: String, ts: String }, // Reply to failed message sent MessageError { ok: bool, reply_to: usize, error: ErrorDetail, }, } #[derive(Debug, Deserialize)] #[allow(dead_code)] struct ErrorDetail { code: usize, msg: String, } fn parse_event(s: String) -> Option<Event> { // Return User Events first, then the other two serde_json::from_str(&s).and_then(|ue| { Ok(Event::UserEvent(ue)) }).or_else(|_| { serde_json::from_str(&s).and_then(|sc| { Ok(Event::SystemControl(sc)) }).or_else(|_| { serde_json::from_str(&s).and_then(|mc| { Ok(Event::MessageControl(mc)) }).or_else(|x| { // TODO: for now print to stderr what didn't get deserialized // later can have config option to log to file the error or not Err(x) }) }) }).ok() } pub async fn send_simple_message( msg_id: MsgId, tx: &mut mpsc::Sender<tungstenite::tungstenite::Message>, channel: String, thread_ts: Option<String>, text: String ) -> Result<(), &'static str> { if text.is_empty() { return Err("Empty string, not sending"); } // TODO: track if it got santized or not let text = santizer::santize_output(&text); // TODO: register this message send to be tracked later let ws_msg = match thread_ts { Some(ts) => json!({ "id": msg_id.inc(), "type": "message", "channel": channel, "text": text, "thread_ts": ts, }).to_string(), None => json!({ "id": msg_id.inc(), "type": "message", "channel": channel, "text": text, }).to_string(), }; tx.send(tungstenite::tungstenite::Message::from(ws_msg)).await.map_err(|_| "Error sending") } pub async fn send_slack_ping( msg_id: MsgId, tx: &mut mpsc::Sender<tungstenite::tungstenite::Message>, last_ping_sent: Arc<RwLock<Instant>>, ) -> Result<(), &'static str> { { let mut timer = last_ping_sent.write().unwrap(); *timer = Instant::now(); } let ws_msg = json!({ "id": msg_id.inc(), "type": "ping", "timestamp": Utc::now().timestamp_millis(), }).to_string(); tx.send(tungstenite::tungstenite::Message::from(ws_msg)).await.map_err(|_| "Error sending") } pub async fn process_control_message( tx: mpsc::Sender<tungstenite::tungstenite::Message>, can_send: Arc<AtomicBool>, reconnect: Arc<AtomicBool>, reconnect_count: Arc<RelaxedCounter>, last_message_recieved: Arc<RwLock<Instant>>, msg: tungstenite::tungstenite::Message, ) -> Result<Option<UserEvent>, Box<dyn std::error::Error>> { // Parse incoming message let raw_msg = match msg { tungstenite::tungstenite::Message::Text(x) => { { let mut timer = last_message_recieved.write().unwrap(); *timer = Instant::now(); } Some(x) }, tungstenite::tungstenite::Message::Ping(x) => { let _ = tx.send(tungstenite::tungstenite::Message::Pong(x)).await; None }, tungstenite::tungstenite::Message::Close(reason) => { println!("SYSTEM [Inbound]: Close: {:?}", reason); reconnect.store(true, Ordering::Relaxed); can_send.store(false, Ordering::Relaxed); None }, _ => { eprintln!("SYSTEM [Inbound]: Unsupported websocket type: {:?}", msg); None }, }; if let Some(e) = raw_msg.and_then(parse_event) { match e { Event::UserEvent(event) => Ok(Some(event)), Event::MessageControl(_mc) => Ok(None), Event::SystemControl(sc) => { match sc { SystemControl::Hello => { // Hold on sending messages till this is recieved. can_send.store(true, Ordering::Relaxed); reconnect_count.reset(); }, SystemControl::Goodbye => { // When this is recieved, reconnect reconnect.store(true, Ordering::Relaxed); can_send.store(false, Ordering::Relaxed); }, SystemControl::Pong{reply_to: _, timestamp: _ts} => { // if let Some(old) = _ts { // let now = Utc::now().timestamp_millis(); // println!("SYSTEM [Inbound]: Ping delta: {:?}ms", now - old); // } }, } Ok(None) }, } } else { Ok(None) } }
{'content_hash': 'f471bedf3e4833e19c035e0480f305d2', 'timestamp': '', 'source': 'github', 'line_count': 278, 'max_line_length': 95, 'avg_line_length': 26.769784172661872, 'alnum_prop': 0.5362805697393174, 'repo_name': 'pharaun/Karmator', 'id': '7246fa46c3c633f37a56153f6f44b455b7a5b5f4', 'size': '7442', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/core/event.rs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Rust', 'bytes': '159400'}, {'name': 'Shell', 'bytes': '505'}]}
package gigaherz.survivalist; import gigaherz.survivalist.chopblock.ChoppingBlock; import gigaherz.survivalist.rack.DryingRackBlock; import gigaherz.survivalist.rack.DryingRackTileEntity; import gigaherz.survivalist.sawmill.SawmillBlock; import gigaherz.survivalist.sawmill.SawmillTileEntity; import gigaherz.survivalist.util.RegSitter; import net.minecraft.block.AbstractBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraftforge.common.ToolType; import net.minecraftforge.fml.RegistryObject; public class SurvivalistBlocks { static final RegSitter HELPER = new RegSitter(SurvivalistMod.MODID); public static final RegistryObject<DryingRackBlock> RACK = HELPER .block("rack", () -> new DryingRackBlock(AbstractBlock.Properties.create(Material.WOOD).sound(SoundType.WOOD).hardnessAndResistance(1.0f).notSolid())) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).withTileEntity(DryingRackTileEntity::new).defer(); public static final RegistryObject<SawmillBlock> SAWMILL = HELPER .block("sawmill", () -> new SawmillBlock(AbstractBlock.Properties.create(Material.ROCK).hardnessAndResistance(3.5F).sound(SoundType.STONE))) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).withTileEntity(SawmillTileEntity::new).defer(); public static final RegistryObject<ChoppingBlock> OAK_CHOPPING_BLOCK = HELPER .block("oak_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.CHIPPED_OAK_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> CHIPPED_OAK_CHOPPING_BLOCK = HELPER .block("chipped_oak_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.DAMAGED_OAK_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DAMAGED_OAK_CHOPPING_BLOCK = HELPER .block("damaged_oak_chopping_block", SurvivalistBlocks::getChoppingBlock) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> BIRCH_CHOPPING_BLOCK = HELPER .block("birch_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.CHIPPED_BIRCH_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> CHIPPED_BIRCH_CHOPPING_BLOCK = HELPER .block("chipped_birch_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.DAMAGED_BIRCH_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DAMAGED_BIRCH_CHOPPING_BLOCK = HELPER .block("damaged_birch_chopping_block", SurvivalistBlocks::getChoppingBlock) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> SPRUCE_CHOPPING_BLOCK = HELPER .block("spruce_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.CHIPPED_SPRUCE_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> CHIPPED_SPRUCE_CHOPPING_BLOCK = HELPER .block("chipped_spruce_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.DAMAGED_SPRUCE_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DAMAGED_SPRUCE_CHOPPING_BLOCK = HELPER .block("damaged_spruce_chopping_block", SurvivalistBlocks::getChoppingBlock) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> JUNGLE_CHOPPING_BLOCK = HELPER .block("jungle_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.CHIPPED_JUNGLE_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> CHIPPED_JUNGLE_CHOPPING_BLOCK = HELPER .block("chipped_jungle_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.DAMAGED_JUNGLE_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DAMAGED_JUNGLE_CHOPPING_BLOCK = HELPER .block("damaged_jungle_chopping_block", SurvivalistBlocks::getChoppingBlock) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DARK_OAK_CHOPPING_BLOCK = HELPER .block("dark_oak_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.CHIPPED_DARK_OAK_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> CHIPPED_DARK_OAK_CHOPPING_BLOCK = HELPER .block("chipped_dark_oak_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.DAMAGED_DARK_OAK_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DAMAGED_DARK_OAK_CHOPPING_BLOCK = HELPER .block("damaged_dark_oak_chopping_block", SurvivalistBlocks::getChoppingBlock) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> ACACIA_CHOPPING_BLOCK = HELPER .block("acacia_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.CHIPPED_ACACIA_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> CHIPPED_ACACIA_CHOPPING_BLOCK = HELPER .block("chipped_acacia_chopping_block", () -> getChoppingBlock(SurvivalistBlocks.DAMAGED_ACACIA_CHOPPING_BLOCK)) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); public static final RegistryObject<ChoppingBlock> DAMAGED_ACACIA_CHOPPING_BLOCK = HELPER .block("damaged_acacia_chopping_block", SurvivalistBlocks::getChoppingBlock) .withItem(new Item.Properties().group(SurvivalistMod.SURVIVALIST_ITEMS)).defer(); private static ChoppingBlock getChoppingBlock() { return new ChoppingBlock(null, defaultChopBlockProperties()); } private static ChoppingBlock getChoppingBlock(RegistryObject<ChoppingBlock> breaksInto) { return new ChoppingBlock(() -> breaksInto.get().getDefaultState(), defaultChopBlockProperties()); } private static AbstractBlock.Properties defaultChopBlockProperties() { return AbstractBlock.Properties.create(Material.WOOD).sound(SoundType.WOOD).hardnessAndResistance(5.0f).harvestTool(ToolType.AXE).harvestLevel(0); } }
{'content_hash': '30c4ae03ff23a4317215bec07eb9191f', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 162, 'avg_line_length': 64.14912280701755, 'alnum_prop': 0.7470258443867086, 'repo_name': 'gigaherz/Survivalist', 'id': '642f25404d311f71f0a8dca3b1c6565cddb7a490', 'size': '7313', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/gigaherz/survivalist/SurvivalistBlocks.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '169'}, {'name': 'Java', 'bytes': '269676'}]}
Documentation, download, and usage instructions =============================================== Full usage details, FAQs, background and more are available on the **[project documentation website](https://danielflower.github.io/multi-module-maven-release-plugin/index.html)**. Development =========== [![Build Status](https://travis-ci.org/danielflower/multi-module-maven-release-plugin.svg?branch=master)](https://travis-ci.org/danielflower/multi-module-maven-release-plugin) ![Maven Central](https://img.shields.io/maven-central/v/com.github.danielflower.mavenplugins/multi-module-maven-release-plugin.svg) Contributing ------------ To build and run the tests, you need Java 8 or later and Maven 3 or later. Simply clone and run `mvn install` Note that the tests run the plugin against a number of sample test projects, located in the `test-projects` folder. If adding new functionality, or fixing a bug, it is recommended that a sample project be set up so that the scenario can be tested end-to-end. See also [CONTRIBUTING.md](CONTRIBUTING.md) for information on deploying to Nexus and releasing the plugin.
{'content_hash': 'b1f5240d78e03007ddf4d8b0cd04c7f7', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 307, 'avg_line_length': 50.90909090909091, 'alnum_prop': 0.7410714285714286, 'repo_name': 'danielflower/multi-module-maven-release-plugin', 'id': '60206018b462ac9035f0e935909e2a90f4432ff7', 'size': '1120', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '254695'}]}
/* eslint quote-props: ["error", "as-needed"] */ import React, { PropTypes } from 'react'; import { css, StyleSheet } from 'aphrodite/no-important'; import Button from '../Button'; import Glyph from '../Glyph'; function GlyphButton ({ children, glyph, glyphColor, glyphSize, position, ...props, }) { const isDefault = position === 'default'; const isLeft = position === 'left'; const isRight = position === 'right'; const glyphStyles = {}; if (isLeft) glyphStyles.marginRight = '0.5em'; if (isRight) glyphStyles.marginLeft = '0.5em'; const icon = ( <Glyph className={css(classes.glyph)} color={glyphColor} name={glyph} size={glyphSize} style={glyphStyles} /> ); return ( <Button {...props}> {(isDefault || isLeft) && icon} {children} {isRight && icon} </Button> ); }; // For props "glyph", "glyphColor", and "glyphSize": // prop type validation will occur within the Glyph component, no need to // duplicate, just pass it through. GlyphButton.propTypes = { glyph: PropTypes.string, glyphColor: PropTypes.string, glyphSize: PropTypes.string, position: PropTypes.oneOf(['default', 'left', 'right']), }; GlyphButton.defaultProps = { position: 'default', // no margin, assumes no children }; const classes = StyleSheet.create({ glyph: { display: 'inline-block', marginTop: '-0.125em', // fix icon alignment verticalAlign: 'middle', }, }); module.exports = GlyphButton;
{'content_hash': '5d9dccde51b27725121b4e739d269b51', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 73, 'avg_line_length': 22.40625, 'alnum_prop': 0.6652719665271967, 'repo_name': 'dvdcastro/keystone', 'id': '3113d9d2bcde6d9a57d8aec363593c6ca1d88e85', 'size': '1434', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'admin/client/App/elemental/GlyphButton/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '297575'}, {'name': 'HTML', 'bytes': '23033'}, {'name': 'JavaScript', 'bytes': '2797350'}]}
package com.lachesis.mnis.core.infusionmonitor.repository.impl; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import com.lachesis.mnis.core.SpringTest; import com.lachesis.mnis.core.infusionmonitor.entity.InfusionMonitorInfo; import com.lachesis.mnis.core.infusionmonitor.entity.InfusionMonitorRecord; import com.lachesis.mnis.core.infusionmonitor.repository.InfusionMonitorRepository; import com.lachesis.mnis.core.util.DateUtil; import com.lachesis.mnis.core.util.DateUtil.DateFormat; public class InfusionMonitorRepositoryTest extends SpringTest { private static final String patId = "test1"; @Autowired InfusionMonitorRepository infusionMonitorRepository; @Test public void testGetInfusionMonitorList() { List<String> patientList = new ArrayList<String>(); patientList.add(patId); String[] dates = DateUtil.getTimeEndPoints("2014-11-18"); infusionMonitorRepository .selectInfusionMonitorList(patientList, DateUtil.parse(dates[0], DateFormat.FULL), DateUtil.parse(dates[1], DateFormat.FULL)); } @Test public void testAddInfusionMonitor() { InfusionMonitorInfo info = new InfusionMonitorInfo(); InfusionMonitorRecord record = new InfusionMonitorRecord(); info.setCurrentRecord(record); record.setAbnormal(true); record.setAnomalyDisposal("已处置"); record.setAnomalyMsg("过敏"); record.setDeliverSpeed(60); record.setRecordDate(DateUtil.parse("2014-07-5 08:30:30", DateFormat.FULL)); record.setRecordNurseId("000156"); record.setRecordNurseName("测试护士1"); record.setResidue(0); record.setStatus("N"); info.setDeptId("1005"); info.setOrderExecId("I1234567890"); info.setPatientId(patId); info.setBedNo("1床"); info.setPatientName("测试病人1"); int count = infusionMonitorRepository.saveInfusionMonitor(info); Assert.isTrue(info.getCurrentRecord().getId() > 0); Assert.isTrue(count == 1); } @Test public void testSelectInfusionMonitorByExecId() { InfusionMonitorInfo info = infusionMonitorRepository .selectInfusionMonitorForOrderExec("I123456789"); Assert.notNull(info); } @Test public void testModifyInfusionMonitor() { InfusionMonitorRecord record = new InfusionMonitorRecord(); record.setAbnormal(false); record.setAnomalyDisposal("已处置2"); record.setAnomalyMsg("过敏2"); record.setDeliverSpeed(60); record.setResidue(100); record.setStatus("N"); record.setId(1); int count = infusionMonitorRepository.updateInfusionMonitorItem(record); Assert.isTrue(count == 1); } }
{'content_hash': '819e9111ddefd13ff2bc0cf581f8478d', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 83, 'avg_line_length': 32.20987654320987, 'alnum_prop': 0.778459179762361, 'repo_name': 'gavin2lee/incubator', 'id': '1465e34a30100f5bab9ab719e69b00bba89efe3b', 'size': '2647', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mnis/core/src/test/java/com/lachesis/mnis/core/infusionmonitor/repository/impl/InfusionMonitorRepositoryTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '43520'}, {'name': 'Batchfile', 'bytes': '26665'}, {'name': 'CSS', 'bytes': '2876598'}, {'name': 'FreeMarker', 'bytes': '130'}, {'name': 'HTML', 'bytes': '1622322'}, {'name': 'Java', 'bytes': '6718384'}, {'name': 'JavaScript', 'bytes': '10783743'}, {'name': 'Mathematica', 'bytes': '28028'}, {'name': 'PHP', 'bytes': '2352569'}, {'name': 'Shell', 'bytes': '24983'}, {'name': 'Smarty', 'bytes': '10759'}]}
/** * Created by paipeng on 29.05.15. */ angular.module("fifaApp").directive("footer", function() { return { restrict: 'A', templateUrl: '/views/footer.html', scope: true, transclude : false, controller: 'FooterController' }; });
{'content_hash': 'fad7ff6a86f58a92315c6346485255c2', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 58, 'avg_line_length': 20.071428571428573, 'alnum_prop': 0.5622775800711743, 'repo_name': 'paipeng/fifa-app', 'id': '793b170ba891733c733b79a2ac96346084fc3051', 'size': '281', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scripts/directives/footer_directive.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '380'}, {'name': 'HTML', 'bytes': '10104'}, {'name': 'JavaScript', 'bytes': '10748'}]}
/** * @file nbc_test.cpp * * Test for the Naive Bayes classifier. */ #include <mlpack/core.hpp> #include <mlpack/methods/naive_bayes/naive_bayes_classifier.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; using namespace naive_bayes; BOOST_AUTO_TEST_SUITE(NBCTest); BOOST_AUTO_TEST_CASE(NaiveBayesClassifierTest) { const char* trainFilename = "trainSet.csv"; const char* testFilename = "testSet.csv"; const char* trainResultFilename = "trainRes.csv"; const char* testResultFilename = "testRes.csv"; size_t classes = 2; arma::mat trainData, trainRes, calcMat; data::Load(trainFilename, trainData, true); data::Load(trainResultFilename, trainRes, true); // Get the labels out. arma::Col<size_t> labels(trainData.n_cols); for (size_t i = 0; i < trainData.n_cols; ++i) labels[i] = trainData(trainData.n_rows - 1, i); trainData.shed_row(trainData.n_rows - 1); NaiveBayesClassifier<> nbcTest(trainData, labels, classes); size_t dimension = nbcTest.Means().n_rows; calcMat.zeros(2 * dimension + 1, classes); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < classes; j++) { calcMat(i, j) = nbcTest.Means()(i, j); calcMat(i + dimension, j) = nbcTest.Variances()(i, j); } } for (size_t i = 0; i < classes; i++) calcMat(2 * dimension, i) = nbcTest.Probabilities()(i); for (size_t i = 0; i < calcMat.n_rows; i++) for (size_t j = 0; j < classes; j++) BOOST_REQUIRE_CLOSE(trainRes(i, j) + .00001, calcMat(i, j), 0.01); arma::mat testData; arma::Mat<size_t> testRes; arma::Col<size_t> calcVec; data::Load(testFilename, testData, true); data::Load(testResultFilename, testRes, true); testData.shed_row(testData.n_rows - 1); // Remove the labels. nbcTest.Classify(testData, calcVec); for (size_t i = 0; i < testData.n_cols; i++) BOOST_REQUIRE_EQUAL(testRes(i), calcVec(i)); } // The same test, but this one uses the incremental algorithm to calculate // variance. BOOST_AUTO_TEST_CASE(NaiveBayesClassifierIncrementalTest) { const char* trainFilename = "trainSet.csv"; const char* testFilename = "testSet.csv"; const char* trainResultFilename = "trainRes.csv"; const char* testResultFilename = "testRes.csv"; size_t classes = 2; arma::mat trainData, trainRes, calcMat; data::Load(trainFilename, trainData, true); data::Load(trainResultFilename, trainRes, true); // Get the labels out. arma::Col<size_t> labels(trainData.n_cols); for (size_t i = 0; i < trainData.n_cols; ++i) labels[i] = trainData(trainData.n_rows - 1, i); trainData.shed_row(trainData.n_rows - 1); NaiveBayesClassifier<> nbcTest(trainData, labels, classes, true); size_t dimension = nbcTest.Means().n_rows; calcMat.zeros(2 * dimension + 1, classes); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < classes; j++) { calcMat(i, j) = nbcTest.Means()(i, j); calcMat(i + dimension, j) = nbcTest.Variances()(i, j); } } for (size_t i = 0; i < classes; i++) calcMat(2 * dimension, i) = nbcTest.Probabilities()(i); for (size_t i = 0; i < calcMat.n_rows; i++) for (size_t j = 0; j < classes; j++) BOOST_REQUIRE_CLOSE(trainRes(i, j) + .00001, calcMat(i, j), 0.01); arma::mat testData; arma::Mat<size_t> testRes; arma::Col<size_t> calcVec; data::Load(testFilename, testData, true); data::Load(testResultFilename, testRes, true); testData.shed_row(testData.n_rows - 1); // Remove the labels. nbcTest.Classify(testData, calcVec); for (size_t i = 0; i < testData.n_cols; i++) BOOST_REQUIRE_EQUAL(testRes(i), calcVec(i)); } BOOST_AUTO_TEST_SUITE_END();
{'content_hash': '49c263284f8ffd948b33061946cc34ad', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 74, 'avg_line_length': 29.68, 'alnum_prop': 0.6557951482479785, 'repo_name': 'bmswgnp/mlpack', 'id': 'a8b6ad741491c5b21188309e663fa0847994698c', 'size': '3710', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'src/mlpack/tests/nbc_test.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C++', 'bytes': '3150494'}, {'name': 'CMake', 'bytes': '110876'}, {'name': 'Matlab', 'bytes': '20967'}, {'name': 'Shell', 'bytes': '4045'}]}
<?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.0"?> <plugin> <extension point="org.eclipse.cdt.managedbuilder.core.buildDefinitions" id="C5500" name="C5500 Build Definitions"> <managedBuildRevision fileVersion="3.1.0"/> <projectType id="com.ti.ccstudio.buildDefinitions.C5500.ProjectType" name="C5500" isTest="true"> <configuration id="com.ti.ccstudio.buildDefinitions.C5500.Default" name="Default" cleanCommand="${CG_CLEAN_CMD}"> <toolChain id="com.ti.ccstudio.buildDefinitions.C5500.Default.ToolchainPlaceholder" isToolChainSupported="com.ti.ccstudio.buildmodel.IsToolchainSupported" isAbstract="true"/> </configuration> <configuration id="com.ti.ccstudio.buildDefinitions.C5500.Debug" name="Debug" cleanCommand="${CG_CLEAN_CMD}"> <toolChain id="com.ti.ccstudio.buildDefinitions.C5500.Debug.ToolchainPlaceholder" isToolChainSupported="com.ti.ccstudio.buildmodel.IsToolchainSupported" isAbstract="true"/> </configuration> <configuration id="com.ti.ccstudio.buildDefinitions.C5500.Release" name="Release" cleanCommand="${CG_CLEAN_CMD}"> <toolChain id="com.ti.ccstudio.buildDefinitions.C5500.Release.ToolchainPlaceholder" isToolChainSupported="com.ti.ccstudio.buildmodel.IsToolchainSupported" isAbstract="true"/> </configuration> </projectType> </extension> </plugin>
{'content_hash': '7063a6b827c36d41ba584f1f1294fd6f', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 77, 'avg_line_length': 30.25531914893617, 'alnum_prop': 0.7194092827004219, 'repo_name': 'xkus/DSP_ADPCM', 'id': 'aaffcb5bef3885ae97831ba5ea3ef10bbe57ee40', 'size': '1422', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': '.metadata/.plugins/com.ti.ccstudio.builddefinitions.generator/6.1.3/C5500.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '44'}, {'name': 'C', 'bytes': '28313'}, {'name': 'C++', 'bytes': '838'}, {'name': 'Matlab', 'bytes': '2875'}]}
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.github.mingchen.sampleproject"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
{'content_hash': '7e37e3a04781a4748d753043ab66471e', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 76, 'avg_line_length': 34.666666666666664, 'alnum_prop': 0.6236263736263736, 'repo_name': 'mingchen/docker-android-build-box', 'id': '6d38b54aa71e0105bf5e2d159baa73b8fc85b706', 'size': '728', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test_projects/SampleProject/app/src/main/AndroidManifest.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '8951'}, {'name': 'Kotlin', 'bytes': '1366'}, {'name': 'Ruby', 'bytes': '1085'}, {'name': 'Shell', 'bytes': '1347'}]}
""" Generate and compile C modules for Python. """ from __future__ import print_function import atexit import six.moves.cPickle as pickle import logging import os import re import shutil import stat import subprocess import sys import tempfile import time import platform import distutils.sysconfig import warnings import numpy.distutils # TODO: TensorType should handle this import theano from theano.compat import PY3, decode, decode_iter from six import b, BytesIO, StringIO, string_types, iteritems from theano.gof.utils import flatten from theano.configparser import config from theano.gof.utils import hash_from_code from theano.misc.windows import (subprocess_Popen, output_subprocess_Popen) # we will abuse the lockfile mechanism when reading and writing the registry from theano.gof import compilelock from theano.configdefaults import gcc_version_str, local_bitwidth importlib = None try: import importlib except ImportError: pass _logger = logging.getLogger("theano.gof.cmodule") METH_VARARGS = "METH_VARARGS" METH_NOARGS = "METH_NOARGS" # global variable that represent the total time spent in importing module. import_time = 0 class MissingGXX(Exception): """ This error is raised when we try to generate c code, but g++ is not available. """ pass def debug_counter(name, every=1): """ Debug counter to know how often we go through some piece of code. This is a utility function one may use when debugging. Example ------- debug_counter('I want to know how often I run this line') """ setattr(debug_counter, name, getattr(debug_counter, name, 0) + 1) n = getattr(debug_counter, name) if n % every == 0: print("debug_counter [%s]: %s" % (name, n), file=sys.stderr) class ExtFunction(object): """ A C function to put into a DynamicModule. """ name = "" """ str - function's name. """ code_block = "" """ str - the entire code for the function. Has the form ``static PyObject* <name>([...]){ ... } See Python's C API Reference for how to write c functions for python modules. """ method = "" """ str - calling method for this function (i.e. 'METH_VARARGS', 'METH_NOARGS'). """ doc = "" """ str - documentation string for this function. """ def __init__(self, name, code_block, method, doc="undocumented"): self.name = name self.code_block = code_block self.method = method self.doc = doc def method_decl(self): """ Returns the signature for this function. It goes into the DynamicModule's method table. """ return '\t{"%s", %s, %s, "%s"}' % ( self.name, self.name, self.method, self.doc) class DynamicModule(object): def __init__(self, name=None): assert name is None, ( "The 'name' parameter of DynamicModule" " cannot be specified anymore. Instead, 'code_hash'" " will be automatically computed and can be used as" " the module's name.") # While the module is not finalized, we can call add_... # when it is finalized, a hash is computed and used instead of # the placeholder, and as module name. self.finalized = False self.code_hash = None self.hash_placeholder = '<<<<HASH_PLACEHOLDER>>>>' self.support_code = [] self.functions = [] self.includes = ["<Python.h>", "<iostream>", '"theano_mod_helper.h"'] self.init_blocks = [] def print_methoddef(self, stream): print("static PyMethodDef MyMethods[] = {", file=stream) for f in self.functions: print(f.method_decl(), ',', file=stream) print("\t{NULL, NULL, 0, NULL}", file=stream) print("};", file=stream) def print_init(self, stream): if PY3: print("""\ static struct PyModuleDef moduledef = {{ PyModuleDef_HEAD_INIT, "{name}", NULL, -1, MyMethods, }}; """.format(name=self.hash_placeholder), file=stream) print(("PyMODINIT_FUNC PyInit_%s(void) {" % self.hash_placeholder), file=stream) for block in self.init_blocks: print(' ', block, file=stream) print(" PyObject *m = PyModule_Create(&moduledef);", file=stream) print(" return m;", file=stream) else: print(("PyMODINIT_FUNC init%s(void){" % self.hash_placeholder), file=stream) for block in self.init_blocks: print(' ', block, file=stream) print(' ', ('(void) Py_InitModule("%s", MyMethods);' % self.hash_placeholder), file=stream) print("}", file=stream) def add_include(self, str): assert not self.finalized self.includes.append(str) def add_init_code(self, code): assert not self.finalized self.init_blocks.append(code) def add_support_code(self, code): assert not self.finalized if code not in self.support_code: # TODO: KLUDGE self.support_code.append(code) def add_function(self, fn): assert not self.finalized self.functions.append(fn) def code(self): sio = StringIO() for inc in self.includes: if not inc: continue if inc[0] == '<' or inc[0] == '"': print("#include", inc, file=sio) else: print('#include "%s"' % inc, file=sio) print("//////////////////////", file=sio) print("//// Support Code", file=sio) print("//////////////////////", file=sio) for sc in self.support_code: print(sc, file=sio) print("//////////////////////", file=sio) print("//// Functions", file=sio) print("//////////////////////", file=sio) for f in self.functions: print(f.code_block, file=sio) print("//////////////////////", file=sio) print("//// Module init", file=sio) print("//////////////////////", file=sio) self.print_methoddef(sio) self.print_init(sio) rval = sio.getvalue() # Make sure the hash of the code hasn't changed h = hash_from_code(rval) assert self.code_hash is None or self.code_hash == h self.code_hash = h rval = re.sub(self.hash_placeholder, self.code_hash, rval) # Finalize the Module, so no support code or function # can be added self.finalized = True return rval def list_code(self, ofile=sys.stdout): """ Print out the code with line numbers to `ofile`. """ for i, line in enumerate(self.code().split('\n')): print(('%4i' % (i + 1)), line, file=ofile) ofile.flush() # TODO: add_type def dlimport(fullpath, suffix=None): """ Dynamically load a .so, .pyd, .dll, or .py file. Parameters ---------- fullpath : str A fully-qualified path do a compiled python module. suffix : str A suffix to strip from the end of fullpath to get the import name. Returns ------- object The dynamically loaded module (from __import__). """ if not os.path.isabs(fullpath): raise ValueError('`fullpath` must be an absolute path', fullpath) if suffix is None: if fullpath.endswith('.so'): suffix = '.so' elif fullpath.endswith('.pyd'): suffix = '.pyd' elif fullpath.endswith('.dll'): suffix = '.dll' elif fullpath.endswith('.py'): suffix = '.py' else: suffix = '' rval = None if fullpath.endswith(suffix): module_name = '.'.join(fullpath.split(os.path.sep)[-2:])[:-len(suffix)] else: raise ValueError('path has wrong suffix', (fullpath, suffix)) workdir = fullpath[:-len(module_name) - 1 - len(suffix)] _logger.debug("WORKDIR %s", workdir) _logger.debug("module_name %s", module_name) sys.path[0:0] = [workdir] # insert workdir at beginning (temporarily) global import_time try: if importlib is not None: if hasattr(importlib, "invalidate_caches"): importlib.invalidate_caches() t0 = time.time() with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="numpy.ndarray size changed") rval = __import__(module_name, {}, {}, [module_name]) t1 = time.time() import_time += t1 - t0 if not rval: raise Exception('__import__ failed', fullpath) finally: del sys.path[0] assert fullpath.startswith(rval.__file__) return rval def dlimport_workdir(basedir): """ Return a directory where you should put your .so file for dlimport to be able to load it, given a basedir which should normally be config.compiledir. """ return tempfile.mkdtemp(dir=basedir) def last_access_time(path): """ Return the number of seconds since the epoch of the last access of a given file. """ return os.stat(path)[stat.ST_ATIME] def module_name_from_dir(dirname, err=True, files=None): """ Scan the contents of a cache directory and return full path of the dynamic lib in it. """ if files is None: files = os.listdir(dirname) names = [file for file in files if file.endswith('.so') or file.endswith('.pyd')] if len(names) == 0 and not err: return None elif len(names) == 1: return os.path.join(dirname, names[0]) else: raise ValueError("More than 1 compiled module in this directory:" + dirname) def is_same_entry(entry_1, entry_2): """ Return True iff both paths can be considered to point to the same module. This is the case if and only if at least one of these conditions holds: - They are equal. - Their real paths are equal. - They share the same temporary work directory and module file name. """ if entry_1 == entry_2: return True if os.path.realpath(entry_1) == os.path.realpath(entry_2): return True if (os.path.basename(entry_1) == os.path.basename(entry_2) and (os.path.basename(os.path.dirname(entry_1)) == os.path.basename(os.path.dirname(entry_2))) and os.path.basename(os.path.dirname(entry_1)).startswith('tmp')): return True return False def get_module_hash(src_code, key): """ Return an MD5 hash that uniquely identifies a module. This hash takes into account: 1. The C source code of the module (`src_code`). 2. The version part of the key. 3. The compiler options defined in `key` (command line parameters and libraries to link against). 4. The NumPy ABI version. """ # `to_hash` will contain any element such that we know for sure that if # it changes, then the module hash should be different. # We start with the source code itself (stripping blanks might avoid # recompiling after a basic indentation fix for instance). to_hash = [l.strip() for l in src_code.split('\n')] # Get the version part of the key (ignore if unversioned). if key[0]: to_hash += list(map(str, key[0])) c_link_key = key[1] # Currently, in order to catch potential bugs early, we are very # convervative about the structure of the key and raise an exception # if it does not match exactly what we expect. In the future we may # modify this behavior to be less strict and be able to accomodate # changes to the key in an automatic way. # Note that if the key structure changes, the `get_safe_part` fucntion # below may also need to be modified. error_msg = ("This should not happen unless someone modified the code " "that defines the CLinker key, in which case you should " "ensure this piece of code is still valid (and this " "AssertionError may be removed or modified to accomodate " "this change)") assert c_link_key[0] == 'CLinker.cmodule_key', error_msg for key_element in c_link_key[1:]: if isinstance(key_element, tuple): # This should be the C++ compilation command line parameters or the # libraries to link against. to_hash += list(key_element) elif isinstance(key_element, string_types): if key_element.startswith('md5:'): # This is the md5 hash of the config options. We can stop # here. break elif (key_element.startswith('NPY_ABI_VERSION=0x') or key_element.startswith('c_compiler_str=')): to_hash.append(key_element) else: raise AssertionError(error_msg) else: raise AssertionError(error_msg) return hash_from_code('\n'.join(to_hash)) def get_safe_part(key): """ Return a tuple containing a subset of `key`, to be used to find equal keys. This tuple should only contain objects whose __eq__ and __hash__ methods can be trusted (currently: the version part of the key, as well as the md5 hash of the config options). It is used to reduce the amount of key comparisons one has to go through in order to find broken keys (i.e. keys with bad implementations of __eq__ or __hash__). """ version = key[0] # This function should only be called on versioned keys. assert version # Find the md5 hash part. c_link_key = key[1] for key_element in c_link_key[1:]: if (isinstance(key_element, string_types) and key_element.startswith('md5:')): md5 = key_element[4:] break return key[0] + (md5, ) class KeyData(object): """ Used to store the key information in the cache. Parameters ---------- keys Set of keys that are associated to the exact same module. module_hash Hash identifying the module (it should hash both the code and the compilation options). key_pkl Path to the file in which this KeyData object should be pickled. """ def __init__(self, keys, module_hash, key_pkl, entry): self.keys = keys self.module_hash = module_hash self.key_pkl = key_pkl self.entry = entry def add_key(self, key, save_pkl=True): """ Add a key to self.keys, and update pickled file if asked to. """ assert key not in self.keys self.keys.add(key) if save_pkl: self.save_pkl() def remove_key(self, key, save_pkl=True): """ Remove a key from self.keys, and update pickled file if asked to. """ self.keys.remove(key) if save_pkl: self.save_pkl() def save_pkl(self): """ Dump this object into its `key_pkl` file. May raise a cPickle.PicklingError if such an exception is raised at pickle time (in which case a warning is also displayed). """ # Note that writing in binary mode is important under Windows. try: with open(self.key_pkl, 'wb') as f: pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL) except pickle.PicklingError: _logger.warning("Cache leak due to unpickle-able key data %s", self.keys) os.remove(self.key_pkl) raise def get_entry(self): """ Return path to the module file. """ # TODO This method may be removed in the future (e.g. in 0.5) since # its only purpose is to make sure that old KeyData objects created # before the 'entry' field was added are properly handled. if not hasattr(self, 'entry'): self.entry = module_name_from_dir(os.path.dirname(self.key_pkl)) return self.entry def delete_keys_from(self, entry_from_key, do_manual_check=True): """ Delete from entry_from_key all keys associated to this KeyData object. Note that broken keys will not appear in the keys field, so we also manually look for keys associated to the same entry, unless do_manual_check is False. """ entry = self.get_entry() for key in self.keys: del entry_from_key[key] if do_manual_check: to_del = [] for key, key_entry in iteritems(entry_from_key): if key_entry == entry: to_del.append(key) for key in to_del: del entry_from_key[key] class ModuleCache(object): """ Interface to the cache of dynamically compiled modules on disk. Note that this interface does not assume exclusive use of the cache directory. It is built to handle the case where multiple programs are also using instances of this class to manage the same directory. The cache works on the basis of keys. Each key is mapped to only one dynamic module, but multiple keys may be mapped to the same module (see below for details). Each module is a dynamic library file, that Python can import. The cache contains one directory for each module, containing: - the dynamic library file itself (.so/.pyd), - an empty __init__.py file, so Python can import it, - a file containing the source code for the module (mod.cpp/mod.cu), - a key.pkl file, containing a KeyData object with all the keys associated with that module, - possibly a delete.me file, meaning this directory has been marked for deletion. Keys should be tuples of length 2: (version, rest). The ``rest`` can be anything hashable and picklable, that uniquely identifies the computation in the module. The key is returned by ``CLinker.cmodule_key_``. The ``version`` should be a hierarchy of tuples of integers. If the ``version`` is either 0 or (), then the key is unversioned, and its corresponding module will be marked for deletion in an atexit() handler. If the ``version`` is neither 0 nor (), then the module will be kept in the cache between processes. An unversioned module is not always deleted by the process that creates it. Deleting such modules may not work on NFS filesystems because the tmpdir in which the library resides is in use until the end of the process' lifetime. In this case, unversioned modules are left in their tmpdirs without corresponding .pkl files. These modules and their directories are erased by subsequent processes' refresh() functions. Two different keys are mapped to the same module when all conditions below are met: - They have the same version. - They share the same compilation options in their ``rest`` part (see ``CLinker.cmodule_key_`` for how this part is built). - They share the same C code. These three elements uniquely identify a module, and are summarized in a single "module hash". Parameters ---------- check_for_broken_eq A bad __eq__ implementation can break this cache mechanism. This option turns on a not-too-expensive sanity check every time a new key is added to the cache. do_refresh : bool If True, then the ``refresh`` method will be called in the constructor. """ dirname = "" """ The working directory that is managed by this interface. """ module_from_name = {} """ Maps a module filename to the loaded module object. """ entry_from_key = {} """ Maps keys to the filename of a .so/.pyd. """ similar_keys = {} """ Maps a part-of-key to all keys that share this same part. """ module_hash_to_key_data = {} """ Maps a module hash to its corresponding KeyData object. """ stats = [] """ A list with counters for the number of hits, loads, compiles issued by module_from_key(). """ loaded_key_pkl = set() """ Set of all key.pkl files that have been loaded. """ def __init__(self, dirname, check_for_broken_eq=True, do_refresh=True): self.dirname = dirname self.module_from_name = dict(self.module_from_name) self.entry_from_key = dict(self.entry_from_key) self.module_hash_to_key_data = dict(self.module_hash_to_key_data) self.similar_keys = dict(self.similar_keys) self.stats = [0, 0, 0] self.check_for_broken_eq = check_for_broken_eq self.loaded_key_pkl = set() self.time_spent_in_check_key = 0 if do_refresh: self.refresh() age_thresh_use = 60 * 60 * 24 * 24 # 24 days """ The default age threshold (in seconds) for cache files we want to use. Older modules will be deleted in ``clear_old``. """ def _get_module(self, name): """ Fetch a compiled module from the loaded cache or the disk. """ if name not in self.module_from_name: _logger.debug('loading name %s', name) self.module_from_name[name] = dlimport(name) self.stats[1] += 1 else: _logger.debug('returning compiled module from cache %s', name) self.stats[0] += 1 return self.module_from_name[name] def refresh(self, age_thresh_use=None, delete_if_problem=False, cleanup=True): """ Update cache data by walking the cache directory structure. Load key.pkl files that have not been loaded yet. Remove entries which have been removed from the filesystem. Also, remove malformed cache directories. Parameters ---------- age_thresh_use Do not use modules other than this. Defaults to self.age_thresh_use. delete_if_problem : bool If True, cache entries that meet one of those two conditions are deleted: - Those for which unpickling the KeyData file fails with an unknown exception. - Duplicated modules, regardless of their age. cleanup : bool Do a cleanup of the cache removing expired and broken modules. Returns ------- list A list of modules of age higher than age_thresh_use. """ if age_thresh_use is None: age_thresh_use = self.age_thresh_use start_time = time.time() too_old_to_use = [] to_delete = [] to_delete_empty = [] def rmtree(*args, **kwargs): if cleanup: to_delete.append((args, kwargs)) def rmtree_empty(*args, **kwargs): if cleanup: to_delete_empty.append((args, kwargs)) # add entries that are not in the entry_from_key dictionary time_now = time.time() # Go through directories in alphabetical order to ensure consistent # behavior. subdirs = sorted(os.listdir(self.dirname)) files, root = None, None # To make sure the "del" below works for subdirs_elem in subdirs: # Never clean/remove lock_dir if subdirs_elem == 'lock_dir': continue root = os.path.join(self.dirname, subdirs_elem) key_pkl = os.path.join(root, 'key.pkl') if key_pkl in self.loaded_key_pkl: continue if not os.path.isdir(root): continue files = os.listdir(root) if not files: rmtree_empty(root, ignore_nocleanup=True, msg="empty dir") continue if 'delete.me' in files: rmtree(root, ignore_nocleanup=True, msg="delete.me found in dir") continue elif 'key.pkl' in files: try: entry = module_name_from_dir(root, files=files) except ValueError: # there is a key but no dll! if not root.startswith("/tmp"): # Under /tmp, file are removed periodically by the # os. So it is normal that this happens from time # to time. _logger.warning("ModuleCache.refresh() Found key " "without dll in cache, deleting it. %s", key_pkl) rmtree(root, ignore_nocleanup=True, msg="missing module file", level=logging.INFO) continue if (time_now - last_access_time(entry)) < age_thresh_use: _logger.debug('refresh adding %s', key_pkl) def unpickle_failure(): _logger.info("ModuleCache.refresh() Failed to " "unpickle cache file %s", key_pkl) try: with open(key_pkl, 'rb') as f: key_data = pickle.load(f) except EOFError: # Happened once... not sure why (would be worth # investigating if it ever happens again). unpickle_failure() rmtree(root, ignore_nocleanup=True, msg='broken cache directory [EOF]', level=logging.WARNING) continue except ValueError: # This can happen when we have bad config value # in the cuda.nvcc_compiler.py file. # We should not hide it here, as this will cause # an unrelated error to appear. raise except Exception: unpickle_failure() if delete_if_problem: rmtree(root, ignore_nocleanup=True, msg='broken cache directory', level=logging.INFO) else: # This exception is often triggered by keys # that contain references to classes that have # not yet been imported (e.g. when running two # different Theano-based scripts). They are not # necessarily broken, but we cannot load them # now. They will be loaded later if needed. pass continue if not isinstance(key_data, KeyData): # This is some old cache data, that does not fit # the new cache format. It would be possible to # update it, but it is not entirely safe since we # do not know the config options that were used. # As a result, we delete it instead (which is also # simpler to implement). rmtree(root, ignore_nocleanup=True, msg=( 'invalid cache entry format -- this ' 'should not happen unless your cache ' 'was really old'), level=logging.WARN) continue # Check the path to the module stored in the KeyData # object matches the path to `entry`. There may be # a mismatch e.g. due to symlinks, or some directory # being renamed since last time cache was created. kd_entry = key_data.get_entry() if kd_entry != entry: if is_same_entry(entry, kd_entry): # Update KeyData object. Note that we also need # to update the key_pkl field, because it is # likely to be incorrect if the entry itself # was wrong. key_data.entry = entry key_data.key_pkl = key_pkl else: # This is suspicious. Better get rid of it. rmtree(root, ignore_nocleanup=True, msg='module file path mismatch', level=logging.INFO) continue # Find unversioned keys from other processes. # TODO: check if this can happen at all to_del = [key for key in key_data.keys if not key[0]] if to_del: _logger.warning( "ModuleCache.refresh() Found unversioned " "key in cache, removing it. %s", key_pkl) # Since the version is in the module hash, all # keys should be unversioned. if len(to_del) != len(key_data.keys): _logger.warning( 'Found a mix of unversioned and ' 'versioned keys for the same ' 'module %s', key_pkl) rmtree(root, ignore_nocleanup=True, msg="unversioned key(s) in cache", level=logging.INFO) continue mod_hash = key_data.module_hash if mod_hash in self.module_hash_to_key_data: # This may happen when two processes running # simultaneously compiled the same module, one # after the other. We delete one once it is old # enough (to be confident there is no other process # using it), or if `delete_if_problem` is True. # Note that it is important to walk through # directories in alphabetical order so as to make # sure all new processes only use the first one. if cleanup: age = time.time() - last_access_time(entry) if delete_if_problem or age > self.age_thresh_del: rmtree(root, ignore_nocleanup=True, msg='duplicated module', level=logging.DEBUG) else: _logger.debug('Found duplicated module not ' 'old enough yet to be deleted ' '(age: %s): %s', age, entry) continue # Remember the map from a module's hash to the KeyData # object associated with it. self.module_hash_to_key_data[mod_hash] = key_data for key in key_data.keys: if key not in self.entry_from_key: self.entry_from_key[key] = entry # Assert that we have not already got this # entry somehow. assert entry not in self.module_from_name # Store safe part of versioned keys. if key[0]: self.similar_keys.setdefault( get_safe_part(key), []).append(key) else: dir1 = os.path.dirname(self.entry_from_key[key]) dir2 = os.path.dirname(entry) _logger.warning( "The same cache key is associated to " "different modules (%s and %s). This " "is not supposed to happen! You may " "need to manually delete your cache " "directory to fix this.", dir1, dir2) # Clean up the name space to prevent bug. if key_data.keys: del key self.loaded_key_pkl.add(key_pkl) else: too_old_to_use.append(entry) # If the compilation failed, no key.pkl is in that # directory, but a mod.* should be there. # We do nothing here. # Clean up the name space to prevent bug. del root, files, subdirs # Remove entries that are not in the filesystem. items_copy = list(self.module_hash_to_key_data.items()) for module_hash, key_data in items_copy: entry = key_data.get_entry() try: # Test to see that the file is [present and] readable. open(entry).close() gone = False except IOError: gone = True if gone: # Assert that we did not have one of the deleted files # loaded up and in use. # If so, it should not have been deleted. This should be # considered a failure of the OTHER process, that deleted # it. if entry in self.module_from_name: _logger.warning("A module that was loaded by this " "ModuleCache can no longer be read from file " "%s... this could lead to problems.", entry) del self.module_from_name[entry] _logger.info("deleting ModuleCache entry %s", entry) key_data.delete_keys_from(self.entry_from_key) del self.module_hash_to_key_data[module_hash] if key_data.keys and list(key_data.keys)[0][0]: # this is a versioned entry, so should have been on # disk. Something weird happened to cause this, so we # are responding by printing a warning, removing # evidence that we ever saw this mystery key. pkl_file_to_remove = key_data.key_pkl if not key_data.key_pkl.startswith("/tmp"): # Under /tmp, file are removed periodically by the # os. So it is normal that this happen from time to # time. _logger.warning("Removing key file %s because the " "corresponding module is gone from the " "file system.", pkl_file_to_remove) self.loaded_key_pkl.remove(pkl_file_to_remove) if to_delete or to_delete_empty: with compilelock.lock_ctx(): for a, kw in to_delete: _rmtree(*a, **kw) for a, kw in to_delete_empty: files = os.listdir(a[0]) if not files: _rmtree(*a, **kw) _logger.debug('Time needed to refresh cache: %s', (time.time() - start_time)) return too_old_to_use def _get_from_key(self, key, key_data=None): """ Returns a module if the passed-in key is found in the cache and None otherwise. May raise ValueError if the key is malformed. """ name = None if key is not None: assert key_data is None try: _version, _rest = key except (TypeError, ValueError): raise ValueError( "Invalid key. key must have form (version, rest)", key) if key in self.entry_from_key: name = self.entry_from_key[key] else: assert key_data is not None name = key_data.get_entry() if name is None: return None return self._get_module(name) def _get_from_hash(self, module_hash, key, keep_lock=False): if module_hash in self.module_hash_to_key_data: key_data = self.module_hash_to_key_data[module_hash] module = self._get_from_key(None, key_data) with compilelock.lock_ctx(keep_lock=keep_lock): try: key_data.add_key(key, save_pkl=bool(key[0])) key_broken = False except pickle.PicklingError: key_data.remove_key(key) key_broken = True # We need the lock while we check in case of parallel # process that could be changing the file at the same # time. if (key[0] and not key_broken and self.check_for_broken_eq): self.check_key(key, key_data.key_pkl) self._update_mappings(key, key_data, module.__file__, check_in_keys=not key_broken) return module else: return None def _update_mappings(self, key, key_data, name, check_in_keys): all_keys = key_data.keys if not all_keys: all_keys = [key] if check_in_keys: assert key in all_keys for k in all_keys: if k in self.entry_from_key: assert self.entry_from_key[k] == name else: self.entry_from_key[k] = name if key[0]: self.similar_keys.setdefault(get_safe_part(k), []).append(key) def _add_to_cache(self, module, key, module_hash): """ This function expects the compile lock to be held. """ name = module.__file__ _logger.debug("Adding module to cache %s %s", key, name) # Changing the hash of the key is not allowed during # compilation. That is the only cause found that makes # the following assert fail. assert key not in self.entry_from_key location = os.path.dirname(name) key_pkl = os.path.join(location, 'key.pkl') assert not os.path.exists(key_pkl) key_data = KeyData( keys=set([key]), module_hash=module_hash, key_pkl=key_pkl, entry=name) key_broken = False if key[0]: try: key_data.save_pkl() except pickle.PicklingError: key_broken = True key_data.remove_key(key) key_data.save_pkl() if not key_broken and self.check_for_broken_eq: self.check_key(key, key_pkl) self.loaded_key_pkl.add(key_pkl) elif config.cmodule.warn_no_version: key_flat = flatten(key) ops = [k for k in key_flat if isinstance(k, theano.Op)] _logger.warning("not all the" " following op(s) implement" " c_code_cache_version(). This makes them" " recompiled for each process." + str(ops)) self._update_mappings(key, key_data, module.__file__, not key_broken) return key_data def module_from_key(self, key, lnk=None, keep_lock=False): """ Return a module from the cache, compiling it if necessary. Parameters ---------- key The key object associated with the module. If this hits a match, we avoid compilation. lnk Usually a CLinker instance, but it can be any object that defines the `get_src_code()` and `compile_cmodule(location)` functions. The first one returns the source code of the module to load/compile and the second performs the actual compilation. keep_lock : bool If True, the compilation lock will not be released if taken. """ # Is the module in the cache? module = self._get_from_key(key) if module is not None: return module src_code = lnk.get_src_code() # Is the source code already in the cache? module_hash = get_module_hash(src_code, key) module = self._get_from_hash(module_hash, key, keep_lock=keep_lock) if module is not None: return module with compilelock.lock_ctx(keep_lock=keep_lock): # 1) Maybe somebody else compiled it for us while we # where waiting for the lock. Try to load it again. # 2) If other repo that import Theano have Theano ops defined, # we need to refresh the cache here. Otherwise, there are import # order problems. # When device=gpu, we compile during Theano # import. This triggers the loading of the cache. But # unpickling the cache asks that the external Ops are # completly loaded, which isn't always the case! # If a module isn't completly loaded and its unpickling # fails, it means it is safe for this function # compilation to skip them, but not for future # compilations. So reloading the cache here # compilation fixes this problem. (we could do that only once) self.refresh(cleanup=False) module = self._get_from_key(key) if module is not None: return module module = self._get_from_hash(module_hash, key) if module is not None: return module hash_key = hash(key) nocleanup = False try: location = dlimport_workdir(self.dirname) module = lnk.compile_cmodule(location) name = module.__file__ assert name.startswith(location) assert name not in self.module_from_name self.module_from_name[name] = module nocleanup = True except OSError as e: _logger.error(e) if e.errno == 31: _logger.error('There are %i files in %s', len(os.listdir(config.compiledir)), config.compiledir) raise finally: if not nocleanup: _rmtree(location, ignore_if_missing=True, msg='exception during compilation') # Changing the hash of the key is not allowed during # compilation. assert hash(key) == hash_key key_data = self._add_to_cache(module, key, module_hash) self.module_hash_to_key_data[module_hash] = key_data self.stats[2] += 1 return module def check_key(self, key, key_pkl): """ Perform checks to detect broken __eq__ / __hash__ implementations. Parameters ---------- key The key to be checked. key_pkl Its associated pickled file containing a KeyData. """ start_time = time.time() # Verify that when we reload the KeyData from the pickled file, the # same key can be found in it, and is not equal to more than one # other key. for i in range(3): try: with open(key_pkl, 'rb') as f: key_data = pickle.load(f) break except EOFError: # This file is probably getting written/updated at the # same time. This can happen as we read the cache # without taking the lock. if i == 2: with compilelock.lock_ctx(): with open(key_pkl, 'rb') as f: key_data = pickle.load(f) time.sleep(2) found = sum(key == other_key for other_key in key_data.keys) msg = '' if found == 0: msg = 'Key not found in unpickled KeyData file' if key_data.keys: # This is to make debugging in pdb easier, by providing # the offending keys in the local context. # key_data_keys = list(key_data.keys) # import pdb; pdb.set_trace() pass elif found > 1: msg = 'Multiple equal keys found in unpickled KeyData file' if msg: raise AssertionError( "%s. Verify the __eq__ and __hash__ functions of your " "Ops. The file is: %s. The key is: %s" % (msg, key_pkl, key)) # Also verify that there exists no other loaded key that would be equal # to this key. In order to speed things up, we only compare to keys # with the same version part and config md5, since we can assume this # part of the key is not broken. for other in self.similar_keys.get(get_safe_part(key), []): if other is not key and other == key and hash(other) != hash(key): raise AssertionError( "Found two keys that are equal but have a different hash. " "Verify the __eq__ and __hash__ functions of your Ops. " "The keys are:\n %s\nand\n %s\n(found in %s)." % (other, key, key_pkl)) self.time_spent_in_check_key += time.time() - start_time age_thresh_del = 60 * 60 * 24 * 31 # 31 days age_thresh_del_unversioned = 60 * 60 * 24 * 7 # 7 days """ The default age threshold for `clear_old` (in seconds). """ def clear_old(self, age_thresh_del=None, delete_if_problem=False): """Delete entries from the filesystem for cache entries that are too old. This refreshes the content of the cache. Don't hold the lock while calling this method, this is useless. It will be taken if needed. Parameters ---------- age_thresh_del Dynamic modules whose last access time is more than ``age_thresh_del`` seconds ago will be erased. Defaults to 31-day age if not provided. delete_if_problem See help of refresh() method. """ if age_thresh_del is None: age_thresh_del = self.age_thresh_del # Ensure that the too_old_to_use list return by refresh() will # contain all modules older than age_thresh_del. if age_thresh_del < self.age_thresh_use: if age_thresh_del > 0: _logger.warning("Clearing modules that were not deemed " "too old to use: age_thresh_del=%d, " "self.age_thresh_use=%d", age_thresh_del, self.age_thresh_use) else: _logger.info("Clearing all modules.") age_thresh_use = age_thresh_del else: age_thresh_use = None too_old_to_use = self.refresh( age_thresh_use=age_thresh_use, delete_if_problem=delete_if_problem, # The clean up is done at init, no need to trigger it again cleanup=False) if not too_old_to_use: return with compilelock.lock_ctx(): # Update the age of modules that have been accessed by other # processes and get all module that are too old to use # (not loaded in self.entry_from_key). for entry in too_old_to_use: # TODO: we are assuming that modules that haven't been # accessed in over age_thresh_del are not currently in # use by other processes, but that could be false for # long-running jobs, or if age_thresh_del < 0. assert entry not in self.module_from_name parent = os.path.dirname(entry) assert parent.startswith(os.path.join(self.dirname, 'tmp')) _rmtree(parent, msg='old cache directory', level=logging.INFO, ignore_nocleanup=True) def clear(self, unversioned_min_age=None, clear_base_files=False, delete_if_problem=False): """ Clear all elements in the cache. Parameters ---------- unversioned_min_age Forwarded to `clear_unversioned`. In particular, you can set it to -1 in order to delete all unversioned cached modules regardless of their age. clear_base_files : bool If True, then delete base directories 'cuda_ndarray', 'cutils_ext', 'lazylinker_ext' and 'scan_perform' if they are present. If False, those directories are left intact. delete_if_problem See help of refresh() method. """ with compilelock.lock_ctx(): self.clear_old( age_thresh_del=-1.0, delete_if_problem=delete_if_problem) self.clear_unversioned(min_age=unversioned_min_age) if clear_base_files: self.clear_base_files() def clear_base_files(self): """ Remove base directories 'cuda_ndarray', 'cutils_ext', 'lazylinker_ext' and 'scan_perform' if present. Note that we do not delete them outright because it may not work on some systems due to these modules being currently in use. Instead we rename them with the '.delete.me' extension, to mark them to be deleted next time we clear the cache. """ with compilelock.lock_ctx(): for base_dir in ('cuda_ndarray', 'cutils_ext', 'lazylinker_ext', 'scan_perform'): to_delete = os.path.join(self.dirname, base_dir + '.delete.me') if os.path.isdir(to_delete): try: shutil.rmtree(to_delete) _logger.debug('Deleted: %s', to_delete) except Exception: _logger.warning('Could not delete %s', to_delete) continue to_rename = os.path.join(self.dirname, base_dir) if os.path.isdir(to_rename): try: shutil.move(to_rename, to_delete) except Exception: _logger.warning('Could not move %s to %s', to_rename, to_delete) def clear_unversioned(self, min_age=None): """Delete unversioned dynamic modules. They are deleted both from the internal dictionaries and from the filesystem. No need to have the lock when calling this method. It does not take the lock as unversioned module aren't shared. This method does not refresh the cache content, it just accesses the in-memory known module(s). Parameters ---------- min_age Minimum age to be deleted, in seconds. Defaults to 7-day age if not provided. """ if min_age is None: min_age = self.age_thresh_del_unversioned # As this delete object that we build and other don't use, we # don't need the lock. all_key_datas = list(self.module_hash_to_key_data.values()) for key_data in all_key_datas: if not key_data.keys: # May happen for broken versioned keys. continue for key_idx, key in enumerate(key_data.keys): version, rest = key if version: # Since the version is included in the module hash, # it should not be possible to mix versioned and # unversioned keys in the same KeyData object. assert key_idx == 0 break if not version: # Note that unversioned keys cannot be broken, so we can # set do_manual_check to False to speed things up. key_data.delete_keys_from(self.entry_from_key, do_manual_check=False) entry = key_data.get_entry() # Entry is guaranteed to be in this dictionary, because # an unversioned entry should never have been loaded via # refresh. assert entry in self.module_from_name del self.module_from_name[entry] del self.module_hash_to_key_data[key_data.module_hash] parent = os.path.dirname(entry) assert parent.startswith(os.path.join(self.dirname, 'tmp')) _rmtree(parent, msg='unversioned', level=logging.INFO, ignore_nocleanup=True) # Sanity check: all unversioned keys should have been removed at # this point. for key in self.entry_from_key: assert key[0] to_del = [] time_now = time.time() for filename in os.listdir(self.dirname): if filename.startswith('tmp'): try: fname = os.path.join(self.dirname, filename, 'key.pkl') open(fname).close() has_key = True except IOError: has_key = False if not has_key: # Use the compiled file by default path = module_name_from_dir(os.path.join(self.dirname, filename), False) # If it don't exist, use any file in the directory. if path is None: path = os.path.join(self.dirname, filename) files = os.listdir(path) if files: path = os.path.join(path, files[0]) else: # If the directory is empty skip it. # They are deleted elsewhere. continue age = time_now - last_access_time(path) # In normal case, the processus that created this # directory will delete it. However, if this processus # crashes, it will not be cleaned up. # As we don't know if this directory is still used, # we wait one week and suppose that the processus # crashed, and we take care of the clean-up. if age > min_age: to_del.append(os.path.join(self.dirname, filename)) # No need to take the lock as it isn't shared. for f in to_del: _rmtree(f, msg='old unversioned', level=logging.INFO, ignore_nocleanup=True) def _on_atexit(self): # Note: no need to call refresh() since it is called by clear_old(). # Note: no need to take the lock. For unversioned files, we # don't need it as they aren't shared. For old unversioned # files, this happen rarely, so we take the lock only when # this happen. # Note: for clear_old(), as this happen unfrequently, we only # take the lock when it happen. self.clear_old() self.clear_unversioned() _logger.debug('Time spent checking keys: %s', self.time_spent_in_check_key) def _rmtree(parent, ignore_nocleanup=False, msg='', level=logging.DEBUG, ignore_if_missing=False): # On NFS filesystems, it is impossible to delete a directory with open # files in it. So instead, some commands in this file will respond to a # failed rmtree() by touching a 'delete.me' file. This file is a message # for a future process to try deleting the directory. if ignore_if_missing and not os.path.exists(parent): return try: if ignore_nocleanup or not config.nocleanup: log_msg = 'Deleting' if msg: log_msg += ' (%s)' % msg _logger.log(level, '%s: %s', log_msg, parent) shutil.rmtree(parent) except Exception as e: # If parent still exists, mark it for deletion by a future refresh() _logger.debug('In _rmtree, encountered exception: %s(%s)', type(e), e) if os.path.exists(parent): try: _logger.info('placing "delete.me" in %s', parent) open(os.path.join(parent, 'delete.me'), 'w').close() except Exception as ee: _logger.warning("Failed to remove or mark cache directory %s " "for removal %s", parent, ee) _module_cache = None def get_module_cache(dirname, init_args=None): """ Parameters ---------- init_args If not None, the (k, v) pairs in this dictionary will be forwarded to the ModuleCache constructor as keyword arguments. """ global _module_cache if init_args is None: init_args = {} if _module_cache is None: _module_cache = ModuleCache(dirname, **init_args) atexit.register(_module_cache._on_atexit) elif init_args: _logger.warning('Ignoring init arguments for module cache because it ' 'was created prior to this call') if _module_cache.dirname != dirname: _logger.warning("Returning module cache instance with different " "dirname (%s) than you requested (%s)", _module_cache.dirname, dirname) return _module_cache def get_lib_extension(): """ Return the platform-dependent extension for compiled modules. """ if sys.platform in ['win32', 'cygwin']: return 'pyd' else: return 'so' def get_gcc_shared_library_arg(): """ Return the platform-dependent GCC argument for shared libraries. """ if sys.platform == 'darwin': return '-dynamiclib' else: return '-shared' def std_include_dirs(): numpy_inc_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() py_inc = distutils.sysconfig.get_python_inc() py_plat_spec_inc = distutils.sysconfig.get_python_inc(plat_specific=True) python_inc_dirs = ([py_inc] if py_inc == py_plat_spec_inc else [py_inc, py_plat_spec_inc]) gof_inc_dir = os.path.abspath(os.path.dirname(__file__)) return numpy_inc_dirs + python_inc_dirs + [gof_inc_dir] def std_lib_dirs_and_libs(): # We cache the results as on Windows, this trigger file access and # this method is called many times. if std_lib_dirs_and_libs.data is not None: return std_lib_dirs_and_libs.data python_inc = distutils.sysconfig.get_python_inc() if sys.platform == 'win32': # Obtain the library name from the Python version instead of the # installation directory, in case the user defined a custom # installation directory. python_version = distutils.sysconfig.get_python_version() libname = 'python' + python_version.replace('.', '') # Also add directory containing the Python library to the library # directories. python_lib_dirs = [os.path.join(os.path.dirname(python_inc), 'libs')] if "Canopy" in python_lib_dirs[0]: # Canopy stores libpython27.a and libmsccr90.a in this directory. # For some reason, these files are needed when compiling Python # modules, even when libpython27.lib and python27.dll are # available, and the *.a files have to be found earlier than # the other ones. # When Canopy is installed for the user: # sys.prefix:C:\Users\username\AppData\Local\Enthought\Canopy\User # sys.base_prefix:C:\Users\username\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64 # When Canopy is installed for all users: # sys.base_prefix: C:\Program Files\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64 # sys.prefix: C:\Users\username\AppData\Local\Enthought\Canopy\User # So we need to use sys.prefix as it support both cases. # sys.base_prefix support only one case libdir = os.path.join(sys.prefix, 'libs') for f, lib in [('libpython27.a', 'libpython 1.2')]: if not os.path.exists(os.path.join(libdir, f)): print(("Your Python version is from Canopy. " + "You need to install the package '" + lib + "' from Canopy package manager." )) libdirs = [ # Used in older Canopy os.path.join(sys.prefix, 'libs'), # Used in newer Canopy os.path.join(sys.prefix, r'EGG-INFO\mingw\usr\x86_64-w64-mingw32\lib')] for f, lib in [('libmsvcr90.a', 'mingw 4.5.2 or 4.8.1-2 (newer could work)')]: if not any([os.path.exists(os.path.join(tmp_libdir, f)) for tmp_libdir in libdirs]): print(("Your Python version is from Canopy. " + "You need to install the package '" + lib + "' from Canopy package manager." )) python_lib_dirs.insert(0, libdir) std_lib_dirs_and_libs.data = [libname], python_lib_dirs # Suppress -lpython2.x on OS X since the `-undefined dynamic_lookup` # makes it unnecessary. elif sys.platform == 'darwin': std_lib_dirs_and_libs.data = [], [] else: # assume Linux # Typical include directory: /usr/include/python2.6 # get the name of the python library (shared object) libname = distutils.sysconfig.get_config_var("LDLIBRARY") if libname.startswith("lib"): libname = libname[3:] # remove extension if present if libname.endswith(".so"): libname = libname[:-3] elif libname.endswith(".a"): libname = libname[:-2] libdir = distutils.sysconfig.get_config_var("LIBDIR") std_lib_dirs_and_libs.data = [libname], [libdir] # sometimes, the linker cannot find -lpython so we need to tell it # explicitly where it is located this returns # somepath/lib/python2.x python_lib = distutils.sysconfig.get_python_lib(plat_specific=1, standard_lib=1) python_lib = os.path.dirname(python_lib) if python_lib not in std_lib_dirs_and_libs.data[1]: std_lib_dirs_and_libs.data[1].append(python_lib) return std_lib_dirs_and_libs.data std_lib_dirs_and_libs.data = None def std_libs(): return std_lib_dirs_and_libs()[0] def std_lib_dirs(): return std_lib_dirs_and_libs()[1] def gcc_version(): return gcc_version_str def gcc_llvm(): """ Detect if the g++ version used is the llvm one or not. It don't support all g++ parameters even if it support many of them. """ if gcc_llvm.is_llvm is None: try: p_out = output_subprocess_Popen([theano.config.cxx, '--version']) output = p_out[0] + p_out[1] except OSError: # Typically means g++ cannot be found. # So it is not an llvm compiler. # Normally this should not happen as we should not try to # compile when g++ is not available. If this happen, it # will crash later so supposing it is not llvm is "safe". output = b('') gcc_llvm.is_llvm = b("llvm") in output return gcc_llvm.is_llvm gcc_llvm.is_llvm = None class Compiler(object): """ Meta compiler that offer some generic function. """ @staticmethod def _try_compile_tmp(src_code, tmp_prefix='', flags=(), try_run=False, output=False, compiler=None): """ Try to compile (and run) a test program. This is useful in various occasions, to check if libraries or compilers are behaving as expected. If try_run is True, the src_code is assumed to be executable, and will be run. If try_run is False, returns the compilation status. If try_run is True, returns a (compile_status, run_status) pair. If output is there, we append the stdout and stderr to the output. """ if not compiler: return False flags = list(flags) compilation_ok = True run_ok = False out, err = None, None try: fd, path = tempfile.mkstemp(suffix='.c', prefix=tmp_prefix) exe_path = path[:-2] try: # Python3 compatibility: try to cast Py3 strings as Py2 strings try: src_code = b(src_code) except Exception: pass os.write(fd, src_code) os.close(fd) fd = None out, err, p_ret = output_subprocess_Popen( [compiler, path, '-o', exe_path] + flags) if p_ret != 0: compilation_ok = False elif try_run: out, err, p_ret = output_subprocess_Popen([exe_path]) run_ok = (p_ret == 0) finally: try: if fd is not None: os.close(fd) finally: if os.path.exists(path): os.remove(path) if os.path.exists(exe_path): os.remove(exe_path) if os.path.exists(exe_path + ".exe"): os.remove(exe_path + ".exe") except OSError as e: if err is None: err = str(e) else: err += "\n" + str(e) compilation_ok = False if not try_run and not output: return compilation_ok elif not try_run and output: return (compilation_ok, out, err) elif not output: return (compilation_ok, run_ok) else: return (compilation_ok, run_ok, out, err) @staticmethod def _try_flags(flag_list, preambule="", body="", try_run=False, output=False, compiler=None): """ Try to compile a dummy file with these flags. Returns True if compilation was successful, False if there were errors. """ if not compiler: return False code = b(""" %(preambule)s int main(int argc, char** argv) { %(body)s return 0; } """ % locals()) return Compiler._try_compile_tmp(code, tmp_prefix='try_flags_', flags=flag_list, try_run=try_run, output=output, compiler=compiler) class GCC_compiler(Compiler): # The equivalent flags of --march=native used by g++. march_flags = None supports_amdlibm = True @staticmethod def version_str(): return theano.config.cxx + " " + gcc_version_str @staticmethod def compile_args(): cxxflags = [flag for flag in config.gcc.cxxflags.split(' ') if flag] # Add the equivalent of -march=native flag. We can't use # -march=native as when the compiledir is shared by multiple # computers (for example, if the home directory is on NFS), this # won't be optimum or cause crash depending if the file is compiled # on an older or more recent computer. # Those URL discuss how to find witch flags are used by -march=native. # http://en.gentoo-wiki.com/wiki/Safe_Cflags#-march.3Dnative # http://en.gentoo-wiki.com/wiki/Hardware_CFLAGS detect_march = GCC_compiler.march_flags is None if detect_march: for f in cxxflags: # If the user give an -march=X parameter, don't add one ourself if ((f.startswith("--march=") or f.startswith("-march="))): _logger.warn( "WARNING: your Theano flags `gcc.cxxflags` specify" " an `-march=X` flags.\n" " It is better to let Theano/g++ find it" " automatically, but we don't do it now") detect_march = False GCC_compiler.march_flags = [] break if ('g++' not in theano.config.cxx and 'clang++' not in theano.config.cxx and 'clang-omp++' not in theano.config.cxx): _logger.warn( "OPTIMIZATION WARNING: your Theano flag `cxx` seems not to be" " the g++ compiler. So we disable the compiler optimization" " specific to g++ that tell to compile for a specific CPU." " At worst, this could cause slow down.\n" " You can add those parameters to the compiler yourself" " via the Theano flag `gcc.cxxflags`." ) detect_march = False if detect_march: GCC_compiler.march_flags = [] def get_lines(cmd, parse=True): p = subprocess_Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) # For mingw64 with GCC >= 4.7, passing os.devnull # as stdin (which is the default) results in the process # waiting forever without returning. For that reason, # we use a pipe, and use the empty string as input. (stdout, stderr) = p.communicate(input=b('')) if p.returncode != 0: return None lines = BytesIO(stdout + stderr).readlines() lines = decode_iter(lines) if parse: selected_lines = [] for line in lines: if ("COLLECT_GCC_OPTIONS=" in line or "CFLAGS=" in line or "CXXFLAGS=" in line or "-march=native" in line): continue elif "-march=" in line: selected_lines.append(line.strip()) elif "-mtune=" in line: selected_lines.append(line.strip()) elif "-target-cpu" in line: selected_lines.append(line.strip()) lines = list(set(selected_lines)) # to remove duplicate return lines # The '-' at the end is needed. Otherwise, g++ do not output # enough information. native_lines = get_lines("%s -march=native -E -v -" % theano.config.cxx) if native_lines is None: _logger.info("Call to 'g++ -march=native' failed," "not setting -march flag") detect_march = False else: _logger.info("g++ -march=native selected lines: %s", native_lines) if detect_march: if len(native_lines) != 1: if len(native_lines) == 0: # That means we did not select the right lines, so # we have to report all the lines instead reported_lines = get_lines("%s -march=native -E -v -" % theano.config.cxx, parse=False) else: reported_lines = native_lines _logger.warn( "OPTIMIZATION WARNING: Theano was not able to find the" " g++ parameters that tune the compilation to your " " specific CPU. This can slow down the execution of Theano" " functions. Please submit the following lines to" " Theano's mailing list so that we can fix this" " problem:\n %s", reported_lines) else: default_lines = get_lines("%s -E -v -" % theano.config.cxx) _logger.info("g++ default lines: %s", default_lines) if len(default_lines) < 1: _logger.warn( "OPTIMIZATION WARNING: Theano was not able to find the" " default g++ parameters. This is needed to tune" " the compilation to your specific" " CPU. This can slow down the execution of Theano" " functions. Please submit the following lines to" " Theano's mailing list so that we can fix this" " problem:\n %s", get_lines("%s -E -v -" % theano.config.cxx, parse=False)) else: # Some options are actually given as "-option value", # we want to treat them as only one token when comparing # different command lines. # Heuristic: tokens not starting with a dash should be # joined with the previous one. def join_options(init_part): new_part = [] for i in range(len(init_part)): p = init_part[i] if p.startswith('-'): p_list = [p] while ((i + 1 < len(init_part)) and not init_part[i + 1].startswith('-')): # append that next part to p_list p_list.append(init_part[i + 1]) i += 1 new_part.append(' '.join(p_list)) elif i == 0: # The first argument does not usually start # with "-", still add it new_part.append(p) # Else, skip it, as it was already included # with the previous part. return new_part part = join_options(native_lines[0].split()) for line in default_lines: if line.startswith(part[0]): part2 = [p for p in join_options(line.split()) if ('march' not in p and 'mtune' not in p and 'target-cpu' not in p)] if sys.platform == 'darwin': # We only use translated target-cpu on # mac since the other flags are not # supported as compiler flags for the # driver. new_flags = [p for p in part if 'target-cpu' in p] else: new_flags = [p for p in part if p not in part2] # Replace '-target-cpu value', which is an option # of clang, with '-march=value'. for i, p in enumerate(new_flags): if 'target-cpu' in p: opt = p.split() if len(opt) == 2: opt_name, opt_val = opt new_flags[i] = '-march=%s' % opt_val # Some versions of GCC report the native arch # as "corei7-avx", but it generates illegal # instructions, and should be "corei7" instead. # Affected versions are: # - 4.6 before 4.6.4 # - 4.7 before 4.7.3 # - 4.8 before 4.8.1 # Earlier versions did not have arch "corei7-avx" for i, p in enumerate(new_flags): if 'march' not in p: continue opt = p.split('=') if len(opt) != 2: # Inexpected, but do not crash continue opt_val = opt[1] if not opt_val.endswith('-avx'): # OK continue # Check the version of GCC version = gcc_version_str.split('.') if len(version) != 3: # Unexpected, but should not be a problem continue mj, mn, patch = [int(vp) for vp in version] if (((mj, mn) == (4, 6) and patch < 4) or ((mj, mn) == (4, 7) and patch <= 3) or ((mj, mn) == (4, 8) and patch < 1)): new_flags[i] = p.rstrip('-avx') # Go back to split arguments, like # ["-option", "value"], # as this is the way g++ expects them split. split_flags = [] for p in new_flags: split_flags.extend(p.split()) GCC_compiler.march_flags = split_flags break _logger.info("g++ -march=native equivalent flags: %s", GCC_compiler.march_flags) # Add the detected -march=native equivalent flags if GCC_compiler.march_flags: cxxflags.extend(GCC_compiler.march_flags) # NumPy 1.7 Deprecate the old API. I updated most of the places # to use the new API, but not everywhere. When finished, enable # the following macro to assert that we don't bring new code # that use the old API. cxxflags.append("-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION") numpy_ver = [int(n) for n in numpy.__version__.split('.')[:2]] # numpy 1.7 deprecated the following macro but the new one didn't # existed in the past if bool(numpy_ver < [1, 7]): cxxflags.append("-DNPY_ARRAY_ENSUREARRAY=NPY_ENSUREARRAY") cxxflags.append("-DNPY_ARRAY_ENSURECOPY=NPY_ENSURECOPY") cxxflags.append("-DNPY_ARRAY_ALIGNED=NPY_ALIGNED") cxxflags.append("-DNPY_ARRAY_WRITEABLE=NPY_WRITEABLE") cxxflags.append("-DNPY_ARRAY_UPDATE_ALL=NPY_UPDATE_ALL") cxxflags.append("-DNPY_ARRAY_C_CONTIGUOUS=NPY_C_CONTIGUOUS") cxxflags.append("-DNPY_ARRAY_F_CONTIGUOUS=NPY_F_CONTIGUOUS") # Platform-specific flags. # We put them here, rather than in compile_str(), so they en up # in the key of the compiled module, avoiding potential conflicts. # Figure out whether the current Python executable is 32 # or 64 bit and compile accordingly. This step is ignored for # ARM (32-bit and 64-bit) architectures in order to make # Theano compatible with the Raspberry Pi, Raspberry Pi 2, or # other systems with ARM processors. if (not any(['arm' in flag for flag in cxxflags]) and not any(arch in platform.machine() for arch in ['arm', 'aarch'])): n_bits = local_bitwidth() cxxflags.append('-m%d' % n_bits) _logger.debug("Compiling for %s bit architecture", n_bits) if sys.platform != 'win32': # Under Windows it looks like fPIC is useless. Compiler warning: # '-fPIC ignored for target (all code is position independent)' cxxflags.append('-fPIC') if sys.platform == 'win32' and local_bitwidth() == 64: # Under 64-bit Windows installation, sys.platform is 'win32'. # We need to define MS_WIN64 for the preprocessor to be able to # link with libpython. cxxflags.append('-DMS_WIN64') if sys.platform == 'darwin': # Use the already-loaded python symbols. cxxflags.extend(['-undefined', 'dynamic_lookup']) return cxxflags @staticmethod def try_compile_tmp(src_code, tmp_prefix='', flags=(), try_run=False, output=False): return Compiler._try_compile_tmp(src_code, tmp_prefix, flags, try_run, output, theano.config.cxx) @staticmethod def try_flags(flag_list, preambule="", body="", try_run=False, output=False): return Compiler._try_flags(flag_list, preambule, body, try_run, output, theano.config.cxx) @staticmethod def compile_str(module_name, src_code, location=None, include_dirs=None, lib_dirs=None, libs=None, preargs=None, py_module=True, hide_symbols=True): """ Parameters ---------- module_name : str This has been embedded in the src_code. src_code A complete c or c++ source listing for the module. location A pre-existing filesystem directory where the cpp file and .so will be written. include_dirs A list of include directory names (each gets prefixed with -I). lib_dirs A list of library search path directory names (each gets prefixed with -L). libs A list of libraries to link with (each gets prefixed with -l). preargs A list of extra compiler arguments. py_module If False, compile to a shared library, but do not import it as a Python module. hide_symbols If True (the default) all symbols will be hidden from the library symbol table (which means that other objects can't use them). Returns ------- object Dynamically-imported python module of the compiled code (unless py_module is False, in that case returns None). """ # TODO: Do not do the dlimport in this function if not theano.config.cxx: raise MissingGXX("g++ not available! We can't compile c code.") if include_dirs is None: include_dirs = [] if lib_dirs is None: lib_dirs = [] if libs is None: libs = [] if preargs is None: preargs = [] # Remove empty string directory include_dirs = [d for d in include_dirs if d] lib_dirs = [d for d in lib_dirs if d] include_dirs = include_dirs + std_include_dirs() libs = libs + std_libs() lib_dirs = lib_dirs + std_lib_dirs() cppfilename = os.path.join(location, 'mod.cpp') with open(cppfilename, 'w') as cppfile: _logger.debug('Writing module C++ code to %s', cppfilename) cppfile.write(src_code) # Avoid gcc warning "no newline at end of file". if not src_code.endswith('\n'): cppfile.write('\n') lib_filename = os.path.join( location, '%s.%s' % (module_name, get_lib_extension())) _logger.debug('Generating shared lib %s', lib_filename) cmd = [theano.config.cxx, get_gcc_shared_library_arg(), '-g'] if config.cmodule.remove_gxx_opt: cmd.extend(p for p in preargs if not p.startswith('-O')) else: cmd.extend(preargs) cmd.extend('-I%s' % idir for idir in include_dirs) if hide_symbols and sys.platform != 'win32': # This has been available since gcc 4.0 so we suppose it # is always available. We pass it here since it # significantly reduces the size of the symbol table for # the objects we want to share. This in turns leads to # improved loading times on most platforms (win32 is # different, as usual). cmd.append('-fvisibility=hidden') cmd.extend(['-o', lib_filename]) cmd.append(cppfilename) cmd.extend(['-L%s' % ldir for ldir in lib_dirs]) cmd.extend(['-l%s' % l for l in libs]) # print >> sys.stderr, 'COMPILING W CMD', cmd _logger.debug('Running cmd: %s', ' '.join(cmd)) def print_command_line_error(): # Print command line when a problem occurred. print(("Problem occurred during compilation with the " "command line below:"), file=sys.stderr) print(' '.join(cmd), file=sys.stderr) try: p_out = output_subprocess_Popen(cmd) compile_stderr = decode(p_out[1]) except Exception: # An exception can occur e.g. if `g++` is not found. print_command_line_error() raise status = p_out[2] if status: print('===============================') for i, l in enumerate(src_code.split('\n')): # gcc put its messages to stderr, so we add ours now print('%05i\t%s' % (i + 1, l), file=sys.stderr) print('===============================') print_command_line_error() # Print errors just below the command line. print(compile_stderr) # We replace '\n' by '. ' in the error message because when Python # prints the exception, having '\n' in the text makes it more # difficult to read. raise Exception('Compilation failed (return status=%s): %s' % (status, compile_stderr.replace('\n', '. '))) elif config.cmodule.compilation_warning and compile_stderr: # Print errors just below the command line. print(compile_stderr) if py_module: # touch the __init__ file open(os.path.join(location, "__init__.py"), 'w').close() assert os.path.isfile(lib_filename) return dlimport(lib_filename) def icc_module_compile_str(*args): raise NotImplementedError()
{'content_hash': 'cc21c77cbfbe9f973e705d58bd8843da', 'timestamp': '', 'source': 'github', 'line_count': 2217, 'max_line_length': 119, 'avg_line_length': 39.885881822282364, 'alnum_prop': 0.5234374116502878, 'repo_name': 'marcsans/cnn-physics-perception', 'id': '7e884e044a77708dc5f5eb5c3b4b98ba51d02fa3', 'size': '88427', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'phy/lib/python2.7/site-packages/theano/gof/cmodule.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '489272'}, {'name': 'C++', 'bytes': '3521811'}, {'name': 'CSS', 'bytes': '7132'}, {'name': 'Cuda', 'bytes': '232079'}, {'name': 'FORTRAN', 'bytes': '9868'}, {'name': 'HTML', 'bytes': '131419'}, {'name': 'JavaScript', 'bytes': '23881'}, {'name': 'Jupyter Notebook', 'bytes': '16254'}, {'name': 'Makefile', 'bytes': '75861'}, {'name': 'Matlab', 'bytes': '4346'}, {'name': 'Objective-C', 'bytes': '567'}, {'name': 'Python', 'bytes': '36682149'}, {'name': 'Shell', 'bytes': '3878'}, {'name': 'TeX', 'bytes': '14053'}]}
namespace gl46 { // import booleans to namespace using gl::GL_FALSE; using gl::GL_TRUE; } // namespace gl46
{'content_hash': 'cb28cf7fd07227e99229e832251726c5', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 31, 'avg_line_length': 10.272727272727273, 'alnum_prop': 0.6902654867256637, 'repo_name': 'mcleary/glbinding', 'id': '946032a0f2a96cee218ab5fc967630456e419314', 'size': '194', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/glbinding/include/glbinding/gl46/boolean.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '30448'}, {'name': 'C++', 'bytes': '13978290'}, {'name': 'CMake', 'bytes': '101634'}, {'name': 'GLSL', 'bytes': '2055'}, {'name': 'M4', 'bytes': '25387'}, {'name': 'Makefile', 'bytes': '29093'}, {'name': 'Objective-C', 'bytes': '3143'}, {'name': 'Python', 'bytes': '514656'}, {'name': 'Shell', 'bytes': '26659'}, {'name': 'Smarty', 'bytes': '37681'}]}
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ gTestfile = 'ToLong-001.js'; /** * Preferred Argument Conversion. * * Passing a JavaScript boolean to a Java method should prefer to call * a Java method of the same name that expects a Java boolean. * */ var SECTION = "Preferred argument conversion: JavaScript Object to Long"; var VERSION = "1_4"; var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " + SECTION; startTest(); var TEST_CLASS = new Packages.com.netscape.javascript.qa.lc3.jsobject.JSObject_006; function MyObject( value ) { this.value = value; this.valueOf = new Function( "return this.value" ); } function MyFunction() { return; } MyFunction.valueOf = new Function( "return 6060842" ); new TestCase( "TEST_CLASS.ambiguous( new String() ) +''", "LONG", TEST_CLASS.ambiguous(new String()) +'' ); new TestCase( "TEST_CLASS.ambiguous( new Boolean() ) +''", "LONG", TEST_CLASS.ambiguous( new Boolean() )+'' ); new TestCase( "TEST_CLASS.ambiguous( new Number() ) +''", "LONG", TEST_CLASS.ambiguous( new Number() )+'' ); new TestCase( "TEST_CLASS.ambiguous( new Date(0) ) +''", "LONG", TEST_CLASS.ambiguous( new Date(0) )+'' ); new TestCase( "TEST_CLASS.ambiguous( new MyObject(999) ) +''", "LONG", TEST_CLASS.ambiguous( new MyObject(999) )+'' ); new TestCase( "TEST_CLASS.ambiguous( MyFunction ) +''", "LONG", TEST_CLASS.ambiguous( MyFunction )+'' ); test();
{'content_hash': '3502be3cfdcac3dbca0a96597b167ca1', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 83, 'avg_line_length': 32.96938775510204, 'alnum_prop': 0.6957598266790468, 'repo_name': 'm0ppers/arangodb', 'id': '87a004fabdfe0148d19de82c73a9e1325ebc673f', 'size': '3231', 'binary': False, 'copies': '4', 'ref': 'refs/heads/devel', 'path': '3rdParty/V8/V8-5.0.71.39/test/mozilla/data/lc3/ConvertJSObject/ToLong-001.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '397438'}, {'name': 'Batchfile', 'bytes': '36479'}, {'name': 'C', 'bytes': '4981599'}, {'name': 'C#', 'bytes': '96430'}, {'name': 'C++', 'bytes': '273207213'}, {'name': 'CLIPS', 'bytes': '5291'}, {'name': 'CMake', 'bytes': '526333'}, {'name': 'CSS', 'bytes': '634304'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '33549'}, {'name': 'Emacs Lisp', 'bytes': '14357'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'Groff', 'bytes': '272212'}, {'name': 'Groovy', 'bytes': '131'}, {'name': 'HTML', 'bytes': '3470113'}, {'name': 'IDL', 'bytes': '14'}, {'name': 'Java', 'bytes': '2325801'}, {'name': 'JavaScript', 'bytes': '66968092'}, {'name': 'LLVM', 'bytes': '38070'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'Lua', 'bytes': '16189'}, {'name': 'M4', 'bytes': '64965'}, {'name': 'Makefile', 'bytes': '1268118'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Module Management System', 'bytes': '1545'}, {'name': 'NSIS', 'bytes': '28404'}, {'name': 'Objective-C', 'bytes': '30435'}, {'name': 'Objective-C++', 'bytes': '2503'}, {'name': 'PHP', 'bytes': '39473'}, {'name': 'Pascal', 'bytes': '145688'}, {'name': 'Perl', 'bytes': '205308'}, {'name': 'Python', 'bytes': '6937381'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'R', 'bytes': '5123'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Ruby', 'bytes': '910409'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'Scheme', 'bytes': '10604'}, {'name': 'Shell', 'bytes': '986221'}, {'name': 'Swift', 'bytes': '116'}, {'name': 'Vim script', 'bytes': '4075'}, {'name': 'XSLT', 'bytes': '473118'}, {'name': 'Yacc', 'bytes': '72510'}]}
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/ngAnimate/animate.js?message=docs(ngAnimate)%3A%20describe%20your%20change...#L4' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this Doc</a> <h1> <code>ngAnimate</code> </h1> <p>The <code>ngAnimate</code> module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.</p> <div doc-module-components="ngAnimate"></div> <h1 id="usage">Usage</h1> <p>To see animations in action, all that is required is to define the appropriate CSS classes or to register a JavaScript animation via the <code>myModule.animation()</code> function. The directives that support animation automatically are: <code>ngRepeat</code>, <code>ngInclude</code>, <code>ngIf</code>, <code>ngSwitch</code>, <code>ngShow</code>, <code>ngHide</code>, <code>ngView</code> and <code>ngClass</code>. Custom directives can take advantage of animation by using the <code>$animate</code> service.</p> <p>Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:</p> <table> <thead> <tr> <th>Directive</th> <th>Supported Animations</th> </tr> </thead> <tbody> <tr> <td><a href="api/ng/directive/ngRepeat#animations">ngRepeat</a></td> <td>enter, leave and move</td> </tr> <tr> <td><a href="api/ngRoute/directive/ngView#animations">ngView</a></td> <td>enter and leave</td> </tr> <tr> <td><a href="api/ng/directive/ngInclude#animations">ngInclude</a></td> <td>enter and leave</td> </tr> <tr> <td><a href="api/ng/directive/ngSwitch#animations">ngSwitch</a></td> <td>enter and leave</td> </tr> <tr> <td><a href="api/ng/directive/ngIf#animations">ngIf</a></td> <td>enter and leave</td> </tr> <tr> <td><a href="api/ng/directive/ngClass#animations">ngClass</a></td> <td>add and remove (the CSS class(es) present)</td> </tr> <tr> <td><a href="api/ng/directive/ngShow#animations">ngShow</a> &amp; <a href="api/ng/directive/ngHide#animations">ngHide</a></td> <td>add and remove (the ng-hide class value)</td> </tr> <tr> <td><a href="api/ng/directive/form#animation-hooks">form</a> &amp; <a href="api/ng/directive/ngModel#animation-hooks">ngModel</a></td> <td>add and remove (dirty, pristine, valid, invalid &amp; all other validations)</td> </tr> <tr> <td><a href="api/ngMessages#animations">ngMessages</a></td> <td>add and remove (ng-active &amp; ng-inactive)</td> </tr> <tr> <td><a href="api/ngMessages#animations">ngMessage</a></td> <td>enter and leave</td> </tr> </tbody> </table> <p>You can find out more information about animations upon visiting each directive page.</p> <p>Below is an example of how to apply animations to a directive that supports animation hooks:</p> <pre><code class="lang-html">&lt;style type=&quot;text/css&quot;&gt; .slide.ng-enter, .slide.ng-leave { -webkit-transition:0.5s linear all; transition:0.5s linear all; } .slide.ng-enter { } /* starting animations for enter */ .slide.ng-enter.ng-enter-active { } /* terminal animations for enter */ .slide.ng-leave { } /* starting animations for leave */ .slide.ng-leave.ng-leave-active { } /* terminal animations for leave */ &lt;/style&gt; &lt;!-- the animate service will automatically add .ng-enter and .ng-leave to the element to trigger the CSS transition/animations --&gt; &lt;ANY class=&quot;slide&quot; ng-include=&quot;...&quot;&gt;&lt;/ANY&gt; </code></pre> <p>Keep in mind that, by default, if an animation is running, any child elements cannot be animated until the parent element&#39;s animation has completed. This blocking feature can be overridden by placing the <code>ng-animate-children</code> attribute on a parent container tag.</p> <pre><code class="lang-html">&lt;div class=&quot;slide-animation&quot; ng-if=&quot;on&quot; ng-animate-children&gt; &lt;div class=&quot;fade-animation&quot; ng-if=&quot;on&quot;&gt; &lt;div class=&quot;explode-animation&quot; ng-if=&quot;on&quot;&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>When the <code>on</code> expression value changes and an animation is triggered then each of the elements within will all animate without the block being applied to child elements.</p> <h2 id="are-animations-run-when-the-application-starts-">Are animations run when the application starts?</h2> <p>No they are not. When an application is bootstrapped Angular will disable animations from running to avoid a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work, Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering layout changes in the application will trigger animations as normal.</p> <p>In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular will automatically extend the wait time to enable animations once <strong>all</strong> of the outbound HTTP requests are complete.</p> <h2 id="css-defined-animations">CSS-defined Animations</h2> <p>The animate service will automatically apply two CSS classes to the animated element and these two CSS classes are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported and can be used to play along with this naming structure.</p> <p>The following code below demonstrates how to perform animations using <strong>CSS transitions</strong> with Angular:</p> <pre><code class="lang-html">&lt;style type=&quot;text/css&quot;&gt; /* The animate class is apart of the element and the ng-enter class is attached to the element once the enter animation event is triggered */ .reveal-animation.ng-enter { -webkit-transition: 1s linear all; /* Safari/Chrome */ transition: 1s linear all; /* All other modern browsers and IE10+ */ /* The animation preparation code */ opacity: 0; } /* Keep in mind that you want to combine both CSS classes together to avoid any CSS-specificity conflicts */ .reveal-animation.ng-enter.ng-enter-active { /* The animation code itself */ opacity: 1; } &lt;/style&gt; &lt;div class=&quot;view-container&quot;&gt; &lt;div ng-view class=&quot;reveal-animation&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The following code below demonstrates how to perform animations using <strong>CSS animations</strong> with Angular:</p> <pre><code class="lang-html">&lt;style type=&quot;text/css&quot;&gt; .reveal-animation.ng-enter { -webkit-animation: enter_sequence 1s linear; /* Safari/Chrome */ animation: enter_sequence 1s linear; /* IE10+ and Future Browsers */ } @-webkit-keyframes enter_sequence { from { opacity:0; } to { opacity:1; } } @keyframes enter_sequence { from { opacity:0; } to { opacity:1; } } &lt;/style&gt; &lt;div class=&quot;view-container&quot;&gt; &lt;div ng-view class=&quot;reveal-animation&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.</p> <p>Upon DOM mutation, the event class is added first (something like <code>ng-enter</code>), then the browser prepares itself to add the active class (in this case <code>ng-enter-active</code>) which then triggers the animation. The animation module will automatically detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end immediately resulting in a DOM element that is at its final state. This final state is when the DOM element has no CSS transition/animation classes applied to it.</p> <h3 id="structural-transition-animations">Structural transition animations</h3> <p>Structural transitions (such as enter, leave and move) will always apply a <code>0s none</code> transition value to force the browser into rendering the styles defined in the setup (<code>.ng-enter</code>, <code>.ng-leave</code> or <code>.ng-move</code>) class. This means that any active transition animations operating on the element will be cut off to make way for the enter, leave or move animation.</p> <h3 id="class-based-transition-animations">Class-based transition animations</h3> <p>Class-based transitions refer to transition animations that are triggered when a CSS class is added to or removed from the element (via <code>$animate.addClass</code>, <code>$animate.removeClass</code>, <code>$animate.setClass</code>, or by directives such as <code>ngClass</code>, <code>ngModel</code> and <code>form</code>). They are different when compared to structural animations since they <strong>do not cancel existing animations</strong> nor do they <strong>block successive transitions</strong> from rendering on the same element. This distinction allows for <strong>multiple class-based transitions</strong> to be performed on the same element.</p> <p>In addition to ngAnimate supporting the default (natural) functionality of class-based transition animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the developer in further styling the element throughout the transition animation. Earlier versions of ngAnimate may have caused natural CSS transitions to break and not render properly due to $animate temporarily blocking transitions using <code>0s none</code> in order to allow the setup CSS class (the <code>-add</code> or <code>-remove</code> class) to be applied without triggering an animation. However, as of <strong>version 1.3</strong>, this workaround has been removed with ngAnimate and all non-ngAnimate CSS class transitions are compatible with ngAnimate.</p> <p>There is, however, one special case when dealing with class-based transitions in ngAnimate. When rendering class-based transitions that make use of the setup and active CSS classes (e.g. <code>.fade-add</code> and <code>.fade-add-active</code> for when <code>.fade</code> is added) be sure to define the transition value <strong>on the active CSS class</strong> and not the setup class.</p> <pre><code class="lang-css">.fade-add { /* remember to place a 0s transition here to ensure that the styles are applied instantly even if the element already has a transition style */ transition:0s linear all; /* starting CSS styles */ opacity:1; } .fade-add.fade-add-active { /* this will be the length of the animation */ transition:1s linear all; opacity:0; } </code></pre> <p>The setup CSS class (in this case <code>.fade-add</code>) also has a transition style property, however, it has a duration of zero. This may not be required, however, incase the browser is unable to render the styling present in this CSS class instantly then it could be that the browser is attempting to perform an unnecessary transition.</p> <p>This workaround, however, does not apply to standard class-based transitions that are rendered when a CSS class containing a transition is applied to an element:</p> <pre><code class="lang-css">/* this works as expected */ .fade { transition:1s linear all; opacity:0; } </code></pre> <p>Please keep this in mind when coding the CSS markup that will be used within class-based transitions. Also, try not to mix the two class-based animation flavors together since the CSS code may become overly complex.</p> <h3 id="preventing-collisions-with-third-party-libraries">Preventing Collisions With Third Party Libraries</h3> <p>Some third-party frameworks place animation duration defaults across many element or className selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which is expecting actual animations on these elements and has to wait for their completion.</p> <p>You can prevent this unwanted behavior by using a prefix on all your animation classes:</p> <pre><code class="lang-css">/* prefixed with animate- */ .animate-fade-add.animate-fade-add-active { transition:1s linear all; opacity:0; } </code></pre> <p>You then configure <code>$animate</code> to enforce this prefix:</p> <pre><code class="lang-js">$animateProvider.classNameFilter(/animate-/); </code></pre> <p></div></p> <h3 id="css-staggering-animations">CSS Staggering Animations</h3> <p>A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a curtain-like effect. The ngAnimate module (versions &gt;=1.2) supports staggering animations and the stagger effect can be performed by creating a <strong>ng-EVENT-stagger</strong> CSS class and attaching that class to the base CSS class used for the animation. The style property expected within the stagger class can either be a <strong>transition-delay</strong> or an <strong>animation-delay</strong> property (or both if your animation contains both transitions and keyframe animations).</p> <pre><code class="lang-css">.my-animation.ng-enter { /* standard transition code */ -webkit-transition: 1s linear all; transition: 1s linear all; opacity:0; } .my-animation.ng-enter-stagger { /* this will have a 100ms delay between each successive leave animation */ -webkit-transition-delay: 0.1s; transition-delay: 0.1s; /* in case the stagger doesn&#39;t work then these two values must be set to 0 to avoid an accidental CSS inheritance */ -webkit-transition-duration: 0s; transition-duration: 0s; } .my-animation.ng-enter.ng-enter-active { /* standard transition styles */ opacity:1; } </code></pre> <p>Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation will also be reset if more than 10ms has passed after the last animation has been fired.</p> <p>The following code will issue the <strong>ng-leave-stagger</strong> event on the element provided:</p> <pre><code class="lang-js">var kids = parent.children(); $animate.leave(kids[0]); //stagger index=0 $animate.leave(kids[1]); //stagger index=1 $animate.leave(kids[2]); //stagger index=2 $animate.leave(kids[3]); //stagger index=3 $animate.leave(kids[4]); //stagger index=4 $timeout(function() { //stagger has reset itself $animate.leave(kids[5]); //stagger index=0 $animate.leave(kids[6]); //stagger index=1 }, 100, false); </code></pre> <p>Stagger animations are currently only supported within CSS-defined animations.</p> <h2 id="javascript-defined-animations">JavaScript-defined Animations</h2> <p>In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.</p> <pre><code class="lang-js">//!annotate=&quot;YourApp&quot; Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. var ngModule = angular.module(&#39;YourApp&#39;, [&#39;ngAnimate&#39;]); ngModule.animation(&#39;.my-crazy-animation&#39;, function() { return { enter: function(element, done) { //run the animation here and call done when the animation is complete return function(cancelled) { //this (optional) function will be called when the animation //completes or when the animation is cancelled (the cancelled //flag will be set to true if cancelled). }; }, leave: function(element, done) { }, move: function(element, done) { }, //animation that can be triggered before the class is added beforeAddClass: function(element, className, done) { }, //animation that can be triggered after the class is added addClass: function(element, className, done) { }, //animation that can be triggered before the class is removed beforeRemoveClass: function(element, className, done) { }, //animation that can be triggered after the class is removed removeClass: function(element, className, done) { } }; }); </code></pre> <p>JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits the element&#39;s CSS class attribute value and then run the matching animation event function (if found). In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).</p> <p>Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation or transition code that is defined via a stylesheet).</p> <h3 id="applying-directive-specific-styles-to-an-animation">Applying Directive-specific Styles to an Animation</h3> <p>In some cases a directive or service may want to provide <code>$animate</code> with extra details that the animation will include into its animation. Let&#39;s say for example we wanted to render an animation that animates an element towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click (via the event parameter) we can set the <code>top</code> and <code>left</code> styles into an object and pass that into our function call to <code>$animate.addClass</code>.</p> <pre><code class="lang-js">canvas.on(&#39;click&#39;, function(e) { $animate.addClass(element, &#39;on&#39;, { to: { left : e.client.x + &#39;px&#39;, top : e.client.y + &#39;px&#39; } }): }); </code></pre> <p>Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will also include and transition the styling of the <code>left</code> and <code>top</code> properties into its running animation. If we want to provide some starting animation values then we can do so by placing the starting animations styles into an object called <code>from</code> in the same object as the <code>to</code> animations.</p> <pre><code class="lang-js">canvas.on(&#39;click&#39;, function(e) { $animate.addClass(element, &#39;on&#39;, { from: { position: &#39;absolute&#39;, left: &#39;0px&#39;, top: &#39;0px&#39; }, to: { left : e.client.x + &#39;px&#39;, top : e.client.y + &#39;px&#39; } }): }); </code></pre> <p>Once the animation is complete or cancelled then the union of both the before and after styles are applied to the element. If <code>ngAnimate</code> is not present then the styles will be applied immediately.</p> <h2>Installation</h2> <p>First include <code>angular-animate.js</code> in your HTML:</p> <pre><code>&lt;script src=&quot;angular.js&quot;&gt;&#10;&lt;script src=&quot;angular-animate.js&quot;&gt;</code></pre> <p>You can download this file from the following places:</p> <ul> <li> <a href="https://developers.google.com/speed/libraries/devguide#angularjs">Google CDN</a><br> e.g. <code>//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-animate.js</code> </li> <li> <a href="http://bower.io">Bower</a><br> e.g. <pre><code>bower install [email protected]</code></pre> </li> <li> <a href="http://code.angularjs.org/">code.angularjs.org</a><br> e.g. <pre><code>&quot;//code.angularjs.org/X.Y.Z/angular-animate.js&quot;</code></pre> </li> </ul> <p>where X.Y.Z is the AngularJS version you are running.</p> <p>Then load the module in your application by adding it as a dependent module:</p> <pre><code>angular.module(&#39;app&#39;, [&#39;ngAnimate&#39;]);</code></pre> <p>With that you&apos;re ready to get started!</p> <div class="component-breakdown"> <h2>Module Components</h2> <div> <h3 class="component-heading" id="provider">Provider</h3> <table class="definition-table"> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td><a href="api/ngAnimate/provider/$animateProvider">$animateProvider</a></td> <td><p>The <code>$animateProvider</code> allows developers to register JavaScript animation event handlers directly inside of a module. When an animation is triggered, the $animate service will query the $animate service to find any animations that match the provided name value.</p> </td> </tr> </table> </div> <div> <h3 class="component-heading" id="service">Service</h3> <table class="definition-table"> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td><a href="api/ngAnimate/service/$animate">$animate</a></td> <td><p>The <code>$animate</code> service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. When any of these operations are run, the $animate service will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.</p> </td> </tr> </table> </div> </div>
{'content_hash': 'e679715c5b30dceebfd9f5555602e3f1', 'timestamp': '', 'source': 'github', 'line_count': 437, 'max_line_length': 248, 'avg_line_length': 50.11441647597254, 'alnum_prop': 0.732648401826484, 'repo_name': 'dolymood/angular-packages', 'id': 'b23f172f7b6ef6ea3ba3f359c2c9d8801a1fbb38', 'size': '21900', 'binary': False, 'copies': '14', 'ref': 'refs/heads/gh-pages', 'path': 'angular-1.4.0-beta.4/docs/partials/api/ngAnimate.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1454701'}, {'name': 'HTML', 'bytes': '82151465'}, {'name': 'JavaScript', 'bytes': '15628922'}]}
<?php /** * @category Payment Gateway * @package Adyen_Payment * @author Adyen * @property Adyen B.V * @copyright Copyright (c) 2014 Adyen BV (http://www.adyen.com) */ class Adyen_Payment_Adminhtml_Adyen_Event_QueueController extends Mage_Adminhtml_Controller_Action { public function indexAction() { Mage::getSingleton('adminhtml/session')->addNotice(Mage::helper('adyen')->__('If you are using Adyen CreditCard payment method it could be that the notifcation that is send from the Adyen Platform is faster then Magento saves the order. The notification is saved and when a new notification is send it will try to update the previous notification as well. You can see here what notifications did not processed yet and you can proccess it here manual if you want to by selecting "Execute" under the Actions column ')); $this->_title(Mage::helper('sales')->__('Sales'))->_title(Mage::helper('adyen')->__('Adyen Event Queue')) ->loadLayout() ->_setActiveMenu('sales/adyen_event_queue') ->renderLayout(); return $this; } /** * Event queue ajax grid */ public function gridAction() { try { $this->loadLayout()->renderLayout(); return; } catch (Mage_Core_Exception $e) { $this->_getSession()->addError($e->getMessage()); } catch (Exception $e) { Adyen_Payment_Exception::logException($e); } $this->_redirect('*/*/'); } /** * This tries to process the notification again */ public function executeAction() { // get event queue id $eventQueueId = $this->getRequest()->getParam('event_queue_id'); $this->_executeEventQueue($eventQueueId); // return back to the view $this->_redirect('*/*/'); } private function _executeEventQueue($eventQueueId) { $eventQueue = Mage::getModel('adyen/event_queue')->load($eventQueueId); $incrementId = $eventQueue->getIncrementId(); $varienObj = unserialize($eventQueue->getResponse()); $orderExist = Mage::getResourceModel('adyen/order')->orderExist($incrementId); if (!empty($orderExist)) { $order = Mage::getModel('sales/order'); $order->loadByIncrementId($incrementId); // process it Mage::getModel('adyen/processNotification')->updateOrder($order, $varienObj); // remove it from queue $eventQueue->delete(); } else { // add this $currentAttempt = $eventQueue->getAttempt(); $eventQueue->setAttempt(++$currentAttempt); $eventQueue->save(); $this->_getSession()->addError($this->__('The order does not exist.')); } } public function deleteAction() { $eventQueueId = $this->getRequest()->getParam('event_queue_id'); $eventQueue = Mage::getModel('adyen/event_queue')->load($eventQueueId); $eventQueue->delete(); // return back to the view $this->_redirect('*/*/'); } public function massDeleteAction() { $queueIds = $this->getRequest()->getParam('queue_id'); // $this->getMassactionBlock()->setFormFieldName('queue_id'); from Adyen_Payment_Block_Adminhtml_Adyen_Event_Queue_Grid if(!is_array($queueIds)) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adyen')->__('Please select notification queue(s).')); } else { try { $eventQueueModel = Mage::getModel('adyen/event_queue'); foreach ($queueIds as $queueId) { $eventQueueModel->load($queueId)->delete(); } Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('adyen')->__( 'Total of %d record(s) were deleted.', count($queueIds) ) ); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } } $this->_redirect('*/*/index'); } public function massExecuteAction() { $queueIds = $this->getRequest()->getParam('queue_id'); // $this->getMassactionBlock()->setFormFieldName('queue_id'); from Adyen_Payment_Block_Adminhtml_Adyen_Event_Queue_Grid if(!is_array($queueIds)) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adyen')->__('Please select notification queue(s).')); } else { try { $eventQueueModel = Mage::getModel('adyen/event_queue'); foreach ($queueIds as $queueId) { $this->_executeEventQueue($queueId); } Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('adyen')->__( 'Total of %d record(s) were deleted.', count($queueIds) ) ); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } } $this->_redirect('*/*/index'); } /** * @return bool */ protected function _isAllowed() { return Mage::getSingleton('admin/session')->isAllowed('sales/adyen_payment'); } }
{'content_hash': '6000a2a39108fc5be4ce3253b495c656', 'timestamp': '', 'source': 'github', 'line_count': 147, 'max_line_length': 525, 'avg_line_length': 36.863945578231295, 'alnum_prop': 0.5650489020114412, 'repo_name': 'newsjunk/magepaything', 'id': '22bc9909450fe8356e0ce086f53b45c7038bf1ea', 'size': '6118', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'app/code/community/Adyen/Payment/controllers/Adminhtml/Adyen/Event/QueueController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '7139'}, {'name': 'HTML', 'bytes': '154863'}, {'name': 'JavaScript', 'bytes': '59072'}, {'name': 'PHP', 'bytes': '605617'}]}
package com.annimon.stream.intstreamtests; import com.annimon.stream.IntStream; import org.junit.Test; import static org.junit.Assert.assertEquals; public final class EmptyTest { @Test public void testStreamEmpty() { assertEquals(0, IntStream.empty().count()); assertEquals(0, IntStream.empty().iterator().nextInt()); } }
{'content_hash': '6bb65d28b302a9c8a510a4fefdbdfb64', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 64, 'avg_line_length': 25.214285714285715, 'alnum_prop': 0.7138810198300283, 'repo_name': 'aNNiMON/Lightweight-Stream-API', 'id': '0e81a488a92c71dafa565a20ffdff2be471f9efa', 'size': '353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'stream/src/test/java/com/annimon/stream/intstreamtests/EmptyTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1368955'}]}
// Copyright 2022 Google LLC // // 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 // // https://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. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(parent) { // [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] /** * This snippet has been automatically generated and should be regarded as a code template only. * It will require modifications to work. * It may require correct/in-range values for request initialization. * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. Resource name of the parent of sources to list. Its format should be * "organizations/[organization_id], folders/[folder_id], or * projects/[project_id]". */ // const parent = 'abc123' /** * The value returned by the last `ListSourcesResponse`; indicates * that this is a continuation of a prior `ListSources` call, and * that the system should return the next page of data. */ // const pageToken = 'abc123' /** * The maximum number of results to return in a single response. Default is * 10, minimum is 1, maximum is 1000. */ // const pageSize = 1234 // Imports the Securitycenter library const {SecurityCenterClient} = require('@google-cloud/security-center').v1p1beta1; // Instantiates a client const securitycenterClient = new SecurityCenterClient(); async function callListSources() { // Construct request const request = { parent, }; // Run request const iterable = await securitycenterClient.listSourcesAsync(request); for await (const response of iterable) { console.log(response); } } callListSources(); // [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
{'content_hash': 'ef67833fb3e6b1be746b787cd7155bbe', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 98, 'avg_line_length': 33.81578947368421, 'alnum_prop': 0.708171206225681, 'repo_name': 'googleapis/nodejs-security-center', 'id': '6544f637a5cd1d744d1f2444bfe48d35385aadf3', 'size': '2570', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'samples/generated/v1p1beta1/security_center.list_sources.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '3166'}, {'name': 'Python', 'bytes': '666'}]}
/** * Created by huanghaiying on 14/12/5. */ var console = {}; var window = {}; console.log = function (message) { egtlog(message); } egret_native.setSearchPaths([""]); egret_native.requireFiles = function () { require("bin-debug/lib/egret_file_list.js"); require("bin-debug/src/game_file_list.js"); for (var key in egret_file_list) { var src = "libs/" + egret_file_list[key]; require(src); } for (var key in game_file_list) { var src = "bin-debug/src/" + game_file_list[key]; require(src); } }; egret_native.egretInit = function () { //此变量用于加载文件判断,请勿修改此处 var needCompile = true; if (!needCompile) { egret_native.requireFiles(); } else { require("launcher/game-min-native.js"); } //egret.dom为空实现 egret.dom = {}; egret.dom.drawAsCanvas = function () { }; var context = egret.MainContext.instance; context.rendererContext = new egret.NativeRendererContext(); context.netContext = new egret.NativeNetContext(); context.touchContext = new egret.NativeTouchContext(); context.deviceContext = new egret.NativeDeviceContext(); egret.StageDelegate.getInstance().setDesignSize(480, 800); context.stage = new egret.Stage(); context.stage.scaleMode = egret.StageScaleMode.SHOW_ALL; egret.RendererContext.texture_scale_factor = 1; context.run(); }; egret_native.loadVersion = function (completeCall) { var ctr = egret.MainContext.instance.netContext._versionCtr; ctr.addEventListener(egret.IOErrorEvent.IO_ERROR, loadError, this); ctr.addEventListener(egret.Event.COMPLETE, loadComplete, this); ctr.fetchVersion(); function loadError(e) { ctr.removeEventListener(egret.IOErrorEvent.IO_ERROR, loadError, this); ctr.removeEventListener(egret.Event.COMPLETE, loadComplete, this); } function loadComplete(e) { ctr.removeEventListener(egret.IOErrorEvent.IO_ERROR, loadError, this); ctr.removeEventListener(egret.Event.COMPLETE, loadComplete, this); completeCall(); } }; egret_native.egretStart = function () { Object.defineProperty(egret.DisplayObject.prototype, "cacheAsBitmap", { get: function () { return false; }, set: function (bool) { }, enumerable: true, configurable: true }); var document_class = "Main"; var rootClass; if (document_class) { rootClass = egret.getDefinitionByName(document_class); } var context = egret.MainContext.instance; if (rootClass) { var rootContainer = new rootClass(); if (rootContainer instanceof egret.DisplayObjectContainer) { context.stage.addChild(rootContainer); } else { throw new Error("文档类必须是egret.DisplayObjectContainer的子类!"); } } else { throw new Error("找不到文档类!"); } }; egret_native.pauseApp = function () { console.log("pauseApp"); egret_native.Audio.pauseBackgroundMusic(); egret_native.Audio.pauseAllEffects(); }; egret_native.resumeApp = function () { console.log("resumeApp"); egret_native.Audio.resumeBackgroundMusic(); egret_native.Audio.resumeAllEffects(); };
{'content_hash': '3be82238d8e3698414658a2df73b09da', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 78, 'avg_line_length': 27.56779661016949, 'alnum_prop': 0.6477098063326161, 'repo_name': 'sunzhaoping/fastmsg', 'id': 'b19c6f6ff5f7d38a1983348d07e98f54a8766780', 'size': '3329', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'snowpear/launcher/native_require.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '921078'}, {'name': 'Python', 'bytes': '24947'}, {'name': 'TypeScript', 'bytes': '17871'}]}
'''Walk: Small example to make Nao walk''' import sys import motion import time from naoqi import ALProxy def StiffnessOn(proxy): # We use the "Body" name to signify the collection of all joints pNames = "Body" pStiffnessLists = 1.0 pTimeLists = 1.0 proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists) def main(robotIP): # Init proxies. try: motionProxy = ALProxy("ALMotion", robotIP, 9559) except Exception, e: print "Could not create proxy to ALMotion" print "Error was: ", e try: postureProxy = ALProxy("ALRobotPosture", robotIP, 9559) except Exception, e: print "Could not create proxy to ALRobotPosture" print "Error was: ", e # Set NAO in Stiffness On StiffnessOn(motionProxy) # Send NAO to Pose Init postureProxy.goToPosture("StandInit", 0.5) ##################### ## Enable arms control by Walk algorithm ##################### motionProxy.setWalkArmsEnabled(True, True) #~ motionProxy.setWalkArmsEnabled(False, False) ##################### ## FOOT CONTACT PROTECTION ##################### #~ motionProxy.setMotionConfig([["ENABLE_FOOT_CONTACT_PROTECTION", False]]) motionProxy.setMotionConfig([["ENABLE_FOOT_CONTACT_PROTECTION", True]]) #TARGET VELOCITY X = -0.5 #backward Y = 0.0 Theta = 0.0 Frequency =0.0 # low speed motionProxy.setWalkTargetVelocity(X, Y, Theta, Frequency) time.sleep(4.0) #TARGET VELOCITY X = 0.8 Y = 0.0 Theta = 0.0 Frequency =1.0 # max speed motionProxy.setWalkTargetVelocity(X, Y, Theta, Frequency) time.sleep(4.0) #TARGET VELOCITY X = 0.2 Y = -0.5 Theta = 0.2 Frequency =1.0 motionProxy.setWalkTargetVelocity(X, Y, Theta, Frequency) time.sleep(2.0) ##################### ## Arms User Motion ##################### # Arms motion from user have always the priority than walk arms motion JointNames = ["LShoulderPitch", "LShoulderRoll", "LElbowYaw", "LElbowRoll"] Arm1 = [-40, 25, 0, -40] Arm1 = [ x * motion.TO_RAD for x in Arm1] Arm2 = [-40, 50, 0, -80] Arm2 = [ x * motion.TO_RAD for x in Arm2] pFractionMaxSpeed = 0.6 motionProxy.angleInterpolationWithSpeed(JointNames, Arm1, pFractionMaxSpeed) motionProxy.angleInterpolationWithSpeed(JointNames, Arm2, pFractionMaxSpeed) motionProxy.angleInterpolationWithSpeed(JointNames, Arm1, pFractionMaxSpeed) time.sleep(2.0) ##################### ## End Walk ##################### #TARGET VELOCITY X = 0.0 Y = 0.0 Theta = 0.0 motionProxy.setWalkTargetVelocity(X, Y, Theta, Frequency) if __name__ == "__main__": robotIp = "127.0.0.1" if len(sys.argv) <= 1: print "Usage python motion_walk.py robotIP (optional default: 127.0.0.1)" else: robotIp = sys.argv[1] main(robotIp)
{'content_hash': 'e169c229597a4506d29dba089f2afdb2', 'timestamp': '', 'source': 'github', 'line_count': 112, 'max_line_length': 81, 'avg_line_length': 26.214285714285715, 'alnum_prop': 0.6083106267029973, 'repo_name': 'kwailamchan/programming-languages', 'id': 'fee9b1bbc05e57686a966ee4c0d6059b46347ab2', 'size': '2964', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'python/aldebaran/hana/hana/motion/move/motion_walk.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '2321'}, {'name': 'Batchfile', 'bytes': '7087'}, {'name': 'C', 'bytes': '2883116'}, {'name': 'C++', 'bytes': '12948373'}, {'name': 'CMake', 'bytes': '128629'}, {'name': 'CSS', 'bytes': '197791'}, {'name': 'Cuda', 'bytes': '687316'}, {'name': 'E', 'bytes': '2914'}, {'name': 'Eiffel', 'bytes': '1073'}, {'name': 'Fortran', 'bytes': '1332263'}, {'name': 'HTML', 'bytes': '257547'}, {'name': 'Java', 'bytes': '102661'}, {'name': 'JavaScript', 'bytes': '439019'}, {'name': 'Jupyter Notebook', 'bytes': '5488542'}, {'name': 'Makefile', 'bytes': '24949'}, {'name': 'Matlab', 'bytes': '32307'}, {'name': 'PHP', 'bytes': '21650'}, {'name': 'PLpgSQL', 'bytes': '16859'}, {'name': 'Python', 'bytes': '5424664'}, {'name': 'QMake', 'bytes': '787'}, {'name': 'R', 'bytes': '105611'}, {'name': 'Ruby', 'bytes': '152074'}, {'name': 'SAS', 'bytes': '4505'}, {'name': 'Scala', 'bytes': '6121'}, {'name': 'Shell', 'bytes': '49387'}, {'name': 'Visual Basic', 'bytes': '1174'}]}
<?php echo "<script>location.href='items.php';</script>"; ?>
{'content_hash': 'f22e0fb09e1202b5ac6c051bdfb9a1ac', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 51, 'avg_line_length': 20.0, 'alnum_prop': 0.65, 'repo_name': 'drodopuck/drodo.net', 'id': '4b7f2167bcf87cada1d6c641dc531d8188b82224', 'size': '60', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.php', 'mode': '33188', 'license': 'mit', 'language': []}
using System; using System.Collections.Generic; using System.Text; namespace Haukcode.TaxifyDotNet.Models { public class Security { public string Password { get; set; } } }
{'content_hash': '939cf887c2b4de9e17cebfda68fcc5b7', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 44, 'avg_line_length': 17.727272727272727, 'alnum_prop': 0.6923076923076923, 'repo_name': 'HakanL/TaxifyDotNet', 'id': '4605dea73390929a373ffb6d6fb95a43786ded20', 'size': '197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'TaxifyDotNet/Models/Security.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '25461'}]}
package org.twig4j.core.syntax.parser.node.type.expression; import org.twig4j.core.compiler.ClassCompiler; import org.twig4j.core.exception.LoaderException; import org.twig4j.core.exception.Twig4jRuntimeException; public class Name extends Expression { public Name(String name, Integer line) { super(line); putAttribute("name", name); } @Override public void compile(ClassCompiler compiler) throws LoaderException, Twig4jRuntimeException { compiler.writeRaw("getContext(context, \"" + getAttribute("name") + "\", false, " + getLine() +")"); } }
{'content_hash': '3211f9c7008133fee76a286c01138cf2', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 108, 'avg_line_length': 34.8235294117647, 'alnum_prop': 0.7179054054054054, 'repo_name': 'palmfjord/twig-java', 'id': '3c27089289ab2e810c9b0083368eeaa2afd505fb', 'size': '592', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/twig4j/core/syntax/parser/node/type/expression/Name.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '48'}, {'name': 'Java', 'bytes': '443218'}]}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. --> <modelVersion>4.0.0</modelVersion> <groupId>com.esri.geoevent.solutions.adapter</groupId> <version>10.2.0</version> <artifactId>cot-adapter</artifactId> <name>Esri :: AGES :: Solutions :: Adapter :: CoT</name> <packaging>bundle</packaging> <properties> <contact.address>[email protected]</contact.address> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.bundle.plugin.version>2.3.6</maven.bundle.plugin.version> <junit.version>4.8.1</junit.version> <jackson.version>1.9.5</jackson.version> </properties> <dependencies> <dependency> <groupId>com.esri.geoevent.sdk</groupId> <artifactId>geoevent-sdk</artifactId> <version>10.2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.apache.felix</groupId> <artifactId>org.osgi.core</artifactId> <version>1.0.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId>org.codehaus.mojo</groupId> <artifactId> license-maven-plugin </artifactId> <versionRange>[1.5,)</versionRange> <goals> <goal>update-file-header</goal> </goals> </pluginExecutionFilter> <action> <ignore></ignore> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>license-maven-plugin</artifactId> <version>1.5</version> <configuration> <verbose>false</verbose> <addSvnKeyWords>true</addSvnKeyWords> </configuration> <executions> <execution> <id>first</id> <goals> <goal>update-file-header</goal> </goals> <phase>process-sources</phase> <configuration> <descriptionTemplate>${basedir}/src/license/descTemplate.ftl</descriptionTemplate> <organizationName>Esri</organizationName> <inceptionYear>2013</inceptionYear> <licenseName>apache_v2</licenseName> <roots> <root>src/main/java</root> <root>src/test</root> </roots> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.3.7</version> <extensions>true</extensions> <configuration> <instructions> <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName> <Esri-Adapter-Name>${project.artifactId}</Esri-Adapter-Name> <Export-Package /> <AGES-Domain>com.esri.ges.solutions.adapter</AGES-Domain> <Private-Package>com.esri.geoevent.solutions.adapter.cot</Private-Package> </instructions> </configuration> </plugin> </plugins> </build> </project>
{'content_hash': '752bff0572b8a5426ad213a7d8d26c02', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 204, 'avg_line_length': 33.62837837837838, 'alnum_prop': 0.6795258187663251, 'repo_name': 'abrowning80/solutions-geoevent-java', 'id': '1292cf68b637251f7960f1962a49e01bcfe44571', 'size': '4977', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'solutions-geoevent/10.1.x-10.2.2/adapters/cot-adapter/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '138'}, {'name': 'HTML', 'bytes': '534'}, {'name': 'Java', 'bytes': '1346608'}, {'name': 'Python', 'bytes': '109038'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>vst-32: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.2 / vst-32 - 2.11</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> vst-32 <small> 2.11 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-07 17:03:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-07 17:03:26 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; synopsis: &quot;Verified Software Toolchain&quot; description: &quot;The software toolchain includes static analyzers to check assertions about your program; optimizing compilers to translate your program to machine language; operating systems and libraries to supply context for your program. The Verified Software Toolchain project assures with machine-checked proofs that the assertions claimed at the top of the toolchain really hold in the machine-language program, running in the operating-system context.&quot; authors: [ &quot;Andrew W. Appel&quot; &quot;Lennart Beringer&quot; &quot;Josiah Dodds&quot; &quot;Qinxiang Cao&quot; &quot;Aquinas Hobor&quot; &quot;Gordon Stewart&quot; &quot;Qinshi Wang&quot; &quot;Sandrine Blazy&quot; &quot;Santiago Cuellar&quot; &quot;Robert Dockins&quot; &quot;Nick Giannarakis&quot; &quot;Samuel Gruetter&quot; &quot;Jean-Marie Madiot&quot; ] maintainer: &quot;VST team&quot; homepage: &quot;http://vst.cs.princeton.edu/&quot; dev-repo: &quot;git+https://github.com/PrincetonUniversity/VST.git&quot; bug-reports: &quot;https://github.com/PrincetonUniversity/VST/issues&quot; license: &quot;https://raw.githubusercontent.com/PrincetonUniversity/VST/master/LICENSE&quot; build: [ [make &quot;-j%{jobs}%&quot; &quot;vst&quot; &quot;IGNORECOQVERSION=true&quot; &quot;ZLIST=platform&quot; &quot;BITSIZE=32&quot;] ] install: [ [make &quot;install&quot; &quot;IGNORECOQVERSION=true&quot; &quot;ZLIST=platform&quot; &quot;BITSIZE=32&quot;] ] run-test: [ [make &quot;-j%{jobs}%&quot; &quot;test&quot; &quot;IGNORECOQVERSION=true&quot; &quot;ZLIST=platform&quot; &quot;BITSIZE=32&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.14&quot; &amp; &lt; &quot;8.17~&quot;} &quot;coq-compcert-32&quot; {= &quot;3.11&quot;} &quot;coq-vst-zlist&quot; {= &quot;2.11&quot;} &quot;coq-flocq&quot; {&gt;= &quot;4.1.0&quot;} ] conflicts: [ &quot;coq-vst&quot; ] tags: [ &quot;category:Computer Science/Semantics and Compilation/Semantics&quot; &quot;keyword:C&quot; &quot;logpath:VST&quot; &quot;date:2022-08-19&quot; ] url { src: &quot;https://github.com/PrincetonUniversity/VST/archive/refs/tags/v2.11.tar.gz&quot; checksum: &quot;sha512=655123f4ddb3221020c1034e3e1bed4ccd277d50b155947962009081d45abce0081abc0c2ac7a7f234a0b3ce0a169475e2d0dbd5250e3ab9d4f2503dcc67353f&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-vst-32.2.11 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2). The following dependencies couldn&#39;t be met: - coq-vst-32 -&gt; coq-flocq &gt;= 4.1.0 -&gt; coq &gt;= 8.12 -&gt; ocaml &gt;= 4.09.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-vst-32.2.11</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{'content_hash': '9123750db84a827d052aefe264215964', 'timestamp': '', 'source': 'github', 'line_count': 194, 'max_line_length': 467, 'avg_line_length': 42.118556701030926, 'alnum_prop': 0.5744706890221515, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '993aeea573559b1a939887cc59acd083193531c1', 'size': '8196', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.06.1-2.0.5/released/8.8.2/vst-32/2.11.html', 'mode': '33188', 'license': 'mit', 'language': []}
<?php namespace DvsaCommonApi\Controller; use DataCatalogApi\Service\DataCatalogService; use DvsaCommon\DtoSerialization\DtoReflectiveSerializer; use DvsaCommon\Http\HttpStatus; use DvsaCommon\Validation\ValidationResponseMessages; use DvsaCommonApi\Model\ApiResponse; use DvsaCommonApi\Service\Exception\EmptyRequestBodyException; use DvsaCommonApi\Service\Exception\NotFoundException; use DvsaCommonApi\Service\Exception\UnauthenticatedException; use Zend\Http\Request; use Zend\Http\Response; use Zend\Json\Json; use Zend\Log\Logger; use Zend\Mvc\Controller\AbstractRestfulController; use Zend\Mvc\MvcEvent; use Zend\Stdlib\RequestInterface; use Zend\View\Model\JsonModel; /** * AbstractDvsaRestfulController. */ class AbstractDvsaRestfulController extends AbstractRestfulController { const ERROR_CODE_NOT_ALLOWED = 10; const ERROR_CODE_REQUIRED = 20; const ERROR_CODE_NOT_FOUND = 40; const ERROR_CODE_INVALID_DATA = 60; const ERROR_CODE_UNAUTHORIZED = 401; const CHECK_POSITIVE_INTEGER = 'positiveInteger'; const CHECK_POSITIVE_INTEGER_OR_NULL = 'positiveIntegerOrNull'; const ERROR_GENERIC_MSG = 'An error occurred.'; const ERROR_MSG_IS_REQUIRED = ' is required'; const ERROR_MSG_POSITIVE_INTEGER = ' must be a positive integer'; const ERROR_MSG_POSITIVE_INTEGER_OR_NULL = ' must be a positive integer or null'; const DISPLAY_MSG_IS_REQUIRED = 'Values are missing.'; const ERROR_MSG_UNAUTHORIZED_REQUEST = 'Unauthorised request, please supply valid token in authorisation header'; /** * @var \DvsaAuthentication\Identity */ private $identity; public function isFeatureEnabled($name) { return $this ->getServiceLocator() ->get('Feature\FeatureToggles') ->isEnabled($name); } public function assertFeatureEnabled($name) { if (!$this->isFeatureEnabled($name)) { throw new NotFoundException("Feature '".$name."' is turned off", null, false); } } // Override default actions as they do not return valid JsonModels /** * @param mixed $data * * @return \Zend\View\Model\JsonModel */ public function create($data) { return $this->returnMethodNotAllowedResponseModel(); } /** * @param mixed $id * * @return \Zend\View\Model\JsonModel */ public function delete($id) { return $this->returnMethodNotAllowedResponseModel(); } /** * @param mixed $data * * @return \Zend\View\Model\JsonModel */ public function deleteList($data) { return $this->returnMethodNotAllowedResponseModel(); } /** * @param mixed $id * * @return \Zend\View\Model\JsonModel */ public function get($id) { return $this->returnMethodNotAllowedResponseModel(); } /** * @return \Zend\View\Model\JsonModel */ public function getList() { return $this->returnMethodNotAllowedResponseModel(); } /** * @param null $id * * @return \Zend\View\Model\JsonModel */ public function head($id = null) { return $this->returnMethodNotAllowedResponseModel(); } /** * @return \Zend\View\Model\JsonModel */ public function options() { return $this->returnMethodNotAllowedResponseModel(); } /** * @param $id * @param $data * * @return \Zend\View\Model\JsonModel */ public function patch($id, $data) { return $this->returnMethodNotAllowedResponseModel(); } /** * @param mixed $data * * @return \Zend\View\Model\JsonModel */ public function replaceList($data) { return $this->returnMethodNotAllowedResponseModel(); } /** * @param mixed $data * * @return \Zend\View\Model\JsonModel */ public function patchList($data) { return $this->returnMethodNotAllowedResponseModel(); } /** * @param mixed $id * @param mixed $data * * @return \Zend\View\Model\JsonModel */ public function update($id, $data) { return $this->returnMethodNotAllowedResponseModel(); } /** * Base helper for methods returning Apigility API Problem style responses. * * See {@http://tools.ietf.org/html/draft-nottingham-http-problem-06} and * {@link https://apigility.org/documentation/api-primer/error-reporting} for an explanation of the format used. * * @param int $statusCode * @param array $properties * * @return \Zend\View\Model\JsonModel */ public function createApiProblemResponseModel($statusCode, array $properties = []) { $this->getResponse()->setStatusCode($statusCode); $properties = array_merge([ 'type' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html', 'status' => $statusCode, 'title' => HttpStatus::$statusTexts[$statusCode], 'detail' => '', ], $properties); // Legacy response body $errors = ['errors' => [ 'message' => $properties['title'], 'code' => $statusCode, 'displayMessage' => $properties['detail'], 'problem' => $properties, // Problem Details for HTTP APIs (application/problem+json) ], ]; return new JsonModel($errors); } //TODO please, delete this after removing empty calls public function processPostData(RequestInterface $request) { if ($this->requestHasContentType($request, self::CONTENT_TYPE_JSON)) { $data = $this->decodeJsonIfNotEmpty($request->getContent()); } else { $data = $request->getPost()->toArray(); } return $this->create($data); } //TODO please, delete this after removing empty calls protected function processBodyContent($request) { $content = $request->getContent(); // JSON content? decode and return it. if ($this->requestHasContentType($request, self::CONTENT_TYPE_JSON)) { return $this->decodeJsonIfNotEmpty($request->getContent()); } parse_str($content, $parsedParams); // If parse_str fails to decode, or we have a single element with empty value if (!is_array($parsedParams) || empty($parsedParams) || (1 == count($parsedParams) && '' === reset($parsedParams)) ) { return $content; } return $parsedParams; } //TODO please, delete this after removing empty calls private function decodeJsonIfNotEmpty($content) { if(!empty($content)) { return Json::decode($content, $this->jsonDecodeType); } else { return null; } } /** * Helper method to be used when a resource does not exist. * * @param string $detail * * @return \Zend\View\Model\JsonModel */ public function createNotFoundResponseModel($detail = 'Resource not found') { return $this->createApiProblemResponseModel(HttpStatus::HTTP_NOT_FOUND, [ 'detail' => $detail, ]); } /** * Helper method to be used when a validation pass fails. * * See {@link https://apigility.org/documentation/content-validation/validating}. * * @param array $errors * * @return \Zend\View\Model\JsonModel */ public function createValidationProblemResponseModel(ValidationResponseMessages $messages) { return $this->createApiProblemResponseModel(HttpStatus::HTTP_UNPROCESSABLE_ENTITY, [ 'detail' => 'Failed Validation', 'validation_messages' => $messages->toArray(), ]); } /** * Wraps the parent onDispatch with some request/response logging. * * @param MvcEvent $e * * @return mixed|void the parent's response */ public function onDispatch(MvcEvent $e) { $routeMatch = $e->getRouteMatch(); if ($routeMatch !== null) { $this->logEvent( 'Received API request to: ['.$routeMatch->getMatchedRouteName(). '] method: ['.$e->getRequest()->getMethod().'] url: ['.$this->getRequest()->getUriString().'] content: '.$e->getRequest()->getContent(), Logger::INFO ); } $response = parent::onDispatch($e); if ($routeMatch !== null) { if ($response instanceof JsonModel) { $this->logEvent('Returning json '.$response->serialize()); } else { // We're meant to be always returning JSON, so no reason to end up here $this->logEvent('Returning unknown object'); } } } /** * Get the identity of the person making this request. * * @throws UnauthenticatedException when there is no identity * * @return \DvsaAuthentication\Identity */ protected function getIdentity() { // check for cached identity call and return it if set if ($this->identity instanceof \DvsaAuthentication\Identity) { return $this->identity; } /** @var \Zend\Authentication\AuthenticationService $service */ $service = $this->getServiceLocator()->get('DvsaAuthenticationService'); $identity = $service->getIdentity(); if (!$identity) { throw new UnauthenticatedException(); } $this->identity = $identity; return $this->identity; } /** * Convenience method for obtaining the authenticated users' username. * * @throws UnauthenticatedException when there is no identity * * @return string */ protected function getUsername() { return $this->getIdentity()->getUsername(); } /** * Convenience method for obtaining the authenticated users' user id. * * @throws UnauthenticatedException when there is no identity * * @return int */ protected function getUserId() { return $this->getIdentity()->getUserId(); } /** * @return Logger */ protected function getLogger() { return $this->getServiceLocator()->get('Application\Logger'); } /** * @return DataCatalogService */ protected function getCatalog() { return $this->getServiceLocator()->get(DataCatalogService::class); } /** * @param $fieldName * @param $postData * @param $errors * @param null $dataTypeCheck * * @return array */ protected function checkForRequiredFieldAndAddToErrors($fieldName, $postData, $errors, $dataTypeCheck = null) { if (!array_key_exists($fieldName, $postData)) { $errors[] = [ 'message' => $fieldName.self::ERROR_MSG_IS_REQUIRED, 'code' => self::ERROR_CODE_REQUIRED, 'displayMessage' => self::DISPLAY_MSG_IS_REQUIRED, ]; } else { if ($dataTypeCheck) { $fieldValue = $postData[$fieldName]; switch ($dataTypeCheck) { case self::CHECK_POSITIVE_INTEGER: if (!is_numeric($fieldValue) || ((int) $fieldValue) < 0) { $message = $fieldName.self::ERROR_MSG_POSITIVE_INTEGER; $errors[] = [ 'message' => $message, 'code' => self::ERROR_CODE_INVALID_DATA, 'displayMessage' => $message, ]; } break; case self::CHECK_POSITIVE_INTEGER_OR_NULL: if (!is_null($fieldValue) && (!is_numeric($fieldValue) || ((int) $fieldValue) < 0)) { $message = $fieldName.self::ERROR_MSG_POSITIVE_INTEGER_OR_NULL; $errors[] = [ 'message' => $message, 'code' => self::ERROR_CODE_INVALID_DATA, 'displayMessage' => $message, ]; } break; } } } return $errors; } /** * Allow a message to be added independently of any other checks. * * @param $text String the full error message to add * @param $code int contains the error code indicator * @param int|string $msgType int contains the display message indicator * * @return array */ protected function makeErrorMessage( $text, $code = self::ERROR_CODE_REQUIRED, $msgType = self::DISPLAY_MSG_IS_REQUIRED ) { return [ 'message' => $text, 'code' => $code, 'displayMessage' => $msgType, ]; } /** * Add a "required field missing" error message. * * @param $fieldName String contains the fieldname that is missing * * @return array */ protected function makeFieldIsRequiredError($fieldName) { return $this->makeErrorMessage($fieldName.self::ERROR_MSG_IS_REQUIRED); } /** * @return \Zend\View\Model\JsonModel */ protected function returnMethodNotFoundModel() { $this->response->setStatusCode(HttpStatus::HTTP_NOT_FOUND); return new JsonModel( [ 'errors' => [ [ 'message' => HttpStatus::$statusTexts[HttpStatus::HTTP_NOT_FOUND], 'code' => self::ERROR_CODE_NOT_FOUND, 'displayMessage' => self::ERROR_GENERIC_MSG, ], ], ] ); } /** * @return \Zend\View\Model\JsonModel */ protected function returnMethodNotAllowedResponseModel() { $this->response->setStatusCode(405); return new JsonModel( [ 'errors' => [ [ 'message' => 'Method Not Allowed', 'code' => self::ERROR_CODE_NOT_ALLOWED, 'displayMessage' => self::ERROR_GENERIC_MSG, ], ], ] ); } /** * @param $errorMessage * @param $code * @param string $displayMessage * * @return \Zend\View\Model\JsonModel */ protected function returnBadRequestResponseModel($errorMessage, $code, $displayMessage = self::ERROR_GENERIC_MSG) { $this->response->setStatusCode(Response::STATUS_CODE_400); return new JsonModel( [ 'errors' => [ [ 'message' => $errorMessage, 'code' => $code, 'displayMessage' => $displayMessage, ], ], ] ); } /** * @param $errors * * @return \Zend\View\Model\JsonModel */ protected function returnBadRequestResponseModelWithErrors($errors) { $this->response->setStatusCode(Response::STATUS_CODE_400); return new JsonModel(['errors' => $errors]); } /** * If logging is enabled then write some logger output. * * @param $message String */ protected function logEvent($message, $level = Logger::DEBUG) { static $doLog = null; if (is_null($doLog)) { $config = $this->getServiceLocator()->get('config'); $doLog = array_key_exists('logJson', $config) && $config['logJson']; } if ($doLog) { $this->getLogger()->log($level, $message); } } protected function returnDto($dto) { $dtoSerializer = $this->getDtoSerializer(); return ApiResponse::jsonOk($dtoSerializer->serialize($dto)); } public function assertContentNotEmpty($content) { if (empty($content)) { throw new EmptyRequestBodyException(); } } /** * @return DtoReflectiveSerializer */ private function getDtoSerializer() { return $this->getServiceLocator()->get(DtoReflectiveSerializer::class); } }
{'content_hash': '9c9fdcba853df82568702cc869aaafc0', 'timestamp': '', 'source': 'github', 'line_count': 571, 'max_line_length': 152, 'avg_line_length': 29.04203152364273, 'alnum_prop': 0.5555689561599229, 'repo_name': 'dvsa/mot', 'id': '36e5907d4e7d2af8d5af728ccfad7ed5efaf142d', 'size': '16583', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mot-api/module/DvsaCommonApi/src/DvsaCommonApi/Controller/AbstractDvsaRestfulController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '604618'}, {'name': 'Dockerfile', 'bytes': '2693'}, {'name': 'Gherkin', 'bytes': '189981'}, {'name': 'HTML', 'bytes': '1579702'}, {'name': 'Java', 'bytes': '1631717'}, {'name': 'JavaScript', 'bytes': '156823'}, {'name': 'Makefile', 'bytes': '2877'}, {'name': 'PHP', 'bytes': '20142004'}, {'name': 'PLpgSQL', 'bytes': '61098'}, {'name': 'Python', 'bytes': '3354'}, {'name': 'Ruby', 'bytes': '72'}, {'name': 'SQLPL', 'bytes': '1739266'}, {'name': 'Shell', 'bytes': '203709'}]}
use LoxBerry::System; my $entered_pin = $ARGV[0]; print "Checking pin '$entered_pin'...\n"; my $result = LoxBerry::System::check_securepin($entered_pin); if ( !$result ) { print "SecurePIN OK"; } elsif ( $result == 1 ) { print "SecurePIN wrong"; } elsif ( $result == 2 ) { print "SecurePIN file could not be opened"; } elsif ( $result == 3 ) { print "SecurePIN currently is LOCKED"; } else { print "Undefined result $result"; } print "\n";
{'content_hash': 'c7e3447595e8f112516a06a079328568', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 61, 'avg_line_length': 22.65, 'alnum_prop': 0.6335540838852097, 'repo_name': 'mschlenstedt/Loxberry', 'id': '5eaecf55c15abb60a1f90bf830f60c3db63a89b8', 'size': '469', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'libs/perllib/LoxBerry/testing/check_secpin.pl', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '440852'}, {'name': 'Dockerfile', 'bytes': '479'}, {'name': 'HTML', 'bytes': '439151'}, {'name': 'JavaScript', 'bytes': '1285923'}, {'name': 'PHP', 'bytes': '1058360'}, {'name': 'Perl', 'bytes': '1366827'}, {'name': 'Python', 'bytes': '2073'}, {'name': 'Raku', 'bytes': '1129'}, {'name': 'Sass', 'bytes': '12604'}, {'name': 'Shell', 'bytes': '90137'}]}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:background="@drawable/gfan_dialog_bg" android:orientation="vertical" android:padding="20dp"> <TextView android:id="@+id/tv_dialog_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/tv_dialog_message" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="3dp" android:textColor="#000" android:textSize="16sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="right" android:orientation="horizontal"> <Button android:id="@+id/btn_negative" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:background="#FFF" android:text="取消" android:textColor="#1cafa3" android:textSize="15sp" /> <Button android:id="@+id/btn_positive" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FFF" android:text="确定" android:textColor="#1cafa3" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <!-- From: file:/Users/lizeng/Work/pro_android/GfanSDK/SDK/src/main/res/layout/gfan_custom_dialog_layout.xml -->
{'content_hash': 'bd4077e9007c43faa784bfd7bbe3372c', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 112, 'avg_line_length': 32.79661016949152, 'alnum_prop': 0.6175710594315246, 'repo_name': 'l1fan/GameAne', 'id': '2bf3860d359a42e2d4b7fe3249d3de3f6cdaa754', 'size': '1943', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sdks/gfan/res/layout/gfan_custom_dialog_layout.xml', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '5322'}, {'name': 'Batchfile', 'bytes': '216'}, {'name': 'CSS', 'bytes': '17478'}, {'name': 'HTML', 'bytes': '118872'}, {'name': 'Java', 'bytes': '180464'}, {'name': 'Objective-C', 'bytes': '152626'}, {'name': 'Shell', 'bytes': '529'}]}
''' ## License The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) 2015 Dexter Industries Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi # Connect the Grove Button to digital port D3 # SIG,NC,VCC,GND button = 3 grovepi.pinMode(button,"INPUT") while True: try: print (grovepi.digitalRead(button)) time.sleep(.5) except IOError: print ("Error")
{'content_hash': '29dc26f62847ce0c9b4b254f1a5a112f', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 103, 'avg_line_length': 35.19047619047619, 'alnum_prop': 0.7713125845737483, 'repo_name': 'stwolny/GrovePi', 'id': '3239f36955709f13c82b7f83ea63312f46cd5aa3', 'size': '1859', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'Software/Python/grove_button.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '102575'}, {'name': 'C', 'bytes': '156120'}, {'name': 'C#', 'bytes': '45868'}, {'name': 'C++', 'bytes': '306347'}, {'name': 'Go', 'bytes': '3646'}, {'name': 'Groff', 'bytes': '14045'}, {'name': 'JavaScript', 'bytes': '30142'}, {'name': 'Makefile', 'bytes': '7061'}, {'name': 'Perl', 'bytes': '96047'}, {'name': 'Processing', 'bytes': '1304'}, {'name': 'Python', 'bytes': '598139'}, {'name': 'Shell', 'bytes': '25525'}]}
<?php namespace Exa\ProdeBundle\Entity; use FOS\UserBundle\Entity\User as BaseUser; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\Validator\Constraints as Assert; /** * Usuario * * @ORM\Table() * @ORM\Entity(repositoryClass="Exa\ProdeBundle\Entity\UsuarioRepository") */ class Usuario extends BaseUser { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) * * * @Assert\NotBlank(message="Please enter your name.", groups={"Registration", "Profile"}) * @Assert\MinLength(limit="3", message="The name is too short.", groups={"Registration", "Profile"}) * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"}) */ protected $name; /** * @var integer * @ORM\ManyToOne(targetEntity="Equipo", inversedBy="usuarios"); * @ORM\JoinColumn(name="equipo_id", referencedColumnName="id") * * @Assert\NotBlank(message="Selecciona tu equipo.", groups={"Registration", "Profile"}) * @Assert\Type(type="Exa\ProdeBundle\Entity\Equipo") */ protected $equipo; /** * * @ORM\OneToMany(targetEntity="TarjetaApuestas", mappedBy="usuario") */ protected $tarjetasApuesta; public function __construct() { parent::__construct(); // busco las tarjetas de apuestas $this->tarjetasApuesta = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } public function getNameTeam() { return sprintf("%s (%s)", $this->getName(), $this->getEquipo()->getName()); } /** * Set name * * @param string $name * @return Usuario */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set equipo_id * * @param integer $equipoId * @return Usuario */ public function setEquipoId($equipoId) { $this->equipo_id = $equipoId; return $this; } /** * Get equipo_id * * @return integer */ public function getEquipoId() { return $this->equipo_id; } /** * Set email * * @param string $email * @return Usuario */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set equipo * * @param \Exa\ProdeBundle\Entity\Equipo $equipo * @return Usuario */ public function setEquipo(\Exa\ProdeBundle\Entity\Equipo $equipo = null) { $this->equipo = $equipo; return $this; } /** * Get equipo * * @return \Exa\ProdeBundle\Entity\Equipo */ public function getEquipo() { return $this->equipo; } /** * Add tarjetasApuesta * * @param \Exa\ProdeBundle\Entity\TarjetaApuestas $tarjetasApuesta * @return Usuario */ public function addTarjetasApuesta(\Exa\ProdeBundle\Entity\TarjetaApuestas $tarjetasApuesta) { $this->tarjetasApuesta[] = $tarjetasApuesta; return $this; } /** * Remove tarjetasApuesta * * @param \Exa\ProdeBundle\Entity\TarjetaApuestas $tarjetasApuesta */ public function removeTarjetasApuesta(\Exa\ProdeBundle\Entity\TarjetaApuestas $tarjetasApuesta) { $this->tarjetasApuesta->removeElement($tarjetasApuesta); } /** * Get tarjetasApuesta * * @return \Doctrine\Common\Collections\Collection */ public function getTarjetasApuesta() { return $this->tarjetasApuesta; } /** * Set password * * @param string $password * @return Usuario */ public function setPassword($password) { $this->password = $password; return $this; } /** * Get password * * @return string */ public function getPassword() { return $this->password; } }
{'content_hash': 'b87f1b18baa9da5aeaae33d742f7ebdf', 'timestamp': '', 'source': 'github', 'line_count': 221, 'max_line_length': 106, 'avg_line_length': 20.65158371040724, 'alnum_prop': 0.5569675723049956, 'repo_name': 'pmartelletti/prode-exa', 'id': 'a057c6a41b43a894debc43dd91eea04b9d8c48af', 'size': '4564', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Exa/ProdeBundle/Entity/Usuario.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1307'}, {'name': 'PHP', 'bytes': '116809'}]}
!function(globals){ 'use strict' //*** UMD BEGIN if (typeof define !== 'undefined' && define.amd) { //require.js / AMD define([], function() { return secureRandom }) } else if (typeof module !== 'undefined' && module.exports) { //CommonJS module.exports = secureRandom } else { //script / browser globals.secureRandom = secureRandom } //*** UMD END //options.type is the only valid option function secureRandom(count, options) { options = options || {type: 'Array'} //we check for process.pid to prevent browserify from tricking us if (typeof process != 'undefined' && typeof process.pid == 'number') { return nodeRandom(count, options) } else { var crypto = window.crypto || window.msCrypto if (!crypto) throw new Error("Your browser does not support window.crypto.") return browserRandom(count, options) } } function nodeRandom(count, options) { var crypto = require('crypto') var buf = crypto.randomBytes(count) switch (options.type) { case 'Array': return [].slice.call(buf) case 'Buffer': return buf case 'Uint8Array': var arr = new Uint8Array(count) for (var i = 0; i < count; ++i) { arr[i] = buf.readUInt8(i) } return arr default: throw new Error(options.type + " is unsupported.") } } function browserRandom(count, options) { var nativeArr = new Uint8Array(count) var crypto = window.crypto || window.msCrypto crypto.getRandomValues(nativeArr) switch (options.type) { case 'Array': return [].slice.call(nativeArr) case 'Buffer': try { var b = new Buffer(1) } catch(e) { throw new Error('Buffer not supported in this environment. Use Node.js or Browserify for browser support.')} return new Buffer(nativeArr) case 'Uint8Array': return nativeArr default: throw new Error(options.type + " is unsupported.") } } secureRandom.randomArray = function(byteCount) { return secureRandom(byteCount, {type: 'Array'}) } secureRandom.randomUint8Array = function(byteCount) { return secureRandom(byteCount, {type: 'Uint8Array'}) } secureRandom.randomBuffer = function(byteCount) { return secureRandom(byteCount, {type: 'Buffer'}) } }(this);
{'content_hash': 'bd76fd94f2dbe5227ff84c4191fdf707', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 155, 'avg_line_length': 28.26923076923077, 'alnum_prop': 0.671201814058957, 'repo_name': 'jamescarter-le/brainwallet.github.io', 'id': '96a59d0c317782c128763d3b46be19eab51d2394', 'size': '2205', 'binary': False, 'copies': '23', 'ref': 'refs/heads/master', 'path': 'js/secure-random.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '272'}, {'name': 'HTML', 'bytes': '33648'}, {'name': 'JavaScript', 'bytes': '186739'}]}
from django.conf.urls.defaults import patterns from django.conf.urls.defaults import url from .ports.views import AddInterfaceView from .ports.views import SetGatewayView from .views import CreateView from .views import DetailView from .views import IndexView urlpatterns = patterns('horizon.dashboards.project.routers.views', url(r'^$', IndexView.as_view(), name='index'), url(r'^create/$', CreateView.as_view(), name='create'), url(r'^(?P<router_id>[^/]+)/$', DetailView.as_view(), name='detail'), url(r'^(?P<router_id>[^/]+)/addinterface', AddInterfaceView.as_view(), name='addinterface'), url(r'^(?P<router_id>[^/]+)/setgateway', SetGatewayView.as_view(), name='setgateway'), )
{'content_hash': '1e8c9a70b36c5f0926d00cb1c1d83ece', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 74, 'avg_line_length': 33.86363636363637, 'alnum_prop': 0.6671140939597315, 'repo_name': 'fajoy/horizon-example', 'id': '4345ca54896ca0d13c3cb2d311f52b9ad0f7bd8d', 'size': '1412', 'binary': False, 'copies': '1', 'ref': 'refs/heads/example', 'path': 'openstack_dashboard/dashboards/project/routers/urls.py', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
from ggrc import db from ggrc.models.deferred import deferred from ggrc.models.mixins import Base, Described class Option(Described, Base, db.Model): __tablename__ = 'options' role = db.Column(db.String) title = deferred(db.Column(db.String), 'Option') required = deferred(db.Column(db.Boolean), 'Option') @staticmethod def _extra_table_args(cls): return ( db.Index('ix_options_role', 'role'), ) _publish_attrs = [ 'role', 'title', 'required', ] _sanitize_html = [ 'title', ]
{'content_hash': '4186a2c46c504051cc85448392d9766b', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 54, 'avg_line_length': 20.807692307692307, 'alnum_prop': 0.6284658040665434, 'repo_name': 'josthkko/ggrc-core', 'id': '81b7a02b5d32980558bf134ff66556530f8481a1', 'size': '654', 'binary': False, 'copies': '6', 'ref': 'refs/heads/develop', 'path': 'src/ggrc/models/option.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '163629'}, {'name': 'Cucumber', 'bytes': '136321'}, {'name': 'HTML', 'bytes': '1057288'}, {'name': 'JavaScript', 'bytes': '1492054'}, {'name': 'Makefile', 'bytes': '6161'}, {'name': 'Mako', 'bytes': '2178'}, {'name': 'Python', 'bytes': '2148568'}, {'name': 'Shell', 'bytes': '29929'}]}
#include "qnetworkproxy.h" #ifndef QT_NO_NETWORKPROXY #include <qmutex.h> #include <qstringlist.h> #include <qregexp.h> #include <qurl.h> #include <private/qsystemlibrary_p.h> #include <qnetworkinterface.h> #include <string.h> #include <qt_windows.h> #include <wininet.h> #include <lmcons.h> #include "qnetworkfunctions_wince.h" /* * Information on the WinHTTP DLL: * http://msdn.microsoft.com/en-us/library/aa384122(VS.85).aspx example for WPAD * * http://msdn.microsoft.com/en-us/library/aa384097(VS.85).aspx WinHttpGetProxyForUrl * http://msdn.microsoft.com/en-us/library/aa384096(VS.85).aspx WinHttpGetIEProxyConfigForCurrentUs * http://msdn.microsoft.com/en-us/library/aa384095(VS.85).aspx WinHttpGetDefaultProxyConfiguration */ // We don't want to include winhttp.h because that's not // present in some Windows SDKs (I don't know why) // So, instead, copy the definitions here typedef struct { DWORD dwFlags; DWORD dwAutoDetectFlags; LPCWSTR lpszAutoConfigUrl; LPVOID lpvReserved; DWORD dwReserved; BOOL fAutoLogonIfChallenged; } WINHTTP_AUTOPROXY_OPTIONS; typedef struct { DWORD dwAccessType; LPWSTR lpszProxy; LPWSTR lpszProxyBypass; } WINHTTP_PROXY_INFO; typedef struct { BOOL fAutoDetect; LPWSTR lpszAutoConfigUrl; LPWSTR lpszProxy; LPWSTR lpszProxyBypass; } WINHTTP_CURRENT_USER_IE_PROXY_CONFIG; #define WINHTTP_AUTOPROXY_AUTO_DETECT 0x00000001 #define WINHTTP_AUTOPROXY_CONFIG_URL 0x00000002 #define WINHTTP_AUTO_DETECT_TYPE_DHCP 0x00000001 #define WINHTTP_AUTO_DETECT_TYPE_DNS_A 0x00000002 #define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY 0 #define WINHTTP_ACCESS_TYPE_NO_PROXY 1 #define WINHTTP_ACCESS_TYPE_NAMED_PROXY 3 #define WINHTTP_NO_PROXY_NAME NULL #define WINHTTP_NO_PROXY_BYPASS NULL #define WINHTTP_ERROR_BASE 12000 #define ERROR_WINHTTP_LOGIN_FAILURE (WINHTTP_ERROR_BASE + 15) #define ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT (WINHTTP_ERROR_BASE + 167) #define ERROR_WINHTTP_AUTODETECTION_FAILED (WINHTTP_ERROR_BASE + 180) QT_BEGIN_NAMESPACE typedef BOOL (WINAPI * PtrWinHttpGetProxyForUrl)(HINTERNET, LPCWSTR, WINHTTP_AUTOPROXY_OPTIONS*, WINHTTP_PROXY_INFO*); typedef HINTERNET (WINAPI * PtrWinHttpOpen)(LPCWSTR, DWORD, LPCWSTR, LPCWSTR,DWORD); typedef BOOL (WINAPI * PtrWinHttpGetDefaultProxyConfiguration)(WINHTTP_PROXY_INFO*); typedef BOOL (WINAPI * PtrWinHttpGetIEProxyConfigForCurrentUser)(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG*); typedef BOOL (WINAPI * PtrWinHttpCloseHandle)(HINTERNET); typedef BOOL (WINAPI * PtrCloseServiceHandle)(SC_HANDLE hSCObject); static PtrWinHttpGetProxyForUrl ptrWinHttpGetProxyForUrl = 0; static PtrWinHttpOpen ptrWinHttpOpen = 0; static PtrWinHttpGetDefaultProxyConfiguration ptrWinHttpGetDefaultProxyConfiguration = 0; static PtrWinHttpGetIEProxyConfigForCurrentUser ptrWinHttpGetIEProxyConfigForCurrentUser = 0; static PtrWinHttpCloseHandle ptrWinHttpCloseHandle = 0; #ifndef Q_OS_WINCE static bool currentProcessIsService() { typedef BOOL (WINAPI *PtrGetUserName)(LPTSTR lpBuffer, LPDWORD lpnSize); typedef BOOL (WINAPI *PtrLookupAccountName)(LPCTSTR lpSystemName, LPCTSTR lpAccountName, PSID Sid, LPDWORD cbSid, LPTSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); static PtrGetUserName ptrGetUserName = (PtrGetUserName)QSystemLibrary::resolve(QLatin1String("Advapi32"), "GetUserNameW"); static PtrLookupAccountName ptrLookupAccountName = (PtrLookupAccountName)QSystemLibrary::resolve(QLatin1String("Advapi32"), "LookupAccountNameW"); if (ptrGetUserName && ptrLookupAccountName) { wchar_t userName[UNLEN + 1] = L""; DWORD size = UNLEN; if (ptrGetUserName(userName, &size)) { SID_NAME_USE type = SidTypeUser; DWORD dummy = MAX_PATH; wchar_t dummyStr[MAX_PATH] = L""; PSID psid = 0; if (ptrLookupAccountName(NULL, userName, &psid, &dummy, dummyStr, &dummy, &type)) return type != SidTypeUser; //returns true if the current user is not a user } } return false; } #endif // ! Q_OS_WINCE static QStringList splitSpaceSemicolon(const QString &source) { QStringList list; int start = 0; int end; while (true) { int space = source.indexOf(QLatin1Char(' '), start); int semicolon = source.indexOf(QLatin1Char(';'), start); end = space; if (semicolon != -1 && (end == -1 || semicolon < end)) end = semicolon; if (end == -1) { if (start != source.length()) list.append(source.mid(start)); return list; } if (start != end) list.append(source.mid(start, end - start)); start = end + 1; } return list; } static bool isBypassed(const QString &host, const QStringList &bypassList) { if (host.isEmpty()) return false; bool isSimple = !host.contains(QLatin1Char('.')) && !host.contains(QLatin1Char(':')); QHostAddress ipAddress; bool isIpAddress = ipAddress.setAddress(host); // always exclude loopback if (isIpAddress && ipAddress.isLoopback()) return true; // does it match the list of exclusions? foreach (const QString &entry, bypassList) { if (entry == QLatin1String("<local>")) { if (isSimple) return true; if (isIpAddress) { //exclude all local subnets foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) { foreach (const QNetworkAddressEntry netaddr, iface.addressEntries()) { if (ipAddress.isInSubnet(netaddr.ip(), netaddr.prefixLength())) { return true; } } } } } if (isIpAddress && ipAddress.isInSubnet(QHostAddress::parseSubnet(entry))) { return true; // excluded } else { // do wildcard matching QRegExp rx(entry, Qt::CaseInsensitive, QRegExp::Wildcard); if (rx.exactMatch(host)) return true; } } // host was not excluded return false; } static QList<QNetworkProxy> filterProxyListByCapabilities(const QList<QNetworkProxy> &proxyList, const QNetworkProxyQuery &query) { QNetworkProxy::Capabilities requiredCaps; switch (query.queryType()) { case QNetworkProxyQuery::TcpSocket: requiredCaps = QNetworkProxy::TunnelingCapability; break; case QNetworkProxyQuery::UdpSocket: requiredCaps = QNetworkProxy::UdpTunnelingCapability; break; case QNetworkProxyQuery::TcpServer: requiredCaps = QNetworkProxy::ListeningCapability; break; default: return proxyList; break; } QList<QNetworkProxy> result; foreach (const QNetworkProxy& proxy, proxyList) { if (proxy.capabilities() & requiredCaps) result.append(proxy); } return result; } static QList<QNetworkProxy> removeDuplicateProxies(const QList<QNetworkProxy> &proxyList) { QList<QNetworkProxy> result; foreach (QNetworkProxy proxy, proxyList) { bool append = true; for (int i=0; i < result.count(); i++) { if (proxy.hostName() == result.at(i).hostName() && proxy.port() == result.at(i).port()) { append = false; // HttpProxy trumps FtpCachingProxy or HttpCachingProxy on the same host/port if (proxy.type() == QNetworkProxy::HttpProxy) result[i] = proxy; } } if (append) result.append(proxy); } return result; } static QList<QNetworkProxy> parseServerList(const QNetworkProxyQuery &query, const QStringList &proxyList) { // Reference documentation from Microsoft: // http://msdn.microsoft.com/en-us/library/aa383912(VS.85).aspx // // According to the website, the proxy server list is // one or more of the space- or semicolon-separated strings in the format: // ([<scheme>=][<scheme>"://"]<server>[":"<port>]) // The first scheme relates to the protocol tag // The second scheme, if present, overrides the proxy type QList<QNetworkProxy> result; QHash<QString, QNetworkProxy> taggedProxies; const QString requiredTag = query.protocolTag(); bool checkTags = !requiredTag.isEmpty() && query.queryType() != QNetworkProxyQuery::TcpServer; //windows tags are only for clients foreach (const QString &entry, proxyList) { int server = 0; QNetworkProxy::ProxyType proxyType = QNetworkProxy::HttpProxy; quint16 port = 8080; int pos = entry.indexOf(QLatin1Char('=')); QStringRef scheme; QStringRef protocolTag; if (pos != -1) { scheme = protocolTag = entry.leftRef(pos); server = pos + 1; } pos = entry.indexOf(QLatin1String("://"), server); if (pos != -1) { scheme = entry.midRef(server, pos - server); server = pos + 3; } if (!scheme.isEmpty()) { if (scheme == QLatin1String("http") || scheme == QLatin1String("https")) { // no-op // defaults are above } else if (scheme == QLatin1String("socks") || scheme == QLatin1String("socks5")) { proxyType = QNetworkProxy::Socks5Proxy; port = 1080; } else if (scheme == QLatin1String("ftp")) { proxyType = QNetworkProxy::FtpCachingProxy; port = 2121; } else { // unknown proxy type continue; } } pos = entry.indexOf(QLatin1Char(':'), server); if (pos != -1) { bool ok; uint value = entry.mid(pos + 1).toUInt(&ok); if (!ok || value > 65535) continue; // invalid port number port = value; } else { pos = entry.length(); } result << QNetworkProxy(proxyType, entry.mid(server, pos - server), port); if (!protocolTag.isEmpty()) taggedProxies.insert(protocolTag.toString(), result.last()); } if (checkTags && taggedProxies.contains(requiredTag)) { if (query.queryType() == QNetworkProxyQuery::UrlRequest) { result.clear(); result.append(taggedProxies.value(requiredTag)); return result; } else { result.prepend(taggedProxies.value(requiredTag)); } } if (!checkTags || requiredTag != QLatin1String("http")) { // if there are different http proxies for http and https, prefer the https one (more likely to be capable of CONNECT) QNetworkProxy httpProxy = taggedProxies.value(QLatin1String("http")); QNetworkProxy httpsProxy = taggedProxies.value(QLatin1String("http")); if (httpProxy != httpsProxy && httpProxy.type() == QNetworkProxy::HttpProxy && httpsProxy.type() == QNetworkProxy::HttpProxy) { for (int i = 0; i < result.count(); i++) { if (httpProxy == result.at(i)) result[i].setType(QNetworkProxy::HttpCachingProxy); } } } result = filterProxyListByCapabilities(result, query); return removeDuplicateProxies(result); } class QWindowsSystemProxy { public: QWindowsSystemProxy(); ~QWindowsSystemProxy(); void init(); QMutex mutex; HINTERNET hHttpSession; WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions; QString autoConfigUrl; QStringList proxyServerList; QStringList proxyBypass; QList<QNetworkProxy> defaultResult; bool initialized; bool functional; bool isAutoConfig; }; Q_GLOBAL_STATIC(QWindowsSystemProxy, systemProxy) QWindowsSystemProxy::QWindowsSystemProxy() : hHttpSession(0), initialized(false), functional(false), isAutoConfig(false) { defaultResult << QNetworkProxy::NoProxy; } QWindowsSystemProxy::~QWindowsSystemProxy() { if (hHttpSession) ptrWinHttpCloseHandle(hHttpSession); } void QWindowsSystemProxy::init() { if (initialized) return; initialized = true; #ifdef Q_OS_WINCE // Windows CE does not have any of the following API return; #else // load the winhttp.dll library QSystemLibrary lib(L"winhttp"); if (!lib.load()) return; // failed to load ptrWinHttpOpen = (PtrWinHttpOpen)lib.resolve("WinHttpOpen"); ptrWinHttpCloseHandle = (PtrWinHttpCloseHandle)lib.resolve("WinHttpCloseHandle"); ptrWinHttpGetProxyForUrl = (PtrWinHttpGetProxyForUrl)lib.resolve("WinHttpGetProxyForUrl"); ptrWinHttpGetDefaultProxyConfiguration = (PtrWinHttpGetDefaultProxyConfiguration)lib.resolve("WinHttpGetDefaultProxyConfiguration"); ptrWinHttpGetIEProxyConfigForCurrentUser = (PtrWinHttpGetIEProxyConfigForCurrentUser)lib.resolve("WinHttpGetIEProxyConfigForCurrentUser"); // Try to obtain the Internet Explorer configuration. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig; const bool hasIEConfig = ptrWinHttpGetIEProxyConfigForCurrentUser(&ieProxyConfig); if (hasIEConfig) { if (ieProxyConfig.lpszAutoConfigUrl) { autoConfigUrl = QString::fromWCharArray(ieProxyConfig.lpszAutoConfigUrl); GlobalFree(ieProxyConfig.lpszAutoConfigUrl); } if (ieProxyConfig.lpszProxy) { // http://msdn.microsoft.com/en-us/library/aa384250%28VS.85%29.aspx speaks only about a "proxy URL", // not multiple URLs. However we tested this and it can return multiple URLs. So we use splitSpaceSemicolon // on it. proxyServerList = splitSpaceSemicolon(QString::fromWCharArray(ieProxyConfig.lpszProxy)); GlobalFree(ieProxyConfig.lpszProxy); } if (ieProxyConfig.lpszProxyBypass) { proxyBypass = splitSpaceSemicolon(QString::fromWCharArray(ieProxyConfig.lpszProxyBypass)); GlobalFree(ieProxyConfig.lpszProxyBypass); } } if (!hasIEConfig || (currentProcessIsService() && proxyServerList.isEmpty() && proxyBypass.isEmpty())) { // no user configuration // attempt to get the default configuration instead // that config will serve as default if WPAD fails WINHTTP_PROXY_INFO proxyInfo; if (ptrWinHttpGetDefaultProxyConfiguration(&proxyInfo) && proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY) { // we got information from the registry // overwrite the IE configuration, if any proxyBypass = splitSpaceSemicolon(QString::fromWCharArray(proxyInfo.lpszProxyBypass)); proxyServerList = splitSpaceSemicolon(QString::fromWCharArray(proxyInfo.lpszProxy)); } if (proxyInfo.lpszProxy) GlobalFree(proxyInfo.lpszProxy); if (proxyInfo.lpszProxyBypass) GlobalFree(proxyInfo.lpszProxyBypass); } hHttpSession = NULL; if (ieProxyConfig.fAutoDetect || !autoConfigUrl.isEmpty()) { // open the handle and obtain the options hHttpSession = ptrWinHttpOpen(L"Qt System Proxy access/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hHttpSession) return; isAutoConfig = true; memset(&autoProxyOptions, 0, sizeof autoProxyOptions); autoProxyOptions.fAutoLogonIfChallenged = false; //Although it is possible to specify dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT | WINHTTP_AUTOPROXY_CONFIG_URL //this has poor performance (WPAD is attempted for every url, taking 2.5 seconds per interface, //before the configured pac file is used) if (ieProxyConfig.fAutoDetect) { autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; } else { autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; autoProxyOptions.lpszAutoConfigUrl = (LPCWSTR)autoConfigUrl.utf16(); } } functional = isAutoConfig || !proxyServerList.isEmpty(); #endif } QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query) { QWindowsSystemProxy *sp = systemProxy(); if (!sp) return QList<QNetworkProxy>() << QNetworkProxy(); QMutexLocker locker(&sp->mutex); sp->init(); if (!sp->functional) return sp->defaultResult; if (sp->isAutoConfig) { WINHTTP_PROXY_INFO proxyInfo; // try to get the proxy config for the URL QUrl url = query.url(); // url could be empty, e.g. from QNetworkProxy::applicationProxy(), that's fine, // we'll still ask for the proxy. // But for a file url, we know we don't need one. if (url.scheme() == QLatin1String("file") || url.scheme() == QLatin1String("qrc")) return sp->defaultResult; if (query.queryType() != QNetworkProxyQuery::UrlRequest) { // change the scheme to https, maybe it'll work url.setScheme(QLatin1String("https")); } bool getProxySucceeded = ptrWinHttpGetProxyForUrl(sp->hHttpSession, (LPCWSTR)url.toString().utf16(), &sp->autoProxyOptions, &proxyInfo); DWORD getProxyError = GetLastError(); if (!getProxySucceeded && (ERROR_WINHTTP_AUTODETECTION_FAILED == getProxyError)) { // WPAD failed if (sp->autoConfigUrl.isEmpty()) { //No config file could be retrieved on the network. //Don't search for it next time again. sp->isAutoConfig = false; } else { //pac file URL is specified as well, try using that sp->autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; sp->autoProxyOptions.lpszAutoConfigUrl = (LPCWSTR)sp->autoConfigUrl.utf16(); getProxySucceeded = ptrWinHttpGetProxyForUrl(sp->hHttpSession, (LPCWSTR)url.toString().utf16(), &sp->autoProxyOptions, &proxyInfo); getProxyError = GetLastError(); } } if (!getProxySucceeded && (ERROR_WINHTTP_LOGIN_FAILURE == getProxyError)) { // We first tried without AutoLogon, because this might prevent caching the result. // But now we've to enable it (http://msdn.microsoft.com/en-us/library/aa383153%28v=VS.85%29.aspx) sp->autoProxyOptions.fAutoLogonIfChallenged = TRUE; getProxySucceeded = ptrWinHttpGetProxyForUrl(sp->hHttpSession, (LPCWSTR)url.toString().utf16(), &sp->autoProxyOptions, &proxyInfo); getProxyError = GetLastError(); } if (!getProxySucceeded && (ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT == getProxyError)) { // PAC file url is not connectable, or server returned error (e.g. http 404) //Don't search for it next time again. sp->isAutoConfig = false; } if (getProxySucceeded) { // yes, we got a config for this URL QString proxyBypass = QString::fromWCharArray(proxyInfo.lpszProxyBypass); QStringList proxyServerList = splitSpaceSemicolon(QString::fromWCharArray(proxyInfo.lpszProxy)); if (proxyInfo.lpszProxy) GlobalFree(proxyInfo.lpszProxy); if (proxyInfo.lpszProxyBypass) GlobalFree(proxyInfo.lpszProxyBypass); if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY) return sp->defaultResult; //i.e. the PAC file result was "DIRECT" if (isBypassed(query.peerHostName(), splitSpaceSemicolon(proxyBypass))) return sp->defaultResult; return parseServerList(query, proxyServerList); } // GetProxyForUrl failed, fall back to static configuration } // static configuration if (isBypassed(query.peerHostName(), sp->proxyBypass)) return sp->defaultResult; QList<QNetworkProxy> result = parseServerList(query, sp->proxyServerList); // In some cases, this was empty. See SF task 00062670 if (result.isEmpty()) return sp->defaultResult; return result; } QT_END_NAMESPACE #endif
{'content_hash': '8c4213c428a29700d87404fdae6014c8', 'timestamp': '', 'source': 'github', 'line_count': 550, 'max_line_length': 150, 'avg_line_length': 38.56909090909091, 'alnum_prop': 0.626408334511856, 'repo_name': 'smasala/phantomjs', 'id': 'e16d7e557e65e102e9bc667e19cee00d8f878f37', 'size': '23183', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'src/qt/qtbase/src/network/kernel/qnetworkproxy_win.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '825'}, {'name': 'Assembly', 'bytes': '268988'}, {'name': 'Bison', 'bytes': '12791'}, {'name': 'C', 'bytes': '8684702'}, {'name': 'C#', 'bytes': '1101'}, {'name': 'C++', 'bytes': '126605812'}, {'name': 'CMake', 'bytes': '554470'}, {'name': 'CSS', 'bytes': '760708'}, {'name': 'DTrace', 'bytes': '1931'}, {'name': 'Emacs Lisp', 'bytes': '393'}, {'name': 'GAP', 'bytes': '194281'}, {'name': 'Groff', 'bytes': '570631'}, {'name': 'HTML', 'bytes': '5465225'}, {'name': 'Java', 'bytes': '339535'}, {'name': 'JavaScript', 'bytes': '9553650'}, {'name': 'Makefile', 'bytes': '21096'}, {'name': 'Objective-C', 'bytes': '2820750'}, {'name': 'Objective-C++', 'bytes': '7474669'}, {'name': 'Perl', 'bytes': '1736748'}, {'name': 'Perl6', 'bytes': '38417'}, {'name': 'Prolog', 'bytes': '14631'}, {'name': 'Protocol Buffer', 'bytes': '8758'}, {'name': 'Python', 'bytes': '5502820'}, {'name': 'QML', 'bytes': '170356'}, {'name': 'QMake', 'bytes': '583682'}, {'name': 'Ruby', 'bytes': '424059'}, {'name': 'Shell', 'bytes': '469013'}, {'name': 'XSLT', 'bytes': '1047'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tree-automata: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.12.2 / tree-automata - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tree-automata <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-23 21:58:20 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-23 21:58:20 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.12.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/tree-automata&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/TreeAutomata&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} &quot;coq-int-map&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: tree automatas&quot; &quot;keyword: bottom up reflexion terms&quot; &quot;category: Computer Science/Formal Languages Theory and Automata&quot; &quot;date: september 1999&quot; ] authors: [ &quot;Xavier Rival [http://www.eleves.ens.fr/home/rival]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/tree-automata/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/tree-automata.git&quot; synopsis: &quot;Tree automatas&quot; description: &quot;&quot;&quot; provides tree automatas algorithms in Coq (merge, intersection, vacuity test, deletion of empty states, coaccessiblity test, deletion of non coaccessible states)&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/tree-automata/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=5997a776ec452efacb22bbd3baf3654a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-tree-automata.8.10.0 coq.8.12.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.12.2). The following dependencies couldn&#39;t be met: - coq-tree-automata -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tree-automata.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{'content_hash': '9f9a169558256909d1ccf8a6f1b1a6d8', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 159, 'avg_line_length': 40.95977011494253, 'alnum_prop': 0.5480566858425705, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'f7a1032edb8eeed410b242f2236c3f146c6ac680', 'size': '7152', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.05.0-2.0.1/released/8.12.2/tree-automata/8.10.0.html', 'mode': '33188', 'license': 'mit', 'language': []}
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <meta charset="utf-8"/> <title>API Documentation</title> <meta name="author" content=""/> <meta name="description" content=""/> <link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet"> <link href="../css/font-awesome.min.css" rel="stylesheet"> <link href="../css/prism.css" rel="stylesheet" media="all"/> <link href="../css/template.css" rel="stylesheet" media="all"/> <!--[if lt IE 9]> <script src="../js/html5.js"></script> <![endif]--> <script src="../js/jquery-1.11.0.min.js"></script> <script src="../js/ui/1.10.4/jquery-ui.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script src="../js/jquery.smooth-scroll.js"></script> <script src="../js/prism.min.js"></script> <!-- TODO: Add http://jscrollpane.kelvinluck.com/ to style the scrollbars for browsers not using webkit--> <script type="text/javascript"> function loadExternalCodeSnippets() { Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function (pre) { var src = pre.getAttribute('data-src'); var extension = (src.match(/\.(\w+)$/) || [, ''])[1]; var language = 'php'; var code = document.createElement('code'); code.className = 'language-' + language; pre.textContent = ''; code.textContent = 'Loading…'; pre.appendChild(code); var xhr = new XMLHttpRequest(); xhr.open('GET', src, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status < 400 && xhr.responseText) { code.textContent = xhr.responseText; Prism.highlightElement(code); } else if (xhr.status >= 400) { code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText; } else { code.textContent = '✖ Error: File does not exist or is empty'; } } }; xhr.send(null); }); } $(document).ready(function(){ loadExternalCodeSnippets(); }); $('#source-view').on('shown', function () { loadExternalCodeSnippets(); }) </script> <link rel="shortcut icon" href="../images/favicon.ico"/> <link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/> <link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/> <link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <i class="icon-ellipsis-vertical"></i> </a> <a class="brand" href="../index.html">API Documentation</a> <div class="nav-collapse"> <ul class="nav pull-right"> <li class="dropdown" id="charts-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Charts <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="../graphs/class.html"> <i class="icon-list-alt"></i>&#160;Class hierarchy diagram </a> </li> </ul> </li> <li class="dropdown" id="reports-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="../reports/errors.html"> <i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">113</span> </a> </li> <li> <a href="../reports/markers.html"> <i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">8</span> </a> </li> <li> <a href="../reports/deprecated.html"> <i class="icon-list-alt"></i>&#160;Deprecated <span class="label label-info pull-right">0</span> </a> </li> </ul> </li> </ul> </div> </div> </div> <!--<div class="go_to_top">--> <!--<a href="#___" style="color: inherit">Back to top&#160;&#160;<i class="icon-upload icon-white"></i></a>--> <!--</div>--> </div> <div id="___" class="container-fluid"> <section class="row-fluid"> <div class="span2 sidebar"> <div class="accordion" style="margin-bottom: 0"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-1585998653"></a> <a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a> </div> <div id="namespace-1585998653" class="accordion-body collapse in"> <div class="accordion-inner"> <ul> <li class="class"><a href="../classes/Anemometer.html">Anemometer</a></li> <li class="class"><a href="../classes/AnemometerModel.html">AnemometerModel</a></li> <li class="class"><a href="../classes/Loader.html">Loader</a></li> <li class="class"><a href="../classes/MySQLTableReport.html">MySQLTableReport</a></li> <li class="class"><a href="../classes/QueryExplain.html">QueryExplain</a></li> <li class="class"><a href="../classes/QueryRewrite.html">QueryRewrite</a></li> <li class="class"><a href="../classes/QueryTableParser.html">QueryTableParser</a></li> </ul> </div> </div> </div> </div> </div> </section> <section class="row-fluid"> <div class="span10 offset2"> <div class="row-fluid"> <div class="span8 content class"> <nav> <a href="../namespaces/default.html">\</a> <i class="icon-level-up"></i> </nav> <a href="#source-view" role="button" class="pull-right btn" data-toggle="modal"><i class="icon-code"></i></a> <h1><small>\</small>Loader</h1> <p><em>class to mimic codigniter&#039;s syntax for loading views from the controller</em></p> <section id="summary"> <h2>Summary</h2> <section class="row-fluid heading"> <section class="span4"> <a href="#methods">Methods</a> </section> <section class="span4"> <a href="#properties">Properties</a> </section> <section class="span4"> <a href="#constants">Constants</a> </section> </section> <section class="row-fluid public"> <section class="span4"> <a href="../classes/Loader.html#method_view" class="">view()</a><br /> </section> <section class="span4"> <em>No public properties found</em> </section> <section class="span4"> <em>No constants found</em> </section> </section> <section class="row-fluid protected"> <section class="span4"> <em>No protected methods found</em> </section> <section class="span4"> <em>No protected properties found</em> </section> <section class="span4"> <em>N/A</em> </section> </section> <section class="row-fluid private"> <section class="span4"> <em>No private methods found</em> </section> <section class="span4"> <em>No private properties found</em> </section> <section class="span4"> <em>N/A</em> </section> </section> </section> </div> <aside class="span4 detailsbar"> <dl> <dt>File</dt> <dd><a href="../files/Loader.html"><div class="path-wrapper">Loader.php</div></a></dd> <dt>Package</dt> <dd><div class="namespace-wrapper">Default</div></dd> <dt>Class hierarchy</dt> <dd class="hierarchy"> <div class="namespace-wrapper">\Loader</div> </dd> </dl> <h2>Tags</h2> <table class="table table-condensed"> <tr> <th> author </th> <td> <p>Gavin Towey <a href="mailto:[email protected]">[email protected]</a></p> </td> </tr> <tr> <th> created </th> <td> <p>2012-01-01</p> </td> </tr> <tr> <th> license </th> <td> <p>Apache 2.0 license. See LICENSE document for more info</p> </td> </tr> </table> </aside> </div> <a id="methods" name="methods"></a> <div class="row-fluid"> <div class="span8 content class"><h2>Methods</h2></div> <aside class="span4 detailsbar"></aside> </div> <div class="row-fluid"> <div class="span8 content class"> <a id="method_view" name="method_view" class="anchor"></a> <article class="method"> <h3 class="public ">view()</h3> <a href="#source-view" role="button" class="pull-right btn" data-toggle="modal" style="font-size: 1.1em; padding: 9px 14px"><i class="icon-code"></i></a> <pre class="signature" style="margin-right: 54px;">view(string <span class="argument">$view_name</span>, \type <span class="argument">$data = null</span>) </pre> <p><em>Finds and displays the given view, and makes the values in $data available to it.</em></p> <p>The name of the view is passed in without the leading &quot;views/&quot; directory or the trailing &quot;.php&quot; extension. So loading a view with $this-&gt;view(&quot;myview&quot;); would look for a file called &quot;views/myview.php&quot;</p> <p>the data is made available my taking the keys of $data, and assigning them to a locally scoped variable of the same name. array( 'title' =&gt; 'The Title' ) would be available in the view as $title.</p> <h4>Parameters</h4> <table class="table table-condensed table-hover"> <tr> <td>string</td> <td>$view_name </td> <td><p>The name of the view to load</p></td> </tr> <tr> <td>\type</td> <td>$data </td> <td><p>array of values to make available to the view</p></td> </tr> </table> </article> </div> <aside class="span4 detailsbar"> <h1><i class="icon-arrow-down"></i></h1> <dl> </dl> <h2>Tags</h2> <table class="table table-condensed"> <tr><td colspan="2"><em>None found</em></td></tr> </table> </aside> </div> </div> </section> <div id="source-view" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="source-view-label" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="source-view-label">Loader.php</h3> </div> <div class="modal-body"> <pre data-src="../files/Loader.php.txt" class="language-php line-numbers"></pre> </div> </div> <footer class="row-fluid"> <section class="span10 offset2"> <section class="row-fluid"> <section class="span10 offset1"> <section class="row-fluid footer-sections"> <section class="span4"> <h1><i class="icon-code"></i></h1> <div> <ul> </ul> </div> </section> <section class="span4"> <h1><i class="icon-bar-chart"></i></h1> <div> <ul> <li><a href="../graphs/class.html">Class Hierarchy Diagram</a></li> </ul> </div> </section> <section class="span4"> <h1><i class="icon-pushpin"></i></h1> <div> <ul> <li><a href="../reports/errors.html">Errors</a></li> <li><a href="../reports/markers.html">Markers</a></li> </ul> </div> </section> </section> </section> </section> <section class="row-fluid"> <section class="span10 offset1"> <hr /> Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored on October 12th, 2016 at 17:04. </section> </section> </section> </footer> </div> </body> </html>
{'content_hash': '0d993e5597b27d823bef57a38a6c261e', 'timestamp': '', 'source': 'github', 'line_count': 381, 'max_line_length': 810, 'avg_line_length': 52.63517060367454, 'alnum_prop': 0.33833649147302286, 'repo_name': 'box/Anemometer', 'id': '5111e45ede3ef98d2da51b7d2774f0f1b7fab131', 'size': '20061', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'docs/classes/Loader.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1570'}, {'name': 'JavaScript', 'bytes': '365433'}, {'name': 'Makefile', 'bytes': '2153'}, {'name': 'PHP', 'bytes': '208434'}, {'name': 'Puppet', 'bytes': '3451'}, {'name': 'Python', 'bytes': '3892'}, {'name': 'Ruby', 'bytes': '686'}, {'name': 'Shell', 'bytes': '4160'}]}
MaternidadInteractiva_Android ============================= Applicacion de Android que funciona como un servidor transcriptor de SMS a Datos.
{'content_hash': 'eebdc1b55ba810138250a6ebde41300b', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 81, 'avg_line_length': 35.75, 'alnum_prop': 0.6713286713286714, 'repo_name': 'MesoamericaAppsHackatonPanama2013/MaternidadInteractiva_Android', 'id': '45c4dd3256b6610dac1db0190c96320b6480cdff', 'size': '143', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '5038'}]}
package dems.helper; import java.time.LocalDateTime; public class SchedulePoint { public LocalDateTime time; public double schedule; public SchedulePoint(LocalDateTime t, double s){ this.time = t; this.schedule = s; } public String toString(){ return "Time:" + time + " Schedule:" + schedule; } }
{'content_hash': '48e35496fc46dd3e660dc3b74f0a551d', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 50, 'avg_line_length': 15.95, 'alnum_prop': 0.6990595611285266, 'repo_name': 'SES-fortiss/SmartGridCoSimulation', 'id': 'ba8ae10ae60e9ece792dfed448e90a210a7b17e1', 'size': '606', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'projects/previousProjects/strategyNoHierarchy-V0.1/src/main/java/dems/helper/SchedulePoint.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '494'}, {'name': 'C++', 'bytes': '68972'}, {'name': 'CSS', 'bytes': '10495'}, {'name': 'HTML', 'bytes': '27854'}, {'name': 'Java', 'bytes': '23777284'}, {'name': 'JavaScript', 'bytes': '144441'}, {'name': 'Processing', 'bytes': '16761'}, {'name': 'Shell', 'bytes': '1069'}, {'name': 'Solidity', 'bytes': '18269'}]}
package entity import ( "encoding/json" "fmt" "io" "io/ioutil" "log" "os" ) type User struct { UserName string `json:"username"` Password string `json:"password"` Email string `json:"email"` Tel string `json:"telephone"` } var users = map[string]User{} var currentUser User // InitAllUsers initialize all users func InitAllUsers() { allUsers := ReadJson("./json_files/users.json") for _, value := range allUsers { users[value.UserName] = value } guest := NewUser("guest", "guest") users["guest"] = guest current := ReadJson("./json_files/currentUser.json") currentUser = current[0] } func GetCurrentUser() User { return currentUser } func NewUser(username string, password string) User { var user User user.UserName = username user.Password = password user.Email = "" user.Tel = "" return user } // read json file func ReadJson(filePath string) []User { file, err := os.OpenFile(filePath, os.O_RDONLY, 0) if err != nil { log.Fatal(err) } ms := make([]User, 0) decoder := json.NewDecoder(file) for { m := new(User) if err := decoder.Decode(m); err == io.EOF { break } else if err != nil { log.Fatal(err) } ms = append(ms, *m) } file.Close() return ms } //convert string to json format func ToJson(p interface{}) string { bytes, err := json.Marshal(p) if err != nil { fmt.Println(err.Error()) os.Exit(1) } return string(bytes) } //write to json file func WriteJson(contents string, destination string) { file, _ := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0) encoder := json.NewEncoder(file) for _, v := range users { if v.UserName != "" { encoder.Encode(v) } } file.Close() } func usernameIsUnique(registerName string) bool { _, exist := users[registerName] if exist { log.Fatal("this username has been occupied") return false } else { return true } } func Register(username string, password string) bool { if !usernameIsUnique(username) || username == "" || password == "" { return false } else { new_user := NewUser(username, password) users[username] = new_user // fmt.Println(users) WriteJson("", "./json_files/users.json") return true } } func Login(username string, password string) bool { if GetCurrentUser().UserName != "guest" { log.Fatal("you have already logged in, to switch to another account," + "you must log out first") } user, exist := users[username] if exist { if user.Password == password { temp := ToJson(user) ioutil.WriteFile("./json_files/currentUser.json", []byte(temp), 0644) return true } else { return false } } else { return false } } func (user User) SetEmail(email string) bool { if currentUser.UserName == "guest" { fmt.Println("guest have no access to this") return false } else { currentUser.Email = email users[currentUser.UserName] = currentUser WriteJson("", "./json_files/users.json") temp := ToJson(currentUser) ioutil.WriteFile("./json_files/currentUser.json", []byte(temp), 0644) return true } } func (user User) SetTelephone(tel string) bool { if currentUser.UserName == "guest" { fmt.Println("guest have no access to this") return false } else { currentUser.Tel = tel users[currentUser.UserName] = currentUser WriteJson("", "./json_files/users.json") temp := ToJson(currentUser) ioutil.WriteFile("./json_files/currentUser.json", []byte(temp), 0644) return true } } func (user User) Logout() bool { if user.UserName == "guest" { log.Fatal("you haven't logged in!") return false } else { temp := ToJson(users["guest"]) ioutil.WriteFile("./json_files/currentUser.json", []byte(temp), 0644) return true } } func (user User) LookupAllUser() { fmt.Println("there are", len(users), " users:") fmt.Println("--------------------------") if user.UserName == "guest" { log.Fatal("only users loged in have access to this") return } else { for _, user := range users { fmt.Println("user:" + user.UserName) fmt.Println("email:" + user.Email) fmt.Println("tel:" + user.Tel) fmt.Println("--------------------------") } } } func (user User) CancelAccount() bool { if user.UserName != "guest" { for _, m := range AllMeetings.onesMeetings[user.UserName] { user.QuitMeeting(m.Title) } user.ClearAllMeetings() user.Logout() delete(users, user.UserName) WriteJson("", "./json_files/users.json") return true } else { log.Fatal("you can not cancel guest public account") return false } } func (user User) CancelMeeting(title string) { meeting, exist := AllMeetings.onesMeetings[user.UserName][title] // fmt.Println(AllMeetings.onesMeetings[user.UserName]) if exist { // cancel the target meeting delete(AllMeetings.allMeetings, title) delete(AllMeetings.onesMeetings[user.UserName], title) fmt.Println("cancel meeting " + meeting.Title + " called!") } else { log.Fatal("meeting under the given title sponsored by current user doesn't exist") } } // func (user User) QuitMeeting(title string) { // remove user from meeting participators meeting, exist := AllMeetings.onesMeetings[user.UserName][title] if exist { if meeting.Sponsor != user.UserName { RemoveParticipator(title, user.UserName) } } else { log.Fatal("meeting under the given title participated by current user doesn't exist") } fmt.Println("quitMeeting Called") } func (user User) ClearAllMeetings() { for _, m := range AllMeetings.onesMeetings[user.UserName] { if m.Sponsor == user.UserName { delete(AllMeetings.allMeetings, m.Title) delete(AllMeetings.onesMeetings[user.UserName], m.Title) } } } //创建会议 //增删会议 //查询给定时间段的会议
{'content_hash': '87c7191b141096838e159b524115ca1e', 'timestamp': '', 'source': 'github', 'line_count': 243, 'max_line_length': 87, 'avg_line_length': 23.160493827160494, 'alnum_prop': 0.670042643923241, 'repo_name': 'smallGum/CLI-agenda', 'id': '376600bf08f2eba7d29edf6a7dc37acbea51ca0e', 'size': '5664', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'entity/user.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '31669'}]}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCoalesceExpression { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId); protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return SpecializedTasks.EmptyTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(conditionalExpression, (c, g) => { syntaxFacts.GetPartsOfConditionalExpression( c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse); return whenPart == whenTrue ? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue)) : g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse)); }); } return SpecializedTasks.EmptyTask; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Use_coalesce_expression, createChangedDocument) { } } } }
{'content_hash': '7859554b7e60d820e948fa65c5fa059c', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 161, 'avg_line_length': 45.45333333333333, 'alnum_prop': 0.6911117629803462, 'repo_name': 'a-ctor/roslyn', 'id': '6f73ad2c463b75ee28c5f3567e8b198160103385', 'size': '3411', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/Features/Core/Portable/UseCoalesceExpression/UseCoalesceExpressionForNullableCodeFixProvider.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '20688'}, {'name': 'C#', 'bytes': '85699636'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'F#', 'bytes': '3632'}, {'name': 'Groovy', 'bytes': '9673'}, {'name': 'Makefile', 'bytes': '3339'}, {'name': 'PowerShell', 'bytes': '66445'}, {'name': 'Shell', 'bytes': '7465'}, {'name': 'Visual Basic', 'bytes': '63276193'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Sun Jul 28 11:30:14 JST 2013 --> <title>D-Index</title> <meta name="date" content="2013-07-28"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="D-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-3.html">Prev Letter</a></li> <li><a href="index-5.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-4.html" target="_top">Frames</a></li> <li><a href="index-4.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">V</a>&nbsp;<a href="index-20.html">W</a>&nbsp;<a name="_D_"> <!-- --> </a> <h2 class="title">D</h2> <dl> <dt><span class="strong"><a href="../cz/jaybee/intelhex/IntelHexDataListener.html#data(long, byte[])">data(long, byte[])</a></span> - Method in interface cz.jaybee.intelhex.<a href="../cz/jaybee/intelhex/IntelHexDataListener.html" title="interface in cz.jaybee.intelhex">IntelHexDataListener</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../cz/jaybee/intelhex/IntelHexParserRun.html#data(long, byte[])">data(long, byte[])</a></span> - Method in class cz.jaybee.intelhex.<a href="../cz/jaybee/intelhex/IntelHexParserRun.html" title="class in cz.jaybee.intelhex">IntelHexParserRun</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html#DATA_BITS7">DATA_BITS7</a></span> - Static variable in class com.physicaloid.lib.usb.driver.uart.<a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html" title="class in com.physicaloid.lib.usb.driver.uart">UartConfig</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html#DATA_BITS8">DATA_BITS8</a></span> - Static variable in class com.physicaloid.lib.usb.driver.uart.<a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html" title="class in com.physicaloid.lib.usb.driver.uart">UartConfig</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html#dataBits">dataBits</a></span> - Variable in class com.physicaloid.lib.usb.driver.uart.<a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html" title="class in com.physicaloid.lib.usb.driver.uart">UartConfig</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/BuildConfig.html#DEBUG">DEBUG</a></span> - Static variable in class com.physicaloid.<a href="../com/physicaloid/BuildConfig.html" title="class in com.physicaloid">BuildConfig</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/programmer/avr/AvrConf.html#desc">desc</a></span> - Variable in class com.physicaloid.lib.programmer.avr.<a href="../com/physicaloid/lib/programmer/avr/AvrConf.html" title="class in com.physicaloid.lib.programmer.avr">AvrConf</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/usb/UsbAccessor.html#device(int)">device(int)</a></span> - Method in enum com.physicaloid.lib.usb.<a href="../com/physicaloid/lib/usb/UsbAccessor.html" title="enum in com.physicaloid.lib.usb">UsbAccessor</a></dt> <dd> <div class="block">Gets UsbDevice by a hierarchy device number</div> </dd> <dt><span class="strong"><a href="../com/physicaloid/lib/usb/UsbAccessor.html#deviceIsConnected(int)">deviceIsConnected(int)</a></span> - Method in enum com.physicaloid.lib.usb.<a href="../com/physicaloid/lib/usb/UsbAccessor.html" title="enum in com.physicaloid.lib.usb">UsbAccessor</a></dt> <dd> <div class="block">Check whether a device is connected or not</div> </dd> <dt><span class="strong"><a href="../com/physicaloid/lib/programmer/avr/Stk500.html#disable()">disable()</a></span> - Method in class com.physicaloid.lib.programmer.avr.<a href="../com/physicaloid/lib/programmer/avr/Stk500.html" title="class in com.physicaloid.lib.programmer.avr">Stk500</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/programmer/avr/Stk500V2.html#disable()">disable()</a></span> - Method in class com.physicaloid.lib.programmer.avr.<a href="../com/physicaloid/lib/programmer/avr/Stk500V2.html" title="class in com.physicaloid.lib.programmer.avr">Stk500V2</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/programmer/avr/UploadProtocol.html#disable()">disable()</a></span> - Method in class com.physicaloid.lib.programmer.avr.<a href="../com/physicaloid/lib/programmer/avr/UploadProtocol.html" title="class in com.physicaloid.lib.programmer.avr">UploadProtocol</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html#dtrOn">dtrOn</a></span> - Variable in class com.physicaloid.lib.usb.driver.uart.<a href="../com/physicaloid/lib/usb/driver/uart/UartConfig.html" title="class in com.physicaloid.lib.usb.driver.uart">UartConfig</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">V</a>&nbsp;<a href="index-20.html">W</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-3.html">Prev Letter</a></li> <li><a href="index-5.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-4.html" target="_top">Frames</a></li> <li><a href="index-4.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{'content_hash': 'fe0897179dca97a05c84e213edc5ab58', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 735, 'avg_line_length': 60.96621621621622, 'alnum_prop': 0.6702870442203258, 'repo_name': 'guiruiz/Twiteckon', 'id': '6225dc6c664f20862b6cf17df79b410c7487a77f', 'size': '9023', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Android/libs/PhysicaloidLibrary/doc/index-files/index-4.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '1605'}, {'name': 'CSS', 'bytes': '11139'}, {'name': 'Groovy', 'bytes': '385'}, {'name': 'Java', 'bytes': '271432'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '233a1ca6c492958e1a44794ed6e92d31', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'b5267a9775f814fd3e097fc41fb32ec5e911ac51', 'size': '178', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Allium/Allium paniculatum/ Syn. Allium collinum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
define({ labels: { address: 'Endereço', neighborhood: 'Bairro', city: 'Cidade', subregion: 'Subregião', region: 'Região', postalCode: 'Código postal', countryCode: 'Código do país', locatorName: 'Nome do localizador', getAddressHere: 'Obter o endereço daqui' } });
{'content_hash': 'c549bc1288a360f842a2061d99b18834', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 48, 'avg_line_length': 26.46153846153846, 'alnum_prop': 0.5552325581395349, 'repo_name': 'cmv/cmv-app', 'id': '2d2f1e9d4b23bb5fed41774087baf66a98c910f9', 'size': '351', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'viewer/js/gis/dijit/ReverseGeocoder/nls/pt-pt/resource.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '43112'}, {'name': 'HTML', 'bytes': '30816'}, {'name': 'JavaScript', 'bytes': '451055'}]}
#include <aws/external/gtest.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/threading/ReaderWriterLock.h> #include <aws/core/utils/memory/stl/AWSString.h> using namespace Aws::Utils::Threading; TEST(ReaderWriterLock, MultipleReadersMultipleWriters) { Aws::String resource = "It's still Day One"; std::atomic<size_t> resourceLength { resource.length() }; const int ITERATIONS = 100; const int READER_THREADS = 100; const int WRITER_THREADS = 20; Semaphore ev(0, READER_THREADS + WRITER_THREADS); ReaderWriterLock rwlock; { DefaultExecutor exec; auto reader = [&] { ev.WaitOne(); for(int i = 0; i < ITERATIONS; i++) { ReaderLockGuard guard(rwlock); ASSERT_GE(resource.length(), resourceLength); } }; auto writer = [&] { ev.WaitOne(); for(int i = 0; i < ITERATIONS; i++) { WriterLockGuard guard(rwlock); resource += "!"; resourceLength = resource.length(); } }; for(int i = 0; i < WRITER_THREADS; i++) { exec.Submit(writer); } for(int i = 0; i < READER_THREADS; i++) { exec.Submit(reader); } ev.ReleaseAll(); } } TEST(ReaderWriterLock, NoReadersMultipleWriters) { Aws::String resource = "It's still Day One"; const auto originalLength = resource.length(); const int THREADS_NUM = 8; const int ITERATIONS = 100; Semaphore ev(0, 100); ReaderWriterLock rwlock; { DefaultExecutor exec; auto writer = [&] { ev.WaitOne(); for(int i = 0; i < ITERATIONS; i++) { WriterLockGuard guard(rwlock); resource += "!"; } }; for(int i = 0; i < THREADS_NUM; i++) { exec.Submit(writer); } ev.ReleaseAll(); } ASSERT_EQ(originalLength + THREADS_NUM * ITERATIONS, resource.length()); }
{'content_hash': 'eb0f08f03f70555c60fb266441421b52', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 76, 'avg_line_length': 26.11111111111111, 'alnum_prop': 0.5304964539007092, 'repo_name': 'JoyIfBam5/aws-sdk-cpp', 'id': '435a0066aa58551f8766557ac0f8f6a3231ed8b8', 'size': '2686', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-core-tests/utils/threading/ReaderWriterLockTest.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '11868'}, {'name': 'C++', 'bytes': '167818064'}, {'name': 'CMake', 'bytes': '591577'}, {'name': 'HTML', 'bytes': '4471'}, {'name': 'Java', 'bytes': '271801'}, {'name': 'Python', 'bytes': '85650'}, {'name': 'Shell', 'bytes': '5277'}]}
/* 基本测试,req.param 的例子 */ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; var should = require('should'); var request = require('request'); var path = require('path'); var fs = require('fs'); var testconf = require('./testconf.js'); module.exports.rrestjsconfig = { listenPort:3000, tempSet:'ejs', tempFolder :'/static', postLimit:1024*1024*10, connectTimeout:1000, baseDir: path.join(__dirname), }; var options = { key: fs.readFileSync('./key/key.pem'), cert: fs.readFileSync('./key/cert.pem') }; var http = require('http'); var https = require('https'); var rrest = require('../'); var server = https.createServer(options, function (req, res){ if(req.path[0] == 'upload2'){ if(req.param.my_file){ delete req.param.my_file.path; delete req.param.my_file.lastModifiedDate } res.sendjson(req.param) } }).listen(rrest.config.listenPort); //设置全局的模版option https.globalAgent.maxSockets = 10; var fs = require('fs'); var i = 2; var r = 0 var result = function(name){ var num = ++r; console.log('%s test done, receive %d/%d', name, num, i); if(num>=i){ console.log('https req_param.js test done.') process.exit(); } } var png = fs.readFileSync(path.join(__dirname, '/static/octocat.png')); var len = (new Buffer(png)).length; var from = request({ method:'post', uri:'https://'+testconf.hostname+':3000/upload2?number=123&getnumber=123', headers:{ /*"content-length":500*/ } }, function(error,res,body){ should.strictEqual(body, '{"number":"456","getnumber":"123","postnumber":"123","my_file":{"size":9311,"name":"octocat.png","type":"image/png","hash":false,"length":9311,"filename":"octocat.png","mime":"image/png"}}') result('req.param post') }).form() from.append('number','456') from.append('postnumber','123') from.append('my_file', fs.createReadStream(path.join(__dirname, '/static/octocat.png'))); var bodyobj = { user: { name: '123', sex: 'male', age: '11', score: { yuwen: '99', shuxue: '90', yingyu: '100' } }, teacher: { name: 'yy', sex: 'female' }, mypost1: '1', a: { x: '1', y: '2' }, b: [ '1', '2', '3', '4' ], c: '3' } var from = request({ method:'get', uri:'https://'+testconf.hostname+':3000/upload2?mypost1=1&a%5Bx%5D=1&a%5By%5D=2&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3&b%5B%5D=4&c=3&user.name=123&user.sex=male&user.age=11&user.score.yuwen=99&user.score.shuxue=90&user.score.yingyu=100&teacher.name=yy&teacher.sex=female', }, function(error,res,body){ should.strictEqual(body, JSON.stringify(bodyobj)) result('req.param get') });
{'content_hash': '07cedc3019205cdeb438f660bdf74288', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 263, 'avg_line_length': 23.971698113207548, 'alnum_prop': 0.6430539157811885, 'repo_name': 'cj1240/crm', 'id': '27c7db0377f93ec24cfbfaffadc4b4fd92791b77', 'size': '2571', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'node_modules/rrestjs/test/https_req_param.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '36027'}, {'name': 'JavaScript', 'bytes': '545624'}]}
if not ARGV.length.between?(1, 4) then puts "Usage: #{$0} <trials> [die1_sides] [die2_sides]" exit 1 end # Grab arguments. ('to_i' means "convert to integer") num_trials = (ARGV[0]).to_i # no default die1_sides = (ARGV[1] || 6).to_i # default = 6 die2_sides = (ARGV[2] || 6).to_i # default = 6 # Create a new array full of zeros. results = Array.new(die1_sides + die2_sides - 1) { 0 } # Function to draw a progress bar. def progress_bar(complete, total) @old_perc ||= -1 perc = (100*complete/total).round # only update when we get a new percent return if perc == @old_perc @old_perc = perc print "\r#{perc}% #{"#"*(perc/2)}" $stdout.flush end # Run the trials and collect the data. num_trials.times do |i| die1 = rand(die1_sides) die2 = rand(die2_sides) results[die1+die2] += 1 progress_bar(i+1, num_trials) end puts "" # Print out the data to the console and the CSV file. File.open("data.csv", "w") do |f| f.write("value,occurrences\n") results.each_with_index do |occurrences, value| printf("%2d: %2d\n", value+2, occurrences) f.write("#{value+2},#{occurrences}\n"); end end # Graph the data and delete the CSV file. puts "Graphing results..." `Rscript ./plot.r` File.delete("data.csv")
{'content_hash': '7f07445e73e9efd285a64e976df5775a', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 58, 'avg_line_length': 25.7, 'alnum_prop': 0.6249027237354086, 'repo_name': 'kdomen/DiceSimulator', 'id': '465da5f66a114468f86c19e0073aa9e30d4dc123', 'size': '1353', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'diceSimulator.rb', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2677'}, {'name': 'Python', 'bytes': '1035'}, {'name': 'R', 'bytes': '506'}, {'name': 'Ruby', 'bytes': '2349'}, {'name': 'Shell', 'bytes': '1012'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:33 PST 2014 --> <title>Uses of Class java.lang.InstantiationException (Java Platform SE 7 )</title> <meta name="date" content="2014-12-18"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class java.lang.InstantiationException (Java Platform SE 7 )"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/lang/InstantiationException.html" title="class in java.lang">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/lang/class-use/InstantiationException.html" target="_top">Frames</a></li> <li><a href="InstantiationException.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class java.lang.InstantiationException" class="title">Uses of Class<br>java.lang.InstantiationException</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#java.lang">java.lang</a></td> <td class="colLast"> <div class="block">Provides classes that are fundamental to the design of the Java programming language.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#java.lang.reflect">java.lang.reflect</a></td> <td class="colLast"> <div class="block">Provides classes and interfaces for obtaining reflective information about classes and objects.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#java.util">java.util</a></td> <td class="colLast"> <div class="block">Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#javax.swing">javax.swing</a></td> <td class="colLast"> <div class="block">Provides a set of &quot;lightweight&quot; (all-Java language) components that, to the maximum degree possible, work the same on all platforms.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.w3c.dom.bootstrap">org.w3c.dom.bootstrap</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.xml.sax.helpers">org.xml.sax.helpers</a></td> <td class="colLast"> <div class="block">This package contains "helper" classes, including support for bootstrapping SAX-based applications.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="java.lang"> <!-- --> </a> <h3>Uses of <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a> in <a href="../../../java/lang/package-summary.html">java.lang</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/lang/package-summary.html">java.lang</a> that throw <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../java/lang/Class.html" title="type parameter in Class">T</a></code></td> <td class="colLast"><span class="strong">Class.</span><code><strong><a href="../../../java/lang/Class.html#newInstance()">newInstance</a></strong>()</code> <div class="block">Creates a new instance of the class represented by this <code>Class</code> object.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="java.lang.reflect"> <!-- --> </a> <h3>Uses of <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a> in <a href="../../../java/lang/reflect/package-summary.html">java.lang.reflect</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/lang/reflect/package-summary.html">java.lang.reflect</a> that throw <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../java/lang/reflect/Constructor.html" title="type parameter in Constructor">T</a></code></td> <td class="colLast"><span class="strong">Constructor.</span><code><strong><a href="../../../java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)">newInstance</a></strong>(<a href="../../../java/lang/Object.html" title="class in java.lang">Object</a>...&nbsp;initargs)</code> <div class="block">Uses the constructor represented by this <code>Constructor</code> object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="java.util"> <!-- --> </a> <h3>Uses of <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a> in <a href="../../../java/util/package-summary.html">java.util</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/util/package-summary.html">java.util</a> that throw <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../java/util/ResourceBundle.html" title="class in java.util">ResourceBundle</a></code></td> <td class="colLast"><span class="strong">ResourceBundle.Control.</span><code><strong><a href="../../../java/util/ResourceBundle.Control.html#newBundle(java.lang.String,%20java.util.Locale,%20java.lang.String,%20java.lang.ClassLoader,%20boolean)">newBundle</a></strong>(<a href="../../../java/lang/String.html" title="class in java.lang">String</a>&nbsp;baseName, <a href="../../../java/util/Locale.html" title="class in java.util">Locale</a>&nbsp;locale, <a href="../../../java/lang/String.html" title="class in java.lang">String</a>&nbsp;format, <a href="../../../java/lang/ClassLoader.html" title="class in java.lang">ClassLoader</a>&nbsp;loader, boolean&nbsp;reload)</code> <div class="block">Instantiates a resource bundle for the given bundle name of the given format and locale, using the given class loader if necessary.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="javax.swing"> <!-- --> </a> <h3>Uses of <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a> in <a href="../../../javax/swing/package-summary.html">javax.swing</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../javax/swing/package-summary.html">javax.swing</a> that throw <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><span class="strong">UIManager.</span><code><strong><a href="../../../javax/swing/UIManager.html#setLookAndFeel(java.lang.String)">setLookAndFeel</a></strong>(<a href="../../../java/lang/String.html" title="class in java.lang">String</a>&nbsp;className)</code> <div class="block">Loads the <code>LookAndFeel</code> specified by the given class name, using the current thread's context class loader, and passes it to <code>setLookAndFeel(LookAndFeel)</code>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.w3c.dom.bootstrap"> <!-- --> </a> <h3>Uses of <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a> in <a href="../../../org/w3c/dom/bootstrap/package-summary.html">org.w3c.dom.bootstrap</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../org/w3c/dom/bootstrap/package-summary.html">org.w3c.dom.bootstrap</a> that throw <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../org/w3c/dom/bootstrap/DOMImplementationRegistry.html" title="class in org.w3c.dom.bootstrap">DOMImplementationRegistry</a></code></td> <td class="colLast"><span class="strong">DOMImplementationRegistry.</span><code><strong><a href="../../../org/w3c/dom/bootstrap/DOMImplementationRegistry.html#newInstance()">newInstance</a></strong>()</code> <div class="block">Obtain a new instance of a <code>DOMImplementationRegistry</code>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.xml.sax.helpers"> <!-- --> </a> <h3>Uses of <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a> in <a href="../../../org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a> that throw <a href="../../../java/lang/InstantiationException.html" title="class in java.lang">InstantiationException</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../org/xml/sax/Parser.html" title="interface in org.xml.sax">Parser</a></code></td> <td class="colLast"><span class="strong">ParserFactory.</span><code><strong><a href="../../../org/xml/sax/helpers/ParserFactory.html#makeParser()">makeParser</a></strong>()</code> <div class="block"><strong>Deprecated.</strong>&nbsp;</div> <div class="block">Create a new SAX parser using the `org.xml.sax.parser' system property.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../org/xml/sax/Parser.html" title="interface in org.xml.sax">Parser</a></code></td> <td class="colLast"><span class="strong">ParserFactory.</span><code><strong><a href="../../../org/xml/sax/helpers/ParserFactory.html#makeParser(java.lang.String)">makeParser</a></strong>(<a href="../../../java/lang/String.html" title="class in java.lang">String</a>&nbsp;className)</code> <div class="block"><strong>Deprecated.</strong>&nbsp;</div> <div class="block">Create a new SAX parser object using the class name provided.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/lang/InstantiationException.html" title="class in java.lang">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/lang/class-use/InstantiationException.html" target="_top">Frames</a></li> <li><a href="InstantiationException.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
{'content_hash': '4315fc3377493c0b1840ba9653af2e24', 'timestamp': '', 'source': 'github', 'line_count': 316, 'max_line_length': 596, 'avg_line_length': 51.037974683544306, 'alnum_prop': 0.6799975198412699, 'repo_name': 'fbiville/annotation-processing-ftw', 'id': 'bddf556a01f346053ac75a653a848f57d27d74d2', 'size': '16128', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/java/jdk7/java/lang/class-use/InstantiationException.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '191178'}, {'name': 'HTML', 'bytes': '63904'}, {'name': 'Java', 'bytes': '107042'}, {'name': 'JavaScript', 'bytes': '246677'}]}
<template name="adminDefaultWidgets"> {{#each admin_collections}} {{#unless $eq showWidget false}} {{> adminCollectionWidget collection=name}} {{/unless}} {{/each}} </template> <template name="adminCollectionWidget"> <div class="{{#if class}}{{class}}{{else}}col-lg-3 col-xs-6{{/if}}"> {{#with adminGetCollection collection}} <a href="/admin/{{this.name}}"> <div class="small-box bg-{{color}}"> <div class="inner"> <h3> {{adminCollectionCount name}} </h3> <p> {{this.label}} </p> </div> <div class="icon"> <i class="fa fa-{{this.icon}}"></i> </div> <a class="small-box-footer"> 查看 <i class="fa fa-arrow-circle-right"></i> </a> </div> </a> {{/with}} </div> </template>
{'content_hash': '950a6f1c4c0acdb0f6974a9a53d20546', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 69, 'avg_line_length': 23.6875, 'alnum_prop': 0.5659630606860159, 'repo_name': 'andadeng/workstation', 'id': 'c55757db88b451e4fec2fb9007a09ea4fd87b5da', 'size': '762', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/kcms/lib/client/html/admin_widgets.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1044'}, {'name': 'CoffeeScript', 'bytes': '27420'}, {'name': 'HTML', 'bytes': '16503'}, {'name': 'JavaScript', 'bytes': '46716'}]}
/*! \file registermetatype.h * * A metatype registration file to solve an issues with old Qt code */ #pragma once #include "isqobject.h" #include <QMetaType> #include <QString> namespace dukpp03 { namespace qt { /*! Checks, whether following meta type is pointer to qobject \param[in] name a type name \return true or false */ bool is_metatype_qobject(const QString& name); /*! Registers qobject as descendant of current type \param[in] name a type name */ void register_qobject_descendant(const QString& name); /*! Register meta type for specified type. This is common part, which just registers meta type */ template<bool IsQObject, typename T> struct RegisterMetaType { public: /*! Performs actual type registration */ inline static void perform() { qRegisterMetaType<T>(); qRegisterMetaType<T*>(); } }; /*! Register meta type for specified type. This is part for QObjects */ template<typename T> struct RegisterMetaType<true, T> { public: /*! Performs actual type registration */ inline static void perform() { qRegisterMetaType<T*>(); const int type = qMetaTypeId<T*>(); #if ( QT_VERSION >= 0x060000 ) register_qobject_descendant(QMetaType(type).name()); #else register_qobject_descendant(QMetaType::typeName(type)); #endif } }; /*! Registers common data, needed for meta type */ template<typename T> void registerMetaType() { RegisterMetaType<static_cast<bool>(dukpp03::qt::IsQObject<T>::Value::Result), T>::perform(); } } }
{'content_hash': 'b4157d25211c2c490f944a0623c85523', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 96, 'avg_line_length': 20.88, 'alnum_prop': 0.6781609195402298, 'repo_name': 'mamontov-cpp/dukpp-03', 'id': '9691f15fd116905ca1f53048b87b7b0b66924edc', 'size': '1566', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugins/qt/registermetatype.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '440'}, {'name': 'C', 'bytes': '15057306'}, {'name': 'C++', 'bytes': '1528863'}, {'name': 'CMake', 'bytes': '3183'}, {'name': 'CSS', 'bytes': '8851'}, {'name': 'CoffeeScript', 'bytes': '1029'}, {'name': 'HTML', 'bytes': '3949'}, {'name': 'JavaScript', 'bytes': '209128'}, {'name': 'Makefile', 'bytes': '33817'}, {'name': 'Python', 'bytes': '330461'}, {'name': 'QMake', 'bytes': '2791'}, {'name': 'Raku', 'bytes': '68643'}, {'name': 'Ruby', 'bytes': '1445'}, {'name': 'Shell', 'bytes': '231'}]}
describe "Quickbooks::Service::Report" do before(:all) do construct_service :reports end describe '.url_for_query()' do it 'uses "BalanceSheet" and "This Fiscal Year to date" as the default parameters' do expect(@service.url_for_query()).to eq('https://quickbooks.api.intuit.com/v3/company/9991111222/reports/BalanceSheet?date_macro=This+Fiscal+Year-to-date') end it 'allows overriding the report type' do expect(@service.url_for_query('ProfitAndLoss')).to eq('https://quickbooks.api.intuit.com/v3/company/9991111222/reports/ProfitAndLoss?date_macro=This+Fiscal+Year-to-date') end it 'allows overriding the date_macro' do expect(@service.url_for_query('BalanceSheet', 'Last Year')).to eq('https://quickbooks.api.intuit.com/v3/company/9991111222/reports/BalanceSheet?date_macro=Last+Year') end it 'allows passing additional query parameters' do url = @service.url_for_query('BalanceSheet', 'Last Year', :start_date => '2015-01-01', :end_date => '2015-01-31', :accounting_method => 'Cash', :columns => 'subt_nat_amount,tax_amount', ) expect(url).to eq('https://quickbooks.api.intuit.com/v3/company/9991111222/reports/BalanceSheet?start_date=2015-01-01&end_date=2015-01-31&accounting_method=Cash&columns=subt_nat_amount,tax_amount') end it 'currently ignores the date_macro argument when passed in additional options' do expect(@service.url_for_query('BalanceSheet', 'Today', :accounting_method => 'Cash')).to eq('https://quickbooks.api.intuit.com/v3/company/9991111222/reports/BalanceSheet?accounting_method=Cash') end end it 'forwards arguments to .url_for_query' do xml = fixture("balancesheet.xml") url = @service.url_for_query('BalanceSheet', 'Today', :accounting_method => 'Cash') stub_http_request(:get, url, ["200", "OK"], xml) @service.query('BalanceSheet', 'Today', :accounting_method => 'Cash') end it "returns a Report model" do xml = fixture("balancesheet.xml") stub_http_request(:get, @service.url_for_query, ["200", "OK"], xml) report = @service.query('BalanceSheet') expect(report).to be_a Quickbooks::Model::Report end end
{'content_hash': '8d16f438540b8450eb9c7f4896150de1', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 203, 'avg_line_length': 43.411764705882355, 'alnum_prop': 0.6924119241192412, 'repo_name': 'ruckus/quickbooks-ruby', 'id': '788aedab31fb494e7bee003b866ff73f9d98401a', 'size': '2214', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/lib/quickbooks/service/reports_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1498'}, {'name': 'Ruby', 'bytes': '409584'}, {'name': 'Shell', 'bytes': '81'}]}
function HFlowLayout() { this.base = new BaseObj(this); this.tpos = new Rect(0, 0, 0, 0); var children = []; this.clear = function () { children = []; this.base.removeAllChildren(); } this.add = function (ui) { children.push(ui); this.base.addChild(ui); } this.insert = function (index, ui) { children.splice(index, 0, ui); this.base.addChild(ui); } this.resize = function (rect) { var height = rect.h; var widths = []; var totalWidth = 0; for (var i = 0; i < children.length; i++) { var child = children[i]; var width = child.optimalWidth(height); totalWidth += width; widths.push(width); } // Make sure we can fit. if (totalWidth > rect.w) { for (var i = 0; i < widths.length; i++) { widths[i] *= rect.w / totalWidth; widths[i] = Math.max(Math.round(widths[i]), 1); } } var curX = rect.x; for (var i = 0; i < children.length; i++) { var width = widths[i]; var childRect = new Rect(curX, rect.y, width, height); children[i].resize(childRect); curX += width; } } this.optimalWidth = function (height) { var totalWidth = 0; for (var i = 0; i < children.length; i++) { totalWidth += children[i].optimalWidth(height); } return totalWidth; } }
{'content_hash': '44316e613e235f2c289b0cd8701554a3', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 66, 'avg_line_length': 26.87719298245614, 'alnum_prop': 0.48825065274151436, 'repo_name': 'yeerkkiller1/quentinbrooks', 'id': '72ab4c6c4fa600c859c78af4c6fb2ce5e4a76662', 'size': '1850', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'site/site/html/gitdefence/game/ui/hFlowLayout.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9639'}, {'name': 'Go', 'bytes': '1153'}, {'name': 'JavaScript', 'bytes': '783452'}, {'name': 'PHP', 'bytes': '1267'}, {'name': 'Python', 'bytes': '186'}, {'name': 'Shell', 'bytes': '4731'}, {'name': 'TypeScript', 'bytes': '13588'}]}
package org.apache.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.util.NumberHelper; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement; import org.apache.tinkerpop.gremlin.process.traversal.util.FastNoSuchElementException; import java.util.Collections; import java.util.Iterator; import java.util.Set; /** * @author Marko A. Rodriguez (http://markorodriguez.com) * @author Daniel Kuppitz (http://gremlin.guru) */ public final class MeanLocalStep<E extends Number, S extends Iterable<E>> extends ScalarMapStep<S, Number> { public MeanLocalStep(final Traversal.Admin traversal) { super(traversal); } @Override protected Number map(final Traverser.Admin<S> traverser) { final Iterator<E> iterator = traverser.get().iterator(); if (iterator.hasNext()) { // forward the iterator to the first non-null or return null E result = untilNonNull(iterator); Long counter = 1L; while (iterator.hasNext()) { final Number n = iterator.next(); if (n != null) { result = (E) NumberHelper.add(result, n); counter++; } } return NumberHelper.div(result, counter, true); } throw FastNoSuchElementException.instance(); } private E untilNonNull(final Iterator<E> itty) { E result = null; while (itty.hasNext() && null == result) { result = itty.next(); } return result; } @Override public Set<TraverserRequirement> getRequirements() { return Collections.singleton(TraverserRequirement.OBJECT); } }
{'content_hash': 'b88ab4c00d582c972e33720bfa86043f', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 108, 'avg_line_length': 34.14545454545455, 'alnum_prop': 0.6522896698615549, 'repo_name': 'apache/tinkerpop', 'id': '2ed1440ad25fbfcea2c7dc82b5133255b99a989c', 'size': '2683', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MeanLocalStep.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '59230'}, {'name': 'Awk', 'bytes': '2335'}, {'name': 'Batchfile', 'bytes': '3976'}, {'name': 'C#', 'bytes': '1745461'}, {'name': 'Dockerfile', 'bytes': '8353'}, {'name': 'Gherkin', 'bytes': '606034'}, {'name': 'Go', 'bytes': '776105'}, {'name': 'Groovy', 'bytes': '337658'}, {'name': 'Java', 'bytes': '11495240'}, {'name': 'JavaScript', 'bytes': '596328'}, {'name': 'Python', 'bytes': '685711'}, {'name': 'Shell', 'bytes': '71980'}, {'name': 'TypeScript', 'bytes': '154521'}, {'name': 'XSLT', 'bytes': '2205'}]}
<?php $example = 'A'; require_once('sqoolExample_sqoolClasses.php'); $page = 'allComments'; include('sqoolExample_htmlTemplate.php');
{'content_hash': '91fa54cbd9239a0c9cf1ed435066f66c', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 46, 'avg_line_length': 22.333333333333332, 'alnum_prop': 0.7313432835820896, 'repo_name': 'fresheneesz/Sqool', 'id': 'f4d753085c90bd34e35bdbaa3439e955de6d5228', 'size': '134', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Sqool-0.8/SqoolExample/SqoolExample A.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4312'}, {'name': 'JavaScript', 'bytes': '22678'}, {'name': 'PHP', 'bytes': '1208181'}]}
class ClientAppRender : public ClientApp , public CefRenderProcessHandler { public: // CefApp methods: virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() OVERRIDE{ return this; } //CefRenderProcessHandler methods virtual void OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) OVERRIDE; private: // Include the default reference counting implementation. IMPLEMENT_REFCOUNTING(ClientAppRender); };
{'content_hash': '873b8b118b752f3b77abf27cfa80a3b5', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 131, 'avg_line_length': 30.25, 'alnum_prop': 0.8140495867768595, 'repo_name': 'huminhuang/DuiCEF', 'id': '5c13e0eb2a6d89f4ee08a06d9ede685cb5cd4700', 'size': '533', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'demo/base/Cef3/renderer/client_renderer_app.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '158'}, {'name': 'C', 'bytes': '598407'}, {'name': 'C++', 'bytes': '1094739'}]}
package com.jeroenreijn.examples.view; import liqp.filters.Filter; import org.springframework.context.MessageSource; import org.springframework.web.servlet.view.AbstractTemplateViewResolver; import java.util.Locale; public class LiqpViewResolver extends AbstractTemplateViewResolver { public LiqpViewResolver(MessageSource messageSource) { this.setViewClass(this.requiredViewClass()); Filter.registerFilter(new Filter("i18n") { @Override public Object apply(Object value, Object... params) { return messageSource.getMessage(value.toString(), null, Locale.ENGLISH); } }); } @Override protected Class<?> requiredViewClass() { return LiqpView.class; } }
{'content_hash': '74feba092c4ab2eb2fcc9c80005ad444', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 76, 'avg_line_length': 27.28, 'alnum_prop': 0.7785923753665689, 'repo_name': 'jreijn/spring-comparing-template-engines', 'id': '02b4a51205e075ce855e86c02bbae0c6c6761e88', 'size': '682', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/jeroenreijn/examples/view/LiqpViewResolver.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '1349'}, {'name': 'HTML', 'bytes': '3943'}, {'name': 'Handlebars', 'bytes': '2230'}, {'name': 'Java', 'bytes': '49340'}, {'name': 'JavaScript', 'bytes': '10076'}, {'name': 'Kotlin', 'bytes': '2535'}, {'name': 'Mustache', 'bytes': '1091'}, {'name': 'Pug', 'bytes': '930'}, {'name': 'Scaml', 'bytes': '1198'}, {'name': 'Shell', 'bytes': '311'}, {'name': 'Smarty', 'bytes': '1082'}]}
- java - boot (brew install boot-clj) ### Create css and css/styles.css ### Create new login.cljs ``` src/cljs/modern_cljs/login.cljs ``` ### Add require login.cljs to main.cljs.edn ``` {:require [modern-cljs.core modern-cljs.login] :compiler-options {:asset-path "js/main.out"}} ```
{'content_hash': '20cca47c7e5f597b1679d4ea74382b5a', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 47, 'avg_line_length': 19.2, 'alnum_prop': 0.6770833333333334, 'repo_name': 'hawkup/learn-web-programming', 'id': 'cc5cf67688cb12dfee79370e082f36230ce5b2ca', 'size': '336', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '08-clojurescript-login-form/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '29'}, {'name': 'Clojure', 'bytes': '6237'}, {'name': 'Elm', 'bytes': '5786'}, {'name': 'HTML', 'bytes': '3303'}, {'name': 'Java', 'bytes': '20297'}, {'name': 'JavaScript', 'bytes': '575'}, {'name': 'Python', 'bytes': '3723'}, {'name': 'Thrift', 'bytes': '42'}]}
package com.opentable.jvm; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Wrapper for Native Memory Tracking information. * @see Memory#getNmt() */ public class Nmt { private static final Logger LOG = LoggerFactory.getLogger(Nmt.class); private static final String NMT_DISABLED = "Native memory tracking is not enabled\n"; /** * We warn only once to avoid cluttering the logs. E.g., consider the use case when otj-metrics repeatedly * tries to get NMT stats, but it's disabled. */ private static boolean NMT_DISABLED_DID_WARN = false; /** * Data comes back in "KB", as formatted by the HotSpot VM. * However, a read of the source code (specifically share/vm/utilities/globalDefinitions.hpp) * reveals that they actually mean KiB. */ @VisibleForTesting static final long K = 1024; public final Usage total; /** * Keys are human-readable category names, such as "Java Heap" or "Arena Chunk". * Categories' usages are not guaranteed to sum to total usage. * Entries will be in the same order as the diagnostic command output. */ public final Map<String, Usage> categories; private Nmt(final Usage total, final Map<String, Usage> categories) { this.total = total; this.categories = categories; } /** * Requires JVM argument {@code -XX:NativeMemoryTracking=summary}. * Logs a warning if there was an error getting the NMT summary or if NMT was disabled. * This warning will be logged only once per process instance. * Available here in case you want easy access to the raw output from the VM (instead of our nice parse). * Like {@code jcmd VM.native_memory summary}. * @return JVM-formatted human-readable NMT summary. null if there was an error getting the summary. */ @Nullable public static String invoke() { final String ret = Dcmd.invoke("vmNativeMemory", "summary"); if (NMT_DISABLED.equals(ret)) { if (!NMT_DISABLED_DID_WARN) { LOG.warn(ret.trim()); NMT_DISABLED_DID_WARN = true; } return null; } return ret; } /** * Produces simpler and more concise human-readable summary of NMT than the native human-readable output from the * JVM. * @return Human-readable NMT summary. */ @Override public String toString() { return new Formatter().toString(); } /** * Requires JVM argument {@code -XX:NativeMemoryTracking=summary}. * Logs a warning if there was an error getting the NMT summary or if NMT was disabled. * This warning will be logged only once per process instance. * @return null if there was an error getting the summary. */ @Nullable static Nmt get() { final String nmt = invoke(); if (nmt == null) { return null; } try { return parse(nmt); } catch (IllegalArgumentException e) { LOG.warn("un-parseable NMT data:\n{}", nmt, e); return null; } } /** * @param s String to parse. * @return Filled-out {@link Usage} instance. * @throws IllegalArgumentException with human-readable error if string couldn't be parsed. */ @VisibleForTesting static Usage parseUsage(final String s) { final String reservedLabel = "reserved="; final String firstKB = "KB, "; int i; int j; i = s.indexOf(reservedLabel); if (i == -1) { throw new IllegalArgumentException("could not find reserved label"); } j = s.indexOf(firstKB, i); if (j == -1) { throw new IllegalArgumentException("could not find KB after reserved label"); } final String reservedStr = s.substring(i + reservedLabel.length(), j); final long reserved; try { reserved = Long.parseLong(reservedStr) * K; } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("could not parse reserved %s", reservedStr), e); } final String committedLabel = "committed="; i = s.indexOf(committedLabel, j + firstKB.length()); if (i == -1) { throw new IllegalArgumentException("could not find committed label"); } j = s.indexOf("KB", i); final String committedStr = s.substring(i + committedLabel.length(), j); final long committed; try { committed = Long.parseLong(committedStr) * K; } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("could not parse committed %s", committedStr), e); } return new Usage(reserved, committed); } /** * @param nmt {@link #invoke()} Diagnostic command} output to parse. * @return Filled-out {@link Nmt} instance. * @throws IllegalArgumentException with human-readable error if string couldn't be parsed. */ @VisibleForTesting static Nmt parse(@Nonnull final String nmt) { final String prefixTotal = "Total: "; final String prefixDash = "-"; final String prefixParen = " ("; final List<String> lines = Arrays.asList(nmt.split("\n")); if (lines.size() < 5) { throw new IllegalArgumentException(String.format("insufficient lines to parse: %s", lines)); } final Iterator<String> itr = lines.iterator(); final String totalStr; itr.next(); // First line expected to be empty. itr.next(); // Second line expected to be "Native Memory Tracking:". itr.next(); // Third line expected to be empty. totalStr = itr.next(); if (!totalStr.startsWith(prefixTotal)) { throw new IllegalArgumentException("first line is not total"); } final Usage total; try { total = parseUsage(totalStr.substring(prefixTotal.length())); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("could not parse total", e); } final Map<String, Usage> categories = new LinkedHashMap<>(); int line = 1; while (itr.hasNext()) { String s = itr.next(); ++line; if (!s.startsWith(prefixDash)) { continue; } s = s.substring(prefixDash.length()).trim(); final int i = s.indexOf(prefixParen); if (i == -1) { throw new IllegalArgumentException(String.format("missing opening paren on line %d", line)); } final String category = s.substring(0, i); final Usage usage; try { usage = parseUsage(s.substring(i + prefixParen.length())); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("could not parse usage on line %d", line), e); } categories.put(category, usage); } if (categories.isEmpty()) { throw new IllegalArgumentException("no categories parsed"); } return new Nmt(total, categories); } /** * Fields are in bytes. */ public static class Usage { public final long reserved; public final long committed; public Usage(final long reserved, final long committed) { this.reserved = reserved; this.committed = committed; } } private class Formatter { @Override public String toString() { final int rows = categories.size() + 2; final List<String> col1 = new ArrayList<>(rows); col1.add("Name"); col1.add("Total"); col1.addAll(categories.keySet()); final int colWidth1 = maxLength(col1); final List<String> col2 = new ArrayList<>(rows); col2.add("Reserved"); col2.add(Memory.formatBytes(total.reserved)); categories.keySet().forEach(name -> col2.add(Memory.formatBytes(categories.get(name).reserved))); final int colWidth2 = maxLength(col2); final List<String> col3 = new ArrayList<>(rows); col3.add("Committed"); col3.add(Memory.formatBytes(total.committed)); categories.keySet().forEach(name -> col3.add(Memory.formatBytes(categories.get(name).committed))); final int colWidth3 = maxLength(col3); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < rows; i++) { sb.append(pad(col1, colWidth1, i)).append(" "); sb.append(pad(col2, colWidth2, i)).append(" "); sb.append(pad(col3, colWidth3, i)).append('\n'); } return sb.toString(); } private int maxLength(final List<String> list) { return list.stream().mapToInt(String::length).max().getAsInt(); } private String pad(final List<String> list, final int width, final int index) { return String.format("%1$" + width + "s", list.get(index)); } } }
{'content_hash': 'ec0010b55760c0adce3d22dede5b31d7', 'timestamp': '', 'source': 'github', 'line_count': 259, 'max_line_length': 117, 'avg_line_length': 36.7992277992278, 'alnum_prop': 0.5993075228202707, 'repo_name': 'opentable/otj-jvm', 'id': '420f17aee10dfe9a50e88d57814082ad9e87d807', 'size': '10656', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/opentable/jvm/Nmt.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '36945'}]}
[![Build Status](https://travis-ci.org/google/jsonnet.svg?branch=master)](https://travis-ci.org/google/jsonnet) Website: http://google.github.io/jsonnet/doc/ Discussion Forum: https://groups.google.com/forum/#!forum/jsonnet
{'content_hash': '4d552b258df1a8bfd6846699860c8b28', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 111, 'avg_line_length': 45.2, 'alnum_prop': 0.7566371681415929, 'repo_name': 'darioajr/jsonnet', 'id': 'd73c36eb77478767e96a3424817acd0883adbf02', 'size': '268', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '17078'}, {'name': 'C++', 'bytes': '245226'}, {'name': 'CSS', 'bytes': '4684'}, {'name': 'HTML', 'bytes': '15929'}, {'name': 'Makefile', 'bytes': '5092'}, {'name': 'Python', 'bytes': '63323'}, {'name': 'Shell', 'bytes': '4628'}, {'name': 'VimL', 'bytes': '2567'}]}
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- This is a sample netbeans project file for a Sun Spot Application project. You may edit it freely, it doesn't affect the ant-powered build. --><project xmlns="http://www.netbeans.org/ns/project/1"> <type>org.netbeans.modules.ant.freeform</type> <configuration> <general-data xmlns="http://www.netbeans.org/ns/freeform-project/1"> <name>FRC_2014_Code</name> <properties> <property-file>${user.home}/.sunspotfrc.properties</property-file> <property-file>build.properties</property-file> <property-file>${sunspot.home}/default.properties</property-file> </properties> <folders> <source-folder> <label>src</label> <type>java</type> <location>src</location> </source-folder> </folders> <ide-actions> <action name="build"> <target>jar-app</target> </action> <action name="clean"> <target>clean</target> </action> <action name="run"> <target>deploy</target> <target>run</target> </action> <action name="rebuild"> <target>clean</target> <target>jar-app</target> </action> <action name="debug"> <target>deploy</target> <target>debug-run</target> </action> <action name="javadoc"> <target>javadoc</target> </action> </ide-actions> <export> <type>folder</type> <location>build</location> <build-target>jar-app</build-target> </export> <view> <items> <source-folder style="packages"> <label>src</label> <location>src</location> </source-folder> <source-file> <location>build.xml</location> </source-file> </items> <context-menu> <ide-action name="build"/> <ide-action name="clean"/> <ide-action name="run"/> <ide-action name="rebuild"/> <ide-action name="debug"/> <ide-action name="javadoc"/> <action> <label>Sun SPOT-deploy</label> <target>deploy</target> </action> <action> <label>Sun SPOT-jar-deploy</label> <target>jar-deploy</target> </action> <separator/> </context-menu> </view> <subprojects/> </general-data> <java-data xmlns="http://www.netbeans.org/ns/freeform-project-java/1"> <compilation-unit> <package-root>src</package-root> <classpath mode="boot">${sunspot.home}\lib\squawk.jar</classpath> <classpath mode="compile">${sunspot.home}\lib\wpilibj.jar;${sunspot.home}\lib\networktables-crio.jar</classpath> <built-to>build</built-to> <source-level>1.4</source-level> </compilation-unit> </java-data> </configuration> </project>
{'content_hash': 'eeb6ce641506af138f641132350071a2', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 128, 'avg_line_length': 40.03260869565217, 'alnum_prop': 0.44990496877545477, 'repo_name': 'chayuso/FRC_2014_Code', 'id': '8382bfa30dbffb6523cbe5f8ef0d69481607254e', 'size': '3683', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'nbproject/project.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '44895'}]}
from cinderclient.tests import utils from cinderclient.tests.v2 import fakes from cinderclient.v2 import services cs = fakes.FakeClient() class ServicesTest(utils.TestCase): def test_list_services(self): svs = cs.services.list() cs.assert_called('GET', '/os-services') self.assertEqual(len(svs), 3) [self.assertTrue(isinstance(s, services.Service)) for s in svs] def test_list_services_with_hostname(self): svs = cs.services.list(host='host2') cs.assert_called('GET', '/os-services?host=host2') self.assertEqual(len(svs), 2) [self.assertTrue(isinstance(s, services.Service)) for s in svs] [self.assertEqual(s.host, 'host2') for s in svs] def test_list_services_with_binary(self): svs = cs.services.list(binary='cinder-volume') cs.assert_called('GET', '/os-services?binary=cinder-volume') self.assertEqual(len(svs), 2) [self.assertTrue(isinstance(s, services.Service)) for s in svs] [self.assertEqual(s.binary, 'cinder-volume') for s in svs] def test_list_services_with_host_binary(self): svs = cs.services.list('host2', 'cinder-volume') cs.assert_called('GET', '/os-services?host=host2&binary=cinder-volume') self.assertEqual(len(svs), 1) [self.assertTrue(isinstance(s, services.Service)) for s in svs] [self.assertEqual(s.host, 'host2') for s in svs] [self.assertEqual(s.binary, 'cinder-volume') for s in svs] def test_services_enable(self): cs.services.enable('host1', 'cinder-volume') values = {"host": "host1", 'binary': 'cinder-volume'} cs.assert_called('PUT', '/os-services/enable', values) def test_services_disable(self): cs.services.disable('host1', 'cinder-volume') values = {"host": "host1", 'binary': 'cinder-volume'} cs.assert_called('PUT', '/os-services/disable', values)
{'content_hash': '3737b00ae8cdc50dcb882fb04ae9a9a5', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 79, 'avg_line_length': 41.02127659574468, 'alnum_prop': 0.6473029045643154, 'repo_name': 'tylertian/Openstack', 'id': 'e4bce290e7375700c0f5257d7fabdcfdf15c0c60', 'size': '2558', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'openstack F/python-cinderclient/cinderclient/tests/v2/test_services.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '239919'}, {'name': 'JavaScript', 'bytes': '156942'}, {'name': 'Python', 'bytes': '16949418'}, {'name': 'Shell', 'bytes': '96743'}]}
{-# LANGUAGE UndecidableInstances, OverlappingInstances, Rank2Types, KindSignatures, EmptyDataDecls, MultiParamTypeClasses, CPP #-} {- (C) 2004--2005 Ralf Laemmel, Simon D. Foster This module approximates Data.Generics.Basics. -} module T1735_Help.Basics ( module Data.Typeable, module T1735_Help.Context, module T1735_Help.Basics ) where import Data.Typeable import T1735_Help.Context ------------------------------------------------------------------------------ -- The ingenious Data class class (Typeable a, Sat (ctx a)) => Data ctx a where gfoldl :: Proxy ctx -> (forall b c. Data ctx b => w (b -> c) -> b -> w c) -> (forall g. g -> w g) -> a -> w a -- Default definition for gfoldl -- which copes immediately with basic datatypes -- gfoldl _ _ z = z gunfold :: Proxy ctx -> (forall b r. Data ctx b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a toConstr :: Proxy ctx -> a -> Constr dataTypeOf :: Proxy ctx -> a -> DataType -- incomplete implementation gunfold _ _ _ _ = undefined dataTypeOf _ _ = undefined -- | Mediate types and unary type constructors dataCast1 :: Typeable t => Proxy ctx -> (forall b. Data ctx b => w (t b)) -> Maybe (w a) dataCast1 _ _ = Nothing -- | Mediate types and binary type constructors dataCast2 :: Typeable t => Proxy ctx -> (forall b c. (Data ctx b, Data ctx c) => w (t b c)) -> Maybe (w a) dataCast2 _ _ = Nothing ------------------------------------------------------------------------------ -- Generic transformations type GenericT ctx = forall a. Data ctx a => a -> a -- Generic map for transformations gmapT :: Proxy ctx -> GenericT ctx -> GenericT ctx gmapT ctx f x = unID (gfoldl ctx k ID x) where k (ID g) y = ID (g (f y)) -- The identity type constructor newtype ID x = ID { unID :: x } ------------------------------------------------------------------------------ -- Generic monadic transformations type GenericM m ctx = forall a. Data ctx a => a -> m a -- Generic map for monadic transformations gmapM :: Monad m => Proxy ctx -> GenericM m ctx -> GenericM m ctx gmapM ctx f = gfoldl ctx k return where k c x = do c' <- c x' <- f x return (c' x') ------------------------------------------------------------------------------ -- Generic queries type GenericQ ctx r = forall a. Data ctx a => a -> r -- Map for queries gmapQ :: Proxy ctx -> GenericQ ctx r -> GenericQ ctx [r] gmapQ ctx f = gmapQr ctx (:) [] f gmapQr :: Data ctx a => Proxy ctx -> (r' -> r -> r) -> r -> GenericQ ctx r' -> a -> r gmapQr ctx o r f x = unQr (gfoldl ctx k (const (Qr id)) x) r where k (Qr g) y = Qr (\s -> g (f y `o` s)) -- The type constructor used in definition of gmapQr newtype Qr r a = Qr { unQr :: r -> r } ------------------------------------------------------------------------------ -- -- Generic unfolding -- ------------------------------------------------------------------------------ -- | Build a term skeleton fromConstr :: Data ctx a => Proxy ctx -> Constr -> a fromConstr ctx = fromConstrB ctx undefined -- | Build a term and use a generic function for subterms fromConstrB :: Data ctx a => Proxy ctx -> (forall b. Data ctx b => b) -> Constr -> a fromConstrB ctx f = unID . gunfold ctx k z where k c = ID (unID c f) z = ID -- | Monadic variation on \"fromConstrB\" fromConstrM :: (Monad m, Data ctx a) => Proxy ctx -> (forall b. Data ctx b => m b) -> Constr -> m a fromConstrM ctx f = gunfold ctx k z where k c = do { c' <- c; b <- f; return (c' b) } z = return ------------------------------------------------------------------------------ -- -- Datatype and constructor representations -- ------------------------------------------------------------------------------ -- -- | Representation of datatypes. -- | A package of constructor representations with names of type and module. -- | The list of constructors could be an array, a balanced tree, or others. -- data DataType = DataType { tycon :: String , datarep :: DataRep } deriving Show -- | Representation of constructors data Constr = Constr { conrep :: ConstrRep , constring :: String , confields :: [String] -- for AlgRep only , confixity :: Fixity -- for AlgRep only , datatype :: DataType } instance Show Constr where show = constring -- | Equality of constructors instance Eq Constr where c == c' = constrRep c == constrRep c' -- | Public representation of datatypes data DataRep = AlgRep [Constr] | IntRep | FloatRep | StringRep | NoRep deriving (Eq,Show) -- | Public representation of constructors data ConstrRep = AlgConstr ConIndex | IntConstr Integer | FloatConstr Double | StringConstr String deriving (Eq,Show) -- -- | Unique index for datatype constructors. -- | Textual order is respected. Starts at 1. -- type ConIndex = Int -- | Fixity of constructors data Fixity = Prefix | Infix -- Later: add associativity and precedence deriving (Eq,Show) ------------------------------------------------------------------------------ -- -- Observers for datatype representations -- ------------------------------------------------------------------------------ -- | Gets the type constructor including the module dataTypeName :: DataType -> String dataTypeName = tycon -- | Gets the public presentation of datatypes dataTypeRep :: DataType -> DataRep dataTypeRep = datarep -- | Gets the datatype of a constructor constrType :: Constr -> DataType constrType = datatype -- | Gets the public presentation of constructors constrRep :: Constr -> ConstrRep constrRep = conrep -- | Look up a constructor by its representation repConstr :: DataType -> ConstrRep -> Constr repConstr dt cr = case (dataTypeRep dt, cr) of (AlgRep cs, AlgConstr i) -> cs !! (i-1) (IntRep, IntConstr i) -> mkIntConstr dt i (FloatRep, FloatConstr f) -> mkFloatConstr dt f (StringRep, StringConstr str) -> mkStringConstr dt str _ -> error "repConstr" ------------------------------------------------------------------------------ -- -- Representations of algebraic data types -- ------------------------------------------------------------------------------ -- | Constructs an algebraic datatype mkDataType :: String -> [Constr] -> DataType mkDataType str cs = DataType { tycon = str , datarep = AlgRep cs } -- | Constructs a constructor mkConstr :: DataType -> String -> [String] -> Fixity -> Constr mkConstr dt str fields fix = Constr { conrep = AlgConstr idx , constring = str , confields = fields , confixity = fix , datatype = dt } where idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..], showConstr c == str ] -- | Gets the constructors dataTypeConstrs :: DataType -> [Constr] dataTypeConstrs dt = case datarep dt of (AlgRep cons) -> cons _ -> error "dataTypeConstrs" -- | Gets the field labels of a constructor constrFields :: Constr -> [String] constrFields = confields -- | Gets the fixity of a constructor constrFixity :: Constr -> Fixity constrFixity = confixity ------------------------------------------------------------------------------ -- -- From strings to constr's and vice versa: all data types -- ------------------------------------------------------------------------------ -- | Gets the string for a constructor showConstr :: Constr -> String showConstr = constring -- | Lookup a constructor via a string readConstr :: DataType -> String -> Maybe Constr readConstr dt str = case dataTypeRep dt of AlgRep cons -> idx cons IntRep -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i))) FloatRep -> mkReadCon (\f -> (mkPrimCon dt str (FloatConstr f))) StringRep -> Just (mkStringConstr dt str) NoRep -> Nothing where -- Read a value and build a constructor mkReadCon :: Read t => (t -> Constr) -> Maybe Constr mkReadCon f = case (reads str) of [(t,"")] -> Just (f t) _ -> Nothing -- Traverse list of algebraic datatype constructors idx :: [Constr] -> Maybe Constr idx cons = let fit = filter ((==) str . showConstr) cons in if fit == [] then Nothing else Just (head fit) ------------------------------------------------------------------------------ -- -- Convenience functions: algebraic data types -- ------------------------------------------------------------------------------ -- | Test for an algebraic type isAlgType :: DataType -> Bool isAlgType dt = case datarep dt of (AlgRep _) -> True _ -> False -- | Gets the constructor for an index indexConstr :: DataType -> ConIndex -> Constr indexConstr dt idx = case datarep dt of (AlgRep cs) -> cs !! (idx-1) _ -> error "indexConstr" -- | Gets the index of a constructor constrIndex :: Constr -> ConIndex constrIndex con = case constrRep con of (AlgConstr idx) -> idx _ -> error "constrIndex" -- | Gets the maximum constructor index maxConstrIndex :: DataType -> ConIndex maxConstrIndex dt = case dataTypeRep dt of AlgRep cs -> length cs _ -> error "maxConstrIndex" ------------------------------------------------------------------------------ -- -- Representation of primitive types -- ------------------------------------------------------------------------------ -- | Constructs the Int type mkIntType :: String -> DataType mkIntType = mkPrimType IntRep -- | Constructs the Float type mkFloatType :: String -> DataType mkFloatType = mkPrimType FloatRep -- | Constructs the String type mkStringType :: String -> DataType mkStringType = mkPrimType StringRep -- | Helper for mkIntType, mkFloatType, mkStringType mkPrimType :: DataRep -> String -> DataType mkPrimType dr str = DataType { tycon = str , datarep = dr } -- Makes a constructor for primitive types mkPrimCon :: DataType -> String -> ConstrRep -> Constr mkPrimCon dt str cr = Constr { datatype = dt , conrep = cr , constring = str , confields = error $ concat ["constrFields : ", (tycon dt), " is primative"] , confixity = error "constrFixity" } mkIntConstr :: DataType -> Integer -> Constr mkIntConstr dt i = case datarep dt of IntRep -> mkPrimCon dt (show i) (IntConstr i) _ -> error "mkIntConstr" mkFloatConstr :: DataType -> Double -> Constr mkFloatConstr dt f = case datarep dt of FloatRep -> mkPrimCon dt (show f) (FloatConstr f) _ -> error "mkFloatConstr" mkStringConstr :: DataType -> String -> Constr mkStringConstr dt str = case datarep dt of StringRep -> mkPrimCon dt str (StringConstr str) _ -> error "mkStringConstr" ------------------------------------------------------------------------------ -- -- Non-representations for non-presentable types -- ------------------------------------------------------------------------------ -- | Constructs a non-representation mkNorepType :: String -> DataType mkNorepType str = DataType { tycon = str , datarep = NoRep } -- | Test for a non-representable type isNorepType :: DataType -> Bool isNorepType dt = case datarep dt of NoRep -> True _ -> False
{'content_hash': '2edddd3482b43f1ca01319a1b343e820', 'timestamp': '', 'source': 'github', 'line_count': 487, 'max_line_length': 101, 'avg_line_length': 26.1129363449692, 'alnum_prop': 0.4895022410945978, 'repo_name': 'shlevy/ghc', 'id': '83b147e413f55240a49d6c459d16274b87c777df', 'size': '12717', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'testsuite/tests/typecheck/should_run/T1735_Help/Basics.hs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '8752'}, {'name': 'Batchfile', 'bytes': '394'}, {'name': 'C', 'bytes': '2939599'}, {'name': 'C++', 'bytes': '114368'}, {'name': 'CSS', 'bytes': '984'}, {'name': 'DTrace', 'bytes': '4068'}, {'name': 'Emacs Lisp', 'bytes': '734'}, {'name': 'Gnuplot', 'bytes': '103851'}, {'name': 'HTML', 'bytes': '6144'}, {'name': 'Haskell', 'bytes': '22341394'}, {'name': 'Haxe', 'bytes': '218'}, {'name': 'Logos', 'bytes': '138312'}, {'name': 'M4', 'bytes': '57247'}, {'name': 'Makefile', 'bytes': '583780'}, {'name': 'Nix', 'bytes': '2162'}, {'name': 'Objective-C', 'bytes': '7276'}, {'name': 'Objective-C++', 'bytes': '535'}, {'name': 'Pascal', 'bytes': '128141'}, {'name': 'Perl', 'bytes': '18385'}, {'name': 'Perl 6', 'bytes': '59030'}, {'name': 'PostScript', 'bytes': '63'}, {'name': 'Python', 'bytes': '117392'}, {'name': 'Roff', 'bytes': '3841'}, {'name': 'Shell', 'bytes': '94851'}, {'name': 'TeX', 'bytes': '667'}, {'name': 'Terra', 'bytes': '480987'}, {'name': 'Yacc', 'bytes': '64411'}]}
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Soeren Sonnenburg, Fernando Iglesias, Giovanni De Toni, * Saurabh Mahindre, Sergey Lisitsyn, Weijie Lin, Heiko Strathmann, * Evgeniy Andreev, Viktor Gal, Bjoern Esser */ #include <shogun/base/Parameter.h> #include <shogun/base/progress.h> #include <shogun/labels/Labels.h> #include <shogun/lib/Signal.h> #include <shogun/lib/Time.h> #include <shogun/mathematics/Math.h> #include <shogun/multiclass/KNN.h> #include <shogun/mathematics/linalg/LinalgNamespace.h> //#define DEBUG_KNN using namespace shogun; CKNN::CKNN() : CDistanceMachine() { init(); } CKNN::CKNN(int32_t k, CDistance* d, CLabels* trainlab, KNN_SOLVER knn_solver) : CDistanceMachine() { init(); m_k=k; REQUIRE(d, "Distance not set.\n"); REQUIRE(trainlab, "Training labels not set.\n"); set_distance(d); set_labels(trainlab); m_train_labels.vlen=trainlab->get_num_labels(); m_knn_solver=knn_solver; } void CKNN::init() { m_k=3; m_q=1.0; m_num_classes=0; m_leaf_size=1; m_knn_solver=KNN_BRUTE; solver=NULL; m_lsh_l = 0; m_lsh_t = 0; /* use the method classify_multiply_k to experiment with different values * of k */ SG_ADD(&m_k, "k", "Parameter k"); SG_ADD(&m_q, "q", "Parameter q", ParameterProperties::HYPER); SG_ADD(&m_num_classes, "num_classes", "Number of classes"); SG_ADD(&m_leaf_size, "leaf_size", "Leaf size for KDTree"); SG_ADD_OPTIONS( (machine_int_t*)&m_knn_solver, "knn_solver", "Algorithm to solve knn", ParameterProperties::NONE, SG_OPTIONS(KNN_BRUTE, KNN_KDTREE, KNN_COVER_TREE, KNN_LSH)); } CKNN::~CKNN() { } bool CKNN::train_machine(CFeatures* data) { REQUIRE(m_labels, "No training labels provided.\n"); REQUIRE(distance, "No training distance provided.\n"); if (data) { REQUIRE( m_labels->get_num_labels() == data->get_num_vectors(), "Number of training vectors (%d) does not match number of labels " "(%d)\n", data->get_num_vectors(), m_labels->get_num_labels()); distance->init(data, data); } SGVector<int32_t> lab=((CMulticlassLabels*) m_labels)->get_int_labels(); m_train_labels=lab.clone(); REQUIRE(m_train_labels.vlen > 0, "Provided training labels are empty\n"); // find minimal and maximal class auto min_class = CMath::min(m_train_labels.vector, m_train_labels.vlen); auto max_class = CMath::max(m_train_labels.vector, m_train_labels.vlen); linalg::add_scalar(m_train_labels, -min_class); m_min_label=min_class; m_num_classes=max_class-min_class+1; SG_INFO("m_num_classes: %d (%+d to %+d) num_train: %d\n", m_num_classes, min_class, max_class, m_train_labels.vlen); return true; } SGMatrix<index_t> CKNN::nearest_neighbors() { //number of examples to which kNN is applied int32_t n=distance->get_num_vec_rhs(); REQUIRE( n >= m_k, "K (%d) must not be larger than the number of examples (%d).\n", m_k, n) //distances to train data SGVector<float64_t> dists(m_train_labels.vlen); //indices to train data SGVector<index_t> train_idxs(m_train_labels.vlen); //pre-allocation of the nearest neighbors SGMatrix<index_t> NN(m_k, n); distance->precompute_lhs(); distance->precompute_rhs(); //for each test example for (auto i : SG_PROGRESS(range(n))) { COMPUTATION_CONTROLLERS //lhs idx 0..num train examples-1 (i.e., all train examples) and rhs idx i distances_lhs(dists,0,m_train_labels.vlen-1,i); //fill in an array with 0..num train examples-1 for (int32_t j=0; j<m_train_labels.vlen; j++) train_idxs[j]=j; //sort the distance vector between test example i and all train examples CMath::qsort_index(dists.vector, train_idxs.vector, m_train_labels.vlen); #ifdef DEBUG_KNN SG_PRINT("\nQuick sort query %d\n", i) for (int32_t j=0; j<m_k; j++) SG_PRINT("%d ", train_idxs[j]) SG_PRINT("\n") #endif //fill in the output the indices of the nearest neighbors for (int32_t j=0; j<m_k; j++) NN(j,i) = train_idxs[j]; } distance->reset_precompute(); return NN; } CMulticlassLabels* CKNN::apply_multiclass(CFeatures* data) { if (data) init_distance(data); //redirecting to fast (without sorting) classify if k==1 if (m_k == 1) return classify_NN(); REQUIRE(m_num_classes > 0, "Machine not trained.\n"); REQUIRE(distance, "Distance not set.\n"); REQUIRE(distance->get_num_vec_rhs(), "No vectors on right hand side.\n"); int32_t num_lab=distance->get_num_vec_rhs(); ASSERT(m_k<=distance->get_num_vec_lhs()) //labels of the k nearest neighbors SGVector<int32_t> train_lab(m_k); SG_INFO("%d test examples\n", num_lab) //histogram of classes and returned output SGVector<float64_t> classes(m_num_classes); init_solver(m_knn_solver); CMulticlassLabels* output = solver->classify_objects(distance, num_lab, train_lab, classes); SG_UNREF(solver); return output; } CMulticlassLabels* CKNN::classify_NN() { REQUIRE(distance, "Distance not set.\n"); REQUIRE(m_num_classes > 0, "Machine not trained.\n"); int32_t num_lab = distance->get_num_vec_rhs(); REQUIRE(num_lab, "No vectors on right hand side\n"); CMulticlassLabels* output = new CMulticlassLabels(num_lab); SGVector<float64_t> distances(m_train_labels.vlen); SG_INFO("%d test examples\n", num_lab) distance->precompute_lhs(); // for each test example for (auto i : SG_PROGRESS(range(num_lab))) { COMPUTATION_CONTROLLERS // get distances from i-th test example to 0..num_m_train_labels-1 train examples distances_lhs(distances,0,m_train_labels.vlen-1,i); int32_t j; // assuming 0th train examples as nearest to i-th test example int32_t out_idx = 0; float64_t min_dist = distances.vector[0]; // searching for nearest neighbor by comparing distances for (j=0; j<m_train_labels.vlen; j++) { if (distances.vector[j]<min_dist) { min_dist = distances.vector[j]; out_idx = j; } } // label i-th test example with label of nearest neighbor with out_idx index output->set_label(i,m_train_labels.vector[out_idx]+m_min_label); } distance->reset_precompute(); return output; } SGMatrix<int32_t> CKNN::classify_for_multiple_k() { REQUIRE(distance, "Distance not set.\n"); REQUIRE(m_num_classes > 0, "Machine not trained.\n"); int32_t num_lab=distance->get_num_vec_rhs(); REQUIRE(num_lab, "No vectors on right hand side\n"); REQUIRE( m_k <= num_lab, "Number of labels (%d) must be at least K (%d).\n", num_lab, m_k); //working buffer of m_train_labels SGVector<int32_t> train_lab(m_k); //histogram of classes and returned output SGVector<int32_t> classes(m_num_classes); SG_INFO("%d test examples\n", num_lab) init_solver(m_knn_solver); SGVector<int32_t> output = solver->classify_objects_k(distance, num_lab, train_lab, classes); SG_UNREF(solver); return SGMatrix<int32_t>(output,num_lab,m_k); } void CKNN::init_distance(CFeatures* data) { REQUIRE(distance, "Distance not set.\n"); CFeatures* lhs=distance->get_lhs(); if (!lhs || !lhs->get_num_vectors()) { SG_UNREF(lhs); SG_ERROR("No vectors on left hand side\n") } distance->init(lhs, data); SG_UNREF(lhs); } bool CKNN::load(FILE* srcfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } bool CKNN::save(FILE* dstfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } void CKNN::init_solver(KNN_SOLVER knn_solver) { switch (knn_solver) { case KNN_BRUTE: { SGMatrix<index_t> NN = nearest_neighbors(); solver = new CBruteKNNSolver(m_k, m_q, m_num_classes, m_min_label, m_train_labels, NN); SG_REF(solver); break; } case KNN_KDTREE: { solver = new CKDTREEKNNSolver(m_k, m_q, m_num_classes, m_min_label, m_train_labels, m_leaf_size); SG_REF(solver); break; } case KNN_COVER_TREE: { #ifdef USE_GPL_SHOGUN solver = new CCoverTreeKNNSolver(m_k, m_q, m_num_classes, m_min_label, m_train_labels); SG_REF(solver); break; #else SG_GPL_ONLY #endif // USE_GPL_SHOGUN } case KNN_LSH: { solver = new CLSHKNNSolver(m_k, m_q, m_num_classes, m_min_label, m_train_labels, m_lsh_l, m_lsh_t); SG_REF(solver); break; } } }
{'content_hash': '43b21afcc0e960a347fc5296da183cba', 'timestamp': '', 'source': 'github', 'line_count': 325, 'max_line_length': 101, 'avg_line_length': 24.796923076923076, 'alnum_prop': 0.6779997518302519, 'repo_name': 'lisitsyn/shogun', 'id': '62b7df41ee2dbf05374fdcd7f9dfdbc3a6c9493e', 'size': '8059', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'src/shogun/multiclass/KNN.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '568'}, {'name': 'C', 'bytes': '12000'}, {'name': 'C++', 'bytes': '10557466'}, {'name': 'CMake', 'bytes': '195345'}, {'name': 'Dockerfile', 'bytes': '2029'}, {'name': 'GDB', 'bytes': '89'}, {'name': 'HTML', 'bytes': '2066'}, {'name': 'MATLAB', 'bytes': '8755'}, {'name': 'Makefile', 'bytes': '244'}, {'name': 'Python', 'bytes': '285072'}, {'name': 'Shell', 'bytes': '11995'}]}
class TestEnvironment def self.launch env = new env.start at_exit { env.stop } end def initialize @rabbit = RabbitControl.new end def start @rabbit.start end def stop @rabbit.stop end end
{'content_hash': '4b7f40e91fa22892f4709c3b12c03b25', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 31, 'avg_line_length': 12.157894736842104, 'alnum_prop': 0.6320346320346321, 'repo_name': 'jarib/cukeq', 'id': '944367f7189f482f43060f923a137a2e945b01af', 'size': '231', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'features/support/test_environment.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '42797'}]}
'use strict'; var Class = require('../imports').HtmlUnitDriver; var Capabilities = require('../interfaces/Capabilities'); var TakesScreenshot = require('../interfaces/TakesScreenshot'); var RemoteWebDriver = require('./RemoteWebDriver'); var extendAll = require('../utils').extendAll; var assert = require('../assert'); var addFinalProp = require('../utils').addFinalProp; module.exports = HtmlUnitDriver; extendAll( HtmlUnitDriver, RemoteWebDriver ); //TODO: Finish constructor arguments function HtmlUnitDriver( desiredCapabilitiesOrEnableJavascript ) { var instance; var first = desiredCapabilitiesOrEnableJavascript; var len = arguments.length; if (!len) { instance = new Class(); } else if (len === 1) { if (assert(first).extends(Capabilities).isValid) { instance = new Class(first._instance); } else if (assert.isBool(first)) { instance = new Class(first); } else { throw new Error( 'The first argument must be an instance of Capabilities or a boolean.' ); } } else { throw new Error('The wrong number of arguments was given.'); } addFinalProp(this, '_instance', instance); } //TODO: finish static fields
{'content_hash': 'ddce2a1aeb371e01e94d5dbd98b4e24e', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 78, 'avg_line_length': 27.25, 'alnum_prop': 0.6872393661384487, 'repo_name': 'jsdevel/travis-debugging', 'id': '7c44570eff2d3663f62daff4ceb638a636ca8f85', 'size': '1199', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/classes/HtmlUnitDriver.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1215'}, {'name': 'JavaScript', 'bytes': '139339'}, {'name': 'Shell', 'bytes': '936'}]}
(function() { var CategoryVm, MainClass, MainClassVm, SubcategoryVm, error, model, model_vm, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; MainClass = Backbone.RelationalModel.extend({ defaults: { number1: 1 }, relations: [ { type: Backbone.HasMany, key: 'categories', relatedModel: 'Category', collectionType: 'Categories', reverseRelation: { key: 'main', includeInJSON: false } } ] }); window.Category = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasMany, key: 'subcategories', relatedModel: 'Subcategory', collectionType: 'Subcategories', reverseRelation: { key: 'category', includeInJSON: false } } ] }); window.Subcategory = Backbone.RelationalModel.extend({ defaults: { number1: 1, number2: 1 } }); window.Categories = Backbone.Collection.extend({ model: Category }); window.Subcategories = Backbone.Collection.extend({ model: Subcategory }); SubcategoryVm = null; CategoryVm = null; MainClassVm = null; SubcategoryVm = (function(_super) { __extends(SubcategoryVm, _super); function SubcategoryVm(model, options) { var _this = this; SubcategoryVm.__super__.constructor.call(this, model, { factories: { 'category': CategoryVm }, options: options }); this.computed = ko.computed(function() { return _this.category().main().number1() + _this.number1() + _this.number2(); }); } return SubcategoryVm; })(kb.ViewModel); CategoryVm = (function(_super) { __extends(CategoryVm, _super); function CategoryVm(model, options) { CategoryVm.__super__.constructor.call(this, model, { requires: ['main'], factories: { 'subcategories.models': SubcategoryVm, 'main': MainClassVm }, options: options }); } return CategoryVm; })(kb.ViewModel); MainClassVm = (function(_super) { __extends(MainClassVm, _super); function MainClassVm(model, options) { MainClassVm.__super__.constructor.call(this, model, { factories: { 'categories.models': CategoryVm }, options: options }); } return MainClassVm; })(kb.ViewModel); model = new MainClass({ categories: [ { subcategories: [{}] } ] }); try { model_vm = new MainClassVm(model); } catch (_error) { error = _error; jQuery('#errorPanel').html(error); } }).call(this);
{'content_hash': '15a1fcc6085427869ec445746a3722db', 'timestamp': '', 'source': 'github', 'line_count': 129, 'max_line_length': 292, 'avg_line_length': 22.930232558139537, 'alnum_prop': 0.5774171737660582, 'repo_name': 'npmcomponent/kmalakoff-knockback', 'id': 'f96b49d3ccac4282e2b4ea8ee3da4dd9caf548d0', 'size': '2993', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'test/issues/issue98/issue.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '547162'}, {'name': 'JavaScript', 'bytes': '1192460'}]}
local possibleSprites = { love.graphics.newImage("assets/images/peg1.png"), love.graphics.newImage("assets/images/peg2.png"), love.graphics.newImage("assets/images/peg3.png"), love.graphics.newImage("assets/images/peg4.png"), love.graphics.newImage("assets/images/peg5.png"), love.graphics.newImage("assets/images/peg6.png"), love.graphics.newImage("assets/images/peg7.png"), love.graphics.newImage("assets/images/peg8.png"), love.graphics.newImage("assets/images/peg9.png"), love.graphics.newImage("assets/images/peg10.png"), love.graphics.newImage("assets/images/peg11.png"), love.graphics.newImage("assets/images/peg12.png"), love.graphics.newImage("assets/images/peg13.png"), love.graphics.newImage("assets/images/peg14.png"), love.graphics.newImage("assets/images/peg15.png"), love.graphics.newImage("assets/images/peg16.png"), love.graphics.newImage("assets/images/peg17.png"), love.graphics.newImage("assets/images/peg18.png"), love.graphics.newImage("assets/images/peg19.png") } local Peg = Class{ init = function(self) -- Spawn pegs in a random Vector location self.position = nil self.wavelength = Utils.randomWavelength() self.color = Utils.wavelengthToRGB(self.wavelength) self.spriteIndex = math.floor(math.random(#possibleSprites)) self.seed = math.random(1, 1000000) end } function Peg:draw(collectable) self:drawAtPosition(self.position, collectable) end -- Draw the peg on screen! function Peg:drawAtPosition(position, collectable) if collectable then self:drawCollectableState(position) love.graphics.setColor(240,240,240) else love.graphics.setColor(150,150,150,150) end love.graphics.circle("fill", position.x, position.y, Constants.PEG_RADIUS) if collectable then love.graphics.setColor(50, 50, 50) love.graphics.circle("line", position.x, position.y, Constants.PEG_RADIUS) end self:setPastellizedColor() love.graphics.draw(possibleSprites[self.spriteIndex], position.x-Constants.PEG_RADIUS, position.y-Constants.PEG_RADIUS) end --Pastellize the color w/o changing hue function Peg:setPastellizedColor() local pastelR local pastelG local pastelB local delta if self.color.r > self.color.g and self.color.r > self.color.b then delta = 255 - self.color.r elseif self.color.g > self.color.r and self.color.g > self.color.b then delta = 255 - self.color.g else delta = 255 - self.color.b end pastelR = self.color.r + delta pastelG = self.color.g + delta pastelB = self.color.b + delta local alpha = 255 if collectable then alpha = 150 end love.graphics.setColor(pastelR, pastelG, pastelB) end function Peg:drawCollectableState(position) time = love.timer.getTime() love.graphics.setColor(200, 0, 0, 50) love.graphics.circle("fill", position.x, position.y, 15 + math.sin(((self.seed + time)/100) * 500) * 4) love.graphics.setColor(0, 200, 0, 50) love.graphics.circle("fill", position.x, position.y, 15 + math.sin(((self.seed + time)/100) * 200) * 6) love.graphics.setColor(0, 0, 200, 50) love.graphics.circle("fill", position.x, position.y, 15 + math.sin(((self.seed + time)/100) * 300) * 5) end -- Used for idiomatic module loading. return Peg
{'content_hash': '60684d4ccee2325e1edc99fa07f3e6ba', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 106, 'avg_line_length': 31.933333333333334, 'alnum_prop': 0.6996719355800776, 'repo_name': 'marczych/PeggleDamacy', 'id': 'febb1ff966c54484fd8026ffafc964e339d8a766', 'size': '3353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'entities/peg.lua', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Lua', 'bytes': '58172'}]}
package org.jboss.weld.metadata.cache; import java.lang.annotation.Annotation; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.inject.Stereotype; import org.jboss.weld.annotated.enhanced.EnhancedAnnotated; import org.jboss.weld.logging.MetadataLogger; import org.jboss.weld.manager.BeanManagerImpl; import org.jboss.weld.resources.SharedObjectCache; /** * Meta model for the merged stereotype for a bean * * @author Pete Muir */ public class MergedStereotypes<T, E> { // The possible scope types private final Set<Annotation> possibleScopeTypes; // Is the bean name defaulted? private boolean beanNameDefaulted; // Are any of the stereotypes alternatives private boolean alternative; private Set<Class<? extends Annotation>> stereotypes; private final BeanManagerImpl manager; public static <T, E> MergedStereotypes<T, E> of(EnhancedAnnotated<T, E> annotated, BeanManagerImpl manager) { return of(annotated.getMetaAnnotations(Stereotype.class), manager); } public static <T, E> MergedStereotypes<T, E> of(Set<Annotation> stereotypeAnnotations, BeanManagerImpl manager) { return new MergedStereotypes<T, E>(stereotypeAnnotations, manager); } /** * Constructor * * @param stereotypeAnnotations The stereotypes to merge */ protected MergedStereotypes(Set<Annotation> stereotypeAnnotations, BeanManagerImpl manager) { this.possibleScopeTypes = new HashSet<Annotation>(); this.stereotypes = new HashSet<Class<? extends Annotation>>(); this.manager = manager; merge(stereotypeAnnotations); this.stereotypes = SharedObjectCache.instance(manager).getSharedSet(stereotypes); } /** * Perform the merge * * @param stereotypeAnnotations The stereotype annotations */ protected void merge(Set<Annotation> stereotypeAnnotations) { final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class); for (Annotation stereotypeAnnotation : stereotypeAnnotations) { // Retrieve and merge all metadata from stereotypes StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType()); if (stereotype == null) { throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation); } if (stereotype.isAlternative()) { alternative = true; } if (stereotype.getDefaultScopeType() != null) { possibleScopeTypes.add(stereotype.getDefaultScopeType()); } if (stereotype.isBeanNameDefaulted()) { beanNameDefaulted = true; } this.stereotypes.add(stereotypeAnnotation.annotationType()); // Merge in inherited stereotypes merge(stereotype.getInheritedStereotypes()); } } public boolean isAlternative() { return alternative; } /** * Returns the possible scope types * * @return The scope types */ public Set<Annotation> getPossibleScopes() { return possibleScopeTypes; } /** * Indicates if the name i defaulted * * @return True if defaulted, false if not */ public boolean isBeanNameDefaulted() { return beanNameDefaulted; } /** * @return the stereotypes */ public Set<Class<? extends Annotation>> getStereotypes() { return stereotypes; } /** * Gets a string representation of the merged stereotypes * * @return The string representation */ @Override public String toString() { return "Merged stereotype model; Any of the stereotypes is an alternative: " + alternative + "; possible scopes " + possibleScopeTypes; } }
{'content_hash': '62240b79149e163713838e7902f1817d', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 117, 'avg_line_length': 32.06611570247934, 'alnum_prop': 0.6646907216494845, 'repo_name': 'weld/core', 'id': '859f11f25d10c6a566b014a324fd8d6c9313114a', 'size': '4655', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'impl/src/main/java/org/jboss/weld/metadata/cache/MergedStereotypes.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '7849'}, {'name': 'HTML', 'bytes': '15226'}, {'name': 'Java', 'bytes': '10585311'}]}
package monitoring_test import "istio.io/pkg/monitoring" var pushLatency = monitoring.NewGauge( "push_latency_seconds", "Duration, measured in seconds, of the last push", monitoring.WithUnit(monitoring.Seconds), ) func init() { monitoring.MustRegister(pushLatency) } func ExampleNewGauge() { // only the last recorded value (99.2) will be exported for this gauge pushLatency.Record(77.3) pushLatency.Record(22.8) pushLatency.Record(99.2) }
{'content_hash': '1a3f5f5821a555344eee50468a1d6c37', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 71, 'avg_line_length': 22.6, 'alnum_prop': 0.7588495575221239, 'repo_name': 'istio/pkg', 'id': 'fe95aaefb57dc9454c7f418b48793db7a80d7133', 'size': '1043', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'monitoring/example_gauge_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '47652'}, {'name': 'Go', 'bytes': '348112'}, {'name': 'HTML', 'bytes': '35223'}, {'name': 'JavaScript', 'bytes': '13'}, {'name': 'Makefile', 'bytes': '9197'}, {'name': 'Ruby', 'bytes': '317'}, {'name': 'Shell', 'bytes': '37015'}]}
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/spanner/v1/result_set.proto namespace Google\Cloud\Spanner\V1; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Partial results from a streaming read or SQL query. Streaming reads and * SQL queries better tolerate large result sets, large rows, and large * values, but are a little trickier to consume. * * Generated from protobuf message <code>google.spanner.v1.PartialResultSet</code> */ class PartialResultSet extends \Google\Protobuf\Internal\Message { /** * Metadata about the result set, such as row type information. * Only present in the first response. * * Generated from protobuf field <code>.google.spanner.v1.ResultSetMetadata metadata = 1;</code> */ private $metadata = null; /** * A streamed result set consists of a stream of values, which might * be split into many `PartialResultSet` messages to accommodate * large rows and/or large values. Every N complete values defines a * row, where N is equal to the number of entries in * [metadata.row_type.fields][google.spanner.v1.StructType.fields]. * Most values are encoded based on type as described * [here][google.spanner.v1.TypeCode]. * It is possible that the last value in values is "chunked", * meaning that the rest of the value is sent in subsequent * `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value] * field. Two or more chunked values can be merged to form a * complete value as follows: * * `bool/number/null`: cannot be chunked * * `string`: concatenate the strings * * `list`: concatenate the lists. If the last element in a list is a * `string`, `list`, or `object`, merge it with the first element in * the next list by applying these rules recursively. * * `object`: concatenate the (field name, field value) pairs. If a * field name is duplicated, then apply these rules recursively * to merge the field values. * Some examples of merging: * # Strings are concatenated. * "foo", "bar" => "foobar" * # Lists of non-strings are concatenated. * [2, 3], [4] => [2, 3, 4] * # Lists are concatenated, but the last and first elements are merged * # because they are strings. * ["a", "b"], ["c", "d"] => ["a", "bc", "d"] * # Lists are concatenated, but the last and first elements are merged * # because they are lists. Recursively, the last and first elements * # of the inner lists are merged because they are strings. * ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] * # Non-overlapping object fields are combined. * {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} * # Overlapping object fields are merged. * {"a": "1"}, {"a": "2"} => {"a": "12"} * # Examples of merging objects containing lists of strings. * {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} * For a more complete example, suppose a streaming SQL query is * yielding a result set whose rows contain a single string * field. The following `PartialResultSet`s might be yielded: * { * "metadata": { ... } * "values": ["Hello", "W"] * "chunked_value": true * "resume_token": "Af65..." * } * { * "values": ["orl"] * "chunked_value": true * "resume_token": "Bqp2..." * } * { * "values": ["d"] * "resume_token": "Zx1B..." * } * This sequence of `PartialResultSet`s encodes two rows, one * containing the field value `"Hello"`, and a second containing the * field value `"World" = "W" + "orl" + "d"`. * * Generated from protobuf field <code>repeated .google.protobuf.Value values = 2;</code> */ private $values; /** * If true, then the final value in [values][google.spanner.v1.PartialResultSet.values] is chunked, and must * be combined with more values from subsequent `PartialResultSet`s * to obtain a complete field value. * * Generated from protobuf field <code>bool chunked_value = 3;</code> */ private $chunked_value = false; /** * Streaming calls might be interrupted for a variety of reasons, such * as TCP connection loss. If this occurs, the stream of results can * be resumed by re-sending the original request and including * `resume_token`. Note that executing any other transaction in the * same session invalidates the token. * * Generated from protobuf field <code>bytes resume_token = 4;</code> */ private $resume_token = ''; /** * Query plan and execution statistics for the statement that produced this * streaming result set. These can be requested by setting * [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent * only once with the last response in the stream. * This field will also be present in the last response for DML * statements. * * Generated from protobuf field <code>.google.spanner.v1.ResultSetStats stats = 5;</code> */ private $stats = null; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type \Google\Cloud\Spanner\V1\ResultSetMetadata $metadata * Metadata about the result set, such as row type information. * Only present in the first response. * @type array<\Google\Protobuf\Value>|\Google\Protobuf\Internal\RepeatedField $values * A streamed result set consists of a stream of values, which might * be split into many `PartialResultSet` messages to accommodate * large rows and/or large values. Every N complete values defines a * row, where N is equal to the number of entries in * [metadata.row_type.fields][google.spanner.v1.StructType.fields]. * Most values are encoded based on type as described * [here][google.spanner.v1.TypeCode]. * It is possible that the last value in values is "chunked", * meaning that the rest of the value is sent in subsequent * `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value] * field. Two or more chunked values can be merged to form a * complete value as follows: * * `bool/number/null`: cannot be chunked * * `string`: concatenate the strings * * `list`: concatenate the lists. If the last element in a list is a * `string`, `list`, or `object`, merge it with the first element in * the next list by applying these rules recursively. * * `object`: concatenate the (field name, field value) pairs. If a * field name is duplicated, then apply these rules recursively * to merge the field values. * Some examples of merging: * # Strings are concatenated. * "foo", "bar" => "foobar" * # Lists of non-strings are concatenated. * [2, 3], [4] => [2, 3, 4] * # Lists are concatenated, but the last and first elements are merged * # because they are strings. * ["a", "b"], ["c", "d"] => ["a", "bc", "d"] * # Lists are concatenated, but the last and first elements are merged * # because they are lists. Recursively, the last and first elements * # of the inner lists are merged because they are strings. * ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] * # Non-overlapping object fields are combined. * {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} * # Overlapping object fields are merged. * {"a": "1"}, {"a": "2"} => {"a": "12"} * # Examples of merging objects containing lists of strings. * {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} * For a more complete example, suppose a streaming SQL query is * yielding a result set whose rows contain a single string * field. The following `PartialResultSet`s might be yielded: * { * "metadata": { ... } * "values": ["Hello", "W"] * "chunked_value": true * "resume_token": "Af65..." * } * { * "values": ["orl"] * "chunked_value": true * "resume_token": "Bqp2..." * } * { * "values": ["d"] * "resume_token": "Zx1B..." * } * This sequence of `PartialResultSet`s encodes two rows, one * containing the field value `"Hello"`, and a second containing the * field value `"World" = "W" + "orl" + "d"`. * @type bool $chunked_value * If true, then the final value in [values][google.spanner.v1.PartialResultSet.values] is chunked, and must * be combined with more values from subsequent `PartialResultSet`s * to obtain a complete field value. * @type string $resume_token * Streaming calls might be interrupted for a variety of reasons, such * as TCP connection loss. If this occurs, the stream of results can * be resumed by re-sending the original request and including * `resume_token`. Note that executing any other transaction in the * same session invalidates the token. * @type \Google\Cloud\Spanner\V1\ResultSetStats $stats * Query plan and execution statistics for the statement that produced this * streaming result set. These can be requested by setting * [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent * only once with the last response in the stream. * This field will also be present in the last response for DML * statements. * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Spanner\V1\ResultSet::initOnce(); parent::__construct($data); } /** * Metadata about the result set, such as row type information. * Only present in the first response. * * Generated from protobuf field <code>.google.spanner.v1.ResultSetMetadata metadata = 1;</code> * @return \Google\Cloud\Spanner\V1\ResultSetMetadata|null */ public function getMetadata() { return $this->metadata; } public function hasMetadata() { return isset($this->metadata); } public function clearMetadata() { unset($this->metadata); } /** * Metadata about the result set, such as row type information. * Only present in the first response. * * Generated from protobuf field <code>.google.spanner.v1.ResultSetMetadata metadata = 1;</code> * @param \Google\Cloud\Spanner\V1\ResultSetMetadata $var * @return $this */ public function setMetadata($var) { GPBUtil::checkMessage($var, \Google\Cloud\Spanner\V1\ResultSetMetadata::class); $this->metadata = $var; return $this; } /** * A streamed result set consists of a stream of values, which might * be split into many `PartialResultSet` messages to accommodate * large rows and/or large values. Every N complete values defines a * row, where N is equal to the number of entries in * [metadata.row_type.fields][google.spanner.v1.StructType.fields]. * Most values are encoded based on type as described * [here][google.spanner.v1.TypeCode]. * It is possible that the last value in values is "chunked", * meaning that the rest of the value is sent in subsequent * `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value] * field. Two or more chunked values can be merged to form a * complete value as follows: * * `bool/number/null`: cannot be chunked * * `string`: concatenate the strings * * `list`: concatenate the lists. If the last element in a list is a * `string`, `list`, or `object`, merge it with the first element in * the next list by applying these rules recursively. * * `object`: concatenate the (field name, field value) pairs. If a * field name is duplicated, then apply these rules recursively * to merge the field values. * Some examples of merging: * # Strings are concatenated. * "foo", "bar" => "foobar" * # Lists of non-strings are concatenated. * [2, 3], [4] => [2, 3, 4] * # Lists are concatenated, but the last and first elements are merged * # because they are strings. * ["a", "b"], ["c", "d"] => ["a", "bc", "d"] * # Lists are concatenated, but the last and first elements are merged * # because they are lists. Recursively, the last and first elements * # of the inner lists are merged because they are strings. * ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] * # Non-overlapping object fields are combined. * {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} * # Overlapping object fields are merged. * {"a": "1"}, {"a": "2"} => {"a": "12"} * # Examples of merging objects containing lists of strings. * {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} * For a more complete example, suppose a streaming SQL query is * yielding a result set whose rows contain a single string * field. The following `PartialResultSet`s might be yielded: * { * "metadata": { ... } * "values": ["Hello", "W"] * "chunked_value": true * "resume_token": "Af65..." * } * { * "values": ["orl"] * "chunked_value": true * "resume_token": "Bqp2..." * } * { * "values": ["d"] * "resume_token": "Zx1B..." * } * This sequence of `PartialResultSet`s encodes two rows, one * containing the field value `"Hello"`, and a second containing the * field value `"World" = "W" + "orl" + "d"`. * * Generated from protobuf field <code>repeated .google.protobuf.Value values = 2;</code> * @return \Google\Protobuf\Internal\RepeatedField */ public function getValues() { return $this->values; } /** * A streamed result set consists of a stream of values, which might * be split into many `PartialResultSet` messages to accommodate * large rows and/or large values. Every N complete values defines a * row, where N is equal to the number of entries in * [metadata.row_type.fields][google.spanner.v1.StructType.fields]. * Most values are encoded based on type as described * [here][google.spanner.v1.TypeCode]. * It is possible that the last value in values is "chunked", * meaning that the rest of the value is sent in subsequent * `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value] * field. Two or more chunked values can be merged to form a * complete value as follows: * * `bool/number/null`: cannot be chunked * * `string`: concatenate the strings * * `list`: concatenate the lists. If the last element in a list is a * `string`, `list`, or `object`, merge it with the first element in * the next list by applying these rules recursively. * * `object`: concatenate the (field name, field value) pairs. If a * field name is duplicated, then apply these rules recursively * to merge the field values. * Some examples of merging: * # Strings are concatenated. * "foo", "bar" => "foobar" * # Lists of non-strings are concatenated. * [2, 3], [4] => [2, 3, 4] * # Lists are concatenated, but the last and first elements are merged * # because they are strings. * ["a", "b"], ["c", "d"] => ["a", "bc", "d"] * # Lists are concatenated, but the last and first elements are merged * # because they are lists. Recursively, the last and first elements * # of the inner lists are merged because they are strings. * ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] * # Non-overlapping object fields are combined. * {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} * # Overlapping object fields are merged. * {"a": "1"}, {"a": "2"} => {"a": "12"} * # Examples of merging objects containing lists of strings. * {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} * For a more complete example, suppose a streaming SQL query is * yielding a result set whose rows contain a single string * field. The following `PartialResultSet`s might be yielded: * { * "metadata": { ... } * "values": ["Hello", "W"] * "chunked_value": true * "resume_token": "Af65..." * } * { * "values": ["orl"] * "chunked_value": true * "resume_token": "Bqp2..." * } * { * "values": ["d"] * "resume_token": "Zx1B..." * } * This sequence of `PartialResultSet`s encodes two rows, one * containing the field value `"Hello"`, and a second containing the * field value `"World" = "W" + "orl" + "d"`. * * Generated from protobuf field <code>repeated .google.protobuf.Value values = 2;</code> * @param array<\Google\Protobuf\Value>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setValues($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Value::class); $this->values = $arr; return $this; } /** * If true, then the final value in [values][google.spanner.v1.PartialResultSet.values] is chunked, and must * be combined with more values from subsequent `PartialResultSet`s * to obtain a complete field value. * * Generated from protobuf field <code>bool chunked_value = 3;</code> * @return bool */ public function getChunkedValue() { return $this->chunked_value; } /** * If true, then the final value in [values][google.spanner.v1.PartialResultSet.values] is chunked, and must * be combined with more values from subsequent `PartialResultSet`s * to obtain a complete field value. * * Generated from protobuf field <code>bool chunked_value = 3;</code> * @param bool $var * @return $this */ public function setChunkedValue($var) { GPBUtil::checkBool($var); $this->chunked_value = $var; return $this; } /** * Streaming calls might be interrupted for a variety of reasons, such * as TCP connection loss. If this occurs, the stream of results can * be resumed by re-sending the original request and including * `resume_token`. Note that executing any other transaction in the * same session invalidates the token. * * Generated from protobuf field <code>bytes resume_token = 4;</code> * @return string */ public function getResumeToken() { return $this->resume_token; } /** * Streaming calls might be interrupted for a variety of reasons, such * as TCP connection loss. If this occurs, the stream of results can * be resumed by re-sending the original request and including * `resume_token`. Note that executing any other transaction in the * same session invalidates the token. * * Generated from protobuf field <code>bytes resume_token = 4;</code> * @param string $var * @return $this */ public function setResumeToken($var) { GPBUtil::checkString($var, False); $this->resume_token = $var; return $this; } /** * Query plan and execution statistics for the statement that produced this * streaming result set. These can be requested by setting * [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent * only once with the last response in the stream. * This field will also be present in the last response for DML * statements. * * Generated from protobuf field <code>.google.spanner.v1.ResultSetStats stats = 5;</code> * @return \Google\Cloud\Spanner\V1\ResultSetStats|null */ public function getStats() { return $this->stats; } public function hasStats() { return isset($this->stats); } public function clearStats() { unset($this->stats); } /** * Query plan and execution statistics for the statement that produced this * streaming result set. These can be requested by setting * [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent * only once with the last response in the stream. * This field will also be present in the last response for DML * statements. * * Generated from protobuf field <code>.google.spanner.v1.ResultSetStats stats = 5;</code> * @param \Google\Cloud\Spanner\V1\ResultSetStats $var * @return $this */ public function setStats($var) { GPBUtil::checkMessage($var, \Google\Cloud\Spanner\V1\ResultSetStats::class); $this->stats = $var; return $this; } }
{'content_hash': 'ea388ba10f852886b783a147669186e2', 'timestamp': '', 'source': 'github', 'line_count': 505, 'max_line_length': 128, 'avg_line_length': 44.59405940594059, 'alnum_prop': 0.5853907637655418, 'repo_name': 'googleapis/google-cloud-php', 'id': 'e85ac14eb057b63020dc5b668585e75a8a5051ed', 'size': '22520', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'Spanner/src/V1/PartialResultSet.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '3333'}, {'name': 'PHP', 'bytes': '47981731'}, {'name': 'Python', 'bytes': '413107'}, {'name': 'Shell', 'bytes': '8171'}]}
namespace asio { namespace detail { namespace io_control { // I/O control command for getting number of bytes available. class bytes_readable { public: // Default constructor. bytes_readable() : value_(0) { } // Construct with a specific command value. bytes_readable(std::size_t value) : value_(static_cast<detail::ioctl_arg_type>(value)) { } // Get the name of the IO control command. int name() const { return static_cast<int>(ASIO_OS_DEF(FIONREAD)); } // Set the value of the I/O control command. void set(std::size_t value) { value_ = static_cast<detail::ioctl_arg_type>(value); } // Get the current value of the I/O control command. std::size_t get() const { return static_cast<std::size_t>(value_); } // Get the address of the command data. detail::ioctl_arg_type* data() { return &value_; } // Get the address of the command data. const detail::ioctl_arg_type* data() const { return &value_; } private: detail::ioctl_arg_type value_; }; } // namespace io_control } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_IO_CONTROL_HPP
{'content_hash': '0b24aacb3768595fe05e592bf22021af', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 61, 'avg_line_length': 19.442622950819672, 'alnum_prop': 0.6517706576728499, 'repo_name': 'sherry0319/YTSvrLib', 'id': '12f35e096fbc81514c57fd18abe7527c3beb2df9', 'size': '1796', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'src/asio/asio/detail/io_control.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5346280'}, {'name': 'C++', 'bytes': '20010804'}, {'name': 'CMake', 'bytes': '3579'}, {'name': 'M4', 'bytes': '1830'}, {'name': 'Makefile', 'bytes': '1280'}, {'name': 'Objective-C', 'bytes': '406560'}, {'name': 'Pascal', 'bytes': '94273'}, {'name': 'Pawn', 'bytes': '5898'}, {'name': 'Python', 'bytes': '1292'}, {'name': 'Shell', 'bytes': '9452'}]}
package net.glowstone.net.handler.status; import com.flowpowered.network.MessageHandler; import net.glowstone.net.GlowSession; import net.glowstone.net.message.status.StatusPingMessage; public final class StatusPingHandler implements MessageHandler<GlowSession, StatusPingMessage> { @Override public void handle(GlowSession session, StatusPingMessage message) { session.send(message); } }
{'content_hash': '4102675556cb93ee56ad75649dd56577', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 96, 'avg_line_length': 31.692307692307693, 'alnum_prop': 0.7961165048543689, 'repo_name': 'GreenBeard/GlowstonePlusPlus', 'id': '33e694d380343541579c5a0127e32ae5ad5f962d', 'size': '412', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/main/java/net/glowstone/net/handler/status/StatusPingHandler.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2375948'}, {'name': 'Python', 'bytes': '1031'}, {'name': 'Ruby', 'bytes': '335'}, {'name': 'Shell', 'bytes': '2214'}]}
using Akka.Actor; using NUnit.Framework; using Akka.TestKit.NUnit; namespace TestKitSample.Examples { public class ChildActor : ReceiveActor { public ChildActor() { ReceiveAny(o => Sender.Tell("hello!")); } } public class ParentActor : ReceiveActor { public ParentActor() { var child = Context.ActorOf(Props.Create(() => new ChildActor())); ReceiveAny(o => child.Forward(o)); } } [TestFixture] public class ParentGreeterSpecs : TestKit { [Test] public void Parent_should_create_child() { // verify child has been created by sending parent a message // that is forwarded to child, and which child replies to sender with var parentProps = Props.Create(() => new ParentActor()); var parent = ActorOfAsTestActorRef<ParentActor>(parentProps, TestActor); parent.Tell("this should be forwarded to the child"); ExpectMsg("hello!"); } } }
{'content_hash': 'd59cfd0b762a6b38da8b18f07234c239', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 84, 'avg_line_length': 26.6, 'alnum_prop': 0.5836466165413534, 'repo_name': 'skotzko/akkadotnet-code-samples', 'id': 'd850cf66c72065a2eee427990b8701cd88a02fab', 'size': '1066', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'TestKit/src/Examples/ParentChild.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '105'}, {'name': 'C#', 'bytes': '183309'}, {'name': 'CSS', 'bytes': '513'}, {'name': 'HTML', 'bytes': '5125'}, {'name': 'JavaScript', 'bytes': '137645'}]}
describe Snapshot do describe Snapshot::DetectValues do describe "value coercion" do it "coerces only_testing to be an array", requires_xcodebuild: true do options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", only_testing: "Bundle/SuiteA" } Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options) expect(Snapshot.config[:only_testing]).to eq(["Bundle/SuiteA"]) end it "coerces skip_testing to be an array", requires_xcodebuild: true do options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", skip_testing: "Bundle/SuiteA,Bundle/SuiteB" } Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options) expect(Snapshot.config[:skip_testing]).to eq(["Bundle/SuiteA", "Bundle/SuiteB"]) end it "leaves skip_testing as an array", requires_xcodebuild: true do options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", skip_testing: ["Bundle/SuiteA", "Bundle/SuiteB"] } Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options) expect(Snapshot.config[:skip_testing]).to eq(["Bundle/SuiteA", "Bundle/SuiteB"]) end end end end
{'content_hash': 'bdf4647921e8eaf07f8ed67ac801e7f0', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 106, 'avg_line_length': 42.42857142857143, 'alnum_prop': 0.6417508417508417, 'repo_name': 'Econa77/fastlane', 'id': '540fa2ccb69323e3a47902f7e9bad989f5f04a0a', 'size': '1485', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'snapshot/spec/detect_values_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '41354'}, {'name': 'Java', 'bytes': '30333'}, {'name': 'JavaScript', 'bytes': '39'}, {'name': 'Matlab', 'bytes': '115'}, {'name': 'Objective-C', 'bytes': '69198'}, {'name': 'Ruby', 'bytes': '3199650'}, {'name': 'Shell', 'bytes': '44177'}, {'name': 'Swift', 'bytes': '11128'}]}
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.action; //~--- non-JDK imports -------------------------------------------------------- import org.apache.commons.math3.stat.StatUtils; import org.broad.igv.logging.*; import org.broad.igv.prefs.Constants; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.track.Track; import org.broad.igv.ui.IGV; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List; /** * @author jrobinso */ public class SetTrackHeightMenuAction extends MenuAction { IGV igv; static Logger log = LogManager.getLogger(SetTrackHeightMenuAction.class); static int lastTrackHeight = -1; /** * Constructs ... * * @param label * @param mnemonic * @param igv */ public SetTrackHeightMenuAction(String label, int mnemonic, IGV igv) { super(label, null, mnemonic); this.igv = igv; } /** * Method description * * @param e */ @Override public void actionPerformed(ActionEvent e) { doSetTrackHeight(); } /** * Method description */ final public void doSetTrackHeight() { boolean repaint = false; try { JPanel container = new JPanel(); JLabel trackHeightLabel = new JLabel("Track Height (pixels)"); JTextField trackHeightField = new JTextField(); Dimension preferredSize = trackHeightField.getPreferredSize(); trackHeightField.setPreferredSize(new Dimension(50, (int) preferredSize.getHeight())); container.add(trackHeightLabel); container.add(trackHeightField); int repTrackHeight = getRepresentativeTrackHeight(); trackHeightField.setText(String.valueOf(repTrackHeight)); int status = JOptionPane.showConfirmDialog(igv.getMainFrame(), container, "Set Track Height", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null); if ((status == JOptionPane.CANCEL_OPTION) || (status == JOptionPane.CLOSED_OPTION)) { return; } try { int newTrackHeight = Integer.parseInt(trackHeightField.getText().trim()); IGV.getInstance().setAllTrackHeights(newTrackHeight); lastTrackHeight = newTrackHeight; repaint = true; } catch (NumberFormatException numberFormatException) { JOptionPane.showMessageDialog(igv.getMainFrame(), "Track height must be an integer number."); } } finally { // Refresh view if (repaint) { // Update the state of the current tracks for drawing purposes igv.repaint(); } igv.resetStatusMessage(); } } /** * Return a representative track height to use as the default. For now * using the median track height. * * @return */ private int getRepresentativeTrackHeight() { if (lastTrackHeight > 0) { return lastTrackHeight; } // Get all tracks except the gene track List<Track> tracks = IGV.getInstance().getAllTracks(); double[] heights = new double[tracks.size()]; for (int i = 0; i < tracks.size(); i++) { heights[i] = tracks.get(i).getHeight(); } int medianTrackHeight = (int) Math.round(StatUtils.percentile(heights, 50)); if (medianTrackHeight > 0) { return medianTrackHeight; } return PreferencesManager.getPreferences().getAsInt(Constants.INITIAL_TRACK_HEIGHT); } }
{'content_hash': 'b589be72cb52b936f7bf2afcedd4ecae', 'timestamp': '', 'source': 'github', 'line_count': 135, 'max_line_length': 109, 'avg_line_length': 28.037037037037038, 'alnum_prop': 0.5970937912813739, 'repo_name': 'amwenger/igv', 'id': '2cb0b176f254012e72b32642da514395107245fe', 'size': '4940', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/broad/igv/ui/action/SetTrackHeightMenuAction.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AngelScript', 'bytes': '1671'}, {'name': 'Batchfile', 'bytes': '3391'}, {'name': 'HTML', 'bytes': '33601'}, {'name': 'Java', 'bytes': '6987237'}, {'name': 'JavaScript', 'bytes': '2514'}, {'name': 'NSIS', 'bytes': '1552'}, {'name': 'Ruby', 'bytes': '93'}, {'name': 'Shell', 'bytes': '9118'}]}
package com.foreveross.common.shiro; import com.foreveross.common.ConstantBean; import com.foreveross.common.ResultBean; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.web.servlet.AdviceFilter; import org.iff.infra.util.Exceptions; import org.iff.infra.util.FCS; import org.iff.infra.util.HttpHelper; import org.iff.infra.util.StringHelper; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Shiro IP验证过滤器 * * @author <a href="mailto:[email protected]">Tyler Chen</a> * @since Aug 11, 2016 */ public class ShiroIpAccessControlFilter extends AdviceFilter implements OnceValidAdvice { private static final org.iff.infra.util.Logger.Log Logger = org.iff.infra.util.Logger.get("FOSS.SHIRO"); private String accessIp = null; private String[] ips = null; public boolean preHandle(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; //String url = StringUtils.removeStart(request.getRequestURI(), request.getContextPath()); //是否为OnceValidAdvice。 boolean isOnceValidAdvice = Boolean.TRUE.equals(request.getAttribute(OnceValidAdvice.REQUEST_MARK)); String ip = HttpHelper.getRemoteIpAddr(request); {/*check the match list.*/ if (accessIp == null) { accessIp = ConstantBean.getProperty("access.ip", "").trim(); } if (accessIp.length() < 1) { return false; } if (ips == null) { ips = StringUtils.split(accessIp, ','); } for (String aip : ips) { if (aip.indexOf('*') < 0 && aip.equals(ip)) { Logger.debug(FCS.get("Shiro ip auth success, ip: {0}", ip)); return true; } else if (StringHelper.wildCardMatch(ip, aip.trim())) { Logger.debug(FCS.get("Shiro ip auth success, ip: {0}", ip)); return true; } } } ShiroHelper.retrun401(request, response, ResultBean.error().setBody("Unauthorized")); if (isOnceValidAdvice) { Exceptions.runtime("Shiro not permit, end OnceValidAdvice chain.", "FOSS-SHIRO-0100"); } return false; } protected void cleanup(ServletRequest request, ServletResponse response, Exception existing) throws ServletException, IOException { super.cleanup(request, response, existing); } }
{'content_hash': '32330190ed7d7ab674160cfae22735a2', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 111, 'avg_line_length': 37.46666666666667, 'alnum_prop': 0.6551601423487544, 'repo_name': 'tylerchen/foss-qdp-project-v4', 'id': '8eeb9687c6c584ecd3066c3a57c31cb9229074a6', 'size': '3212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/foreveross/common/shiro/ShiroIpAccessControlFilter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '107609'}, {'name': 'Groovy', 'bytes': '63323'}, {'name': 'HTML', 'bytes': '757146'}, {'name': 'Java', 'bytes': '1477473'}, {'name': 'JavaScript', 'bytes': '2262139'}, {'name': 'Shell', 'bytes': '9222'}]}
> By submitting this pull request, you agree to the [contribution guidelines](https://github.com/pnp/sp-dev-fx-webparts/blob/main/CONTRIBUTING.md) > If you aren't familiar with how to contribute to open-source repositories using GitHub, or if you find the instructions on this page confusing, [sign up](https://forms.office.com/Pages/ResponsePage.aspx?id=KtIy2vgLW0SOgZbwvQuRaXDXyCl9DkBHq4A2OG7uLpdUREZVRDVYUUJLT1VNRDM4SjhGMlpUNzBORy4u) for one of our [Sharing is Caring](https://pnp.github.io/sharing-is-caring/#pnp-sic-events) events. It's completely free, and we'll guide you through the process. > To submit a pull request with multiple authors, make sure that at least one commit is a co-authored commit by adding a `Co-authored-by:` trailer to the commit's message. E.g.: `Co-authored-by: name <[email protected]>` | Q | A | | --------------- | --------------------------------------- | | Bug fix? | no - yes? | | New feature? | no - yes? | | New sample? | no - yes? | | Related issues? | fixes #X, partially #Y, mentioned in #Z | ## What's in this Pull Request? > Please describe the changes in this PR. Sample description or details around bugs which are being fixed. > > _(DELETE THIS PARAGRAPH AFTER READING)_ ## Submitter Guidance (DELETE AFTER READING) > > *Please update this PR information accordingly. We'll use this as part of our release notes in monthly communications.* > > *Pull requests that do not follow this template will be automatically rejected.* > > *Please target your PR to `main` branch.* > > *Remember that this repository is maintained by community members who volunteer their time to help. Be courteous and patient.* > _(DELETE THIS SECTION AFTER READING)_
{'content_hash': 'e14d0df084e675c7e2eb2e823ce3311e', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 452, 'avg_line_length': 59.903225806451616, 'alnum_prop': 0.6639741518578353, 'repo_name': 'AJIXuMuK/sp-dev-fx-webparts', 'id': '72bd99ac685cda366f780cff8f05fbe720a0a2cd', 'size': '1857', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.github/PULL_REQUEST_TEMPLATE.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '25678'}, {'name': 'SCSS', 'bytes': '19855'}, {'name': 'Shell', 'bytes': '2153'}, {'name': 'TypeScript', 'bytes': '56170'}]}
package batfish.grammar.juniper.firewall; public class ThenTFFStanza { private ThenTFFType _type; public ThenTFFStanza(ThenTFFType t) { _type = t; } public ThenTFFType getType() { return _type; } }
{'content_hash': '3e5bca9dfbbc3e56972e7090d198849f', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 41, 'avg_line_length': 16.153846153846153, 'alnum_prop': 0.7238095238095238, 'repo_name': 'andrenmaia/batfish', 'id': 'fee188decc9da6106cf93acbcc1b2c93dc405c1c', 'size': '210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'projects/batfish/src/batfish/grammar/juniper/firewall/ThenTFFStanza.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '95578'}, {'name': 'GAP', 'bytes': '124516'}, {'name': 'Java', 'bytes': '929538'}, {'name': 'Shell', 'bytes': '1087'}]}
package com.planet_ink.coffee_mud.Abilities.interfaces; import java.lang.reflect.Method; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; /** * DiseaseAffect is an ability interface to denote those properties, * affects, or Disease objects that act as curable physical diseases. */ public interface DiseaseAffect extends HealthCondition { /** denotes a diseases spread by sex with someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_STD=1; /** denotes a diseases spread by touching or making contact with someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_CONTACT=2; /** denotes a diseases spread by being in the same room as someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_PROXIMITY=4; /** denotes a diseases spread by eating the remains of someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_CONSUMPTION=8; /** denotes a diseases spread by taking physical damage from someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_DAMAGE=16; /** denotes a diseases spread by touching or making contact with someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_GET=32; /** denotes a diseases spread by hearing someone who is infected. @see Ability#abilityCode() */ public final static int SPREAD_HEARING=64; /** * Descriptions of the SPREAD_ constants */ public final static String[] SPREAD_DESCS = { "sexual contact", "direct contact", "proximity", "ingestion", "blood contact", "picking up", "hearing" }; /** * This method returns the level from 0-9 of how difficult it * is to cure this disease through mundane or magical means. * 9 is considered more difficult. * * @return the curing difficulty level 0-9 */ public int difficultyLevel(); /** * This method returns a bitmap constant denoting how the * disease is spread. * @see DiseaseAffect#SPREAD_CONSUMPTION * @return the bitmap denoting how spread */ public int spreadBitmap(); /** * This method returns whether this disease, specifically it's spreading, * is a malicious act. Usually that's a NO, but sometimes... * @return true if its malicious, false otherwise */ public boolean isMalicious(); }
{'content_hash': '3240c4b3db3df12372e6e616cbdf6582', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 120, 'avg_line_length': 40.65384615384615, 'alnum_prop': 0.7325764742983286, 'repo_name': 'bozimmerman/CoffeeMud', 'id': '87c659a50825865c054ef1911dce40a87fd17027', 'size': '3775', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'com/planet_ink/coffee_mud/Abilities/interfaces/DiseaseAffect.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5847'}, {'name': 'CSS', 'bytes': '1619'}, {'name': 'HTML', 'bytes': '12319179'}, {'name': 'Java', 'bytes': '38979811'}, {'name': 'JavaScript', 'bytes': '45220'}, {'name': 'Makefile', 'bytes': '23191'}, {'name': 'Shell', 'bytes': '8783'}]}
<?php /** * @file * Definition of Drupal\user\Tests\UserAccountLinksTests. */ namespace Drupal\user\Tests; use Drupal\Core\Menu\MenuTreeParameters; use Drupal\simpletest\WebTestBase; /** * Tests user-account links. * * @group user */ class UserAccountLinksTests extends WebTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('menu_ui', 'block', 'test_page_test'); /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->drupalPlaceBlock('system_menu_block:account'); // Make test-page default. \Drupal::config('system.site')->set('page.front', 'test-page')->save(); } /** * Tests the secondary menu. */ function testSecondaryMenu() { // Create a regular user. $user = $this->drupalCreateUser(array()); // Log in and get the homepage. $this->drupalLogin($user); $this->drupalGet('<front>'); // For a logged-in user, expect the secondary menu to have links for "My // account" and "Log out". $link = $this->xpath('//ul[@class=:menu_class]/li/a[contains(@href, :href) and text()=:text]', array( ':menu_class' => 'menu', ':href' => 'user', ':text' => 'My account', )); $this->assertEqual(count($link), 1, 'My account link is in secondary menu.'); $link = $this->xpath('//ul[@class=:menu_class]/li/a[contains(@href, :href) and text()=:text]', array( ':menu_class' => 'menu', ':href' => 'user/logout', ':text' => 'Log out', )); $this->assertEqual(count($link), 1, 'Log out link is in secondary menu.'); // Log out and get the homepage. $this->drupalLogout(); $this->drupalGet('<front>'); // For a logged-out user, expect no secondary links. $menu_tree = \Drupal::menuTree(); $tree = $menu_tree->load('account', new MenuTreeParameters()); $manipulators = array( array('callable' => 'menu.default_tree_manipulators:checkAccess'), ); $tree = $menu_tree->transform($tree, $manipulators); $this->assertEqual(count($tree), 0, 'The secondary links menu contains no menu link.'); } /** * Tests disabling the 'My account' link. */ function testDisabledAccountLink() { // Create an admin user and log in. $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer menu'))); // Verify that the 'My account' link exists before we check for its // disappearance. $link = $this->xpath('//ul[@class=:menu_class]/li/a[contains(@href, :href) and text()=:text]', array( ':menu_class' => 'menu', ':href' => 'user', ':text' => 'My account', )); $this->assertEqual(count($link), 1, 'My account link is in the secondary menu.'); // Verify that the 'My account' link is enabled. Do not assume the value of // auto-increment is 1. Use XPath to obtain input element id and name using // the consistent label text. $this->drupalGet('admin/structure/menu/manage/account'); $label = $this->xpath('//label[contains(.,:text)]/@for', array(':text' => 'Enable My account menu link')); $this->assertFieldChecked((string) $label[0], "The 'My account' link is enabled by default."); // Disable the 'My account' link. $edit['links[menu_plugin_id:user.page][enabled]'] = FALSE; $this->drupalPostForm('admin/structure/menu/manage/account', $edit, t('Save')); // Get the homepage. $this->drupalGet('<front>'); // Verify that the 'My account' link does not appear when disabled. $link = $this->xpath('//ul[@class=:menu_class]/li/a[contains(@href, :href) and text()=:text]', array( ':menu_class' => 'menu', ':href' => 'user', ':text' => 'My account', )); $this->assertEqual(count($link), 0, 'My account link is not in the secondary menu.'); } /** * Tests page title is set correctly on user account tabs. */ function testAccountPageTitles() { // Default page titles are suffixed with the site name - Drupal. $title_suffix = ' | Drupal'; $this->drupalGet('user'); $this->assertTitle('Log in' . $title_suffix, "Page title of /user is 'Log in'"); $this->drupalGet('user/login'); $this->assertTitle('Log in' . $title_suffix, "Page title of /user/login is 'Log in'"); $this->drupalGet('user/register'); $this->assertTitle('Create new account' . $title_suffix, "Page title of /user/register is 'Create new account' for anonymous users."); $this->drupalGet('user/password'); $this->assertTitle('Request new password' . $title_suffix, "Page title of /user/register is 'Request new password' for anonymous users."); // Check the page title for registered users is "My Account" in menus. $this->drupalLogin($this->drupalCreateUser()); // After login, the client is redirected to /user. $this->assertLink(t('My account'), 0, "Page title of /user is 'My Account' in menus for registered users"); $this->assertLinkByHref(\Drupal::urlGenerator()->generate('user.page'), 0); } }
{'content_hash': '90f97fcd6b0d2fc6ae235298d15d15a4', 'timestamp': '', 'source': 'github', 'line_count': 143, 'max_line_length': 142, 'avg_line_length': 35.19580419580419, 'alnum_prop': 0.6278561494138685, 'repo_name': 'ital-lion/Drupal4Lions', 'id': 'cc85a864423a0c2948621e79523a3eceb4f89a83', 'size': '5033', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'core/modules/user/src/Tests/UserAccountLinksTests.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '280823'}, {'name': 'JavaScript', 'bytes': '742500'}, {'name': 'PHP', 'bytes': '20371861'}, {'name': 'Shell', 'bytes': '70992'}]}
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** SQL Parser Functions for phpMyAdmin * * These functions define an SQL parser system, capable of understanding and * extracting data from a MySQL type SQL query. * * The basic procedure for using the new SQL parser: * On any page that needs to extract data from a query or to pretty-print a * query, you need code like this up at the top: * * ($sql contains the query) * $parsed_sql = PMA_SQP_parse($sql); * * If you want to extract data from it then, you just need to run * $sql_info = PMA_SQP_analyze($parsed_sql); * * See comments in PMA_SQP_analyze for the returned info * from the analyzer. * * If you want a pretty-printed version of the query, do: * $string = PMA_SQP_formatHtml($parsed_sql); * (note that that you need to have syntax.css.php included somehow in your * page for it to work, I recommend '<link rel="stylesheet" type="text/css" * href="syntax.css.php" />' at the moment.) * * @package PhpMyAdmin */ if (! defined('PHPMYADMIN')) { exit; } /** * Minimum inclusion? (i.e. for the stylesheet builder) */ if (! defined('PMA_MINIMUM_COMMON')) { /** * Include the string library as we use it heavily */ include_once './libraries/string.lib.php'; /** * Include data for the SQL Parser */ include_once './libraries/sqlparser.data.php'; if (!defined('TESTSUITE')) { include_once './libraries/mysql_charsets.lib.php'; } if (! isset($mysql_charsets)) { $mysql_charsets = array(); $mysql_collations_flat = array(); } if (!defined('DEBUG_TIMING')) { /** * currently we don't need the $pos (token position in query) * for other purposes than LIMIT clause verification, * so many calls to this function do not include the 4th parameter */ function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0) { $arr[] = array('type' => $type, 'data' => $data, 'pos' => $pos); $arrsize++; } // end of the "PMA_SQP_arrayAdd()" function } else { /** * This is debug variant of above. * @ignore */ function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0) { global $timer; $t = $timer; $arr[] = array( 'type' => $type, 'data' => $data, 'pos' => $pos, 'time' => $t); $timer = microtime(); $arrsize++; } // end of the "PMA_SQP_arrayAdd()" function } // end if... else... /** * Reset the error variable for the SQL parser * * @access public */ function PMA_SQP_resetError() { global $SQP_errorString; $SQP_errorString = ''; unset($SQP_errorString); } /** * Get the contents of the error variable for the SQL parser * * @return string Error string from SQL parser * * @access public */ function PMA_SQP_getErrorString() { global $SQP_errorString; return isset($SQP_errorString) ? $SQP_errorString : ''; } /** * Check if the SQL parser hit an error * * @return boolean error state * * @access public */ function PMA_SQP_isError() { global $SQP_errorString; return isset($SQP_errorString) && !empty($SQP_errorString); } /** * Set an error message for the system * * @param string The error message * @param string The failing SQL query * * @access private * @scope SQL Parser internal */ function PMA_SQP_throwError($message, $sql) { global $SQP_errorString; $SQP_errorString = '<p>'.__('There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem') . '</p>' . "\n" . '<pre>' . "\n" . 'ERROR: ' . $message . "\n" . 'SQL: ' . htmlspecialchars($sql) . "\n" . '</pre>' . "\n"; } // end of the "PMA_SQP_throwError()" function /** * Do display the bug report * * @param string The error message * @param string The failing SQL query * * @access public */ function PMA_SQP_bug($message, $sql) { global $SQP_errorString; $debugstr = 'ERROR: ' . $message . "\n"; $debugstr .= 'MySQL: '.PMA_MYSQL_STR_VERSION . "\n"; $debugstr .= 'USR OS, AGENT, VER: ' . PMA_USR_OS . ' '; $debugstr .= PMA_USR_BROWSER_AGENT . ' ' . PMA_USR_BROWSER_VER . "\n"; $debugstr .= 'PMA: ' . PMA_VERSION . "\n"; $debugstr .= 'PHP VER,OS: ' . PMA_PHP_STR_VERSION . ' ' . PHP_OS . "\n"; $debugstr .= 'LANG: ' . $GLOBALS['lang'] . "\n"; $debugstr .= 'SQL: ' . htmlspecialchars($sql); $encodedstr = $debugstr; if (@function_exists('gzcompress')) { $encodedstr = gzcompress($debugstr, 9); } $encodedstr = preg_replace( "/(\015\012)|(\015)|(\012)/", '<br />' . "\n", chunk_split(base64_encode($encodedstr))); $SQP_errorString .= __('There is a chance that you may have found a bug in the SQL parser. Please examine your query closely, and check that the quotes are correct and not mis-matched. Other possible failure causes may be that you are uploading a file with binary outside of a quoted text area. You can also try your query on the MySQL command line interface. The MySQL server error output below, if there is any, may also help you in diagnosing the problem. If you still have problems or if the parser fails where the command line interface succeeds, please reduce your SQL query input to the single query that causes problems, and submit a bug report with the data chunk in the CUT section below:') . '<br />' . "\n" . '----' . __('BEGIN CUT') . '----' . '<br />' . "\n" . $encodedstr . "\n" . '----' . __('END CUT') . '----' . '<br />' . "\n"; $SQP_errorString .= '----' . __('BEGIN RAW') . '----<br />' . "\n" . '<pre>' . "\n" . $debugstr . '</pre>' . "\n" . '----' . __('END RAW') . '----<br />' . "\n"; } // end of the "PMA_SQP_bug()" function /** * Parses the SQL queries * * @param string The SQL query list * * @return mixed Most of times, nothing... * * @global array The current PMA configuration * @global array MySQL column attributes * @global array MySQL reserved words * @global array MySQL column types * @global array MySQL function names * @global array List of available character sets * @global array List of available collations * * @access public */ function PMA_SQP_parse($sql) { static $PMA_SQPdata_column_attrib, $PMA_SQPdata_reserved_word; static $PMA_SQPdata_column_type; static $PMA_SQPdata_function_name, $PMA_SQPdata_forbidden_word; global $mysql_charsets, $mysql_collations_flat; // Convert all line feeds to Unix style $sql = str_replace("\r\n", "\n", $sql); $sql = str_replace("\r", "\n", $sql); $len = PMA_strlen($sql); if ($len == 0) { return array(); } // Create local hashtables if (!isset($PMA_SQPdata_column_attrib)) { $PMA_SQPdata_column_attrib = array_flip( $GLOBALS['PMA_SQPdata_column_attrib'] ); $PMA_SQPdata_function_name = array_flip( $GLOBALS['PMA_SQPdata_function_name'] ); $PMA_SQPdata_reserved_word = array_flip( $GLOBALS['PMA_SQPdata_reserved_word'] ); $PMA_SQPdata_forbidden_word = array_flip( $GLOBALS['PMA_SQPdata_forbidden_word'] ); $PMA_SQPdata_column_type = array_flip( $GLOBALS['PMA_SQPdata_column_type'] ); } $sql_array = array(); $sql_array['raw'] = $sql; $count1 = 0; $count2 = 0; $punct_queryend = ';'; $punct_qualifier = '.'; $punct_listsep = ','; $punct_level_plus = '('; $punct_level_minus = ')'; $punct_user = '@'; $digit_floatdecimal = '.'; $digit_hexset = 'x'; $bracket_list = '()[]{}'; $allpunct_list = '-,;:!?/.^~\*&%+<=>|'; $allpunct_list_pair = array( '!=' => 1, '&&' => 1, ':=' => 1, '<<' => 1, '<=' => 1, '<=>' => 1, '<>' => 1, '>=' => 1, '>>' => 1, '||' => 1, '==' => 1 ); $quote_list = '\'"`'; $arraysize = 0; $previous_was_space = false; $this_was_space = false; $previous_was_bracket = false; $this_was_bracket = false; $previous_was_punct = false; $this_was_punct = false; $previous_was_listsep = false; $this_was_listsep = false; $previous_was_quote = false; $this_was_quote = false; while ($count2 < $len) { $c = PMA_substr($sql, $count2, 1); $count1 = $count2; $previous_was_space = $this_was_space; $this_was_space = false; $previous_was_bracket = $this_was_bracket; $this_was_bracket = false; $previous_was_punct = $this_was_punct; $this_was_punct = false; $previous_was_listsep = $this_was_listsep; $this_was_listsep = false; $previous_was_quote = $this_was_quote; $this_was_quote = false; if (($c == "\n")) { $this_was_space = true; $count2++; PMA_SQP_arrayAdd($sql_array, 'white_newline', '', $arraysize); continue; } // Checks for white space if (PMA_STR_isSpace($c)) { $this_was_space = true; $count2++; continue; } // Checks for comment lines. // MySQL style # // C style /* */ // ANSI style -- $next_c = PMA_substr($sql, $count2 + 1, 1); if (($c == '#') || (($count2 + 1 < $len) && ($c == '/') && ($next_c == '*')) || (($count2 + 2 == $len) && ($c == '-') && ($next_c == '-')) || (($count2 + 2 < $len) && ($c == '-') && ($next_c == '-') && ((PMA_substr($sql, $count2 + 2, 1) <= ' ')))) { $count2++; $pos = 0; $type = 'bad'; switch ($c) { case '#': $type = 'mysql'; case '-': $type = 'ansi'; $pos = PMA_strpos($sql, "\n", $count2); break; case '/': $type = 'c'; $pos = PMA_strpos($sql, '*/', $count2); $pos += 2; break; default: break; } // end switch $count2 = ($pos < $count2) ? $len : $pos; $str = PMA_substr($sql, $count1, $count2 - $count1); PMA_SQP_arrayAdd($sql_array, 'comment_' . $type, $str, $arraysize); continue; } // end if // Checks for something inside quotation marks if (PMA_strpos($quote_list, $c) !== false) { $startquotepos = $count2; $quotetype = $c; $count2++; $escaped = false; $pos = $count2; $oldpos = 0; do { $oldpos = $pos; $pos = PMA_strpos(' ' . $sql, $quotetype, $oldpos + 1) - 1; // ($pos === false) if ($pos < 0) { if ($c == '`') { /* * Behave same as MySQL and accept end of query as end of backtick. * I know this is sick, but MySQL behaves like this: * * SELECT * FROM `table * * is treated like * * SELECT * FROM `table` */ $pos_quote_separator = PMA_strpos(' ' . $sql, $GLOBALS['sql_delimiter'], $oldpos + 1) - 1; if ($pos_quote_separator < 0) { $len += 1; $sql .= '`'; $sql_array['raw'] .= '`'; $pos = $len; } else { $len += 1; $sql = PMA_substr($sql, 0, $pos_quote_separator) . '`' . PMA_substr($sql, $pos_quote_separator); $sql_array['raw'] = $sql; $pos = $pos_quote_separator; } if (class_exists('PMA_Message') && $GLOBALS['is_ajax_request'] != true) { PMA_Message::notice(__('Automatically appended backtick to the end of query!'))->display(); } } else { $debugstr = __('Unclosed quote') . ' @ ' . $startquotepos. "\n" . 'STR: ' . htmlspecialchars($quotetype); PMA_SQP_throwError($debugstr, $sql); return $sql_array; } } // If the quote is the first character, it can't be // escaped, so don't do the rest of the code if ($pos == 0) { break; } // Checks for MySQL escaping using a \ // And checks for ANSI escaping using the $quotetype character if (($pos < $len) && PMA_STR_charIsEscaped($sql, $pos) && $c != '`') { $pos ++; continue; } elseif (($pos + 1 < $len) && (PMA_substr($sql, $pos, 1) == $quotetype) && (PMA_substr($sql, $pos + 1, 1) == $quotetype)) { $pos = $pos + 2; continue; } else { break; } } while ($len > $pos); // end do $count2 = $pos; $count2++; $type = 'quote_'; switch ($quotetype) { case '\'': $type .= 'single'; $this_was_quote = true; break; case '"': $type .= 'double'; $this_was_quote = true; break; case '`': $type .= 'backtick'; $this_was_quote = true; break; default: break; } // end switch $data = PMA_substr($sql, $count1, $count2 - $count1); PMA_SQP_arrayAdd($sql_array, $type, $data, $arraysize); continue; } // Checks for brackets if (PMA_strpos($bracket_list, $c) !== false) { // All bracket tokens are only one item long $this_was_bracket = true; $count2++; $type_type = ''; if (PMA_strpos('([{', $c) !== false) { $type_type = 'open'; } else { $type_type = 'close'; } $type_style = ''; if (PMA_strpos('()', $c) !== false) { $type_style = 'round'; } elseif (PMA_strpos('[]', $c) !== false) { $type_style = 'square'; } else { $type_style = 'curly'; } $type = 'punct_bracket_' . $type_type . '_' . $type_style; PMA_SQP_arrayAdd($sql_array, $type, $c, $arraysize); continue; } /* DEBUG echo '<pre>1'; var_dump(PMA_STR_isSqlIdentifier($c, false)); var_dump($c == '@'); var_dump($c == '.'); var_dump(PMA_STR_isDigit(PMA_substr($sql, $count2 + 1, 1))); var_dump($previous_was_space); var_dump($previous_was_bracket); var_dump($previous_was_listsep); echo '</pre>'; */ // Checks for identifier (alpha or numeric) if (PMA_STR_isSqlIdentifier($c, false) || $c == '@' || ($c == '.' && PMA_STR_isDigit(PMA_substr($sql, $count2 + 1, 1)) && ($previous_was_space || $previous_was_bracket || $previous_was_listsep))) { /* DEBUG echo PMA_substr($sql, $count2); echo '<hr />'; */ $count2++; /** * @todo a @ can also be present in expressions like * FROM 'user'@'%' or TO 'user'@'%' * in this case, the @ is wrongly marked as alpha_variable */ $is_identifier = $previous_was_punct; $is_sql_variable = $c == '@' && ! $previous_was_quote; $is_user = $c == '@' && $previous_was_quote; $is_digit = !$is_identifier && !$is_sql_variable && PMA_STR_isDigit($c); $is_hex_digit = $is_digit && $c == '0' && $count2 < $len && PMA_substr($sql, $count2, 1) == 'x'; $is_float_digit = $c == '.'; $is_float_digit_exponent = false; /* DEBUG echo '<pre>2'; var_dump($is_identifier); var_dump($is_sql_variable); var_dump($is_digit); var_dump($is_float_digit); echo '</pre>'; */ // Fast skip is especially needed for huge BLOB data if ($is_hex_digit) { $count2++; $pos = strspn($sql, '0123456789abcdefABCDEF', $count2); if ($pos > $count2) { $count2 = $pos; } unset($pos); } elseif ($is_digit) { $pos = strspn($sql, '0123456789', $count2); if ($pos > $count2) { $count2 = $pos; } unset($pos); } while (($count2 < $len) && PMA_STR_isSqlIdentifier(PMA_substr($sql, $count2, 1), ($is_sql_variable || $is_digit))) { $c2 = PMA_substr($sql, $count2, 1); if ($is_sql_variable && ($c2 == '.')) { $count2++; continue; } if ($is_digit && (!$is_hex_digit) && ($c2 == '.')) { $count2++; if (!$is_float_digit) { $is_float_digit = true; continue; } else { $debugstr = __('Invalid Identifer') . ' @ ' . ($count1+1) . "\n" . 'STR: ' . htmlspecialchars(PMA_substr($sql, $count1, $count2 - $count1)); PMA_SQP_throwError($debugstr, $sql); return $sql_array; } } if ($is_digit && (!$is_hex_digit) && (($c2 == 'e') || ($c2 == 'E'))) { if (!$is_float_digit_exponent) { $is_float_digit_exponent = true; $is_float_digit = true; $count2++; continue; } else { $is_digit = false; $is_float_digit = false; } } if (($is_hex_digit && PMA_STR_isHexDigit($c2)) || ($is_digit && PMA_STR_isDigit($c2))) { $count2++; continue; } else { $is_digit = false; $is_hex_digit = false; } $count2++; } // end while $l = $count2 - $count1; $str = PMA_substr($sql, $count1, $l); $type = ''; if ($is_digit || $is_float_digit || $is_hex_digit) { $type = 'digit'; if ($is_float_digit) { $type .= '_float'; } elseif ($is_hex_digit) { $type .= '_hex'; } else { $type .= '_integer'; } } elseif ($is_user) { $type = 'punct_user'; } elseif ($is_sql_variable != false) { $type = 'alpha_variable'; } else { $type = 'alpha'; } // end if... else.... PMA_SQP_arrayAdd($sql_array, $type, $str, $arraysize, $count2); continue; } // Checks for punct if (PMA_strpos($allpunct_list, $c) !== false) { while (($count2 < $len) && PMA_strpos($allpunct_list, PMA_substr($sql, $count2, 1)) !== false) { $count2++; } $l = $count2 - $count1; if ($l == 1) { $punct_data = $c; } else { $punct_data = PMA_substr($sql, $count1, $l); } // Special case, sometimes, althought two characters are // adjectent directly, they ACTUALLY need to be seperate /* DEBUG echo '<pre>'; var_dump($l); var_dump($punct_data); echo '</pre>'; */ if ($l == 1) { $t_suffix = ''; switch ($punct_data) { case $punct_queryend: $t_suffix = '_queryend'; break; case $punct_qualifier: $t_suffix = '_qualifier'; $this_was_punct = true; break; case $punct_listsep: $this_was_listsep = true; $t_suffix = '_listsep'; break; default: break; } PMA_SQP_arrayAdd($sql_array, 'punct' . $t_suffix, $punct_data, $arraysize); } elseif ($punct_data == $GLOBALS['sql_delimiter'] || isset($allpunct_list_pair[$punct_data])) { // Ok, we have one of the valid combined punct expressions PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize); } else { // Bad luck, lets split it up more $first = $punct_data[0]; $first2 = $punct_data[0] . $punct_data[1]; $last2 = $punct_data[$l - 2] . $punct_data[$l - 1]; $last = $punct_data[$l - 1]; if (($first == ',') || ($first == ';') || ($first == '.') || ($first == '*')) { $count2 = $count1 + 1; $punct_data = $first; } elseif (($last2 == '/*') || (($last2 == '--') && ($count2 == $len || PMA_substr($sql, $count2, 1) <= ' '))) { $count2 -= 2; $punct_data = PMA_substr($sql, $count1, $count2 - $count1); } elseif (($last == '-') || ($last == '+') || ($last == '!')) { $count2--; $punct_data = PMA_substr($sql, $count1, $count2 - $count1); } elseif ($last != '~') { /** * @todo for negation operator, split in 2 tokens ? * "select x&~1 from t" * becomes "select x & ~ 1 from t" ? */ $debugstr = __('Unknown Punctuation String') . ' @ ' . ($count1+1) . "\n" . 'STR: ' . htmlspecialchars($punct_data); PMA_SQP_throwError($debugstr, $sql); return $sql_array; } PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize); continue; } // end if... elseif... else continue; } // DEBUG $count2++; $debugstr = 'C1 C2 LEN: ' . $count1 . ' ' . $count2 . ' ' . $len . "\n" . 'STR: ' . PMA_substr($sql, $count1, $count2 - $count1) . "\n"; PMA_SQP_bug($debugstr, $sql); return $sql_array; } // end while ($count2 < $len) /* echo '<pre>'; print_r($sql_array); echo '</pre>'; */ if ($arraysize > 0) { $t_next = $sql_array[0]['type']; $t_prev = ''; $t_bef_prev = ''; $t_cur = ''; $d_next = $sql_array[0]['data']; $d_prev = ''; $d_bef_prev = ''; $d_cur = ''; $d_next_upper = $t_next == 'alpha' ? strtoupper($d_next) : $d_next; $d_prev_upper = ''; $d_bef_prev_upper = ''; $d_cur_upper = ''; } for ($i = 0; $i < $arraysize; $i++) { $t_bef_prev = $t_prev; $t_prev = $t_cur; $t_cur = $t_next; $d_bef_prev = $d_prev; $d_prev = $d_cur; $d_cur = $d_next; $d_bef_prev_upper = $d_prev_upper; $d_prev_upper = $d_cur_upper; $d_cur_upper = $d_next_upper; if (($i + 1) < $arraysize) { $t_next = $sql_array[$i + 1]['type']; $d_next = $sql_array[$i + 1]['data']; $d_next_upper = $t_next == 'alpha' ? strtoupper($d_next) : $d_next; } else { $t_next = ''; $d_next = ''; $d_next_upper = ''; } //DEBUG echo "[prev: <strong>".$d_prev."</strong> ".$t_prev."][cur: <strong>".$d_cur."</strong> ".$t_cur."][next: <strong>".$d_next."</strong> ".$t_next."]<br />"; if ($t_cur == 'alpha') { $t_suffix = '_identifier'; // for example: `thebit` bit(8) NOT NULL DEFAULT b'0' if ($t_prev == 'alpha' && $d_prev == 'DEFAULT' && $d_cur == 'b' && $t_next == 'quote_single') { $t_suffix = '_bitfield_constant_introducer'; } elseif (($t_next == 'punct_qualifier') || ($t_prev == 'punct_qualifier')) { $t_suffix = '_identifier'; } elseif (($t_next == 'punct_bracket_open_round') && isset($PMA_SQPdata_function_name[$d_cur_upper])) { /** * @todo 2005-10-16: in the case of a CREATE TABLE containing * a TIMESTAMP, since TIMESTAMP() is also a function, it's * found here and the token is wrongly marked as alpha_functionName. * But we compensate for this when analysing for timestamp_not_null * later in this script. * * Same applies to CHAR vs. CHAR() function. */ $t_suffix = '_functionName'; /* There are functions which might be as well column types */ } elseif (isset($PMA_SQPdata_column_type[$d_cur_upper])) { $t_suffix = '_columnType'; /** * Temporary fix for BUG #621357 and #2027720 * * @todo FIX PROPERLY NEEDS OVERHAUL OF SQL TOKENIZER */ if (($d_cur_upper == 'SET' || $d_cur_upper == 'BINARY') && $t_next != 'punct_bracket_open_round') { $t_suffix = '_reservedWord'; } //END OF TEMPORARY FIX // CHARACTER is a synonym for CHAR, but can also be meant as // CHARACTER SET. In this case, we have a reserved word. if ($d_cur_upper == 'CHARACTER' && $d_next_upper == 'SET') { $t_suffix = '_reservedWord'; } // experimental // current is a column type, so previous must not be // a reserved word but an identifier // CREATE TABLE SG_Persons (first varchar(64)) //if ($sql_array[$i-1]['type'] =='alpha_reservedWord') { // $sql_array[$i-1]['type'] = 'alpha_identifier'; //} } elseif (isset($PMA_SQPdata_reserved_word[$d_cur_upper])) { $t_suffix = '_reservedWord'; } elseif (isset($PMA_SQPdata_column_attrib[$d_cur_upper])) { $t_suffix = '_columnAttrib'; // INNODB is a MySQL table type, but in "SHOW INNODB STATUS", // it should be regarded as a reserved word. if ($d_cur_upper == 'INNODB' && $d_prev_upper == 'SHOW' && $d_next_upper == 'STATUS') { $t_suffix = '_reservedWord'; } if ($d_cur_upper == 'DEFAULT' && $d_next_upper == 'CHARACTER') { $t_suffix = '_reservedWord'; } // Binary as character set if ($d_cur_upper == 'BINARY' && ( ($d_bef_prev_upper == 'CHARACTER' && $d_prev_upper == 'SET') || ($d_bef_prev_upper == 'SET' && $d_prev_upper == '=') || ($d_bef_prev_upper == 'CHARSET' && $d_prev_upper == '=') || $d_prev_upper == 'CHARSET' ) && in_array($d_cur, $mysql_charsets)) { $t_suffix = '_charset'; } } elseif (in_array($d_cur, $mysql_charsets) || in_array($d_cur, $mysql_collations_flat) || ($d_cur{0} == '_' && in_array(substr($d_cur, 1), $mysql_charsets))) { $t_suffix = '_charset'; } else { // Do nothing } // check if present in the list of forbidden words if ($t_suffix == '_reservedWord' && isset($PMA_SQPdata_forbidden_word[$d_cur_upper])) { $sql_array[$i]['forbidden'] = true; } else { $sql_array[$i]['forbidden'] = false; } $sql_array[$i]['type'] .= $t_suffix; } } // end for // Stores the size of the array inside the array, as count() is a slow // operation. $sql_array['len'] = $arraysize; // DEBUG echo 'After parsing<pre>'; print_r($sql_array); echo '</pre>'; // Sends the data back return $sql_array; } // end of the "PMA_SQP_parse()" function /** * Checks for token types being what we want... * * @param string String of type that we have * @param string String of type that we want * * @return boolean result of check * * @access private */ function PMA_SQP_typeCheck($toCheck, $whatWeWant) { $typeSeperator = '_'; if (strcmp($whatWeWant, $toCheck) == 0) { return true; } else { if (strpos($whatWeWant, $typeSeperator) === false) { return strncmp($whatWeWant, $toCheck, strpos($toCheck, $typeSeperator)) == 0; } else { return false; } } } /** * Analyzes SQL queries * * @param array The SQL queries * * @return array The analyzed SQL queries * * @access public */ function PMA_SQP_analyze($arr) { if ($arr == array() || ! isset($arr['len'])) { return array(); } $result = array(); $size = $arr['len']; $subresult = array( 'querytype' => '', 'select_expr_clause'=> '', // the whole stuff between SELECT and FROM , except DISTINCT 'position_of_first_select' => '', // the array index 'from_clause'=> '', 'group_by_clause'=> '', 'order_by_clause'=> '', 'having_clause' => '', 'limit_clause' => '', 'where_clause' => '', 'where_clause_identifiers' => array(), 'unsorted_query' => '', 'queryflags' => array(), 'select_expr' => array(), 'table_ref' => array(), 'foreign_keys' => array(), 'create_table_fields' => array() ); $subresult_empty = $subresult; $seek_queryend = false; $seen_end_of_table_ref = false; $number_of_brackets_in_extract = 0; $number_of_brackets_in_group_concat = 0; $number_of_brackets = 0; $in_subquery = false; $seen_subquery = false; $seen_from = false; // for SELECT EXTRACT(YEAR_MONTH FROM CURDATE()) // we must not use CURDATE as a table_ref // so we track whether we are in the EXTRACT() $in_extract = false; // for GROUP_CONCAT(...) $in_group_concat = false; /* Description of analyzer results * * db, table, column, alias * ------------------------ * * Inside the $subresult array, we create ['select_expr'] and ['table_ref'] arrays. * * The SELECT syntax (simplified) is * * SELECT * select_expression,... * [FROM [table_references] * * * ['select_expr'] is filled with each expression, the key represents the * expression position in the list (0-based) (so we don't lose track of * multiple occurences of the same column). * * ['table_ref'] is filled with each table ref, same thing for the key. * * I create all sub-values empty, even if they are * not present (for example no select_expression alias). * * There is a debug section at the end of loop #1, if you want to * see the exact contents of select_expr and table_ref * * queryflags * ---------- * * In $subresult, array 'queryflags' is filled, according to what we * find in the query. * * Currently, those are generated: * * ['queryflags']['need_confirm'] = 1; if the query needs confirmation * ['queryflags']['select_from'] = 1; if this is a real SELECT...FROM * ['queryflags']['distinct'] = 1; for a DISTINCT * ['queryflags']['union'] = 1; for a UNION * ['queryflags']['join'] = 1; for a JOIN * ['queryflags']['offset'] = 1; for the presence of OFFSET * ['queryflags']['procedure'] = 1; for the presence of PROCEDURE * * query clauses * ------------- * * The select is splitted in those clauses: * ['select_expr_clause'] * ['from_clause'] * ['group_by_clause'] * ['order_by_clause'] * ['having_clause'] * ['limit_clause'] * ['where_clause'] * * The identifiers of the WHERE clause are put into the array * ['where_clause_identifier'] * * For a SELECT, the whole query without the ORDER BY clause is put into * ['unsorted_query'] * * foreign keys * ------------ * The CREATE TABLE may contain FOREIGN KEY clauses, so they get * analyzed and ['foreign_keys'] is an array filled with * the constraint name, the index list, * the REFERENCES table name and REFERENCES index list, * and ON UPDATE | ON DELETE clauses * * position_of_first_select * ------------------------ * * The array index of the first SELECT we find. Will be used to * insert a SQL_CALC_FOUND_ROWS. * * create_table_fields * ------------------- * * Used to detect the DEFAULT CURRENT_TIMESTAMP and * ON UPDATE CURRENT_TIMESTAMP clauses of the CREATE TABLE query. * Also used to store the default value of the field. * An array, each element is the identifier name. * Note that for now, the timestamp_not_null element is created * even for non-TIMESTAMP fields. * * Sub-elements: ['type'] which contains the column type * optional (currently they are never false but can be absent): * ['default_current_timestamp'] boolean * ['on_update_current_timestamp'] boolean * ['timestamp_not_null'] boolean * * section_before_limit, section_after_limit * ----------------------------------------- * * Marks the point of the query where we can insert a LIMIT clause; * so the section_before_limit will contain the left part before * a possible LIMIT clause * * * End of description of analyzer results */ // must be sorted // TODO: current logic checks for only one word, so I put only the // first word of the reserved expressions that end a table ref; // maybe this is not ok (the first word might mean something else) // $words_ending_table_ref = array( // 'FOR UPDATE', // 'GROUP BY', // 'HAVING', // 'LIMIT', // 'LOCK IN SHARE MODE', // 'ORDER BY', // 'PROCEDURE', // 'UNION', // 'WHERE' // ); $words_ending_table_ref = array( 'FOR' => 1, 'GROUP' => 1, 'HAVING' => 1, 'LIMIT' => 1, 'LOCK' => 1, 'ORDER' => 1, 'PROCEDURE' => 1, 'UNION' => 1, 'WHERE' => 1 ); $words_ending_clauses = array( 'FOR' => 1, 'LIMIT' => 1, 'LOCK' => 1, 'PROCEDURE' => 1, 'UNION' => 1 ); $supported_query_types = array( 'SELECT' => 1, /* // Support for these additional query types will come later on. 'DELETE' => 1, 'INSERT' => 1, 'REPLACE' => 1, 'TRUNCATE' => 1, 'UPDATE' => 1, 'EXPLAIN' => 1, 'DESCRIBE' => 1, 'SHOW' => 1, 'CREATE' => 1, 'SET' => 1, 'ALTER' => 1 */ ); // loop #1 for each token: select_expr, table_ref for SELECT for ($i = 0; $i < $size; $i++) { //DEBUG echo "Loop1 <strong>" . $arr[$i]['data'] . "</strong> (" . $arr[$i]['type'] . ")<br />"; // High speed seek for locating the end of the current query if ($seek_queryend == true) { if ($arr[$i]['type'] == 'punct_queryend') { $seek_queryend = false; } else { continue; } // end if (type == punct_queryend) } // end if ($seek_queryend) /** * Note: do not split if this is a punct_queryend for the first and only query * @todo when we find a UNION, should we split in another subresult? */ if ($arr[$i]['type'] == 'punct_queryend' && ($i + 1 != $size)) { $result[] = $subresult; $subresult = $subresult_empty; continue; } // end if (type == punct_queryend) // ============================================================== if ($arr[$i]['type'] == 'punct_bracket_open_round') { $number_of_brackets++; if ($in_extract) { $number_of_brackets_in_extract++; } if ($in_group_concat) { $number_of_brackets_in_group_concat++; } } // ============================================================== if ($arr[$i]['type'] == 'punct_bracket_close_round') { $number_of_brackets--; if ($number_of_brackets == 0) { $in_subquery = false; } if ($in_extract) { $number_of_brackets_in_extract--; if ($number_of_brackets_in_extract == 0) { $in_extract = false; } } if ($in_group_concat) { $number_of_brackets_in_group_concat--; if ($number_of_brackets_in_group_concat == 0) { $in_group_concat = false; } } } if ($in_subquery) { /** * skip the subquery to avoid setting * select_expr or table_ref with the contents * of this subquery; this is to avoid a bug when * trying to edit the results of * select * from child where not exists (select id from * parent where child.parent_id = parent.id); */ continue; } // ============================================================== if ($arr[$i]['type'] == 'alpha_functionName') { $upper_data = strtoupper($arr[$i]['data']); if ($upper_data =='EXTRACT') { $in_extract = true; $number_of_brackets_in_extract = 0; } if ($upper_data =='GROUP_CONCAT') { $in_group_concat = true; $number_of_brackets_in_group_concat = 0; } } // ============================================================== if ($arr[$i]['type'] == 'alpha_reservedWord' //&& $arr[$i]['forbidden'] == false) { ) { // We don't know what type of query yet, so run this if ($subresult['querytype'] == '') { $subresult['querytype'] = strtoupper($arr[$i]['data']); } // end if (querytype was empty) // Check if we support this type of query if (!isset($supported_query_types[$subresult['querytype']])) { // Skip ahead to the next one if we don't $seek_queryend = true; continue; } // end if (query not supported) // upper once $upper_data = strtoupper($arr[$i]['data']); /** * @todo reset for each query? */ if ($upper_data == 'SELECT') { if ($number_of_brackets > 0) { $in_subquery = true; $seen_subquery = true; // this is a subquery so do not analyze inside it continue; } $seen_from = false; $previous_was_identifier = false; $current_select_expr = -1; $seen_end_of_table_ref = false; } // end if (data == SELECT) if ($upper_data =='FROM' && !$in_extract) { $current_table_ref = -1; $seen_from = true; $previous_was_identifier = false; $save_table_ref = true; } // end if (data == FROM) // here, do not 'continue' the loop, as we have more work for // reserved words below } // end if (type == alpha_reservedWord) // ============================== if ($arr[$i]['type'] == 'quote_backtick' || $arr[$i]['type'] == 'quote_double' || $arr[$i]['type'] == 'quote_single' || $arr[$i]['type'] == 'alpha_identifier' || ($arr[$i]['type'] == 'alpha_reservedWord' && $arr[$i]['forbidden'] == false)) { switch ($arr[$i]['type']) { case 'alpha_identifier': case 'alpha_reservedWord': /** * this is not a real reservedWord, because it's not * present in the list of forbidden words, for example * "storage" which can be used as an identifier * * @todo avoid the pretty printing in color in this case */ $identifier = $arr[$i]['data']; break; case 'quote_backtick': case 'quote_double': case 'quote_single': $identifier = PMA_unQuote($arr[$i]['data']); break; } // end switch if ($subresult['querytype'] == 'SELECT' && ! $in_group_concat && ! ($seen_subquery && $arr[$i - 1]['type'] == 'punct_bracket_close_round')) { if (!$seen_from) { if ($previous_was_identifier && isset($chain)) { // found alias for this select_expr, save it // but only if we got something in $chain // (for example, SELECT COUNT(*) AS cnt // puts nothing in $chain, so we avoid // setting the alias) $alias_for_select_expr = $identifier; } else { $chain[] = $identifier; $previous_was_identifier = true; } // end if !$previous_was_identifier } else { // ($seen_from) if ($save_table_ref && !$seen_end_of_table_ref) { if ($previous_was_identifier) { // found alias for table ref // save it for later $alias_for_table_ref = $identifier; } else { $chain[] = $identifier; $previous_was_identifier = true; } // end if ($previous_was_identifier) } // end if ($save_table_ref &&!$seen_end_of_table_ref) } // end if (!$seen_from) } // end if (querytype SELECT) } // end if (quote_backtick or double quote or alpha_identifier) // =================================== if ($arr[$i]['type'] == 'punct_qualifier') { // to be able to detect an identifier following another $previous_was_identifier = false; continue; } // end if (punct_qualifier) /** * @todo check if 3 identifiers following one another -> error */ // s a v e a s e l e c t e x p r // finding a list separator or FROM // means that we must save the current chain of identifiers // into a select expression // for now, we only save a select expression if it contains // at least one identifier, as we are interested in checking // the columns and table names, so in "select * from persons", // the "*" is not saved if (isset($chain) && !$seen_end_of_table_ref && ((!$seen_from && $arr[$i]['type'] == 'punct_listsep') || ($arr[$i]['type'] == 'alpha_reservedWord' && $upper_data == 'FROM'))) { $size_chain = count($chain); $current_select_expr++; $subresult['select_expr'][$current_select_expr] = array( 'expr' => '', 'alias' => '', 'db' => '', 'table_name' => '', 'table_true_name' => '', 'column' => '' ); if (isset($alias_for_select_expr) && strlen($alias_for_select_expr)) { // we had found an alias for this select expression $subresult['select_expr'][$current_select_expr]['alias'] = $alias_for_select_expr; unset($alias_for_select_expr); } // there is at least a column $subresult['select_expr'][$current_select_expr]['column'] = $chain[$size_chain - 1]; $subresult['select_expr'][$current_select_expr]['expr'] = $chain[$size_chain - 1]; // maybe a table if ($size_chain > 1) { $subresult['select_expr'][$current_select_expr]['table_name'] = $chain[$size_chain - 2]; // we assume for now that this is also the true name $subresult['select_expr'][$current_select_expr]['table_true_name'] = $chain[$size_chain - 2]; $subresult['select_expr'][$current_select_expr]['expr'] = $subresult['select_expr'][$current_select_expr]['table_name'] . '.' . $subresult['select_expr'][$current_select_expr]['expr']; } // end if ($size_chain > 1) // maybe a db if ($size_chain > 2) { $subresult['select_expr'][$current_select_expr]['db'] = $chain[$size_chain - 3]; $subresult['select_expr'][$current_select_expr]['expr'] = $subresult['select_expr'][$current_select_expr]['db'] . '.' . $subresult['select_expr'][$current_select_expr]['expr']; } // end if ($size_chain > 2) unset($chain); /** * @todo explain this: */ if (($arr[$i]['type'] == 'alpha_reservedWord') && ($upper_data != 'FROM')) { $previous_was_identifier = true; } } // end if (save a select expr) //====================================== // s a v e a t a b l e r e f //====================================== // maybe we just saw the end of table refs // but the last table ref has to be saved // or we are at the last token // or we just got a reserved word /** * @todo there could be another query after this one */ if (isset($chain) && $seen_from && $save_table_ref && ($arr[$i]['type'] == 'punct_listsep' || ($arr[$i]['type'] == 'alpha_reservedWord' && $upper_data!="AS") || $seen_end_of_table_ref || $i==$size-1)) { $size_chain = count($chain); $current_table_ref++; $subresult['table_ref'][$current_table_ref] = array( 'expr' => '', 'db' => '', 'table_name' => '', 'table_alias' => '', 'table_true_name' => '' ); if (isset($alias_for_table_ref) && strlen($alias_for_table_ref)) { $subresult['table_ref'][$current_table_ref]['table_alias'] = $alias_for_table_ref; unset($alias_for_table_ref); } $subresult['table_ref'][$current_table_ref]['table_name'] = $chain[$size_chain - 1]; // we assume for now that this is also the true name $subresult['table_ref'][$current_table_ref]['table_true_name'] = $chain[$size_chain - 1]; $subresult['table_ref'][$current_table_ref]['expr'] = $subresult['table_ref'][$current_table_ref]['table_name']; // maybe a db if ($size_chain > 1) { $subresult['table_ref'][$current_table_ref]['db'] = $chain[$size_chain - 2]; $subresult['table_ref'][$current_table_ref]['expr'] = $subresult['table_ref'][$current_table_ref]['db'] . '.' . $subresult['table_ref'][$current_table_ref]['expr']; } // end if ($size_chain > 1) // add the table alias into the whole expression $subresult['table_ref'][$current_table_ref]['expr'] .= ' ' . $subresult['table_ref'][$current_table_ref]['table_alias']; unset($chain); $previous_was_identifier = true; //continue; } // end if (save a table ref) // when we have found all table refs, // for each table_ref alias, put the true name of the table // in the corresponding select expressions if (isset($current_table_ref) && ($seen_end_of_table_ref || $i == $size-1) && $subresult != $subresult_empty) { for ($tr=0; $tr <= $current_table_ref; $tr++) { $alias = $subresult['table_ref'][$tr]['table_alias']; $truename = $subresult['table_ref'][$tr]['table_true_name']; for ($se=0; $se <= $current_select_expr; $se++) { if (isset($alias) && strlen($alias) && $subresult['select_expr'][$se]['table_true_name'] == $alias ) { $subresult['select_expr'][$se]['table_true_name'] = $truename; } // end if (found the alias) } // end for (select expressions) } // end for (table refs) } // end if (set the true names) // e n d i n g l o o p #1 // set the $previous_was_identifier to false if the current // token is not an identifier if (($arr[$i]['type'] != 'alpha_identifier') && ($arr[$i]['type'] != 'quote_double') && ($arr[$i]['type'] != 'quote_single') && ($arr[$i]['type'] != 'quote_backtick')) { $previous_was_identifier = false; } // end if // however, if we are on AS, we must keep the $previous_was_identifier if (($arr[$i]['type'] == 'alpha_reservedWord') && ($upper_data == 'AS')) { $previous_was_identifier = true; } if (($arr[$i]['type'] == 'alpha_reservedWord') && ($upper_data =='ON' || $upper_data =='USING')) { $save_table_ref = false; } // end if (data == ON) if (($arr[$i]['type'] == 'alpha_reservedWord') && ($upper_data =='JOIN' || $upper_data =='FROM')) { $save_table_ref = true; } // end if (data == JOIN) /** * no need to check the end of table ref if we already did * * @todo maybe add "&& $seen_from" */ if (!$seen_end_of_table_ref) { // if this is the last token, it implies that we have // seen the end of table references // Check for the end of table references // // Note: if we are analyzing a GROUP_CONCAT clause, // we might find a word that seems to indicate that // we have found the end of table refs (like ORDER) // but it's a modifier of the GROUP_CONCAT so // it's not the real end of table refs if (($i == $size-1) || ($arr[$i]['type'] == 'alpha_reservedWord' && !$in_group_concat && isset($words_ending_table_ref[$upper_data]))) { $seen_end_of_table_ref = true; // to be able to save the last table ref, but do not // set it true if we found a word like "ON" that has // already set it to false if (isset($save_table_ref) && $save_table_ref != false) { $save_table_ref = true; } //end if } // end if (check for end of table ref) } //end if (!$seen_end_of_table_ref) if ($seen_end_of_table_ref) { $save_table_ref = false; } // end if } // end for $i (loop #1) //DEBUG /* if (isset($current_select_expr)) { for ($trace=0; $trace<=$current_select_expr; $trace++) { echo "<br />"; reset ($subresult['select_expr'][$trace]); while (list ($key, $val) = each ($subresult['select_expr'][$trace])) echo "sel expr $trace $key => $val<br />\n"; } } if (isset($current_table_ref)) { echo "current_table_ref = " . $current_table_ref . "<br>"; for ($trace=0; $trace<=$current_table_ref; $trace++) { echo "<br />"; reset ($subresult['table_ref'][$trace]); while (list ($key, $val) = each ($subresult['table_ref'][$trace])) echo "table ref $trace $key => $val<br />\n"; } } */ // ------------------------------------------------------- // loop #2: - queryflags // - querytype (for queries != 'SELECT') // - section_before_limit, section_after_limit // // we will also need this queryflag in loop 2 // so set it here if (isset($current_table_ref) && $current_table_ref > -1) { $subresult['queryflags']['select_from'] = 1; } $section_before_limit = ''; $section_after_limit = ''; // truly the section after the limit clause $seen_reserved_word = false; $seen_group = false; $seen_order = false; $seen_order_by = false; $in_group_by = false; // true when we are inside the GROUP BY clause $in_order_by = false; // true when we are inside the ORDER BY clause $in_having = false; // true when we are inside the HAVING clause $in_select_expr = false; // true when we are inside the select expr clause $in_where = false; // true when we are inside the WHERE clause $seen_limit = false; // true if we have seen a LIMIT clause $in_limit = false; // true when we are inside the LIMIT clause $after_limit = false; // true when we are after the LIMIT clause $in_from = false; // true when we are in the FROM clause $in_group_concat = false; $first_reserved_word = ''; $current_identifier = ''; $unsorted_query = $arr['raw']; // in case there is no ORDER BY $number_of_brackets = 0; $in_subquery = false; for ($i = 0; $i < $size; $i++) { //DEBUG echo "Loop2 <strong>" . $arr[$i]['data'] . "</strong> (" . $arr[$i]['type'] . ")<br />"; // need_confirm // // check for reserved words that will have to generate // a confirmation request later in sql.php // the cases are: // DROP TABLE // DROP DATABASE // ALTER TABLE... DROP // DELETE FROM... // // this code is not used for confirmations coming from functions.js if ($arr[$i]['type'] == 'punct_bracket_open_round') { $number_of_brackets++; } if ($arr[$i]['type'] == 'punct_bracket_close_round') { $number_of_brackets--; if ($number_of_brackets == 0) { $in_subquery = false; } } if ($arr[$i]['type'] == 'alpha_reservedWord') { $upper_data = strtoupper($arr[$i]['data']); if ($upper_data == 'SELECT' && $number_of_brackets > 0) { $in_subquery = true; } if (!$seen_reserved_word) { $first_reserved_word = $upper_data; $subresult['querytype'] = $upper_data; $seen_reserved_word = true; // if the first reserved word is DROP or DELETE, // we know this is a query that needs to be confirmed if ($first_reserved_word=='DROP' || $first_reserved_word == 'DELETE' || $first_reserved_word == 'TRUNCATE') { $subresult['queryflags']['need_confirm'] = 1; } if ($first_reserved_word=='SELECT') { $position_of_first_select = $i; } } else { if ($upper_data == 'DROP' && $first_reserved_word == 'ALTER') { $subresult['queryflags']['need_confirm'] = 1; } } if ($upper_data == 'LIMIT' && ! $in_subquery) { $section_before_limit = substr($arr['raw'], 0, $arr[$i]['pos'] - 5); $in_limit = true; $seen_limit = true; $limit_clause = ''; $in_order_by = false; // @todo maybe others to set false } if ($upper_data == 'PROCEDURE') { $subresult['queryflags']['procedure'] = 1; $in_limit = false; $after_limit = true; } /** * @todo set also to false if we find FOR UPDATE or LOCK IN SHARE MODE */ if ($upper_data == 'SELECT') { $in_select_expr = true; $select_expr_clause = ''; } if ($upper_data == 'DISTINCT' && !$in_group_concat) { $subresult['queryflags']['distinct'] = 1; } if ($upper_data == 'UNION') { $subresult['queryflags']['union'] = 1; } if ($upper_data == 'JOIN') { $subresult['queryflags']['join'] = 1; } if ($upper_data == 'OFFSET') { $subresult['queryflags']['offset'] = 1; } // if this is a real SELECT...FROM if ($upper_data == 'FROM' && isset($subresult['queryflags']['select_from']) && $subresult['queryflags']['select_from'] == 1) { $in_from = true; $from_clause = ''; $in_select_expr = false; } // (we could have less resetting of variables to false // if we trust that the query respects the standard // MySQL order for clauses) // we use $seen_group and $seen_order because we are looking // for the BY if ($upper_data == 'GROUP') { $seen_group = true; $seen_order = false; $in_having = false; $in_order_by = false; $in_where = false; $in_select_expr = false; $in_from = false; } if ($upper_data == 'ORDER' && !$in_group_concat) { $seen_order = true; $seen_group = false; $in_having = false; $in_group_by = false; $in_where = false; $in_select_expr = false; $in_from = false; } if ($upper_data == 'HAVING') { $in_having = true; $having_clause = ''; $seen_group = false; $seen_order = false; $in_group_by = false; $in_order_by = false; $in_where = false; $in_select_expr = false; $in_from = false; } if ($upper_data == 'WHERE') { $in_where = true; $where_clause = ''; $where_clause_identifiers = array(); $seen_group = false; $seen_order = false; $in_group_by = false; $in_order_by = false; $in_having = false; $in_select_expr = false; $in_from = false; } if ($upper_data == 'BY') { if ($seen_group) { $in_group_by = true; $group_by_clause = ''; } if ($seen_order) { $seen_order_by = true; // Here we assume that the ORDER BY keywords took // exactly 8 characters. // We use PMA_substr() to be charset-safe; otherwise // if the table name contains accents, the unsorted // query would be missing some characters. $unsorted_query = PMA_substr($arr['raw'], 0, $arr[$i]['pos'] - 8); $in_order_by = true; $order_by_clause = ''; } } // if we find one of the words that could end the clause if (isset($words_ending_clauses[$upper_data])) { $in_group_by = false; $in_order_by = false; $in_having = false; $in_where = false; $in_select_expr = false; $in_from = false; } } // endif (reservedWord) // do not add a space after a function name /** * @todo can we combine loop 2 and loop 1? some code is repeated here... */ $sep = ' '; if ($arr[$i]['type'] == 'alpha_functionName') { $sep=''; $upper_data = strtoupper($arr[$i]['data']); if ($upper_data =='GROUP_CONCAT') { $in_group_concat = true; $number_of_brackets_in_group_concat = 0; } } if ($arr[$i]['type'] == 'punct_bracket_open_round') { if ($in_group_concat) { $number_of_brackets_in_group_concat++; } } if ($arr[$i]['type'] == 'punct_bracket_close_round') { if ($in_group_concat) { $number_of_brackets_in_group_concat--; if ($number_of_brackets_in_group_concat == 0) { $in_group_concat = false; } } } // do not add a space after an identifier if followed by a dot if ($arr[$i]['type'] == 'alpha_identifier' && $i < $size - 1 && $arr[$i + 1]['data'] == '.') { $sep = ''; } // do not add a space after a dot if followed by an identifier if ($arr[$i]['data'] == '.' && $i < $size - 1 && $arr[$i + 1]['type'] == 'alpha_identifier') { $sep = ''; } if ($in_select_expr && $upper_data != 'SELECT' && $upper_data != 'DISTINCT') { $select_expr_clause .= $arr[$i]['data'] . $sep; } if ($in_from && $upper_data != 'FROM') { $from_clause .= $arr[$i]['data'] . $sep; } if ($in_group_by && $upper_data != 'GROUP' && $upper_data != 'BY') { $group_by_clause .= $arr[$i]['data'] . $sep; } if ($in_order_by && $upper_data != 'ORDER' && $upper_data != 'BY') { // add a space only before ASC or DESC // not around the dot between dbname and tablename if ($arr[$i]['type'] == 'alpha_reservedWord') { $order_by_clause .= $sep; } $order_by_clause .= $arr[$i]['data']; } if ($in_having && $upper_data != 'HAVING') { $having_clause .= $arr[$i]['data'] . $sep; } if ($in_where && $upper_data != 'WHERE') { $where_clause .= $arr[$i]['data'] . $sep; if (($arr[$i]['type'] == 'quote_backtick') || ($arr[$i]['type'] == 'alpha_identifier')) { $where_clause_identifiers[] = $arr[$i]['data']; } } // to grab the rest of the query after the ORDER BY clause if (isset($subresult['queryflags']['select_from']) && $subresult['queryflags']['select_from'] == 1 && ! $in_order_by && $seen_order_by && $upper_data != 'BY') { $unsorted_query .= $arr[$i]['data']; if ($arr[$i]['type'] != 'punct_bracket_open_round' && $arr[$i]['type'] != 'punct_bracket_close_round' && $arr[$i]['type'] != 'punct') { $unsorted_query .= $sep; } } if ($in_limit) { if ($upper_data == 'OFFSET') { $limit_clause .= $sep; } $limit_clause .= $arr[$i]['data']; if ($upper_data == 'LIMIT' || $upper_data == 'OFFSET') { $limit_clause .= $sep; } } if ($after_limit && $seen_limit) { $section_after_limit .= $arr[$i]['data'] . $sep; } // clear $upper_data for next iteration $upper_data=''; } // end for $i (loop #2) if (empty($section_before_limit)) { $section_before_limit = $arr['raw']; } // ----------------------------------------------------- // loop #3: foreign keys and MySQL 4.1.2+ TIMESTAMP options // (for now, check only the first query) // (for now, identifiers are assumed to be backquoted) // If we find that we are dealing with a CREATE TABLE query, // we look for the next punct_bracket_open_round, which // introduces the fields list. Then, when we find a // quote_backtick, it must be a field, so we put it into // the create_table_fields array. Even if this field is // not a timestamp, it will be useful when logic has been // added for complete field attributes analysis. $seen_foreign = false; $seen_references = false; $seen_constraint = false; $foreign_key_number = -1; $seen_create_table = false; $seen_create = false; $seen_alter = false; $in_create_table_fields = false; $brackets_level = 0; $in_timestamp_options = false; $seen_default = false; for ($i = 0; $i < $size; $i++) { // DEBUG echo "Loop 3 <strong>" . $arr[$i]['data'] . "</strong> " . $arr[$i]['type'] . "<br />"; if ($arr[$i]['type'] == 'alpha_reservedWord') { $upper_data = strtoupper($arr[$i]['data']); if ($upper_data == 'NOT' && $in_timestamp_options) { $create_table_fields[$current_identifier]['timestamp_not_null'] = true; } if ($upper_data == 'CREATE') { $seen_create = true; } if ($upper_data == 'ALTER') { $seen_alter = true; } if ($upper_data == 'TABLE' && $seen_create) { $seen_create_table = true; $create_table_fields = array(); } if ($upper_data == 'CURRENT_TIMESTAMP') { if ($in_timestamp_options) { if ($seen_default) { $create_table_fields[$current_identifier]['default_current_timestamp'] = true; } } } if ($upper_data == 'CONSTRAINT') { $foreign_key_number++; $seen_foreign = false; $seen_references = false; $seen_constraint = true; } if ($upper_data == 'FOREIGN') { $seen_foreign = true; $seen_references = false; $seen_constraint = false; } if ($upper_data == 'REFERENCES') { $seen_foreign = false; $seen_references = true; $seen_constraint = false; } // Cases covered: // [ON DELETE {CASCADE | SET NULL | NO ACTION | RESTRICT}] // [ON UPDATE {CASCADE | SET NULL | NO ACTION | RESTRICT}] // but we set ['on_delete'] or ['on_cascade'] to // CASCADE | SET_NULL | NO_ACTION | RESTRICT // ON UPDATE CURRENT_TIMESTAMP if ($upper_data == 'ON') { if (isset($arr[$i+1]) && $arr[$i+1]['type'] == 'alpha_reservedWord') { $second_upper_data = strtoupper($arr[$i+1]['data']); if ($second_upper_data == 'DELETE') { $clause = 'on_delete'; } if ($second_upper_data == 'UPDATE') { $clause = 'on_update'; } if (isset($clause) && ($arr[$i+2]['type'] == 'alpha_reservedWord' // ugly workaround because currently, NO is not // in the list of reserved words in sqlparser.data // (we got a bug report about not being able to use // 'no' as an identifier) || ($arr[$i+2]['type'] == 'alpha_identifier' && strtoupper($arr[$i+2]['data'])=='NO')) ) { $third_upper_data = strtoupper($arr[$i+2]['data']); if ($third_upper_data == 'CASCADE' || $third_upper_data == 'RESTRICT') { $value = $third_upper_data; } elseif ($third_upper_data == 'SET' || $third_upper_data == 'NO') { if ($arr[$i+3]['type'] == 'alpha_reservedWord') { $value = $third_upper_data . '_' . strtoupper($arr[$i+3]['data']); } } elseif ($third_upper_data == 'CURRENT_TIMESTAMP') { if ($clause == 'on_update' && $in_timestamp_options) { $create_table_fields[$current_identifier]['on_update_current_timestamp'] = true; $seen_default = false; } } else { $value = ''; } if (!empty($value)) { $foreign[$foreign_key_number][$clause] = $value; } unset($clause); } // endif (isset($clause)) } } } // end of reserved words analysis if ($arr[$i]['type'] == 'punct_bracket_open_round') { $brackets_level++; if ($seen_create_table && $brackets_level == 1) { $in_create_table_fields = true; } } if ($arr[$i]['type'] == 'punct_bracket_close_round') { $brackets_level--; if ($seen_references) { $seen_references = false; } if ($seen_create_table && $brackets_level == 0) { $in_create_table_fields = false; } } if (($arr[$i]['type'] == 'alpha_columnAttrib')) { $upper_data = strtoupper($arr[$i]['data']); if ($seen_create_table && $in_create_table_fields) { if ($upper_data == 'DEFAULT') { $seen_default = true; $create_table_fields[$current_identifier]['default_value'] = $arr[$i + 1]['data']; } } } /** * @see @todo 2005-10-16 note: the "or" part here is a workaround for a bug */ if (($arr[$i]['type'] == 'alpha_columnType') || ($arr[$i]['type'] == 'alpha_functionName' && $seen_create_table)) { $upper_data = strtoupper($arr[$i]['data']); if ($seen_create_table && $in_create_table_fields && isset($current_identifier)) { $create_table_fields[$current_identifier]['type'] = $upper_data; if ($upper_data == 'TIMESTAMP') { $arr[$i]['type'] = 'alpha_columnType'; $in_timestamp_options = true; } else { $in_timestamp_options = false; if ($upper_data == 'CHAR') { $arr[$i]['type'] = 'alpha_columnType'; } } } } if ($arr[$i]['type'] == 'quote_backtick' || $arr[$i]['type'] == 'alpha_identifier') { if ($arr[$i]['type'] == 'quote_backtick') { // remove backquotes $identifier = PMA_unQuote($arr[$i]['data']); } else { $identifier = $arr[$i]['data']; } if ($seen_create_table && $in_create_table_fields) { $current_identifier = $identifier; // we set this one even for non TIMESTAMP type $create_table_fields[$current_identifier]['timestamp_not_null'] = false; } if ($seen_constraint) { $foreign[$foreign_key_number]['constraint'] = $identifier; } if ($seen_foreign && $brackets_level > 0) { $foreign[$foreign_key_number]['index_list'][] = $identifier; } if ($seen_references) { if ($seen_alter && $brackets_level > 0) { $foreign[$foreign_key_number]['ref_index_list'][] = $identifier; // here, the first bracket level corresponds to the // bracket of CREATE TABLE // so if we are on level 2, it must be the index list // of the foreign key REFERENCES } elseif ($brackets_level > 1) { $foreign[$foreign_key_number]['ref_index_list'][] = $identifier; } elseif ($arr[$i+1]['type'] == 'punct_qualifier') { // identifier is `db`.`table` // the first pass will pick the db name // the next pass will pick the table name $foreign[$foreign_key_number]['ref_db_name'] = $identifier; } else { // identifier is `table` $foreign[$foreign_key_number]['ref_table_name'] = $identifier; } } } } // end for $i (loop #3) // Fill the $subresult array if (isset($create_table_fields)) { $subresult['create_table_fields'] = $create_table_fields; } if (isset($foreign)) { $subresult['foreign_keys'] = $foreign; } if (isset($select_expr_clause)) { $subresult['select_expr_clause'] = $select_expr_clause; } if (isset($from_clause)) { $subresult['from_clause'] = $from_clause; } if (isset($group_by_clause)) { $subresult['group_by_clause'] = $group_by_clause; } if (isset($order_by_clause)) { $subresult['order_by_clause'] = $order_by_clause; } if (isset($having_clause)) { $subresult['having_clause'] = $having_clause; } if (isset($limit_clause)) { $subresult['limit_clause'] = $limit_clause; } if (isset($where_clause)) { $subresult['where_clause'] = $where_clause; } if (isset($unsorted_query) && !empty($unsorted_query)) { $subresult['unsorted_query'] = $unsorted_query; } if (isset($where_clause_identifiers)) { $subresult['where_clause_identifiers'] = $where_clause_identifiers; } if (isset($position_of_first_select)) { $subresult['position_of_first_select'] = $position_of_first_select; $subresult['section_before_limit'] = $section_before_limit; $subresult['section_after_limit'] = $section_after_limit; } // They are naughty and didn't have a trailing semi-colon, // then still handle it properly if ($subresult['querytype'] != '') { $result[] = $subresult; } return $result; } // end of the "PMA_SQP_analyze()" function /** * Colorizes SQL queries html formatted * * @todo check why adding a "\n" after the </span> would cause extra blanks * to be displayed: SELECT p . person_name * @param array The SQL queries html formatted * * @return array The colorized SQL queries * * @access public */ function PMA_SQP_formatHtml_colorize($arr) { $i = PMA_strpos($arr['type'], '_'); $class = ''; if ($i > 0) { $class = 'syntax_' . PMA_substr($arr['type'], 0, $i) . ' '; } $class .= 'syntax_' . $arr['type']; return '<span class="' . $class . '">' . htmlspecialchars($arr['data']) . '</span>'; } // end of the "PMA_SQP_formatHtml_colorize()" function /** * Formats SQL queries to html * * @param array The SQL queries * @param string mode * @param integer starting token * @param integer number of tokens to format, -1 = all * * @return string The formatted SQL queries * * @access public */ function PMA_SQP_formatHtml($arr, $mode='color', $start_token=0, $number_of_tokens=-1) { global $PMA_SQPdata_operators_docs, $PMA_SQPdata_functions_docs; //DEBUG echo 'in Format<pre>'; print_r($arr); echo '</pre>'; // then check for an array if (! is_array($arr)) { return htmlspecialchars($arr); } // first check for the SQL parser having hit an error if (PMA_SQP_isError()) { return htmlspecialchars($arr['raw']); } // else do it properly switch ($mode) { case 'color': $str = '<span class="syntax">'; $html_line_break = '<br />'; $docu = true; break; case 'query_only': $str = ''; $html_line_break = "\n"; $docu = false; break; case 'text': $str = ''; $html_line_break = '<br />'; $docu = true; break; } // end switch // inner_sql is a span that exists for all cases, except query_only // of $cfg['SQP']['fmtType'] to make possible a replacement // for inline editing if ($mode!='query_only') { $str .= '<span class="inner_sql">'; } $close_docu_link = false; $indent = 0; $bracketlevel = 0; $functionlevel = 0; $infunction = false; $space_punct_listsep = ' '; $space_punct_listsep_function_name = ' '; // $space_alpha_reserved_word = '<br />'."\n"; $space_alpha_reserved_word = ' '; $keywords_with_brackets_1before = array( 'INDEX' => 1, 'KEY' => 1, 'ON' => 1, 'USING' => 1 ); $keywords_with_brackets_2before = array( 'IGNORE' => 1, 'INDEX' => 1, 'INTO' => 1, 'KEY' => 1, 'PRIMARY' => 1, 'PROCEDURE' => 1, 'REFERENCES' => 1, 'UNIQUE' => 1, 'USE' => 1 ); // These reserved words do NOT get a newline placed near them. $keywords_no_newline = array( 'AS' => 1, 'ASC' => 1, 'DESC' => 1, 'DISTINCT' => 1, 'DUPLICATE' => 1, 'HOUR' => 1, 'INTERVAL' => 1, 'IS' => 1, 'LIKE' => 1, 'NOT' => 1, 'NULL' => 1, 'ON' => 1, 'REGEXP' => 1 ); // These reserved words introduce a privilege list $keywords_priv_list = array( 'GRANT' => 1, 'REVOKE' => 1 ); if ($number_of_tokens == -1) { $number_of_tokens = $arr['len']; } $typearr = array(); if ($number_of_tokens >= 0) { $typearr[0] = ''; $typearr[1] = ''; $typearr[2] = ''; $typearr[3] = $arr[$start_token]['type']; } $in_priv_list = false; for ($i = $start_token; $i < $number_of_tokens; $i++) { // DEBUG echo "Loop format <strong>" . $arr[$i]['data'] . "</strong> " . $arr[$i]['type'] . "<br />"; $before = ''; $after = ''; // array_shift($typearr); /* 0 prev2 1 prev 2 current 3 next */ if (($i + 1) < $number_of_tokens) { $typearr[4] = $arr[$i + 1]['type']; } else { $typearr[4] = ''; } for ($j=0; $j<4; $j++) { $typearr[$j] = $typearr[$j + 1]; } switch ($typearr[2]) { case 'alpha_bitfield_constant_introducer': $before = ' '; $after = ''; break; case 'white_newline': $before = ''; break; case 'punct_bracket_open_round': $bracketlevel++; $infunction = false; // Make sure this array is sorted! if (($typearr[1] == 'alpha_functionName') || ($typearr[1] == 'alpha_columnType') || ($typearr[1] == 'punct') || ($typearr[3] == 'digit_integer') || ($typearr[3] == 'digit_hex') || ($typearr[3] == 'digit_float') || (($typearr[0] == 'alpha_reservedWord') && isset($keywords_with_brackets_2before[strtoupper($arr[$i - 2]['data'])])) || (($typearr[1] == 'alpha_reservedWord') && isset($keywords_with_brackets_1before[strtoupper($arr[$i - 1]['data'])])) ) { $functionlevel++; $infunction = true; $after .= ' '; } else { $indent++; $after .= ($mode != 'query_only' ? '<div class="syntax_indent' . $indent . '">' : ' '); } break; case 'alpha_identifier': if (($typearr[1] == 'punct_qualifier') || ($typearr[3] == 'punct_qualifier')) { $after = ''; $before = ''; } // for example SELECT 1 somealias if ($typearr[1] == 'digit_integer') { $before = ' '; } if (($typearr[3] == 'alpha_columnType') || ($typearr[3] == 'alpha_identifier')) { $after .= ' '; } break; case 'punct_user': case 'punct_qualifier': $before = ''; $after = ''; break; case 'punct_listsep': if ($infunction == true) { $after .= $space_punct_listsep_function_name; } else { $after .= $space_punct_listsep; } break; case 'punct_queryend': if (($typearr[3] != 'comment_mysql') && ($typearr[3] != 'comment_ansi') && $typearr[3] != 'comment_c') { $after .= $html_line_break; $after .= $html_line_break; } $space_punct_listsep = ' '; $space_punct_listsep_function_name = ' '; $space_alpha_reserved_word = ' '; $in_priv_list = false; break; case 'comment_mysql': case 'comment_ansi': $after .= $html_line_break; break; case 'punct': $before .= ' '; if ($docu && isset($PMA_SQPdata_operators_docs[$arr[$i]['data']]) && ($arr[$i]['data'] != '*' || in_array($arr[$i]['type'], array('digit_integer','digit_float','digit_hex')))) { $before .= PMA_showMySQLDocu( 'functions', $PMA_SQPdata_operators_docs[$arr[$i]['data']]['link'], false, $PMA_SQPdata_operators_docs[$arr[$i]['data']]['anchor'], true); $after .= '</a>'; } // workaround for // select * from mytable limit 0,-1 // (a side effect of this workaround is that // select 20 - 9 // becomes // select 20 -9 // ) if ($typearr[3] != 'digit_integer') { $after .= ' '; } break; case 'punct_bracket_close_round': // only close bracket level when it was opened before if ($bracketlevel > 0) { $bracketlevel--; if ($infunction == true) { $functionlevel--; $after .= ' '; $before .= ' '; } else { $indent--; $before .= ($mode != 'query_only' ? '</div>' : ' '); } $infunction = ($functionlevel > 0) ? true : false; } break; case 'alpha_columnType': if ($docu) { switch ($arr[$i]['data']) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'decimal': case 'float': case 'double': case 'real': case 'bit': case 'boolean': case 'serial': $before .= PMA_showMySQLDocu('data-types', 'numeric-types', false, '', true); $after = '</a>' . $after; break; case 'date': case 'datetime': case 'timestamp': case 'time': case 'year': $before .= PMA_showMySQLDocu('data-types', 'date-and-time-types', false, '', true); $after = '</a>' . $after; break; case 'char': case 'varchar': case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'binary': case 'varbinary': case 'tinyblob': case 'mediumblob': case 'blob': case 'longblob': case 'enum': case 'set': $before .= PMA_showMySQLDocu('data-types', 'string-types', false, '', true); $after = '</a>' . $after; break; } } if ($typearr[3] == 'alpha_columnAttrib') { $after .= ' '; } if ($typearr[1] == 'alpha_columnType') { $before .= ' '; } break; case 'alpha_columnAttrib': // ALTER TABLE tbl_name AUTO_INCREMENT = 1 // COLLATE LATIN1_GENERAL_CI DEFAULT if ($typearr[1] == 'alpha_identifier' || $typearr[1] == 'alpha_charset') { $before .= ' '; } if (($typearr[3] == 'alpha_columnAttrib') || ($typearr[3] == 'quote_single') || ($typearr[3] == 'digit_integer')) { $after .= ' '; } // workaround for // AUTO_INCREMENT = 31DEFAULT_CHARSET = utf-8 if ($typearr[2] == 'alpha_columnAttrib' && $typearr[3] == 'alpha_reservedWord') { $before .= ' '; } // workaround for // select * from mysql.user where binary user="root" // binary is marked as alpha_columnAttrib // but should be marked as a reserved word if (strtoupper($arr[$i]['data']) == 'BINARY' && $typearr[3] == 'alpha_identifier') { $after .= ' '; } break; case 'alpha_functionName': $funcname = strtoupper($arr[$i]['data']); if ($docu && isset($PMA_SQPdata_functions_docs[$funcname])) { $before .= PMA_showMySQLDocu( 'functions', $PMA_SQPdata_functions_docs[$funcname]['link'], false, $PMA_SQPdata_functions_docs[$funcname]['anchor'], true); $after .= '</a>'; } break; case 'alpha_reservedWord': // do not uppercase the reserved word if we are calling // this function in query_only mode, because we need // the original query (otherwise we get problems with // semi-reserved words like "storage" which is legal // as an identifier name) if ($mode != 'query_only') { $arr[$i]['data'] = strtoupper($arr[$i]['data']); } if ((($typearr[1] != 'alpha_reservedWord') || (($typearr[1] == 'alpha_reservedWord') && isset($keywords_no_newline[strtoupper($arr[$i - 1]['data'])]))) && ($typearr[1] != 'punct_level_plus') && (!isset($keywords_no_newline[$arr[$i]['data']]))) { // do not put a space before the first token, because // we use a lot of pattern matching checking for the // first reserved word at beginning of query // so do not put a newline before // // also we must not be inside a privilege list if ($i > 0) { // the alpha_identifier exception is there to // catch cases like // GRANT SELECT ON mydb.mytable TO myuser@localhost // (else, we get mydb.mytableTO) // // the quote_single exception is there to // catch cases like // GRANT ... TO 'marc'@'domain.com' IDENTIFIED... /** * @todo fix all cases and find why this happens */ if (!$in_priv_list || $typearr[1] == 'alpha_identifier' || $typearr[1] == 'quote_single' || $typearr[1] == 'white_newline') { $before .= $space_alpha_reserved_word; } } else { // on first keyword, check if it introduces a // privilege list if (isset($keywords_priv_list[$arr[$i]['data']])) { $in_priv_list = true; } } } else { $before .= ' '; } switch ($arr[$i]['data']) { case 'CREATE': case 'ALTER': case 'DROP': case 'RENAME'; case 'TRUNCATE': case 'ANALYZE': case 'ANALYSE': case 'OPTIMIZE': if ($docu) { switch ($arr[$i + 1]['data']) { case 'EVENT': case 'TABLE': case 'TABLESPACE': case 'FUNCTION': case 'INDEX': case 'PROCEDURE': case 'TRIGGER': case 'SERVER': case 'DATABASE': case 'VIEW': $before .= PMA_showMySQLDocu('SQL-Syntax', $arr[$i]['data'] . '_' . $arr[$i + 1]['data'], false, '', true); $close_docu_link = true; break; } if ($arr[$i + 1]['data'] == 'LOGFILE' && $arr[$i + 2]['data'] == 'GROUP') { $before .= PMA_showMySQLDocu('SQL-Syntax', $arr[$i]['data'] . '_LOGFILE_GROUP', false, '', true); $close_docu_link = true; } } if (!$in_priv_list) { $space_punct_listsep = $html_line_break; $space_alpha_reserved_word = ' '; } break; case 'EVENT': case 'TABLESPACE': case 'TABLE': case 'FUNCTION': case 'INDEX': case 'PROCEDURE': case 'SERVER': case 'TRIGGER': case 'DATABASE': case 'VIEW': case 'GROUP': if ($close_docu_link) { $after = '</a>' . $after; $close_docu_link = false; } break; case 'SET': if ($docu && ($i == 0 || $arr[$i - 1]['data'] != 'CHARACTER')) { $before .= PMA_showMySQLDocu('SQL-Syntax', $arr[$i]['data'], false, '', true); $after = '</a>' . $after; } if (!$in_priv_list) { $space_punct_listsep = $html_line_break; $space_alpha_reserved_word = ' '; } break; case 'EXPLAIN': case 'DESCRIBE': case 'DELETE': case 'SHOW': case 'UPDATE': if ($docu) { $before .= PMA_showMySQLDocu('SQL-Syntax', $arr[$i]['data'], false, '', true); $after = '</a>' . $after; } if (!$in_priv_list) { $space_punct_listsep = $html_line_break; $space_alpha_reserved_word = ' '; } break; case 'INSERT': case 'REPLACE': if ($docu) { $before .= PMA_showMySQLDocu('SQL-Syntax', $arr[$i]['data'], false, '', true); $after = '</a>' . $after; } if (!$in_priv_list) { $space_punct_listsep = $html_line_break; $space_alpha_reserved_word = $html_line_break; } break; case 'VALUES': $space_punct_listsep = ' '; $space_alpha_reserved_word = $html_line_break; break; case 'SELECT': if ($docu) { $before .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT', false, '', true); $after = '</a>' . $after; } $space_punct_listsep = ' '; $space_alpha_reserved_word = $html_line_break; break; case 'CALL': case 'DO': case 'HANDLER': if ($docu) { $before .= PMA_showMySQLDocu('SQL-Syntax', $arr[$i]['data'], false, '', true); $after = '</a>' . $after; } break; default: if ($close_docu_link && in_array($arr[$i]['data'], array('LIKE', 'NOT', 'IN', 'REGEXP', 'NULL'))) { $after .= '</a>'; $close_docu_link = false; } else if ($docu && isset($PMA_SQPdata_functions_docs[$arr[$i]['data']])) { /* Handle multi word statements first */ if (isset($typearr[4]) && $typearr[4] == 'alpha_reservedWord' && $typearr[3] == 'alpha_reservedWord' && isset($PMA_SQPdata_functions_docs[strtoupper($arr[$i]['data'] . '_' . $arr[$i + 1]['data'] . '_' . $arr[$i + 2]['data'])])) { $tempname = strtoupper($arr[$i]['data'] . '_' . $arr[$i + 1]['data'] . '_' . $arr[$i + 2]['data']); $before .= PMA_showMySQLDocu('functions', $PMA_SQPdata_functions_docs[$tempname]['link'], false, $PMA_SQPdata_functions_docs[$tempname]['anchor'], true); $close_docu_link = true; } else if (isset($typearr[3]) && $typearr[3] == 'alpha_reservedWord' && isset($PMA_SQPdata_functions_docs[strtoupper($arr[$i]['data'] . '_' . $arr[$i + 1]['data'])])) { $tempname = strtoupper($arr[$i]['data'] . '_' . $arr[$i + 1]['data']); $before .= PMA_showMySQLDocu('functions', $PMA_SQPdata_functions_docs[$tempname]['link'], false, $PMA_SQPdata_functions_docs[$tempname]['anchor'], true); $close_docu_link = true; } else { $before .= PMA_showMySQLDocu('functions', $PMA_SQPdata_functions_docs[$arr[$i]['data']]['link'], false, $PMA_SQPdata_functions_docs[$arr[$i]['data']]['anchor'], true); $after .= '</a>'; } } break; } // end switch ($arr[$i]['data']) $after .= ' '; break; case 'digit_integer': case 'digit_float': case 'digit_hex': /** * @todo could there be other types preceding a digit? */ if ($typearr[1] == 'alpha_reservedWord') { $after .= ' '; } if ($infunction && $typearr[3] == 'punct_bracket_close_round') { $after .= ' '; } if ($typearr[1] == 'alpha_columnAttrib') { $before .= ' '; } break; case 'alpha_variable': $after = ' '; break; case 'quote_double': case 'quote_single': // workaround: for the query // REVOKE SELECT ON `base2\_db`.* FROM 'user'@'%' // the @ is incorrectly marked as alpha_variable // in the parser, and here, the '%' gets a blank before, // which is a syntax error if ($typearr[1] != 'punct_user' && $typearr[1] != 'alpha_bitfield_constant_introducer') { $before .= ' '; } if ($infunction && $typearr[3] == 'punct_bracket_close_round') { $after .= ' '; } break; case 'quote_backtick': // here we check for punct_user to handle correctly // DEFINER = `username`@`%` // where @ is the punct_user and `%` is the quote_backtick if ($typearr[3] != 'punct_qualifier' && $typearr[3] != 'alpha_variable' && $typearr[3] != 'punct_user') { $after .= ' '; } if ($typearr[1] != 'punct_qualifier' && $typearr[1] != 'alpha_variable' && $typearr[1] != 'punct_user') { $before .= ' '; } break; default: break; } // end switch ($typearr[2]) /* if ($typearr[3] != 'punct_qualifier') { $after .= ' '; } $after .= "\n"; */ $str .= $before; if ($mode=='color') { $str .= PMA_SQP_formatHTML_colorize($arr[$i]); } elseif ($mode == 'text') { $str .= htmlspecialchars($arr[$i]['data']); } else { $str .= $arr[$i]['data']; } $str .= $after; } // end for // close unclosed indent levels while ($indent > 0) { $indent--; $str .= ($mode != 'query_only' ? '</div>' : ' '); } /* End possibly unclosed documentation link */ if ($close_docu_link) { $str .= '</a>'; $close_docu_link = false; } if ($mode!='query_only') { // close inner_sql span $str .= '</span>'; } if ($mode=='color') { // close syntax span $str .= '</span>'; } return $str; } // end of the "PMA_SQP_formatHtml()" function } /** * Builds a CSS rule used for html formatted SQL queries * * @param string The class name * @param string The property name * @param string The property value * * @return string The CSS rule * * @access public * * @see PMA_SQP_buildCssData() */ function PMA_SQP_buildCssRule($classname, $property, $value) { $str = '.' . $classname . ' {'; if ($value != '') { $str .= $property . ': ' . $value . ';'; } $str .= '}' . "\n"; return $str; } // end of the "PMA_SQP_buildCssRule()" function /** * Builds CSS rules used for html formatted SQL queries * * @return string The CSS rules set * * @access public * * @global array The current PMA configuration * * @see PMA_SQP_buildCssRule() */ function PMA_SQP_buildCssData() { global $cfg; $css_string = ''; foreach ($cfg['SQP']['fmtColor'] AS $key => $col) { $css_string .= PMA_SQP_buildCssRule('syntax_' . $key, 'color', $col); } for ($i = 0; $i < 8; $i++) { $css_string .= PMA_SQP_buildCssRule( 'syntax_indent' . $i, 'margin-left', ($i * $cfg['SQP']['fmtInd']) . $cfg['SQP']['fmtIndUnit']); } return $css_string; } // end of the "PMA_SQP_buildCssData()" function if (! defined('PMA_MINIMUM_COMMON')) { /** * Gets SQL queries with no format * * @param array The SQL queries list * * @return string The SQL queries with no format * * @access public */ function PMA_SQP_formatNone($arr) { $formatted_sql = htmlspecialchars($arr['raw']); $formatted_sql = preg_replace( "@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $formatted_sql); return $formatted_sql; } // end of the "PMA_SQP_formatNone()" function } // end if: minimal common.lib needed? ?>
{'content_hash': '3d5c0861ba74d55b8b762cd32fd376c0', 'timestamp': '', 'source': 'github', 'line_count': 2759, 'max_line_length': 708, 'avg_line_length': 40.71112722000725, 'alnum_prop': 0.4041327611687826, 'repo_name': 'ROOT005/ec_deal', 'id': 'ca30471c7b50bde98687ca2691576d2cbe126c08', 'size': '112322', 'binary': False, 'copies': '83', 'ref': 'refs/heads/master', 'path': 'phpMyAdmin1/libraries/sqlparser.lib.php', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '43520'}, {'name': 'CSS', 'bytes': '1024684'}, {'name': 'HTML', 'bytes': '1099439'}, {'name': 'Java', 'bytes': '11028'}, {'name': 'JavaScript', 'bytes': '2704155'}, {'name': 'PHP', 'bytes': '7461659'}, {'name': 'Roff', 'bytes': '29'}, {'name': 'Shell', 'bytes': '1723'}, {'name': 'Smarty', 'bytes': '8471'}]}
// BridgeDb, // An abstraction layer for identifier mapping services, both local and online. // Copyright 2006-2009 BridgeDb developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.bridgedb; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.bridgedb.impl.TransitiveGraph; /** * combines multiple {@link IDMapper}'s in a stack. * <p> * The behavior of the {@link IDMapper} interface implementations * differs per method: * if the method returns a single result, usually it is * from the first child database that has a sensible result. * This also means that the child databases have a definitive * ordering: the first one shadows the second one for some results. * <p> * If the method returns a list, IDMapperStack joins * the result from all connected child databases together. * <p> * Transitive maps are deduced from the IDMappers, added to this * IDMapperStack. Transitive maps are enabled as soon as the transitivity * is set to be true. * <p> * In order to calculate the deduced transitive mappings, we build * a graph that represents the possible mappings supported by * the IDMappers in this IDMapperStack. The nodes of this graph are * DataSources, the Edges are IDMappers. Possible mappings are * loop free paths in this graph. We consider a path p to be loop free * if no data source in p is reached twice by the same IDMapper. * <p> * The mapping graph for transitive maps is retained and re-calculated * whenever an IDMapper is added or removed from this IDMapperStack. * */ public class IDMapperStack implements IDMapper, AttributeMapper { // reference shared with TransitiveGraph private final List<IDMapper> gdbs = new CopyOnWriteArrayList<IDMapper>(); /** Helper class for calculating transitive paths */ private TransitiveGraph transitiveGraph = null; private TransitiveGraph getTransitiveGraph() throws IDMapperException { if (transitiveGraph == null) transitiveGraph = new TransitiveGraph(gdbs); return transitiveGraph; } /** * Create a fresh IDMapper from a connectionString and add it to the stack. * @param connectionString connectionString for configuring the new IDMapper * @return the newly created IDMapper * @throws IDMapperException when the connection failed. */ public IDMapper addIDMapper(String connectionString) throws IDMapperException { IDMapper idMapper = BridgeDb.connect(connectionString); addIDMapper(idMapper); return idMapper; } /** * Add an existing IDMapper to the stack. * @param idMapper IDMapper to be added. */ public void addIDMapper(IDMapper idMapper) { if (idMapper!=null) { gdbs.add(idMapper); transitiveGraph = null; // trigger rebuild. } } private boolean isTransitive = false; /** * Set Transitivity mode, where all mappings are combined to infer * second degree mappings. * @param value true or false */ public void setTransitive(boolean value) { isTransitive = value; } /** * @return true if the stack is in transitive mode */ public boolean getTransitive() { return isTransitive; } /** * Remove an idMapper from the stack. * Automatically rebuilds the mapping graph. * * @param idMapper IDMapper to be removed. */ public void removeIDMapper(IDMapper idMapper) { gdbs.remove(idMapper); transitiveGraph = null; // trigger rebuild } /** * closes all child databases. * @throws IDMapperException when closing failed for one of the databases. It will still try to * close all child databases even if one throws an exception. However, only the last exception will be thrown. */ public void close() throws IDMapperException { IDMapperException postponed = null; for (IDMapper child : gdbs) { if (child != null) { try { child.close(); child = null; // garbage collect } catch (IDMapperException ex) { postponed = ex; } } } if (postponed != null) { throw postponed; } } /** {@inheritDoc} */ public boolean xrefExists(Xref xref) throws IDMapperException { for (IDMapper child : gdbs) { if (child != null && child.isConnected()) { if(child.xrefExists(xref)) { return true; } } } return false; } /** * @return true if at least one of the child services * are connected. */ public boolean isConnected() { for (IDMapper child : gdbs) { if (child != null && child.isConnected()) { return true; } } return false; } private final IDMapperCapabilities caps = new IDMapperStackCapabilities(); private class IDMapperStackCapabilities implements IDMapperCapabilities { /** * @return union of DataSources supported by child services * @throws IDMapperException when one of the services was unavailable */ public Set<DataSource> getSupportedSrcDataSources() throws IDMapperException { final Set<DataSource> result = new HashSet<DataSource>(); for (IDMapper idm : IDMapperStack.this.gdbs) { Set<DataSource> dss = null; dss = idm.getCapabilities().getSupportedSrcDataSources(); if (dss!=null) { result.addAll (dss); } } return result; } /** * @return union of DataSources supported by child services * @throws IDMapperException when one of the services was unavailable */ public Set<DataSource> getSupportedTgtDataSources() throws IDMapperException { final Set<DataSource> result = new HashSet<DataSource>(); for (IDMapper idm : IDMapperStack.this.gdbs) { Set<DataSource> dss = null; dss = idm.getCapabilities().getSupportedTgtDataSources(); if (dss!=null) { result.addAll (dss); } } return result; } /** {@inheritDoc} */ public boolean isMappingSupported(DataSource src, DataSource tgt) throws IDMapperException { if(isTransitive) { return getTransitiveGraph().isTransitiveMappingSupported(src, tgt); } else { for (IDMapper idm : IDMapperStack.this.gdbs) { if (idm.getCapabilities().isMappingSupported(src, tgt)) { return true; } } } return false; } /** * @return true if free search is supported by one of the children */ public boolean isFreeSearchSupported() { // returns true if any returns true // TODO: not sure if this is the right logic? for (IDMapper idm : IDMapperStack.this.gdbs) { if (idm.getCapabilities().isFreeSearchSupported()) return true; } return false; } /** {@inheritDoc} */ public Set<String> getKeys() { return Collections.emptySet(); } /** {@inheritDoc} */ public String getProperty(String key) { return null; } }; /** * @return an object describing the capabilities of the combined stack of services. */ public IDMapperCapabilities getCapabilities() { return caps; } /** {@inheritDoc} */ public Set<Xref> freeSearch(String text, int limit) throws IDMapperException { Set<Xref> result = new HashSet<Xref>(); for (IDMapper child : gdbs) { if (child != null && child.isConnected()) { result.addAll (child.freeSearch(text, limit)); } } return result; } /** {@inheritDoc} */ public Map<Xref, Set<Xref>> mapID(Collection<Xref> srcXrefs, DataSource... tgtDataSources) throws IDMapperException { if (isTransitive) { return mapIDtransitive(srcXrefs, tgtDataSources); } else { return mapIDnormal(srcXrefs, tgtDataSources); } } /** * helper method to map Id's in non-transitive mode. * @param srcXrefs mapping source * @param tgtDataSources target data sources * @return mapping result * @throws IDMapperException if one of the children fail */ private Map<Xref, Set<Xref>> mapIDnormal(Collection<Xref> srcXrefs, DataSource... tgtDataSources) throws IDMapperException { Map<Xref, Set<Xref>> result = new HashMap<Xref, Set<Xref>>(); for (IDMapper child : gdbs) { if (child != null && child.isConnected()) { for (Map.Entry<Xref, Set<Xref>> entry : child.mapID(srcXrefs, tgtDataSources).entrySet()) { Set<Xref> resultSet = result.get (entry.getKey()); if (resultSet == null) { resultSet = new HashSet<Xref>(); result.put (entry.getKey(), resultSet); } resultSet.addAll (entry.getValue()); } } } return result; } /** * helper method to map Id's in transitive mode. * @param srcXrefs mapping source * @param tgtDataSources target data sources * @return mapping result * @throws IDMapperException if one of the children fail */ private Map<Xref, Set<Xref>> mapIDtransitive(Collection<Xref> srcXrefs, DataSource... tgtDataSources) throws IDMapperException { // Current implementation just repeatedly calls mapIDTransitive (Xref, Set<Ds>) // It may be possible to rearrange loops to optimize for fewer database calls. Map <Xref, Set<Xref>> result = new HashMap<Xref, Set<Xref>>(); for (Xref ref: srcXrefs) { result.put (ref, mapIDtransitive(ref, tgtDataSources)); } return result; } /** {@inheritDoc} */ public Set<String> getAttributes(Xref ref, String attrname) throws IDMapperException { Set<String> result = new HashSet<String>(); for (IDMapper child : gdbs) { if (child != null && child instanceof AttributeMapper && child.isConnected()) { result.addAll (((AttributeMapper)child).getAttributes(ref, attrname)); } } return result; } /** {@inheritDoc} */ public Set<String> getAttributesForAllMappings(Xref ref, String attrname, DataSource... dataSources) throws IDMapperException { Set<String> result = new HashSet<String>(); Set<Xref> mappings = mapID(ref, dataSources); mappings.add(ref); // TODO: check if this is really needed for (Xref mappedRef : mappings) { result.addAll(getAttributes(mappedRef, attrname)); } return result; } /** * @return true if free attribute search is supported by one of the children */ public boolean isFreeAttributeSearchSupported() { // returns true if any returns true // TODO: not sure if this is the right logic? for (IDMapper child : IDMapperStack.this.gdbs) { if (child != null && child instanceof AttributeMapper) { if (((AttributeMapper)child).isFreeAttributeSearchSupported()) return true; } } return false; } /** {@inheritDoc} */ public Map<Xref, String> freeAttributeSearch (String query, String attrType, int limit) throws IDMapperException { Map<Xref, String> result = null; for (IDMapper child : gdbs) { if (child != null && child instanceof AttributeMapper && child.isConnected() && ((AttributeMapper)child).isFreeAttributeSearchSupported()) { Map<Xref, String> childResult = ((AttributeMapper)child).freeAttributeSearch(query, attrType, limit); if (result == null) result = childResult; else { for (Xref ref : childResult.keySet()) { if (!result.containsKey(ref)) result.put (ref, childResult.get(ref)); } } } } return result; } public Map<Xref, Set<String>> freeAttributeSearchEx (String query, String attrType, int limit) throws IDMapperException { Map<Xref, Set<String>> result = new HashMap<Xref, Set<String>>(); for (IDMapper child : gdbs) { if (child != null && child instanceof AttributeMapper && child.isConnected() && ((AttributeMapper)child).isFreeAttributeSearchSupported()) { Map<Xref, Set<String>> childResult = ((AttributeMapper)child).freeAttributeSearchEx(query, attrType, limit); if (result == null) result = childResult; else { for (Xref ref : childResult.keySet()) { if (!result.containsKey(ref)) result.put (ref, childResult.get(ref)); } } } } return result; } /** @return concatenation of toString of each child */ @Override public String toString() { String result = ""; boolean first = true; for (IDMapper child : gdbs) { if (!first) result += ", "; first = false; result += child.toString(); } return result; } /** @return number of child databases */ public int getSize() { return gdbs.size(); } /** * @param index in the range 0 &lt;= index &lt; getSize() * @return the IDMapper at the given position */ public IDMapper getIDMapperAt(int index) { return gdbs.get(index); } /** {@inheritDoc} */ public Set<Xref> mapID(Xref ref, DataSource... resultDs) throws IDMapperException { if (isTransitive) { return mapIDtransitive (ref, resultDs); } else { return mapIDnormal (ref, resultDs); } } /** * Helper method to map Id's in transitive mode. * Relies on pre-calculated mapping graph * in order to deduce transitively mappings. * * @param ref Xref to map * @param resultDs target data sources * @return mapping result * @throws IDMapperException if one of the children fail */ private Set<Xref> mapIDtransitive(Xref ref, DataSource... resultDs) throws IDMapperException { if( resultDs.length == 0 ) { return getTransitiveGraph().mapIDtransitiveUntargetted(ref); } else { Set<DataSource> dsFilter = new HashSet<DataSource>(Arrays .asList(resultDs)); Set<Xref> result = getTransitiveGraph().mapIDtransitiveTargetted(ref, dsFilter); return result; } } /** * helper method to map Id's in transitive mode. * @param ref Xref to map * @param resultDs target data sources * @return mapping result * @throws IDMapperException if one of the children fail */ private Set<Xref> mapIDnormal(Xref ref, DataSource... resultDs) throws IDMapperException { Set<Xref> result = new HashSet<Xref>(); for (IDMapper child : gdbs) { if (child != null && child.isConnected()) { result.addAll (child.mapID(ref, resultDs)); } } return result; } /** {@inheritDoc} */ public Set<String> getAttributeSet() throws IDMapperException { Set<String> result = new HashSet<String>(); for (IDMapper child : gdbs) { if (child != null && child instanceof AttributeMapper && child.isConnected()) { result.addAll (((AttributeMapper)child).getAttributeSet()); } } return result; } /** {@inheritDoc} */ public Map<String, Set<String>> getAttributes(Xref ref) throws IDMapperException { Map<String, Set<String>> result = new HashMap<String, Set<String>>(); for (IDMapper child : gdbs) { if (child != null && child instanceof AttributeMapper && child.isConnected()) { for (Map.Entry<String, Set<String>> entry : ((AttributeMapper)child).getAttributes(ref).entrySet()) { Set<String> thisSet; if (!result.containsKey(entry.getKey())) { thisSet = new HashSet<String>(); result.put (entry.getKey(), thisSet); } else { thisSet = result.get(entry.getKey()); } thisSet.addAll(entry.getValue()); } } } return result; } /** {@inheritDoc} */ public Map<String, Set<String>> getAttributesForAllMappings(Xref ref, DataSource... dataSources) throws IDMapperException { Map<String, Set<String>> result = new HashMap<String, Set<String>>(); Set<Xref> mappings = mapID(ref, dataSources); mappings.add(ref); // TODO: check if this is really needed for (Xref mappedRef : mappings) { result.putAll(getAttributes(mappedRef)); } return result; } /** get all mappers * @return mappers * */ public List<IDMapper> getMappers() { return gdbs; } }
{'content_hash': 'd89a2c314e8fc20fd0a5320839a1a4eb', 'timestamp': '', 'source': 'github', 'line_count': 623, 'max_line_length': 120, 'avg_line_length': 26.287319422150883, 'alnum_prop': 0.6703914025767845, 'repo_name': 'egonw/BridgeDb', 'id': '2819d209079a352ff2d3e246d0c7e17775a8beb6', 'size': '16377', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'org.bridgedb/src/main/java/org/bridgedb/IDMapperStack.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '52'}, {'name': 'CSS', 'bytes': '17388'}, {'name': 'HTML', 'bytes': '2283'}, {'name': 'Java', 'bytes': '1857446'}, {'name': 'Perl', 'bytes': '143672'}, {'name': 'R', 'bytes': '1959'}, {'name': 'Shell', 'bytes': '24947'}]}
package com.apkfuns.jsbridge.module; /** * Created by pengwei on 2017/6/13. */ public interface JsObject { /** * Convert java object to js * @return */ String convertJS(); }
{'content_hash': 'd7fc236160dc53c0d22166845abd372d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 36, 'avg_line_length': 15.461538461538462, 'alnum_prop': 0.6019900497512438, 'repo_name': 'pengwei1024/webviewJsBridge', 'id': '4c56c446e7b1e83cc44bc75cfa10e0cd1eb7641a', 'size': '201', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'jsbridge/src/main/java/com/apkfuns/jsbridge/module/JsObject.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1160'}, {'name': 'Java', 'bytes': '5786'}]}
<!-- Copyright © 2013 Reagan Lopez [This program is licensed under the "MIT License"] Please see the file LICENSE in the source distribution of this software for license terms --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <title>speedbreaker</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" /> <link rel="stylesheet" href="css/speedbreaker.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script> <script src="js/speedbreaker.js"></script> <script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script> <script> $(document).ready(function() { $("#stop-button-div").hide(); $("#speed-limit").html("-- mph"); $("#speed-limit").css("color", "black"); $("#my-speed").html("-- mph"); $("#my-speed").css("color", "black"); var timerId1=0; var timerId2=0; $("#start-button").click(function(){ $("#start-button-div").hide(); $("#stop-button-div").show(); $("#geo-div").show(); tolerance = $("#speed-tolerance").val(); $('#speed-tolerance').slider( 'disable' ); // set the options and call the function to get current speed. var options = { frequency: 2000, timeout: 30000, enableHighAccuracy: true }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); // call the function to get the speedlimit timerId1=setInterval(function(){ loadXMLDoc(); },2000); }); $("#stop-button").click(function() { $("#stop-button-div").hide(); $("#geo-div").hide(); $("#start-button-div").show(); clearWatch(); clearInterval(timerId1); clearInterval(timerId2); $("#speed-limit").html("-- mph"); $("#speed-limit").css("color", "black"); $("#my-speed").html("-- mph"); $("#route-info").html(""); $("#my-speed").css("color", "black"); $('#speed-tolerance').slider( 'enable' ); }); }); </script> </head> <body> <div data-role="page" id="page1"> <div data-theme="b" data-role="header"> <h3 id="page-header" class="page-header"> SpeedBreaker </h3> </div> <!-- end of header --> <div data-role="content"> <div data-role="fieldcontain"> <h3>Speed Information</h3> <div class="ui-grid-a"> <div class="ui-block-a"><div class="ui-bar ui-bar-a ui-center" style="height:20px"> <img style="width: 50px; height: 50px" src="img/speed-limit.png" /> </div></div> <div class="ui-block-b"><div class="ui-bar ui-bar-a ui-center" style="height:20px"> <img style="width: 50px; height: 50px" src="img/my-speed.png" /> </div></div> <div class="ui-block-a"><div id="speed-limit" class="ui-bar ui-bar-c ui-center" style="height:20px"></div></div> <div class="ui-block-b"><div id="my-speed" class="ui-bar ui-bar-c ui-center" style="height:20px"></div></div> </div> </div> <div data-role="fieldcontain"> <h3>Select Speed Tolerance</h3> <input id="speed-tolerance" type="range" name="slider" min="0" max="20" value="5" data-highlight="true"> </div> <div id="start-button-div" class="ui-center"> <input id="start-button" type="button" data-theme="g" value="Start" class="start-button" data-inline="true"/> </div> <div id="stop-button-div" class="ui-center"> <input id="stop-button" type="button" data-theme="r" value="Stop" class="stop-button" data-inline="true" /> </div> <br> <br> <br> <div id="geo-div" class="ui-color-gray"> <!-- used for debugging --> </div> <div id="disclaimer" class="ui-color-gray"> <b> Disclaimer! This app is not responsible for any kind of speeding tickets or road accidents. Speedlimit does not reflect road work and school zones. Drive Safe! </b> </div> </div> <!-- end of content --> </div> <!-- end of page --> </body> </html>
{'content_hash': 'b33548dff72e99070f2493965cbd2a3a', 'timestamp': '', 'source': 'github', 'line_count': 126, 'max_line_length': 120, 'avg_line_length': 34.976190476190474, 'alnum_prop': 0.5770365327887452, 'repo_name': 'reagan-lopez/speedbreaker', 'id': '97629b6ec4ff9e5438afb0f0ea581d8ba87803a4', 'size': '4408', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/www/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9581'}, {'name': 'Java', 'bytes': '2238'}, {'name': 'JavaScript', 'bytes': '316743'}]}
Automated install scripts for Odoo v8 or v9 (Community editions). This scripts just needs to be preconfigured before being launched, no interaction needed. The script is based on the install script from André Schenkels (https://github.com/aschenkels-ictstudio/openerp-install-scripts) and having some additions from the one of Yenthe (https://github.com/Yenthe666/InstallScript) but with a lot of additions as virtualenv and considerations for proxied installs, Nginx, and extra tools. It also follows the approach recommended in Odoo's documentation (https://www.odoo.com/documentation/9.0/setup/install.html) using pip instead of apt-get for python dependencies > It's recommended to install this script with **elevated privileges**, so there's no need to use **sudo** to execute this procedure. <h3>Installation procedure</h3> 1. Download the script ```bash wget https://raw.githubusercontent.com/gustavovalverde/odoo-install-scripts/16.04/odoo_install.sh ``` 2. **THIS IS IMPORTANT!** Modify this variables, otherwise you might get hacked too easily ```bash OE_USER="odoo" OE_VIRTENV="venv" OE_SUPERADMIN="admin" ``` 3. Modify this Odoo variables based on your needs ```bash INSTALL_WKHTMLTOPDF="True" OE_PORT="8069" OE_VERSION="9.0" OE_DB="mydb" OE_INTERFACE='127.0.0.1' PSQL_VERSION="9.6" ``` 4. Modify this Nginx variables based on your needs ```bash DOMAIN_NAME="EXAMPLE.COM" #change with your domain #Odoo Web Gui configuration for Nginx ODOO_SRVC="odoo" ODOO_IP="127.0.0.1" #$SRVR_IP, Loopback or your private odoo server IP ODOO_PORT="8069" HTTP_PORT="80" #HTTP External Port HTTPS_PORT="443" #HTTPS External Port #Change to your company details country="DO" state="Santo_Domingo" locality="DN" organization="iterativo.do" organizationalunit="IT" email="[email protected]" ``` 5. Make the script executable ```bash chmod +x odoo_install.sh ``` 6. Execute the script: ```bash /odoo_install.sh ```
{'content_hash': '5ad927496c8619e910509a4d760a0cc8', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 330, 'avg_line_length': 34.11666666666667, 'alnum_prop': 0.7142159257449927, 'repo_name': 'gustavovalverde/odoo-install-scripts', 'id': 'fe8bd51c126be1b75ad2255d4f193ceabdacdfc4', 'size': '2071', 'binary': False, 'copies': '1', 'ref': 'refs/heads/16.04', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Shell', 'bytes': '19106'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- JBoss, Home of Professional Open Source Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual contributors by the @authors tag. See the copyright.txt in the distribution for a full listing of individual contributors. 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. --> <arquillian xmlns="http://jboss.org/schema/arquillian" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd"> <!-- Uncomment to have test archives exported to the file system for inspection --> <!-- <engine> --> <!-- <property name="deploymentExportPath">target/</property> --> <!-- </engine> --> <!-- Force the use of the Servlet 3.0 protocol with all containers, as it is the most mature --> <defaultProtocol type="Servlet 3.0"/> <!-- Example configuration for a remote JBoss Enterprise Application Platform 6 or AS 7 instance --> <container qualifier="jboss" default="true"> <!-- By default, arquillian will use the JBOSS_HOME environment variable. Alternatively, the configuration below can be uncommented. --> <!--<configuration> --> <!--<property name="jbossHome">/path/to/jboss/as</property> --> <!--</configuration> --> </container> </arquillian>
{'content_hash': '15af458c8003a117ebeeb2cb543919f0', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 145, 'avg_line_length': 48.97435897435897, 'alnum_prop': 0.6926701570680628, 'repo_name': 'johnament/quickstart', 'id': '92606f53fb89de37b7fc0d4b83345e7fcf3a1bfd', 'size': '1910', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'tasks-rs/src/test/resources/arquillian.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package org.gradle.test.performance.mediummonolithicjavaproject.p114; import org.junit.Test; import static org.junit.Assert.*; public class Test2292 { Production2292 objectUnderTest = new Production2292(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
{'content_hash': '88af3d5fe3e497704f5f6a10d9565e52', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 69, 'avg_line_length': 26.72151898734177, 'alnum_prop': 0.6447181430601611, 'repo_name': 'oehme/analysing-gradle-performance', 'id': '84aa187787835945be934f99d83537e21e4359fe', 'size': '2111', 'binary': False, 'copies': '1', 'ref': 'refs/heads/before', 'path': 'my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p114/Test2292.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '40770723'}]}
Run ```bash devicehive-cloud.create ``` to create binaries. Currently, all binaries will not be build, so if you need binaries you can make build for snappy and then extract binaries from snap files(it's archives, just open it with any archinve manager)
{'content_hash': '3a10806a0d4ea28d6d37ae2f514b95ab', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 213, 'avg_line_length': 50.8, 'alnum_prop': 0.7834645669291339, 'repo_name': 'devicehive/IoT-framework', 'id': '2e4dbeb4c7e871fca252e28e518ee9b4fac28246', 'size': '305', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'build/debian/readme.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '26477'}, {'name': 'C++', 'bytes': '2143'}, {'name': 'Go', 'bytes': '91380'}, {'name': 'JavaScript', 'bytes': '8912'}, {'name': 'Python', 'bytes': '17513'}, {'name': 'Shell', 'bytes': '20104'}]}
#ifndef _BITS_TCPIP_H #define _BITS_TCPIP_H /** @file * * Transport-network layer interface * */ FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); extern uint16_t tcpip_continue_chksum ( uint16_t sum, const void *data, size_t len ); #endif /* _BITS_TCPIP_H */
{'content_hash': '4b94e677808fbb8f9b943e7b9e851414', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 71, 'avg_line_length': 17.533333333333335, 'alnum_prop': 0.6539923954372624, 'repo_name': '4km3/netboot', 'id': '68686534ece670d2518d3266568d35d4d84aea5c', 'size': '263', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'third_party/ipxe/src/arch/arm64/include/bits/tcpip.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '3457'}, {'name': 'Go', 'bytes': '238284'}, {'name': 'Makefile', 'bytes': '3913'}]}
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("litecoinz:"); // BIP70 payment protocol messages const char* BIP70_MESSAGE_PAYMENTACK = "PaymentACK"; const char* BIP70_MESSAGE_PAYMENTREQUEST = "PaymentRequest"; // BIP71 payment protocol media types const char* BIP71_MIMETYPE_PAYMENT = "application/bitcoin-payment"; const char* BIP71_MIMETYPE_PAYMENTACK = "application/bitcoin-paymentack"; const char* BIP71_MIMETYPE_PAYMENTREQUEST = "application/bitcoin-paymentrequest"; // BIP70 max payment request size in bytes (DoS protection) const qint64 BIP70_MAX_PAYMENTREQUEST_SIZE = 50000; struct X509StoreDeleter { void operator()(X509_STORE* b) { X509_STORE_free(b); } }; struct X509Deleter { void operator()(X509* b) { X509_free(b); } }; namespace // Anon namespace { std::unique_ptr<X509_STORE, X509StoreDeleter> certStore; } // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("LitecoinzQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GUIUtil::boostPathToQString(GetDataDir(true))); name.append(QString::number(qHash(ddir))); return name; } // // We store payment URIs and requests received before // the main GUI window is up and ready to ask the user // to send payment. static QList<QString> savedPaymentRequests; static void ReportInvalidCertificate(const QSslCertificate& cert) { #if QT_VERSION < 0x050000 qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName); #else qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::DistinguishedNameQualifier) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName); #endif } // // Load OpenSSL's list of root certificate authorities // void PaymentServer::LoadRootCAs(X509_STORE* _store) { // Unit tests mostly use this, to pass in fake root CAs: if (_store) { certStore.reset(_store); return; } // Normal execution, use either -rootcertificates or system certs: certStore.reset(X509_STORE_new()); // Note: use "-system-" default here so that users can pass -rootcertificates="" // and get 'I don't like X.509 certificates, don't trust anybody' behavior: QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-")); // Empty store if (certFile.isEmpty()) { qDebug() << QString("PaymentServer::%1: Payment request authentication via X.509 certificates disabled.").arg(__func__); return; } QList<QSslCertificate> certList; if (certFile != "-system-") { qDebug() << QString("PaymentServer::%1: Using \"%2\" as trusted root certificate.").arg(__func__).arg(certFile); certList = QSslCertificate::fromPath(certFile); // Use those certificates when fetching payment requests, too: QSslSocket::setDefaultCaCertificates(certList); } else certList = QSslSocket::systemCaCertificates(); int nRootCerts = 0; const QDateTime currentTime = QDateTime::currentDateTime(); Q_FOREACH (const QSslCertificate& cert, certList) { // Don't log NULL certificates if (cert.isNull()) continue; // Not yet active/valid, or expired certificate if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) { ReportInvalidCertificate(cert); continue; } #if QT_VERSION >= 0x050000 // Blacklisted certificate if (cert.isBlacklisted()) { ReportInvalidCertificate(cert); continue; } #endif QByteArray certData = cert.toDer(); const unsigned char *data = (const unsigned char *)certData.data(); std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size())); if (x509 && X509_STORE_add_cert(certStore.get(), x509.get())) { // Note: X509_STORE increases the reference count to the X509 object, // we still have to release our reference to it. ++nRootCerts; } else { ReportInvalidCertificate(cert); continue; } } qWarning() << "PaymentServer::LoadRootCAs: Loaded " << nRootCerts << " root certificates"; // Project for another day: // Fetch certificate revocation lists, and add them to certStore. // Issues to consider: // performance (start a thread to fetch in background?) // privacy (fetch through tor/proxy so IP address isn't revealed) // would it be easier to just use a compiled-in blacklist? // or use Qt's blacklist? // "certificate stapling" with server-side caching is more efficient } // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // // Warning: ipcSendCommandLine() is called early in init, // so don't use "Q_EMIT message()", but "QMessageBox::"! // void PaymentServer::ipcParseCommandLine(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { QString arg(argv[i]); if (arg.startsWith("-")) continue; // If the litecoinz: URI contains a payment request, we are not able to detect the // network as that would require fetching and parsing the payment request. // That means clicking such an URI which contains a testnet payment request // will start a mainnet instance and throw a "wrong network" error. if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // litecoinz: URI { savedPaymentRequests.append(arg); SendCoinsRecipient r; if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty()) { if (IsValidDestinationString(r.address.toStdString(), Params(CBaseChainParams::MAIN))) { SelectParams(CBaseChainParams::MAIN); } else { if (IsValidDestinationString(r.address.toStdString(), Params(CBaseChainParams::TESTNET))) { SelectParams(CBaseChainParams::TESTNET); } } } } else if (QFile::exists(arg)) // Filename { savedPaymentRequests.append(arg); PaymentRequestPlus request; if (readPaymentRequestFromFile(arg, request)) { if (request.getDetails().network() == "main") { SelectParams(CBaseChainParams::MAIN); } else if (request.getDetails().network() == "test") { SelectParams(CBaseChainParams::TESTNET); } } } else { // Printing to debug.log is about the best we can do here, the // GUI hasn't started yet so we can't pop up a message box. qWarning() << "PaymentServer::ipcSendCommandLine: Payment request file does not exist: " << arg; } } } // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; Q_FOREACH (const QString& r, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) { delete socket; socket = NULL; return false; } QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << r; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; socket = NULL; fResult = true; } return fResult; } PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) : QObject(parent), saveURIs(true), uriServer(0), netManager(0), optionsModel(0) { // Verify that the version of the library that we linked against is // compatible with the version of the headers we compiled against. GOOGLE_PROTOBUF_VERIFY_VERSION; // Install global event filter to catch QFileOpenEvents // on Mac: sent when you click litecoinz: links // other OSes: helpful when dealing with payment request files if (parent) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); if (startLocalServer) { uriServer = new QLocalServer(this); if (!uriServer->listen(name)) { // constructor is called early in init, so don't use "Q_EMIT message()" here QMessageBox::critical(0, tr("Payment request error"), tr("Cannot start litecoinz: click-to-pay handler")); } else { connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString))); } } } PaymentServer::~PaymentServer() { google::protobuf::ShutdownProtobufLibrary(); } // // OSX-specific way of handling litecoinz: URIs and PaymentRequest mime types. // Also used by paymentservertests.cpp and when opening a payment request file // via "Open URI..." menu entry. // bool PaymentServer::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FileOpen) { QFileOpenEvent *fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->file().isEmpty()) handleURIOrFile(fileEvent->file()); else if (!fileEvent->url().isEmpty()) handleURIOrFile(fileEvent->url().toString()); return true; } return QObject::eventFilter(object, event); } void PaymentServer::initNetManager() { if (!optionsModel) return; if (netManager != NULL) delete netManager; // netManager is used to fetch paymentrequests given in litecoinz: URIs netManager = new QNetworkAccessManager(this); QNetworkProxy proxy; // Query active SOCKS5 proxy if (optionsModel->getProxySettings(proxy)) { netManager->setProxy(proxy); qDebug() << "PaymentServer::initNetManager: Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port(); } else qDebug() << "PaymentServer::initNetManager: No active proxy server found."; connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(netRequestFinished(QNetworkReply*))); connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)), this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError> &))); } void PaymentServer::uiReady() { initNetManager(); saveURIs = false; Q_FOREACH (const QString& s, savedPaymentRequests) { handleURIOrFile(s); } savedPaymentRequests.clear(); } void PaymentServer::handleURIOrFile(const QString& s) { if (saveURIs) { savedPaymentRequests.append(s); return; } if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // litecoinz: URI { #if QT_VERSION < 0x050000 QUrl uri(s); #else QUrlQuery uri((QUrl(s))); #endif if (uri.hasQueryItem("r")) // payment request URI { QByteArray temp; temp.append(uri.queryItemValue("r")); QString decoded = QUrl::fromPercentEncoding(temp); QUrl fetchUrl(decoded, QUrl::StrictMode); if (fetchUrl.isValid()) { qDebug() << "PaymentServer::handleURIOrFile: fetchRequest(" << fetchUrl << ")"; fetchRequest(fetchUrl); } else { qWarning() << "PaymentServer::handleURIOrFile: Invalid URL: " << fetchUrl; Q_EMIT message(tr("URI handling"), tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()), CClientUIInterface::ICON_WARNING); } return; } else // normal URI { SendCoinsRecipient recipient; if (GUIUtil::parseBitcoinURI(s, &recipient)) { if (!IsValidDestinationString(recipient.address.toStdString())) { Q_EMIT message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address), CClientUIInterface::MSG_ERROR); } else Q_EMIT receivedPaymentRequest(recipient); } else Q_EMIT message(tr("URI handling"), tr("URI cannot be parsed! This can be caused by an invalid LitecoinZ address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); return; } } if (QFile::exists(s)) // payment request file { PaymentRequestPlus request; SendCoinsRecipient recipient; if (!readPaymentRequestFromFile(s, request)) { Q_EMIT message(tr("Payment request file handling"), tr("Payment request file cannot be read! This can be caused by an invalid payment request file."), CClientUIInterface::ICON_WARNING); } else if (processPaymentRequest(request, recipient)) Q_EMIT receivedPaymentRequest(recipient); return; } } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString msg; in >> msg; handleURIOrFile(msg); } // // Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine() // so don't use "Q_EMIT message()", but "QMessageBox::"! // bool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request) { QFile f(filename); if (!f.open(QIODevice::ReadOnly)) { qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename); return false; } // BIP70 DoS protection if (!verifySize(f.size())) { return false; } QByteArray data = f.readAll(); return request.parse(data); } bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, SendCoinsRecipient& recipient) { if (!optionsModel) return false; if (request.IsInitialized()) { // Payment request network matches client network? if (!verifyNetwork(request.getDetails())) { Q_EMIT message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."), CClientUIInterface::MSG_ERROR); return false; } // Make sure any payment requests involved are still valid. // This is re-checked just before sending coins in WalletModel::sendCoins(). if (verifyExpired(request.getDetails())) { Q_EMIT message(tr("Payment request rejected"), tr("Payment request expired."), CClientUIInterface::MSG_ERROR); return false; } } else { Q_EMIT message(tr("Payment request error"), tr("Payment request is not initialized."), CClientUIInterface::MSG_ERROR); return false; } recipient.paymentRequest = request; recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo()); request.getMerchant(certStore.get(), recipient.authenticatedMerchant); QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo(); QStringList addresses; Q_FOREACH(const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) { // Extract and check destination addresses CTxDestination dest; if (ExtractDestination(sendingTo.first, dest)) { // Append destination address addresses.append(QString::fromStdString(EncodeDestination(dest))); } else if (!recipient.authenticatedMerchant.isEmpty()) { // Unauthenticated payment requests to custom litecoinz addresses are not supported // (there is no good way to tell the user where they are paying in a way they'd // have a chance of understanding). Q_EMIT message(tr("Payment request rejected"), tr("Unverified payment requests to custom payment scripts are unsupported."), CClientUIInterface::MSG_ERROR); return false; } // LitecoinZ amounts are stored as (optional) uint64 in the protobuf messages (see paymentrequest.proto), // but CAmount is defined as int64_t. Because of that we need to verify that amounts are in a valid range // and no overflow has happened. if (!verifyAmount(sendingTo.second)) { Q_EMIT message(tr("Payment request rejected"), tr("Invalid payment request."), CClientUIInterface::MSG_ERROR); return false; } // Extract and check amounts CTxOut txOut(sendingTo.second, sendingTo.first); if (txOut.IsDust(::minRelayTxFee)) { Q_EMIT message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).") .arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)), CClientUIInterface::MSG_ERROR); return false; } recipient.amount += sendingTo.second; // Also verify that the final amount is still in a valid range after adding additional amounts. if (!verifyAmount(recipient.amount)) { Q_EMIT message(tr("Payment request rejected"), tr("Invalid payment request."), CClientUIInterface::MSG_ERROR); return false; } } // Store addresses and format them to fit nicely into the GUI recipient.address = addresses.join("<br />"); if (!recipient.authenticatedMerchant.isEmpty()) { qDebug() << "PaymentServer::processPaymentRequest: Secure payment request from " << recipient.authenticatedMerchant; } else { qDebug() << "PaymentServer::processPaymentRequest: Insecure payment request to " << addresses.join(", "); } return true; } void PaymentServer::fetchRequest(const QUrl& url) { QNetworkRequest netRequest; netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST); netRequest.setUrl(url); netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str()); netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTREQUEST); netManager->get(netRequest); } void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction) { const payments::PaymentDetails& details = recipient.paymentRequest.getDetails(); if (!details.has_payment_url()) return; QNetworkRequest netRequest; netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK); netRequest.setUrl(QString::fromStdString(details.payment_url())); netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT); netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str()); netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTACK); payments::Payment payment; payment.set_merchant_data(details.merchant_data()); payment.add_transactions(transaction.data(), transaction.size()); // Create a new refund address, or re-use: QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant); std::string strAccount = account.toStdString(); std::set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount); if (!refundAddresses.empty()) { CScript s = GetScriptForDestination(*refundAddresses.begin()); payments::Output* refund_to = payment.add_refund_to(); refund_to->set_script(&s[0], s.size()); } else { CPubKey newKey; if (wallet->GetKeyFromPool(newKey)) { CKeyID keyID = newKey.GetID(); wallet->SetAddressBook(keyID, strAccount, "refund"); CScript s = GetScriptForDestination(keyID); payments::Output* refund_to = payment.add_refund_to(); refund_to->set_script(&s[0], s.size()); } else { // This should never happen, because sending coins should have // just unlocked the wallet and refilled the keypool. qWarning() << "PaymentServer::fetchPaymentACK: Error getting refund key, refund_to not set"; } } int length = payment.ByteSize(); netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length); QByteArray serData(length, '\0'); if (payment.SerializeToArray(serData.data(), length)) { netManager->post(netRequest, serData); } else { // This should never happen, either. qWarning() << "PaymentServer::fetchPaymentACK: Error serializing payment message"; } } void PaymentServer::netRequestFinished(QNetworkReply* reply) { reply->deleteLater(); // BIP70 DoS protection if (!verifySize(reply->size())) { Q_EMIT message(tr("Payment request rejected"), tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).") .arg(reply->request().url().toString()) .arg(reply->size()) .arg(BIP70_MAX_PAYMENTREQUEST_SIZE), CClientUIInterface::MSG_ERROR); return; } if (reply->error() != QNetworkReply::NoError) { QString msg = tr("Error communicating with %1: %2") .arg(reply->request().url().toString()) .arg(reply->errorString()); qWarning() << "PaymentServer::netRequestFinished: " << msg; Q_EMIT message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR); return; } QByteArray data = reply->readAll(); QString requestType = reply->request().attribute(QNetworkRequest::User).toString(); if (requestType == BIP70_MESSAGE_PAYMENTREQUEST) { PaymentRequestPlus request; SendCoinsRecipient recipient; if (!request.parse(data)) { qWarning() << "PaymentServer::netRequestFinished: Error parsing payment request"; Q_EMIT message(tr("Payment request error"), tr("Payment request cannot be parsed!"), CClientUIInterface::MSG_ERROR); } else if (processPaymentRequest(request, recipient)) Q_EMIT receivedPaymentRequest(recipient); return; } else if (requestType == BIP70_MESSAGE_PAYMENTACK) { payments::PaymentACK paymentACK; if (!paymentACK.ParseFromArray(data.data(), data.size())) { QString msg = tr("Bad response from server %1") .arg(reply->request().url().toString()); qWarning() << "PaymentServer::netRequestFinished: " << msg; Q_EMIT message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR); } else { Q_EMIT receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo())); } } } void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError> &errs) { Q_UNUSED(reply); QString errString; Q_FOREACH (const QSslError& err, errs) { qWarning() << "PaymentServer::reportSslErrors: " << err; errString += err.errorString() + "\n"; } Q_EMIT message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR); } void PaymentServer::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void PaymentServer::handlePaymentACK(const QString& paymentACKMsg) { // currently we don't further process or store the paymentACK message Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL); } bool PaymentServer::verifyNetwork(const payments::PaymentDetails& requestDetails) { bool fVerified = requestDetails.network() == Params().NetworkIDString(); if (!fVerified) { qWarning() << QString("PaymentServer::%1: Payment request network \"%2\" doesn't match client network \"%3\".") .arg(__func__) .arg(QString::fromStdString(requestDetails.network())) .arg(QString::fromStdString(Params().NetworkIDString())); } return fVerified; } bool PaymentServer::verifyExpired(const payments::PaymentDetails& requestDetails) { bool fVerified = (requestDetails.has_expires() && (int64_t)requestDetails.expires() < GetTime()); if (fVerified) { const QString requestExpires = QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", (int64_t)requestDetails.expires())); qWarning() << QString("PaymentServer::%1: Payment request expired \"%2\".") .arg(__func__) .arg(requestExpires); } return fVerified; } bool PaymentServer::verifySize(qint64 requestSize) { bool fVerified = (requestSize <= BIP70_MAX_PAYMENTREQUEST_SIZE); if (!fVerified) { qWarning() << QString("PaymentServer::%1: Payment request too large (%2 bytes, allowed %3 bytes).") .arg(__func__) .arg(requestSize) .arg(BIP70_MAX_PAYMENTREQUEST_SIZE); } return fVerified; } bool PaymentServer::verifyAmount(const CAmount& requestAmount) { bool fVerified = MoneyRange(requestAmount); if (!fVerified) { qWarning() << QString("PaymentServer::%1: Payment request amount out of allowed range (%2, allowed 0 - %3).") .arg(__func__) .arg(requestAmount) .arg(MAX_MONEY); } return fVerified; } X509_STORE* PaymentServer::getCertStore() { return certStore.get(); }
{'content_hash': '269c4c388841e83e9103d2fdac574cd0', 'timestamp': '', 'source': 'github', 'line_count': 762, 'max_line_length': 289, 'avg_line_length': 35.44488188976378, 'alnum_prop': 0.6353807989929283, 'repo_name': 'litecoinz-project/litecoinz', 'id': '99499e32a3e9147377d744b9be6b2c1ecdb67c5f', 'size': '28052', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/qt/paymentserver.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '28453'}, {'name': 'C', 'bytes': '730195'}, {'name': 'C++', 'bytes': '6761814'}, {'name': 'HTML', 'bytes': '20970'}, {'name': 'Java', 'bytes': '30291'}, {'name': 'M4', 'bytes': '226422'}, {'name': 'Makefile', 'bytes': '154159'}, {'name': 'Objective-C', 'bytes': '6536'}, {'name': 'Objective-C++', 'bytes': '7240'}, {'name': 'Python', 'bytes': '906305'}, {'name': 'Shell', 'bytes': '103060'}]}
<?php namespace DTS\eBaySDK\MerchantData\Types; /** * * @property \DTS\eBaySDK\MerchantData\Types\AmountType $OriginalPrice * @property \DateTime $StartTime * @property \DateTime $EndTime */ class PromotionalSaleDetailsType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = array( 'OriginalPrice' => array( 'type' => 'DTS\eBaySDK\MerchantData\Types\AmountType', 'unbound' => false, 'attribute' => false, 'elementName' => 'OriginalPrice' ), 'StartTime' => array( 'type' => 'DateTime', 'unbound' => false, 'attribute' => false, 'elementName' => 'StartTime' ), 'EndTime' => array( 'type' => 'DateTime', 'unbound' => false, 'attribute' => false, 'elementName' => 'EndTime' ) ); /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = array()) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents'; } $this->setValues(__CLASS__, $childValues); } }
{'content_hash': 'ed4587bfc9783086358c69786efea3bf', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 116, 'avg_line_length': 29.80701754385965, 'alnum_prop': 0.5626839317245439, 'repo_name': 'emullaraj/ebay-sdk-php', 'id': '488a775bc8d97a9855bbcc40f5fb0cdd1aa04c2b', 'size': '2429', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/DTS/eBaySDK/MerchantData/Types/PromotionalSaleDetailsType.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Makefile', 'bytes': '1933'}, {'name': 'PHP', 'bytes': '8374034'}]}
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MyControlsSDK.Design")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Morten Nielsen")] [assembly: AssemblyProduct("MyControlsSDK.Design")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4591efab-08a0-424b-b66a-32aae8fa8a3f")]
{'content_hash': 'ac98cc6c8c2d2d69445e9c1006ddbe80', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 84, 'avg_line_length': 44.130434782608695, 'alnum_prop': 0.7793103448275862, 'repo_name': 'dotMorten/ExtensionSDKSample', 'id': 'f5a66085029f01145b9a470b75054ffb1f8efdf7', 'size': '1018', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/MyControlsSDK.Design/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '63'}, {'name': 'C#', 'bytes': '28502'}, {'name': 'C++', 'bytes': '318'}]}
Graphics::Graphics(Frame* f) { renderer = f->renderer; } void Graphics::setRender(Component* c) { component = c; SDL_SetRenderTarget(renderer, c ? c->texture: NULL); //SDL_RenderClear(renderer); } void Graphics::setColor(Color* c) { SDL_SetRenderDrawColor(renderer, c->r, c->g, c->b, c->a); } void Graphics::fillBackground() { Bounds b(0, 0, component->bounds.getWidth(), component->bounds.getHeight()); fillRectangle(b); } void Graphics::fillRectangle(Bounds& b) { SDL_Rect rect; rect.x = b.getX(); rect.y = b.getY(); rect.w = b.getWidth(); rect.h = b.getHeight(); SDL_RenderFillRect(renderer, &rect); } void Graphics::drawPoint(int x, int y) { SDL_RenderDrawPoint(renderer, x , y); } void Graphics::drawImage(const char* path, int x, int y) { SDL_Surface* img = IMG_Load(path); if(!img) throw ("Image not found"); SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, img); SDL_Rect rect = {x, y, img->w, img->h}; SDL_RenderCopy(renderer, texture, NULL, &rect); SDL_FreeSurface(img); SDL_DestroyTexture(texture); } void Graphics::finalize(Component* c) { SDL_SetRenderTarget(renderer, NULL); SDL_Rect rect; Bounds b = component->getShowableBounds(); rect.x = b.getX(); rect.y = b.getY(); rect.w = b.getWidth(); rect.h = b.getHeight(); SDL_RenderCopy(renderer, component->texture, NULL, &rect); //TODO : avec les scrollbar, le null sera utile SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); }
{'content_hash': '4ce27da93ffca3b50d5e085aed0d66eb', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 80, 'avg_line_length': 26.24590163934426, 'alnum_prop': 0.6171143035602749, 'repo_name': 'Alias-m/Blackbox', 'id': 'b6d2044c01a266fbaa3f79a1501dd0e148dd1fb4', 'size': '1676', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Blackbox/gui/components/Graphics.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '100499'}]}
package com.opengamma.strata.market.option; import org.joda.convert.FromString; import com.opengamma.strata.collect.TypedString; /** * The type of a strike. * <p> * The strike of option instruments is represented in different ways. * For example, the strike types include delta, moneyness, log-moneyness, and strike itself. */ public final class StrikeType extends TypedString<StrikeType> { /** Serialization version. */ private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The type of a simple strike. * @see SimpleStrike */ public static final StrikeType STRIKE = of("Strike"); /** * The type of a strike based on absolute delta. * @see DeltaStrike */ public static final StrikeType DELTA = of("Delta"); /** * The type of a strike based on moneyness, defined as {@code strike/forward}. * @see MoneynessStrike */ public static final StrikeType MONEYNESS = of("Moneyness"); /** * The type of a strike based on log-moneyness, defined as the {@code ln(strike/forward)}. * @see LogMoneynessStrike */ public static final StrikeType LOG_MONEYNESS = of("LogMoneyness"); //------------------------------------------------------------------------- /** * Obtains an instance from the specified name. * <p> * Strike types may contain any character, but must not be empty. * * @param name the name of the field * @return the type with the specified name */ @FromString public static StrikeType of(String name) { return new StrikeType(name); } /** * Creates an instance. * * @param name the name of the field */ private StrikeType(String name) { super(name); } }
{'content_hash': '6f9ae35efb472a4095c39dd426777317', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 92, 'avg_line_length': 27.153846153846153, 'alnum_prop': 0.6181303116147309, 'repo_name': 'ChinaQuants/Strata', 'id': '1364f4efbfc6a4ad88005e52d0bc8c388ca45616', 'size': '1902', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/market/src/main/java/com/opengamma/strata/market/option/StrikeType.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '23559288'}]}
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.cfg; import org.activiti.engine.impl.interceptor.CommandContext; /** * @author Tom Baeyens */ public interface TransactionListener { void execute(CommandContext commandContext); }
{'content_hash': 'c3a346137a4fb1b6a1f559f80a91bb4e', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 75, 'avg_line_length': 32.625, 'alnum_prop': 0.7509578544061303, 'repo_name': 'springvelocity/xbpm5', 'id': '9774a2516a67616f40bc86d55f7092635806ad00', 'size': '783', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'activiti-engine/src/main/java/org/activiti/engine/impl/cfg/TransactionListener.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '4980251'}, {'name': 'Shell', 'bytes': '250'}]}
namespace base { class TaskLoop; } namespace android { class Platform : public ::Platform { public: Platform(); void Initialize(JNIEnv * env, jobject functorProcessObject, jstring apkPath, jstring storagePath, jstring privatePath, jstring tmpPath, jstring obbGooglePath, jstring flavorName, jstring buildType, bool isTablet); ~Platform() override; void OnExternalStorageStatusChanged(bool isAvailable); /// get storage path without ending "/MapsWithMe/" std::string GetStoragePathPrefix() const; /// assign storage path (should contain ending "/MapsWithMe/") void SetWritableDir(std::string const & dir); void SetSettingsDir(std::string const & dir); bool HasAvailableSpaceForWriting(uint64_t size) const; void SendPushWooshTag(std::string const & tag, std::vector<std::string> const & values); void SendMarketingEvent(std::string const & tag, std::map<std::string, std::string> const & params); void SetGuiThread(std::unique_ptr<base::TaskLoop> guiThread); class AndroidSecureStorage { public: void Save(std::string const & key, std::string const & value); bool Load(std::string const & key, std::string & value); void Remove(std::string const & key); private: void Init(JNIEnv * env); jclass m_secureStorageClass = nullptr; }; AndroidSecureStorage & GetSecureStorage() { return m_secureStorage; } jobject GetContext() { return m_functorProcessObject; } static Platform & Instance(); private: jobject m_functorProcessObject = nullptr; jmethodID m_sendPushWooshTagsMethod = nullptr; jmethodID m_sendAppsFlyerTagsMethod = nullptr; AndroidSecureStorage m_secureStorage; }; extern int GetAndroidSdkVersion(); } // namespace android
{'content_hash': '54bcf89a4c2328763537ed3258767700', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 102, 'avg_line_length': 28.258064516129032, 'alnum_prop': 0.7248858447488584, 'repo_name': 'milchakov/omim', 'id': '27f1ddeae793347a7e17fe91d2a9d5f1b0b6b928', 'size': '1855', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'android/jni/com/mapswithme/platform/Platform.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '3962'}, {'name': 'Batchfile', 'bytes': '3328'}, {'name': 'C', 'bytes': '13762107'}, {'name': 'C++', 'bytes': '39847686'}, {'name': 'CMake', 'bytes': '335312'}, {'name': 'CSS', 'bytes': '26798'}, {'name': 'Common Lisp', 'bytes': '17587'}, {'name': 'DIGITAL Command Language', 'bytes': '36710'}, {'name': 'GLSL', 'bytes': '60719'}, {'name': 'Gherkin', 'bytes': '305230'}, {'name': 'Go', 'bytes': '12771'}, {'name': 'HTML', 'bytes': '1305869'}, {'name': 'Inno Setup', 'bytes': '4337'}, {'name': 'Java', 'bytes': '2758722'}, {'name': 'JavaScript', 'bytes': '3265'}, {'name': 'Lua', 'bytes': '57672'}, {'name': 'M4', 'bytes': '48177'}, {'name': 'Makefile', 'bytes': '303910'}, {'name': 'Metal', 'bytes': '80149'}, {'name': 'Module Management System', 'bytes': '2080'}, {'name': 'Objective-C', 'bytes': '532953'}, {'name': 'Objective-C++', 'bytes': '1052627'}, {'name': 'PHP', 'bytes': '2841'}, {'name': 'Perl', 'bytes': '47465'}, {'name': 'PowerShell', 'bytes': '1885'}, {'name': 'Python', 'bytes': '759461'}, {'name': 'Roff', 'bytes': '13545'}, {'name': 'Ruby', 'bytes': '64691'}, {'name': 'Shell', 'bytes': '959349'}, {'name': 'Starlark', 'bytes': '965'}, {'name': 'Swift', 'bytes': '869832'}, {'name': 'TSQL', 'bytes': '3430'}, {'name': 'sed', 'bytes': '236'}]}