content
stringlengths
128
6.74k
<commit_msg>Make touch plugin touch files with lists <commit_before>from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def touch_file(path, context): content = context.get('article', context.get('page')) if content and hasattr(content, 'date'): mtime = time.mktime(content.date.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def register(): signals.content_written.connect(touch_file) <commit_after>from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def register(): signals.content_written.connect(touch_file)
<commit_msg>Clarify lpBuffer layout in GetUserName unit test <commit_before> using std::string; using std::vector; using SCXCoreLib::Utf16leToUtf8; TEST(GetUserName,simple) { // allocate a WCHAR_T buffer to receive username DWORD lpnSize = 64; WCHAR_T lpBuffer[lpnSize]; BOOL result = GetUserName(lpBuffer, &lpnSize); // GetUserName returns 1 on success ASSERT_EQ(1, result); // get expected username string username = string(getlogin()); // GetUserName sets lpnSize to length of username including null ASSERT_EQ(username.size()+1, lpnSize); // copy UTF-16 bytes from lpBuffer to vector for conversion vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]), reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1])); // convert to UTF-8 for assertion string output; Utf16leToUtf8(input, output); EXPECT_EQ(username, output); } <commit_after> using std::string; using std::vector; using SCXCoreLib::Utf16leToUtf8; TEST(GetUserName,simple) { // allocate a WCHAR_T buffer to receive username DWORD lpnSize = 64; WCHAR_T lpBuffer[lpnSize]; BOOL result = GetUserName(lpBuffer, &lpnSize); // GetUserName returns 1 on success ASSERT_EQ(1, result); // get expected username string username = string(getlogin()); // GetUserName sets lpnSize to length of username including null ASSERT_EQ(username.size()+1, lpnSize); // copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]); // -1 to skip null; *2 because UTF-16 encodes two bytes per character unsigned char *end = begin + (lpnSize-1)*2; vector<unsigned char> input(begin, end); // convert to UTF-8 for assertion string output; Utf16leToUtf8(input, output); EXPECT_EQ(username, output); }
<commit_msg>TDP-2107: Fix issue in filter out node for empty content * Fix issue when filter node filters out all values in source data. <commit_before>package org.talend.dataprep.transformation.pipeline.node; import java.util.function.Function; import java.util.function.Predicate; import org.talend.dataprep.api.dataset.DataSetRow; import org.talend.dataprep.api.dataset.RowMetadata; public class FilteredNode extends BasicNode { private final Function<RowMetadata, Predicate<DataSetRow>> filter; private Predicate<DataSetRow> instance; public FilteredNode(Function<RowMetadata, Predicate<DataSetRow>> filter) { this.filter = filter; } @Override public void receive(DataSetRow row, RowMetadata metadata) { synchronized (filter) { if (instance == null) { instance = filter.apply(metadata); } } if (instance.test(row)) { super.receive(row, metadata); } } } <commit_after>package org.talend.dataprep.transformation.pipeline.node; import java.util.Collections; import java.util.function.Function; import java.util.function.Predicate; import org.talend.dataprep.api.dataset.DataSetRow; import org.talend.dataprep.api.dataset.RowMetadata; import org.talend.dataprep.transformation.pipeline.Signal; public class FilteredNode extends BasicNode { private final Function<RowMetadata, Predicate<DataSetRow>> filter; private Predicate<DataSetRow> instance; private boolean hasMatchedFilter = false; private RowMetadata lastRowMetadata; public FilteredNode(Function<RowMetadata, Predicate<DataSetRow>> filter) { this.filter = filter; } @Override public void receive(DataSetRow row, RowMetadata metadata) { synchronized (filter) { if (instance == null) { instance = filter.apply(metadata); } } if (instance.test(row)) { hasMatchedFilter = true; super.receive(row, metadata); } else { lastRowMetadata = metadata; } } @Override public void signal(Signal signal) { if (signal == Signal.END_OF_STREAM && !hasMatchedFilter) { // Ensure next steps at least receives metadata information. final DataSetRow row = new DataSetRow(lastRowMetadata, Collections.emptyMap()); super.receive(row, lastRowMetadata); } super.signal(signal); } }
<commit_msg>fix: Change default params for plugin affects: sush-plugin-trim-id <commit_before>import { SUSHInfo } from 'sush'; export interface TrimIdParams { head?: number; tail?: number; } /** * `SUSHPluginTrimId` trims head or tail from ID. */ function SUSHPluginTrimId ( { head, tail }: TrimIdParams = { head: 0, tail: 0 } ) { return ({ id, stock }: SUSHInfo) => { const newId = (!tail) ? id.slice(head) : id.slice(head, -1 * tail); return { id: newId, stock } as SUSHInfo; }; }; export default SUSHPluginTrimId; <commit_after>import { SUSHInfo } from 'sush'; export interface TrimIdParams { head?: number; tail?: number; } /** * `SUSHPluginTrimId` trims head or tail from ID. */ function SUSHPluginTrimId ( { head = 0, tail = 0 }: TrimIdParams = {} ) { return ({ id, stock }: SUSHInfo) => { const newId = (!tail) ? id.slice(head) : id.slice(head, -1 * tail); return { id: newId, stock } as SUSHInfo; }; }; export default SUSHPluginTrimId;
<commit_msg>Raise an error when a symbol cannot be found <commit_before>class Environment: def __init__(self, par=None, bnd=None): if bnd: self.binds = bnd else: self.binds = {} self.parent = par if par: self.level = self.parent.level + 1 else: self.level = 0 def get(self, key): if key in self.binds: return self.binds[key] elif self.parent: return self.parent.get(key) else: return None def set(self, key, value): if key in self.binds: self.binds[key] = value elif self.parent: self.parent.set(key,value) else: self.binds[key] = value def __repr__( self): ret = "\n%s:\n" % self.level keys = self.binds.keys() for key in keys: ret = ret + " %5s: %s\n" % (key, self.binds[key]) return ret <commit_after>class Environment: def __init__(self, par=None, bnd=None): if bnd: self.binds = bnd else: self.binds = {} self.parent = par if par: self.level = self.parent.level + 1 else: self.level = 0 def get(self, key): if key in self.binds: return self.binds[key] elif self.parent: return self.parent.get(key) else: raise ValueError("Invalid symbol " + key) def set(self, key, value): if key in self.binds: self.binds[key] = value elif self.parent: self.parent.set(key,value) else: self.binds[key] = value def __repr__( self): ret = "\n%s:\n" % self.level keys = self.binds.keys() for key in keys: ret = ret + " %5s: %s\n" % (key, self.binds[key]) return ret
<commit_msg>Add new custom types, import new mods <commit_before>extern crate hyper; mod contentlength; pub mod http_version; pub mod download; /// Represents a byte, in `u64`. type Byte = u64; <commit_after>extern crate hyper; use std::sync::{Arc, Mutex}; pub mod client; mod contentlength; pub mod download; pub mod http_version; /// Represents a number of bytes, in `u64`. type Byte = u64; /// Represents a 'chunk', which is just a piece of bytes. type Chunk = Vec<u8>; /// Represents a list of chunks type Chunks = Vec<Chunk>; /// Represents a shared mutable reference of chunks type SChunks = Arc<Mutex<Chunks>>;
<commit_msg>Create Typescript types for JoinRule, GuestAccess, HistoryVisibility, including join_rule=restricted <commit_before>/* Copyright 2021 The Matrix.org Foundation C.I.C. 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. */ export interface IImageInfo { size?: number; mimetype?: string; thumbnail_info?: { // eslint-disable-line camelcase w?: number; h?: number; size?: number; mimetype?: string; }; w?: number; h?: number; } export enum Visibility { Public = "public", Private = "private", } export enum Preset { PrivateChat = "private_chat", TrustedPrivateChat = "trusted_private_chat", PublicChat = "public_chat", } <commit_after>/* Copyright 2021 The Matrix.org Foundation C.I.C. 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. */ export interface IImageInfo { size?: number; mimetype?: string; thumbnail_info?: { // eslint-disable-line camelcase w?: number; h?: number; size?: number; mimetype?: string; }; w?: number; h?: number; } export enum Visibility { Public = "public", Private = "private", } export enum Preset { PrivateChat = "private_chat", TrustedPrivateChat = "trusted_private_chat", PublicChat = "public_chat", } // Knock and private are reserved keywords which are not yet implemented. export enum JoinRule { Public = "public", Invite = "invite", Private = "private", // reserved keyword, not yet implemented. Knock = "knock", // MSC2403 - only valid inside experimental room versions at this time. Restricted = "restricted", // MSC3083 - only valid inside experimental room versions at this time. } export enum GuestAccess { CanJoin = "can_join", Forbidden = "forbidden", } export enum HistoryVisibility { Invited = "invited", Joined = "joined", Shared = "shared", WorldReadable = "world_readable", }
<commit_msg>Handle Nonetype values in `html_to_md` <commit_before>import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if strip_html: string = strip_html_tags(string) if markdown: string = text_maker.handle(string) return string def get_formatted_book_data(book_data): template = textwrap.dedent("""\ *Title:* {0} by {1} *Rating:* {2} by {3} users *Description:* {4} *Link*: [click me]({5}) Tip: {6}""") title = book_data['title'] authors = book_data['authors'] average_rating = book_data['average_rating'] ratings_count = book_data['ratings_count'] description = html_to_md(book_data.get('description', '')) url = book_data['url'] tip = 'Use author name also for better search results' template = template.format(title, authors, average_rating, ratings_count, description, url, tip) return template <commit_after>import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if not string: return 'No Description Found' if strip_html: string = strip_html_tags(string) if markdown: string = text_maker.handle(string) return string def get_formatted_book_data(book_data): template = textwrap.dedent("""\ *Title:* {0} by {1} *Rating:* {2} by {3} users *Description:* {4} *Link*: [click me]({5}) Tip: {6}""") title = book_data['title'] authors = book_data['authors'] average_rating = book_data['average_rating'] ratings_count = book_data['ratings_count'] description = html_to_md(book_data.get('description', '')) url = book_data['url'] tip = 'Use author name also for better search results' template = template.format(title, authors, average_rating, ratings_count, description, url, tip) return template
<commit_msg>Add counter Static example plus non Static <commit_before>/** * @file Counter.java * @author Valery Samovich * @version 1 * @date 2015/01/05 */ package com.valerysamovich.java.oop.staticex.counter; public class Counter { NonStaticCounter c1 = new NonStaticCounter(); NonStaticCounter c2 = new NonStaticCounter(); NonStaticCounter c3 = new NonStaticCounter(); } <commit_after>/** * @file Counter.java * @author Valery Samovich * @version 1 * @date 2015/01/05 */ package com.valerysamovich.java.oop.staticex.counter; public class Counter { public static void main(String[] args) { System.out.println("Non Static Objects:"); // Non Static Object Counters NonStaticCounter c1 = new NonStaticCounter(); NonStaticCounter c2 = new NonStaticCounter(); NonStaticCounter c3 = new NonStaticCounter(); System.out.println(" "); System.out.println("Static Objects:"); // Static Object Counters StaticCounter c4 = new StaticCounter(); StaticCounter c5 = new StaticCounter(); StaticCounter c6 = new StaticCounter(); } }
<commit_msg>Check metalanguage applicability in getAllBaseLanguageIdsWithAny() GitOrigin-RevId: f76645e6ba0672f74059aa8b4ec97855d6a5527c<commit_before>// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; import com.intellij.lang.Language; import com.intellij.lang.LanguageExtension; import com.intellij.lang.MetaLanguage; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; class CompletionExtension<T> extends LanguageExtension<T> { CompletionExtension(String epName) { super(epName); } @NotNull @Override protected List<T> buildExtensions(@NotNull String stringKey, @NotNull Language key) { return buildExtensions(getAllBaseLanguageIdsWithAny(key)); } @NotNull private Set<String> getAllBaseLanguageIdsWithAny(@NotNull Language key) { Set<String> allowed = new THashSet<>(); while (key != null) { allowed.add(keyToString(key)); key = key.getBaseLanguage(); } allowed.add("any"); for (MetaLanguage metaLanguage : MetaLanguage.all()) { allowed.add(metaLanguage.getID()); } return allowed; } } <commit_after>// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; import com.intellij.lang.Language; import com.intellij.lang.LanguageExtension; import com.intellij.lang.MetaLanguage; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; class CompletionExtension<T> extends LanguageExtension<T> { CompletionExtension(String epName) { super(epName); } @NotNull @Override protected List<T> buildExtensions(@NotNull String stringKey, @NotNull Language key) { return buildExtensions(getAllBaseLanguageIdsWithAny(key)); } @NotNull private Set<String> getAllBaseLanguageIdsWithAny(@NotNull Language key) { Set<String> allowed = new THashSet<>(); while (key != null) { allowed.add(keyToString(key)); for (MetaLanguage metaLanguage : MetaLanguage.all()) { if (metaLanguage.matchesLanguage(key)) allowed.add(metaLanguage.getID()); } key = key.getBaseLanguage(); } allowed.add("any"); return allowed; } }
<commit_msg>Add a test that reproduces the crash if you sign up a second time with the same name <commit_before>from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it meta.session.delete(user) <commit_after>from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self, actually_delete_it=True): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it if actually_delete_it: meta.session.delete(user) else: return user def test_maintainer_signup_with_duplicate_name(self): self.test_maintainer_signup(actually_delete_it=False) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me_again@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count() self.assertEquals(count, 1)
<commit_msg>Fix mobile test suite was using incorrect desktop image search test. <commit_before>package pt.fccn.mobile.arquivo.suite; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import pt.fccn.arquivo.tests.imagesearch.ImageSearchTest; import pt.fccn.mobile.arquivo.tests.FullTextSearchTest; import pt.fccn.mobile.arquivo.tests.URLSearchTest; import pt.fccn.mobile.arquivo.tests.imagesearch.ImageAdvancedSearchTest; import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchDirectUrlTest; /** * * @author João Nobre * */ @RunWith(Suite.class) @SuiteClasses({ FullTextSearchTest.class, URLSearchTest.class, ImageAdvancedSearchTest.class, ImageSearchDirectUrlTest.class, ImageSearchTest.class }) public class TestSuite { } <commit_after>package pt.fccn.mobile.arquivo.suite; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import pt.fccn.mobile.arquivo.tests.FullTextSearchTest; import pt.fccn.mobile.arquivo.tests.URLSearchTest; import pt.fccn.mobile.arquivo.tests.imagesearch.ImageAdvancedSearchTest; import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchDirectUrlTest; import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchTest; /** * * @author João Nobre * */ @RunWith(Suite.class) @SuiteClasses({ FullTextSearchTest.class, URLSearchTest.class, ImageAdvancedSearchTest.class, ImageSearchDirectUrlTest.class, ImageSearchTest.class }) public class TestSuite { }
<commit_msg>Fix backward compatibility for RN < 0.47<commit_before>package com.react.rnspinkit; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by suzuri04x2 on 2016/5/10. */ public class RNSpinkitPackage implements ReactPackage{ @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> list = new ArrayList<>(); list.add(new RNSpinkit(reactContext)); return list; } } <commit_after>package com.react.rnspinkit; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by suzuri04x2 on 2016/5/10. */ public class RNSpinkitPackage implements ReactPackage{ @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> list = new ArrayList<>(); list.add(new RNSpinkit(reactContext)); return list; } }
<commit_msg>Implement basic printing of the singles chart <commit_before>import click import requests url = 'http://ben-major.co.uk/labs/top40/api/singles/' response = requests.get(url) print response.json() <commit_after> import click import requests url = 'http://ben-major.co.uk/labs/top40/api/singles/' @click.command() @click.option('--count', default=10, help='Number of songs to show. Maximum is 40') def get_charts(count): """Prints the top COUNT songs in the UK Top 40 chart.""" response = requests.get(url).json() data = response['entries'][:count] for index, element in enumerate(data, start=1): click.echo( '{}. {} - {}'.format( index, element['title'], element['artist'].encode('utf-8', 'replace'))) if __name__ == '__main__': get_charts()
<commit_msg>Remove 'limits' fields from 'Edit' form for allocation [WAL-3066] <commit_before>import { gettext } from '@waldur/i18n'; import { ActionConfigurationRegistry } from '@waldur/resource/actions/action-configuration'; import { DEFAULT_EDIT_ACTION } from '@waldur/resource/actions/constants'; ActionConfigurationRegistry.register('SLURM.Allocation', { order: ['details', 'pull', 'edit', 'cancel', 'destroy'], options: { pull: { title: gettext('Synchronise'), }, details: { title: gettext('Details'), component: 'slurmAllocationDetailsDialog', enabled: true, useResolve: true, type: 'form', dialogSize: 'lg', }, edit: { ...DEFAULT_EDIT_ACTION, successMessage: gettext('Allocation has been updated.'), fields: { cpu_limit: { type: 'integer', label: gettext('CPU limit, minutes'), required: true, resource_default_value: true, }, gpu_limit: { type: 'integer', label: gettext('GPU limit, minutes'), required: true, resource_default_value: true, }, ram_limit: { type: 'integer', label: gettext('RAM limit, MB'), required: true, resource_default_value: true, }, }, }, }, }); <commit_after>import { gettext } from '@waldur/i18n'; import { ActionConfigurationRegistry } from '@waldur/resource/actions/action-configuration'; import { DEFAULT_EDIT_ACTION } from '@waldur/resource/actions/constants'; ActionConfigurationRegistry.register('SLURM.Allocation', { order: ['details', 'pull', 'edit', 'cancel', 'destroy'], options: { pull: { title: gettext('Synchronise'), }, details: { title: gettext('Details'), component: 'slurmAllocationDetailsDialog', enabled: true, useResolve: true, type: 'form', dialogSize: 'lg', }, edit: { ...DEFAULT_EDIT_ACTION, successMessage: gettext('Allocation has been updated.'), }, }, });
<commit_msg>Change the background thread to daemon thread so that a script closes all other threads closes as well<commit_before>package detective.common.httpclient; import java.util.concurrent.TimeUnit; import org.apache.http.conn.HttpClientConnectionManager; public class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }<commit_after>package detective.common.httpclient; import java.util.concurrent.TimeUnit; import org.apache.http.conn.HttpClientConnectionManager; public class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) { super(); this.connMgr = connMgr; this.setDaemon(true); } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }
<commit_msg>Create workers base on cpu number. <commit_before>package main import ( "./mega" "./task" "os" "fmt" "log" "io/ioutil" ) const MaxWorker = 10 func main() { if len(os.Args) == 0 { log.Fatal("Please offer json file.") } pool, err := task.CreatePool() if err != nil { log.Fatal(err) } pool.Registry(task.MegaType, mega.MegaRoot{}) file, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { log.Fatal(err) } _, err = pool.Add(task.MegaType, file.Name(), data) if err != nil { log.Fatal(err) } go pool.Start() for i := 0; i < MaxWorker; i++{ go func(i int) { for { fmt.Println("Process", i, "asking...") t, ok := pool.Ask() if ok { fmt.Println("Process", i, "downloading...") t.Download() fmt.Println("Process", i, "reporting...") pool.Report(t) fmt.Println("Process", i, "done") } } }(i) } select{} } <commit_after>package main import ( "./mega" "./task" "os" "fmt" "log" "runtime" "io/ioutil" ) var MaxWorker int func init() { MaxWorker = runtime.NumCPU() << 1 } func main() { if len(os.Args) == 0 { log.Fatal("Please offer json file.") } pool, err := task.CreatePool() if err != nil { log.Fatal(err) } pool.Registry(task.MegaType, mega.MegaRoot{}) file, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { log.Fatal(err) } _, err = pool.Add(task.MegaType, file.Name(), data) if err != nil { log.Fatal(err) } go pool.Start() for i := 0; i < MaxWorker; i++{ go func(i int) { for { fmt.Println("Process", i, "asking...") t, ok := pool.Ask() if ok { fmt.Println("Process", i, "downloading...") t.Download() fmt.Println("Process", i, "reporting...") pool.Report(t) fmt.Println("Process", i, "done") } } }(i) } select{} }
<commit_msg>tests: Add small testcase for 3-arg slices. <commit_before>x = list(range(10)) print(x[::-1]) print(x[::2]) print(x[::-2]) <commit_after>x = list(range(10)) print(x[::-1]) print(x[::2]) print(x[::-2]) x = list(range(9)) print(x[::-1]) print(x[::2]) print(x[::-2])
<commit_msg>[IMP] event_registration_hr_contract: Remove the dependence with the module hr_contract_stage. <commit_before>{ "name": "Event Registration Hr Contract", 'version': '8.0.1.1.0', 'license': "AGPL-3", 'author': "AvanzOSC", 'website': "http://www.avanzosc.es", 'contributors': [ "Ana Juaristi <anajuaristi@avanzosc.es>", "Alfredo de la Fuente <alfredodelafuente@avanzosc.es", ], "category": "Event Management", "depends": [ 'event_track_presence_hr_holidays', 'hr_contract_stages' ], "data": [ 'wizard/wiz_calculate_employee_calendar_view.xml', 'wizard/wiz_event_append_assistant_view.xml', 'views/event_event_view.xml', 'views/hr_contract_view.xml', 'views/event_track_presence_view.xml', 'views/res_partner_calendar_view.xml', 'views/res_partner_calendar_day_view.xml' ], "installable": True, } <commit_after>{ "name": "Event Registration Hr Contract", 'version': '8.0.1.1.0', 'license': "AGPL-3", 'author': "AvanzOSC", 'website': "http://www.avanzosc.es", 'contributors': [ "Ana Juaristi <anajuaristi@avanzosc.es>", "Alfredo de la Fuente <alfredodelafuente@avanzosc.es", ], "category": "Event Management", "depends": [ 'event_track_presence_hr_holidays', ], "data": [ 'wizard/wiz_calculate_employee_calendar_view.xml', 'wizard/wiz_event_append_assistant_view.xml', 'views/event_event_view.xml', 'views/hr_contract_view.xml', 'views/event_track_presence_view.xml', 'views/res_partner_calendar_view.xml', 'views/res_partner_calendar_day_view.xml' ], "installable": True, }
<commit_msg>Add alias to sys_rand and sys_srand <commit_before>static unsigned long next = 1; /* RAND_MAX assumed to be 32767 */ int sys_rand(void) { next = next * 1103515245 + 12345; return((unsigned)(next/65536) % 32768); } void sys_srand(unsigned seed) { next = seed; } <commit_after>static unsigned long next = 1; /* RAND_MAX assumed to be 32767 */ int sys_rand(void) { next = next * 1103515245 + 12345; return((unsigned)(next/65536) % 32768); } void sys_srand(unsigned seed) { next = seed; } __attribute__((weak)) int rand(void) { return sys_rand(); } __attribute__((weak)) void srand(unsigned seed) { srand(seed); }
<commit_msg>Adjust test for new overlap message on default trait impls <commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(optin_builtin_traits)] trait MyTrait {} impl MyTrait for .. {} impl MyTrait for .. {} //~^ ERROR conflicting implementations of trait `MyTrait` trait MySafeTrait {} unsafe impl MySafeTrait for .. {} //~^ ERROR implementing the trait `MySafeTrait` is not unsafe unsafe trait MyUnsafeTrait {} impl MyUnsafeTrait for .. {} //~^ ERROR the trait `MyUnsafeTrait` requires an `unsafe impl` declaration fn main() {} <commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(optin_builtin_traits)] trait MyTrait {} impl MyTrait for .. {} impl MyTrait for .. {} //~^ ERROR redundant default implementations of trait `MyTrait` trait MySafeTrait {} unsafe impl MySafeTrait for .. {} //~^ ERROR implementing the trait `MySafeTrait` is not unsafe unsafe trait MyUnsafeTrait {} impl MyUnsafeTrait for .. {} //~^ ERROR the trait `MyUnsafeTrait` requires an `unsafe impl` declaration fn main() {}
<commit_msg>Add support for multiple datasets <commit_before>import sys import click import json import csv from rdflib import Graph, Namespace, URIRef def observe_dataset(dataset, query, prefixes): g = Graph() if prefixes: prefixes = json.load(prefixes) for name, url in prefixes.items(): g.bind(name, Namespace(url.strip('<>'))) g.parse(dataset) return g, g.query(query.read()) def create_csv(graph, query_result, f): def normalize_field(field): if not field: return None elif isinstance(field, URIRef): return field.n3(graph.namespace_manager) return field writer = csv.writer(f) writer.writerow(query_result.vars) for row in query_result: writer.writerow(map(normalize_field, row)) @click.command() @click.argument('dataset', type=click.File('r')) @click.argument('query', type=click.File('r')) @click.option('--prefixes', '-p', default=None, type=click.File('r')) @click.option('--output', '-o', default=sys.stdout, type=click.File('w')) def command(dataset, query, prefixes, output): graph, query_result = observe_dataset(dataset, query, prefixes) create_csv(graph, query_result, output) if __name__ == '__main__': command() <commit_after>import sys import click import json import csv from rdflib import Graph, Namespace, URIRef def observe_dataset(datasets, query, prefixes): g = Graph() if prefixes: prefixes = json.load(prefixes) for name, url in prefixes.items(): g.bind(name, Namespace(url.strip('<>'))) for dataset in datasets: g.parse(dataset) return g, g.query(query.read()) def create_csv(graph, query_result, f): def normalize_field(field): if not field: return None elif isinstance(field, URIRef): return field.n3(graph.namespace_manager) return field writer = csv.writer(f) writer.writerow(query_result.vars) for row in query_result: writer.writerow(map(normalize_field, row)) @click.command() @click.argument('datasets', type=click.File('r'), nargs=-1) @click.argument('query', type=click.File('r')) @click.option('--prefixes', '-p', default=None, type=click.File('r')) @click.option('--output', '-o', default=sys.stdout, type=click.File('w')) def command(datasets, query, prefixes, output): graph, query_result = observe_dataset(datasets, query, prefixes) create_csv(graph, query_result, output) if __name__ == '__main__': command()
<commit_msg>Allow to properly disable verification of SSL <commit_before>"""Python library to enable Axis devices to integrate with Home Assistant.""" import requests from requests.auth import HTTPDigestAuth class Configuration(object): """Device configuration.""" def __init__(self, *, loop, host, username, password, port=80, web_proto='http', verify_ssl=False, event_types=None, signal=None): """All config params available to the device.""" self.loop = loop self.web_proto = web_proto self.host = host self.port = port self.username = username self.password = password self.session = requests.Session() self.session.auth = HTTPDigestAuth( self.username, self.password) if self.web_proto == 'https': self.session.verify_ssl = verify_ssl self.event_types = event_types self.signal = signal <commit_after>"""Python library to enable Axis devices to integrate with Home Assistant.""" import requests from requests.auth import HTTPDigestAuth class Configuration(object): """Device configuration.""" def __init__(self, *, loop, host, username, password, port=80, web_proto='http', verify_ssl=False, event_types=None, signal=None): """All config params available to the device.""" self.loop = loop self.web_proto = web_proto self.host = host self.port = port self.username = username self.password = password self.session = requests.Session() self.session.auth = HTTPDigestAuth(self.username, self.password) self.session.verify = verify_ssl self.event_types = event_types self.signal = signal
<commit_msg>Add commented-out test for init with no args <commit_before>import os from click.testing import CliRunner from morenines import application def test_init(data_dir): runner = CliRunner() result = runner.invoke(application.main, ['init', data_dir]) assert result.exit_code == 0 mn_dir = os.path.join(data_dir, '.morenines') assert os.path.isdir(mn_dir) == True <commit_after>import os from click.testing import CliRunner from morenines import application def test_init(data_dir): runner = CliRunner() result = runner.invoke(application.main, ['init', data_dir]) assert result.exit_code == 0 mn_dir = os.path.join(data_dir, '.morenines') assert os.path.isdir(mn_dir) == True # XXX I can't get this test to work because chdir() isn't having any effect. # I suspect it's somehow related to testing with click, but I can't figure # out exactly why. # # Leaving the test in but commented because it's failing because of the # testing environment, not the code, so having it always fail won't tell us # anything useful. It would be nice to have it part of the suite eventually. # #def test_init_with_no_args(tmpdir, monkeypatch): # monkeypatch.chdir(tmpdir.strpath) # # runner = CliRunner() # result = runner.invoke(application.main, ['init']) # # mn_dir = tmpdir.join('.morenines').strpath # # assert os.path.isdir(mn_dir) == True
<commit_msg>Set maintainer and add dependencies to distutils config <commit_before>from distutils.core import setup setup(name='pyresttest', version='0.1', description='Python Rest Testing', maintainer='Naveen Malik', maintainer_email='jewzaam@gmail.com', url='https://github.com/svanoort/pyresttest', py_modules=['resttest','pycurl_benchmark','test_resttest'], license='Apache License, Version 2.0' ) <commit_after>from distutils.core import setup setup(name='pyresttest', version='0.1', description='Python Rest Testing', maintainer='Sam Van Oort', maintainer_email='acetonespam@gmail.com', url='https://github.com/svanoort/pyresttest', py_modules=['resttest','test_resttest'], license='Apache License, Version 2.0', requires=['argparse','yaml','pycurl'] )
<commit_msg>Reduce primes calculated by a factor of ten. <commit_before>package com.rmd.personal.projecteuler; import java.util.Date; import java.util.LinkedList; import java.util.List; public final class Common { private static final int MAX_PRIME_VALUE = 20000000; private Common() { } private static List<Long> primes; static { primes = new LinkedList<Long>(); populatePrimesUpTo(MAX_PRIME_VALUE); } protected static List<Long> getPrimes() { return primes; } private static void populatePrimesUpTo(int end) { System.out.println("populating primes up to: " + end); Date startTime = new Date(); boolean[] values = new boolean[end]; for (int i = 2; i < end; i++) { if (!values[i]) { primes.add((long) i); for (int j = i; j < end; j += i) { values[j] = true; } } } Date endTime = new Date(); System.out.println("done - took " + (endTime.getTime() - startTime.getTime()) + " ms."); } protected static long sumPrimesUpTo(int end) { boolean[] values = new boolean[end]; long sum = 0; for (int i = 2; i < end; i++) { if (!values[i]) { primes.add((long) i); sum += i; for (int j = i; j < end; j += i) { values[j] = true; } } } return sum; } protected static long sum(long n) { return (n * (n + 1)) / 2; } } <commit_after>package com.rmd.personal.projecteuler; import java.util.LinkedList; import java.util.Date; import java.util.List; public final class Common { private static final int MAX_PRIME_VALUE = 10000000; private Common() { } private static List<Long> primes; static { primes = new LinkedList<Long>(); populatePrimesUpTo(MAX_PRIME_VALUE); } protected static List<Long> getPrimes() { return primes; } private static void populatePrimesUpTo(int end) { System.out.println("populating primes up to: " + end); Date startTime = new Date(); boolean[] values = new boolean[end]; for (int i = 2; i < end; i++) { if (!values[i]) { primes.add((long) i); for (int j = i; j < end; j += i) { values[j] = true; } } } Date endTime = new Date(); System.out.println("done - took " + (endTime.getTime() - startTime.getTime()) + " ms."); } protected static long sum(long n) { return (n * (n + 1)) / 2; } }
<commit_msg>Fix setting scope of toggle button to work with repeat Signed-off-by: Ann Shumilova <c0ede6ced76ec63a297e8c2e1ba28f92de3dd6cf@codenvy.com> <commit_before>/* * Copyright (c) 2015-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation */ 'use strict'; /** * Defines a directive for a toggle button. * @author Florent Benoit */ export class CheToggleButton { /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor () { this.restrict='E'; this.templateUrl = 'components/widget/toggle-button/che-toggle-button.html'; // scope values this.scope = { title:'@cheTitle', fontIcon: '@cheFontIcon', ngDisabled: '@ngDisabled' }; } link($scope) { $scope.controller = $scope.$parent.$parent.cheToggleCtrl; } } <commit_after>/* * Copyright (c) 2015-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation */ 'use strict'; /** * Defines a directive for a toggle button. * @author Florent Benoit */ export class CheToggleButton { /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor () { this.restrict='E'; this.templateUrl = 'components/widget/toggle-button/che-toggle-button.html'; // scope values this.scope = { title:'@cheTitle', fontIcon: '@cheFontIcon', ngDisabled: '@ngDisabled' }; } link($scope) { $scope.controller = $scope.$parent.$parent.cheToggleCtrl || $scope.$parent.$parent.$parent.cheToggleCtrl; } }
<commit_msg>Define OpenGLES support for ARM <commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #pragma once #if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64) #define OUZEL_PLATFORM_WINDOWS 1 #define OUZEL_SUPPORTS_DIRECT3D11 1 #elif defined(__APPLE__) #include <TargetConditionals.h> #if TARGET_OS_IOS #define OUZEL_PLATFORM_IOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_TV #define OUZEL_PLATFORM_TVOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_MAC #define OUZEL_PLATFORM_OSX 1 #define OUZEL_SUPPORTS_OPENGL 1 #define OUZEL_SUPPORTS_METAL 1 #endif #elif defined(__ANDROID__) #define OUZEL_PLATFORM_ANDROID 1 #define OUZEL_SUPPORTS_OPENGLES 1 #elif defined(__linux__) #define OUZEL_PLATFORM_LINUX 1 #define OUZEL_SUPPORTS_OPENGL 1 #endif <commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #pragma once #if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64) #define OUZEL_PLATFORM_WINDOWS 1 #define OUZEL_SUPPORTS_DIRECT3D11 1 #elif defined(__APPLE__) #include <TargetConditionals.h> #if TARGET_OS_IOS #define OUZEL_PLATFORM_IOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_TV #define OUZEL_PLATFORM_TVOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_MAC #define OUZEL_PLATFORM_OSX 1 #define OUZEL_SUPPORTS_OPENGL 1 #define OUZEL_SUPPORTS_METAL 1 #endif #elif defined(__ANDROID__) #define OUZEL_PLATFORM_ANDROID 1 #define OUZEL_SUPPORTS_OPENGLES 1 #elif defined(__linux__) #define OUZEL_PLATFORM_LINUX 1 #if defined(__i386__) || defined(__x86_64__) #define OUZEL_SUPPORTS_OPENGL 1 #else defined(__arm__) || defined(__aarch64__) #define OUZEL_SUPPORTS_OPENGLES 1 #endif #endif
<commit_msg>Add helper for FlowSpec to add the CFG at a later time <commit_before>package mb.nabl2.spoofax.analysis; import java.io.Serializable; import java.util.Optional; import java.util.Set; import mb.nabl2.constraints.IConstraint; import mb.nabl2.solver.Fresh; import mb.nabl2.solver.ISolution; public interface IScopeGraphUnit extends Serializable { String resource(); Set<IConstraint> constraints(); Optional<ISolution> solution(); Optional<CustomSolution> customSolution(); Fresh fresh(); /** * Check if the solution returned is for this resource exactly, * or if this unit is just a part of it. */ boolean isPrimary(); }<commit_after>package mb.nabl2.spoofax.analysis; import java.io.Serializable; import java.util.Optional; import java.util.Set; import mb.nabl2.constraints.IConstraint; import mb.nabl2.solver.Fresh; import mb.nabl2.solver.ISolution; public interface IScopeGraphUnit extends Serializable { String resource(); Set<IConstraint> constraints(); Optional<ISolution> solution(); Optional<CustomSolution> customSolution(); Fresh fresh(); /** * Check if the solution returned is for this resource exactly, * or if this unit is just a part of it. */ boolean isPrimary(); IScopeGraphUnit withSolution(ISolution solution); }
<commit_msg>Make our LiveFlotWidget not pull in jQuery <commit_before> from tw.jquery.flot import FlotWidget from moksha.api.widgets import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_demo' params = ['id', 'data', 'options', 'height', 'width', 'onmessage'] children = [FlotWidget('flot')] onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' height = '250px' width = '390px' options = {} data = [{}] <commit_after> from tw.jquery.flot import flot_js, excanvas_js, flot_css from moksha.api.widgets import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_demo' params = ['id', 'data', 'options', 'height', 'width', 'onmessage'] onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' javascript = [flot_js, excanvas_js] css = [flot_css] height = '250px' width = '390px' options = {} data = [{}]
<commit_msg>Upgrade to spring boot 2 and java 9 <commit_before>package se.jaitco.queueticketapi.service; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import se.jaitco.queueticketapi.model.Roles; import se.jaitco.queueticketapi.model.User; import java.util.Arrays; import java.util.Optional; @Slf4j @Component public class UserService { public Optional<User> getUser(String username) { Optional<User> user = Optional.empty(); if ("Aschan".equals(username)) { User aschan = User.builder() .username("Aschan") .password("Fotboll") .grantedRoles(Arrays.asList(Roles.CUSTOMER, Roles.ADMIN)) .build(); user = Optional.of(aschan); } else if ("Lmar".equals(username)) { User lmar = User.builder() .username("Lmar") .password("Book") .grantedRoles(Arrays.asList(Roles.ADMIN)) .build(); user = Optional.of(lmar); } return user; } } <commit_after>package se.jaitco.queueticketapi.service; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import se.jaitco.queueticketapi.model.Roles; import se.jaitco.queueticketapi.model.User; import java.util.Arrays; import java.util.Optional; @Slf4j @Component public class UserService { public Optional<User> getUser(String username) { Optional<User> user = Optional.empty(); if ("Aschan".equals(username)) { User aschan = User.builder() .username("Aschan") .password("{noop}Fotboll") .grantedRoles(Arrays.asList(Roles.CUSTOMER, Roles.ADMIN)) .build(); user = Optional.of(aschan); } else if ("Lmar".equals(username)) { User lmar = User.builder() .username("Lmar") .password("{noop}Book") .grantedRoles(Arrays.asList(Roles.ADMIN)) .build(); user = Optional.of(lmar); } return user; } }
<commit_msg>Add a few stubs so we can link the latest OpenGL ES 2.0 conformance tests BUG=83382 Review URL: https://chromiumcodereview.appspot.com/10834073 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@149090 0039d316-1c4b-4281-b951-d872f2087c98 <commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. extern "C" { #if defined(GLES2_CONFORM_SUPPORT_ONLY) #include "gpu/gles2_conform_support/gtf/gtf_stubs.h" #else #include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h" #endif GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay, EGLDisplay eglDisplay, EGLConfig eglConfig, const char *title, int width, int height, EGLNativePixmapType *pNativePixmap) { return GTFtrue; } void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay, EGLNativePixmapType nativePixmap) { } } // extern "C" <commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. extern "C" { #if defined(GLES2_CONFORM_SUPPORT_ONLY) #include "gpu/gles2_conform_support/gtf/gtf_stubs.h" #else #include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h" #endif GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay, EGLDisplay eglDisplay, EGLConfig eglConfig, const char *title, int width, int height, EGLNativePixmapType *pNativePixmap) { return GTFtrue; } void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay, EGLNativePixmapType nativePixmap) { } EGLImageKHR GTFCreateEGLImageExternal( int width, int height, int format, float r, float g, float b, float a, void** resource) { return (EGLImageKHR)NULL; } void GTFDestroyEGLImageExternal(EGLImageKHR image, void* resource) { } const int* GTFQueryFormatsEGLImageExternal(void) { return NULL; } GTFbool GTFIsAlphaFormatEGLImageExternal(int format) { return GTFfalse; } } // extern "C"
<commit_msg>Remove reference from Android project <commit_before>package victoralbertos.io.android; import android.app.Activity; import android.os.Bundle; import io.reactivecache.ReactiveCache; import io.victoralbertos.jolyglot.GsonSpeaker; import java.util.ArrayList; import java.util.List; import rx.Observable; /** * Created by victor on 21/01/16. */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create integration test for max mg limit and clearing expired data final ReactiveCache rxProviders = new ReactiveCache.Builder() .maxMBPersistence(50) .using(getApplicationContext().getFilesDir(), new GsonSpeaker()); /* for (int i = 0; i < 1000; i++) { String key = System.currentTimeMillis() + i + ""; rxProviders.getMocksEphemeralPaginate(createObservableMocks(100), new DynamicKey(key)) .subscribe(); }*/ } private Observable<List<Mock>> createObservableMocks(int size) { List<Mock> mocks = new ArrayList(size); for (int i = 0; i < size; i++) { mocks.add(new Mock("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, " + "making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, " + "consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes " + "from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the " + "theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.")); } return Observable.just(mocks); } } <commit_after>package victoralbertos.io.android; import android.app.Activity; /** * Created by victor on 21/01/16. */ public class MainActivity extends Activity { }
<commit_msg>Switch out django-ecstatic for ManifestFilesMixin. <commit_before>import urlparse from django.conf import settings from ecstatic.storage import CachedStaticFilesMixin, StaticManifestMixin from s3_folder_storage.s3 import DefaultStorage, StaticStorage def domain(url): return urlparse.urlparse(url).hostname class MediaFilesStorage(DefaultStorage): def __init__(self, *args, **kwargs): kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME kwargs['custom_domain'] = domain(settings.MEDIA_URL) super(MediaFilesStorage, self).__init__(*args, **kwargs) class StaticFilesStorage(StaticStorage): def __init__(self, *args, **kwargs): kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME kwargs['custom_domain'] = domain(settings.STATIC_URL) super(StaticFilesStorage, self).__init__(*args, **kwargs) class S3ManifestStorage(StaticManifestMixin, CachedStaticFilesMixin, StaticFilesStorage): pass <commit_after>import urlparse from django.conf import settings from django.contrib.staticfiles.storage import ManifestFilesMixin from s3_folder_storage.s3 import DefaultStorage, StaticStorage def domain(url): return urlparse.urlparse(url).hostname class MediaFilesStorage(DefaultStorage): def __init__(self, *args, **kwargs): kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME kwargs['custom_domain'] = domain(settings.MEDIA_URL) super(MediaFilesStorage, self).__init__(*args, **kwargs) class StaticFilesStorage(StaticStorage): def __init__(self, *args, **kwargs): kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME kwargs['custom_domain'] = domain(settings.STATIC_URL) super(StaticFilesStorage, self).__init__(*args, **kwargs) class S3ManifestStorage(ManifestFilesMixin, StaticFilesStorage): pass
<commit_msg>4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4<commit_before> import ibmcnx.filehandle import sys emp1 = ibmcnx.filehandle.Ibmcnxfile() sys.stdout = emp1 print '# JVM Settings of all AppServers:' execfile( 'ibmcnx/doc/JVMSettings.py' ) print '# Used Ports:' execfile( 'ibmcnx/doc/Ports.py' ) print '# LogFile Settgins:' execfile( 'ibmcnx/doc/LogFiles.py' ) print '# WebSphere Variables' execfile( 'ibmcnx/doc/Variables.py' )<commit_after> import ibmcnx.filehandle import sys emp1 = ibmcnx.filehandle.Ibmcnxfile() sys.stdout = emp1.askFileParams() print '# JVM Settings of all AppServers:' execfile( 'ibmcnx/doc/JVMSettings.py' ) print '# Used Ports:' execfile( 'ibmcnx/doc/Ports.py' ) print '# LogFile Settgins:' execfile( 'ibmcnx/doc/LogFiles.py' ) print '# WebSphere Variables' execfile( 'ibmcnx/doc/Variables.py' )
<commit_msg>Add basic block tracing information as a type of "profiling" information. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@13337 91177308-0d34-0410-b5e6-96231b3b80d8 <commit_before>/*===-- Profiling.h - Profiling support library support routines --*- C -*-===*\ |* |* The LLVM Compiler Infrastructure |* |* This file was developed by the LLVM research group and is distributed under |* the University of Illinois Open Source License. See LICENSE.TXT for details. |* |*===----------------------------------------------------------------------===*| |* |* This file defines functions shared by the various different profiling |* implementations. |* \*===----------------------------------------------------------------------===*/ #ifndef PROFILING_H #define PROFILING_H /* save_arguments - Save argc and argv as passed into the program for the file * we output. */ int save_arguments(int argc, const char **argv); enum ProfilingType { Arguments = 1, /* The command line argument block */ Function = 2, /* Function profiling information */ Block = 3, /* Block profiling information */ Edge = 4, /* Edge profiling information */ Path = 5 /* Path profiling information */ }; void write_profiling_data(enum ProfilingType PT, unsigned *Start, unsigned NumElements); #endif <commit_after>/*===-- Profiling.h - Profiling support library support routines --*- C -*-===*\ |* |* The LLVM Compiler Infrastructure |* |* This file was developed by the LLVM research group and is distributed under |* the University of Illinois Open Source License. See LICENSE.TXT for details. |* |*===----------------------------------------------------------------------===*| |* |* This file defines functions shared by the various different profiling |* implementations. |* \*===----------------------------------------------------------------------===*/ #ifndef PROFILING_H #define PROFILING_H /* save_arguments - Save argc and argv as passed into the program for the file * we output. */ int save_arguments(int argc, const char **argv); enum ProfilingType { Arguments = 1, /* The command line argument block */ Function = 2, /* Function profiling information */ Block = 3, /* Block profiling information */ Edge = 4, /* Edge profiling information */ Path = 5, /* Path profiling information */ BBTrace = 6 /* Basic block trace information */ }; void write_profiling_data(enum ProfilingType PT, unsigned *Start, unsigned NumElements); #endif
<commit_msg>Handle errors in case of a country mismatch. <commit_before>from urlparse import urljoin from django.conf import settings from django_countries import countries import requests COUNTRY_CODES = {key: value for (value, key) in list(countries)} def reverse_geocode(lat, lng): """Query Mapbox API to get data for lat, lng""" query = '{0},{1}.json'.format(lng, lat) url = urljoin(settings.MAPBOX_GEOCODE_URL, query) params = {'access_token': settings.MAPBOX_TOKEN} response = requests.get(url, params=params) results = {} if response.status_code != 200: return results data = response.json() for feature in data['features']: text = feature['text'] if feature['id'].startswith('country.'): results['country'] = COUNTRY_CODES[text] if feature['id'].startswith('region.'): results['region'] = text if feature['id'].startswith('place.'): results['city'] = text if feature['id'].startswith('address.'): results['address'] = text return results <commit_after>from urlparse import urljoin from django.conf import settings from django_countries import countries import requests COUNTRY_CODES = {key: value for (value, key) in list(countries)} def reverse_geocode(lat, lng): """Query Mapbox API to get data for lat, lng""" query = '{0},{1}.json'.format(lng, lat) url = urljoin(settings.MAPBOX_GEOCODE_URL, query) params = {'access_token': settings.MAPBOX_TOKEN} response = requests.get(url, params=params) results = {} if response.status_code != 200: return results data = response.json() for feature in data['features']: text = feature['text'] if feature['id'].startswith('country.'): try: results['country'] = COUNTRY_CODES[text] except KeyError: results['country'] = text if feature['id'].startswith('region.'): results['region'] = text if feature['id'].startswith('place.'): results['city'] = text if feature['id'].startswith('address.'): results['address'] = text return results
<commit_msg>Fix the file type asserts on Python 2 (I hope). <commit_before>from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, File) assert isinstance(file.file, BufferedReader) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): file = images.uploadable_file() assert isinstance(file, BufferedReader) <commit_after>from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() built_file = FileFactory.build().file assert isinstance(built_file, File) assert isinstance(built_file.file, FILE_TYPE) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): built_file = images.uploadable_file() assert isinstance(built_file, FILE_TYPE)
<commit_msg>Add comment to Hex color category <commit_before>// // UIColor+HKHex.h // HKProjectBase-Sample // // Created by Harley.xk on 15/8/26. // Copyright (c) 2015年 Harley.xk. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (HKHex) + (UIColor *)colorWithHexString:(NSString *)hexString; + (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha; @end <commit_after>// // UIColor+HKHex.h // HKProjectBase-Sample // // Created by Harley.xk on 15/8/26. // Copyright (c) 2015年 Harley.xk. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (HKHex) /** * 使用16进制字符串创建颜色 * * @param hexString 16进制字符串,可以是 0XFFFFFF/#FFFFFF/FFFFFF 三种格式之一 * * @return 返回创建的UIColor对象 */ + (UIColor *)colorWithHexString:(NSString *)hexString; + (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha; @end
<commit_msg>Add alias to appropriate raw bytes for this Python. <commit_before>__description__ = "VOEvent Broker" __url__ = "http://comet.transientskp.org/" __author__ = "John Swinbank" __contact__ = "swinbank@princeton.edu" __version__ = "2.1.0-pre" <commit_after>__description__ = "VOEvent Broker" __url__ = "http://comet.transientskp.org/" __author__ = "John Swinbank" __contact__ = "swinbank@princeton.edu" __version__ = "2.1.0-pre" import sys if sys.version_info.major <= 2: BINARY_TYPE = str else: BINARY_TYPE = bytes
<commit_msg>Remove dependency on importing std into global namespace. <commit_before> using namespace std; set<string> done; void dump_header(string header) { if (done.find(header) != done.end()) return; done.insert(header); FILE *f = fopen(header.c_str(), "r"); if (f == NULL) { fprintf(stderr, "Could not open header %s.\n", header.c_str()); exit(1); } char line[1024]; while (fgets(line, 1024, f)) { if (strncmp(line, "#include \"", 10) == 0) { char *sub_header = line + 10; for (int i = 0; i < 1014; i++) { if (sub_header[i] == '"') sub_header[i] = 0; } size_t slash_pos = header.rfind('/'); std::string path; if (slash_pos != std::string::npos) path = header.substr(0, slash_pos + 1); dump_header(path + sub_header); } else { fputs(line, stdout); } } fclose(f); } int main(int argc, char **headers) { for (int i = 1; i < argc; i++) { dump_header(headers[i]); } return 0; } <commit_after> std::set<std::string> done; void dump_header(std::string header) { if (done.find(header) != done.end()) return; done.insert(header); FILE *f = fopen(header.c_str(), "r"); if (f == NULL) { fprintf(stderr, "Could not open header %s.\n", header.c_str()); exit(1); } char line[1024]; while (fgets(line, 1024, f)) { if (strncmp(line, "#include \"", 10) == 0) { char *sub_header = line + 10; for (int i = 0; i < 1014; i++) { if (sub_header[i] == '"') sub_header[i] = 0; } size_t slash_pos = header.rfind('/'); std::string path; if (slash_pos != std::string::npos) path = header.substr(0, slash_pos + 1); dump_header(path + sub_header); } else { fputs(line, stdout); } } fclose(f); } int main(int argc, char **headers) { for (int i = 1; i < argc; i++) { dump_header(headers[i]); } return 0; }
<commit_msg>Use Q_SIGNALS / Q_EMIT macros instead of signals / emit <commit_before> class BINARYNINJAUIAPI ClickableLabel: public QLabel { Q_OBJECT public: ClickableLabel(QWidget* parent = nullptr, const QString& name = ""): QLabel(parent) { setText(name); } signals: void clicked(); protected: void mouseReleaseEvent(QMouseEvent* event) override { if (event->button() == Qt::LeftButton) emit clicked(); } }; <commit_after> class BINARYNINJAUIAPI ClickableLabel: public QLabel { Q_OBJECT public: ClickableLabel(QWidget* parent = nullptr, const QString& name = ""): QLabel(parent) { setText(name); } Q_SIGNALS: void clicked(); protected: void mouseReleaseEvent(QMouseEvent* event) override { if (event->button() == Qt::LeftButton) Q_EMIT clicked(); } };
<commit_msg>Use mobile screenshots on small devices <commit_before>import * as React from "react"; import Slider from "react-slick"; import "slick-carousel/slick/slick-theme.css"; import "slick-carousel/slick/slick.css"; import "./style/Screenshots.css"; const images: string[] = [ require("../images/screenshots/tasks.png"), require("../images/screenshots/articles.png"), require("../images/screenshots/videos.png"), require("../images/screenshots/books.png"), ]; export default class extends React.Component { public render() { return ( <div className="Screenshots-container"> <div className="Screenshots-title">Screenshots</div> <Slider dots={true} adaptiveHeight={true} arrows={false} autoplay={true}> {images.map((path) => // Image component is not available here somehow. <a key={path} href={path} target="_blank"> <img className="Screenshots-image" src={path} /> </a>)} </Slider> </div> ); } } <commit_after>import * as React from "react"; import { connect } from "react-redux"; import Slider from "react-slick"; import "slick-carousel/slick/slick-theme.css"; import "slick-carousel/slick/slick.css"; import "./style/Screenshots.css"; const images: string[] = [ require("../images/screenshots/tasks.png"), require("../images/screenshots/articles.png"), require("../images/screenshots/videos.png"), require("../images/screenshots/books.png"), ]; const mobileImages: string[] = [ require("../images/screenshots/mobile_tasks.png"), require("../images/screenshots/mobile_menu.png"), require("../images/screenshots/mobile_articles.png"), require("../images/screenshots/mobile_trending.png"), ]; interface IProps { isSmallWindow: boolean; } class Screenshots extends React.Component<IProps> { public render() { const { isSmallWindow } = this.props; return ( <div className="Screenshots-container"> <div className="Screenshots-title">Screenshots</div> <Slider dots={true} adaptiveHeight={true} arrows={false} autoplay={true}> {(isSmallWindow ? mobileImages : images).map((path) => // Image component is not available here somehow. <a key={path} href={path} target="_blank"> <img className="Screenshots-image" src={path} /> </a>)} </Slider> </div> ); } } export default connect(({ environment }) => environment)(Screenshots);
<commit_msg>Allow HTTP auth during tests <commit_before>from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( BaseAuthentication, get_authorization_header, BasicAuthentication) from rest_framework.exceptions import AuthenticationFailed class DigestAuthentication(BaseAuthentication): def __init__(self): self.authenticator = HttpDigestAuthenticator() def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'digest': return None if self.authenticator.authenticate(request): return request.user, None else: raise AuthenticationFailed( _(u"Invalid username/password")) def authenticate_header(self, request): response = self.authenticator.build_challenge_response() return response['WWW-Authenticate'] class HttpsOnlyBasicAuthentication(BasicAuthentication): def authenticate(self, request): # The parent class can discern whether basic authentication is even # being attempted; if it isn't, we need to gracefully defer to other # authenticators user_auth = super(HttpsOnlyBasicAuthentication, self).authenticate( request) if user_auth is not None and not request.is_secure(): # Scold the user if they provided correct credentials for basic # auth but didn't use HTTPS raise AuthenticationFailed(_( u'Using basic authentication without HTTPS transmits ' u'credentials in clear text! You MUST connect via HTTPS ' u'to use basic authentication.' )) return user_auth <commit_after>from django.conf import settings from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( BaseAuthentication, get_authorization_header, BasicAuthentication) from rest_framework.exceptions import AuthenticationFailed class DigestAuthentication(BaseAuthentication): def __init__(self): self.authenticator = HttpDigestAuthenticator() def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'digest': return None if self.authenticator.authenticate(request): return request.user, None else: raise AuthenticationFailed( _(u"Invalid username/password")) def authenticate_header(self, request): response = self.authenticator.build_challenge_response() return response['WWW-Authenticate'] class HttpsOnlyBasicAuthentication(BasicAuthentication): def authenticate(self, request): # The parent class can discern whether basic authentication is even # being attempted; if it isn't, we need to gracefully defer to other # authenticators user_auth = super(HttpsOnlyBasicAuthentication, self).authenticate( request) if settings.TESTING_MODE is False and \ user_auth is not None and not request.is_secure(): # Scold the user if they provided correct credentials for basic # auth but didn't use HTTPS raise AuthenticationFailed(_( u'Using basic authentication without HTTPS transmits ' u'credentials in clear text! You MUST connect via HTTPS ' u'to use basic authentication.' )) return user_auth
<commit_msg>Test of format_meter (failed on py32) <commit_before>from __future__ import unicode_literals from tqdm import format_interval def test_format_interval(): assert format_interval(60) == '01:00' assert format_interval(6160) == '1:42:40' assert format_interval(238113) == '66:08:33' <commit_after>from __future__ import unicode_literals from tqdm import format_interval, format_meter def test_format_interval(): assert format_interval(60) == '01:00' assert format_interval(6160) == '1:42:40' assert format_interval(238113) == '66:08:33' def test_format_meter(): assert format_meter(231, 1000, 392) == \ "|##--------| 231/1000 23% [elapsed: " \ "06:32 left: 12:49, 0.00 iters/sec]"
<commit_msg>Use long_description_content_type': 'text/markdown' in README <commit_before>from setuptools import setup setup( name='dblp', version='0.1.0', author='Sebastian Gehrmann', author_email='gehrmann@seas.harvard.edu', packages=['dblp'], url='https://github.com/sebastianGehrmann/dblp-pub/tree/master', license='LICENSE.txt', description='Downloads and formats search results from dblp', long_description=open('README.md').read(), install_requires=[ "beautifulsoup4>=4.3.2", "pandas>=0.16.2", "requests>=2.7.0" ], )<commit_after>from setuptools import setup setup( name='dblp', version='0.1.0', author='Sebastian Gehrmann', author_email='gehrmann@seas.harvard.edu', packages=['dblp'], url='https://github.com/sebastianGehrmann/dblp-pub/tree/master', license='LICENSE.txt', description='Downloads and formats search results from dblp', long_description=open('README.md').read(), long_description_content_type='text/markdown', install_requires=[ "beautifulsoup4>=4.3.2", "pandas>=0.16.2", "requests>=2.7.0" ], )
<commit_msg>Make sure to disconnect the extra connection before finishing the test <commit_before>import pytest from juju.controller import Controller from juju.juju import Juju from .. import base @base.bootstrapped @pytest.mark.asyncio async def test_get_controllers(event_loop): async with base.CleanController() as controller: j = Juju() controllers = j.get_controllers() assert isinstance(controllers, dict) assert len(controllers) >= 1 assert controller.controller_name in controllers cc = await j.get_controller(controller.controller_name) assert isinstance(cc, Controller) assert controller.connection().endpoint == cc.connection().endpoint <commit_after>import pytest from juju.controller import Controller from juju.juju import Juju from .. import base @base.bootstrapped @pytest.mark.asyncio async def test_get_controllers(event_loop): async with base.CleanController() as controller: j = Juju() controllers = j.get_controllers() assert isinstance(controllers, dict) assert len(controllers) >= 1 assert controller.controller_name in controllers cc = await j.get_controller(controller.controller_name) assert isinstance(cc, Controller) assert controller.connection().endpoint == cc.connection().endpoint await cc.disconnect()
<commit_msg>Add new validity state for games unranked by host <commit_before>package com.faforever.api.data.domain; public enum Validity { // Order is crucial VALID, TOO_MANY_DESYNCS, WRONG_VICTORY_CONDITION, NO_FOG_OF_WAR, CHEATS_ENABLED, PREBUILT_ENABLED, NORUSH_ENABLED, BAD_UNIT_RESTRICTIONS, BAD_MAP, TOO_SHORT, BAD_MOD, COOP_NOT_RANKED, MUTUAL_DRAW, SINGLE_PLAYER, FFA_NOT_RANKED, UNEVEN_TEAMS_NOT_RANKED, UNKNOWN_RESULT, TEAMS_UNLOCKED, MULTIPLE_TEAMS, HAS_AI, CIVILIANS_REVEALED, WRONG_DIFFICULTY, EXPANSION_DISABLED, SPAWN_NOT_FIXED, OTHER_UNRANK } <commit_after>package com.faforever.api.data.domain; public enum Validity { // Order is crucial VALID, TOO_MANY_DESYNCS, WRONG_VICTORY_CONDITION, NO_FOG_OF_WAR, CHEATS_ENABLED, PREBUILT_ENABLED, NORUSH_ENABLED, BAD_UNIT_RESTRICTIONS, BAD_MAP, TOO_SHORT, BAD_MOD, COOP_NOT_RANKED, MUTUAL_DRAW, SINGLE_PLAYER, FFA_NOT_RANKED, UNEVEN_TEAMS_NOT_RANKED, UNKNOWN_RESULT, TEAMS_UNLOCKED, MULTIPLE_TEAMS, HAS_AI, CIVILIANS_REVEALED, WRONG_DIFFICULTY, EXPANSION_DISABLED, SPAWN_NOT_FIXED, OTHER_UNRANK, UNRANKED_BY_HOST }
<commit_msg>Enforce better security in sample ReST renderer. <commit_before>from __future__ import unicode_literals try: from docutils.core import publish_parts def render_rest(markup, **docutils_settings): parts = publish_parts(source=markup, writer_name="html4css1", settings_overrides=docutils_settings) return parts["html_body"] except ImportError: pass <commit_after>from __future__ import unicode_literals try: from docutils.core import publish_parts def render_rest(markup, **docutils_settings): docutils_settings.update({ 'raw_enabled': False, 'file_insertion_enabled': False, }) parts = publish_parts( source=markup, writer_name="html4css1", settings_overrides=docutils_settings, ) return parts["html_body"] except ImportError: pass
<commit_msg>Add List Insert function declaration <commit_before>struct ListNode; struct List; typedef struct ListNode ListNode; typedef struct List List; List* List_Create(void); void List_Destroy(List* l); ListNode* ListNode_Create(void *); void ListNode_Destroy(ListNode* n); ListNode* List_Search(List* l, void* k, int (f)(void*, void*)); #endif<commit_after>struct ListNode; struct List; typedef struct ListNode ListNode; typedef struct List List; List* List_Create(void); void List_Destroy(List* l); ListNode* ListNode_Create(void *); void ListNode_Destroy(ListNode* n); ListNode* List_Search(List* l, void* k, int (f)(void*, void*)); void List_Insert(List* l, ListNode* n); #endif
<commit_msg>Add actions behavior for applicationNameSelector. <commit_before>import { Component, OnInit } from '@angular/core'; import { LogService } from 'app/_services'; import { ILogView } from 'app/common/logs/models'; @Component({ selector: 'applicationNameSelector', templateUrl: 'applicationNameSelector.component.html' }) export class ApplicationNameSelectorComponent implements OnInit { private _applicationNames: string[]; private _selected: string[]; constructor( private logService: LogService ) { } onChange(_: boolean): void { console.log(this._selected); } ngOnInit(): void { this.logService.getAllApplicationName() .subscribe(n => this._applicationNames = n); } }<commit_after>import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { EffectDispatcher } from '@ck/rx'; import { IAppState } from 'app/app.state'; import { LogService } from 'app/_services'; import { ILogView } from 'app/common/logs/models'; import { SubmitAppNamesEffect } from '../actions'; @Component({ selector: 'applicationNameSelector', templateUrl: 'applicationNameSelector.component.html' }) export class ApplicationNameSelectorComponent implements OnInit { private _applicationNames$: Observable<string[]>; private _applicationNames: string[]; private _selected: string[]; private _subscription: Subscription; constructor( private logService: LogService, private effectDispatcher: EffectDispatcher, private store: Store<IAppState> ) { this._applicationNames$ = this.store.select(s => s.luceneParameters.appNames); this._subscription = this._applicationNames$.subscribe(a => this._selected = a); } onChange(_: boolean): void { this.effectDispatcher.dispatch(new SubmitAppNamesEffect(this._selected)); } ngOnInit(): void { this.logService.getAllApplicationName() .subscribe(n => this._applicationNames = n); } }
<commit_msg>Fix mapper to convert json to formula options. fixes the custom formula to be selected on rnr template. <commit_before>/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ package org.openlmis.rnr.domain; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List; @Data @NoArgsConstructor @EqualsAndHashCode public class FormulaOption { private List<Formula> formulas; public FormulaOption(String options){ if(options != "DEFAULT"){ ObjectMapper mapper = new ObjectMapper(); try{ formulas = mapper.readValue(options, new TypeReference(){} ); } catch(Exception exp){ } } } } <commit_after>/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ package org.openlmis.rnr.domain; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List; @Data @NoArgsConstructor @EqualsAndHashCode public class FormulaOption { private List<Formula> formulas; public FormulaOption(String options){ if(options != "DEFAULT"){ ObjectMapper mapper = new ObjectMapper(); try{ formulas = mapper.readValue(options, new TypeReference<List<Formula>>(){} ); } catch(Exception exp){ } } } }
<commit_msg>Add aws-status-check to declared binaries <commit_before>import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], ) <commit_after>import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-check', 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
<commit_msg>Add Markov Chain representation class <commit_before>from random import choice class MarkovChain(object): """ An interface for signle-word states Markov Chains """ def __init__(self, text=None): self._states_map = {} if text is not None: self.add_text(text) def add_text(self, text, separator=" "): """ Adds text to the markov chain """ word_list = text.split(separator) for i in range(0, len(word_list)-1): self._states_map.setdefault(word_list[i], []).append(word_list[i+1]) return self def get_word(self, key): """ Returns a word from Markov Chain associated with the key """ values = self._states_map.get(key) return choice(values) if values is not None else None <commit_after>from random import choice class MarkovChain(object): """ An interface for signle-word states Markov Chains """ def __init__(self, text=None): self._states_map = {} if text is not None: self.add_text(text) def add_text(self, text, separator=" "): """ Adds text to the markov chain """ word_list = text.split(separator) for i in range(0, len(word_list)-1): self._states_map.setdefault(word_list[i], []).append(word_list[i+1]) return self def add_text_collection(self, text_col, separator=" "): """ Adds a collection of text strings to the markov chain """ for line in text_col: if line not in ["", "\n", None]: self.add_text(line, separator) def get_word(self, key): """ Returns a word from Markov Chain associated with the key """ values = self._states_map.get(key) return choice(values) if values is not None else None
<commit_msg>Add final to method parameters <commit_before>package rod; public class DummyAnalyzer implements Analyzer { private ObservationToCommandMapping observationToCommand; public void setObservationToCommand(ObservationToCommandMapping observationToCommand) { this.observationToCommand = observationToCommand; } @Override public Command analyze(Observation observation) throws UnrecognizableObservationException { if (observationToCommand.containsKey(observation.getClass())) { return observationToCommand.get(observation.getClass()).build(); } else { throw new UnrecognizableObservationException(observation); } } } <commit_after>package rod; public class DummyAnalyzer implements Analyzer { private ObservationToCommandMapping observationToCommand; public void setObservationToCommand(final ObservationToCommandMapping observationToCommand) { this.observationToCommand = observationToCommand; } @Override public Command analyze(final Observation observation) throws UnrecognizableObservationException { if (observationToCommand.containsKey(observation.getClass())) { return observationToCommand.get(observation.getClass()).build(); } else { throw new UnrecognizableObservationException(observation); } } }
<commit_msg>Use raw_input instead of the unmodified words<commit_before>import urllib import urllib2 import re from random import choice ipList=['120.76.115.134:80','222.83.14.145:3128','119.188.94.145:80'] thisIp=choice(ipList) keyWord=urllib.quote('科学') url='http://search.sina.com.cn/iframe/suggest/index.php?q='+keyWord headers={ 'Get':url, 'Host':'search.sina.com.cn', 'Referer':'http://search.sina.com.cn/', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36' } proxy_support = urllib2.ProxyHandler({'http': 'http://'+thisIp}) opener=urllib2.build_opener(proxy_support) urllib2.install_opener(opener) req=urllib2.Request(url) for key in headers: req.add_header(key,headers[key]) html=urllib2.urlopen(req).read() file=open('C:\Users\Ryan\Desktop\lianXC.txt','w') file.write(html) <commit_after>import urllib import urllib2 import re from random import choice ipList=['120.76.115.134:80','222.83.14.145:3128','119.188.94.145:80'] thisIp=choice(ipList) input = raw_input("Please input your key words:") keyWord=urllib.quote(input) url='http://search.sina.com.cn/iframe/suggest/index.php?q='+keyWord headers={ 'Get':url, 'Host':'search.sina.com.cn', 'Referer':'http://search.sina.com.cn/', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36' } proxy_support = urllib2.ProxyHandler({'http': 'http://'+thisIp}) opener=urllib2.build_opener(proxy_support) urllib2.install_opener(opener) req=urllib2.Request(url) for key in headers: req.add_header(key,headers[key]) html=urllib2.urlopen(req).read() file=open('C:\Users\Ryan\Desktop\lianXC.txt','w') file.write(html)
<commit_msg>Define initializers before use them <commit_before>from Recorders import Recorder, PrintRecorder, FileRecorder factory = dict([ ('print', create_print_recorder), ('file', create_file_recorder)]) def create_recorder(config): return factory[config.type](config.config) def create_print_recorder(config): return PrintRecorder(config) def create_file_recorder(config): return FileRecorder(config)<commit_after>from Recorders import Recorder, PrintRecorder, FileRecorder def create_print_recorder(config): return PrintRecorder(config) def create_file_recorder(config): return FileRecorder(config) recorderInitializers = dict([ ('print', create_print_recorder), ('file', create_file_recorder)]) def create_recorder(config): return recorderInitializers[config.type](config.config)
<commit_msg>Add support for special characters <commit_before>import json import sys if sys.version_info[0] == 2: from StringIO import StringIO else: from io import StringIO from pygments import highlight from pygments.formatters import TerminalFormatter from xml.etree import ElementTree as ET import xmlformatter def format_code(data, is_xml=False): """ Parses data and formats it """ if is_xml: ET.fromstring(data) # Make sure XML is valid formatter = xmlformatter.Formatter(indent=2, indent_char=' ', encoding_output='UTF-8', preserve=['literal']) return formatter.format_string(data) else: obj = json.loads(data) output = StringIO() json.dump(obj, output, sort_keys=True, indent=2) return output.getvalue() def color_yo_shit(code, lexer): """ Calls pygments.highlight to color yo shit """ return highlight(code, lexer, TerminalFormatter()) <commit_after>import json import sys from pygments import highlight from pygments.formatters import TerminalFormatter from xml.etree import ElementTree as ET import xmlformatter def format_code(data, is_xml=False): """ Parses data and formats it """ if is_xml: ET.fromstring(data) # Make sure XML is valid formatter = xmlformatter.Formatter(indent=2, indent_char=' ', encoding_output='UTF-8', preserve=['literal']) return formatter.format_string(data) else: obj = json.loads(data) return json.dumps(obj, sort_keys=True, indent=2, ensure_ascii=False).encode('UTF-8') def color_yo_shit(code, lexer): """ Calls pygments.highlight to color yo shit """ return highlight(unicode(code, 'UTF-8'), lexer, TerminalFormatter())
<commit_msg>Add test for if-elseif for missing else <commit_before>import { singleError } from '../../harness/parser' import { MissingElseError } from '../missingElse' it('detects missing Else case', () => { singleError( ` if (2 === 2) { var x = 2; } `, { errorClass: MissingElseError, explanation: /Missing.*else.*/ } ) }) <commit_after>import { singleError } from '../../harness/parser' import { MissingElseError } from '../missingElse' it('detects missing Else case', () => { singleError( ` if (2 === 2) { var x = 2; } `, { errorClass: MissingElseError, explanation: /Missing.*else.*/ } ) }) it('detects missing Else case in if-elseif', () => { singleError( ` if (2 === 2) { var x = 2; } else if (2 === 1) { var y = 2; } `, { errorClass: MissingElseError, explanation: /Missing.*else.*/ } ) })
<commit_msg>Fix multiselect user/group field when retrieving results from a report <commit_before>from .base import MultiSelectField from swimlane.core.resources.usergroup import UserGroup class UserGroupField(MultiSelectField): """Manages getting/setting users from record User/Group fields""" field_type = 'Core.Models.Fields.UserGroupField, Core' supported_types = [UserGroup] def cast_to_python(self, value): """Convert JSON definition to UserGroup object""" # v2.x does not provide a distinction between users and groups at the field selection level, can only return # UserGroup instances instead of specific User or Group instances if value is not None: value = UserGroup(self.record._swimlane, value) return value def cast_to_swimlane(self, value): """Dump UserGroup back to JSON representation""" if value is not None: value = value.get_usergroup_selection() return value <commit_after>from .base import MultiSelectField from swimlane.core.resources.usergroup import UserGroup class UserGroupField(MultiSelectField): """Manages getting/setting users from record User/Group fields""" field_type = 'Core.Models.Fields.UserGroupField, Core' supported_types = [UserGroup] def set_swimlane(self, value): """Workaround for reports returning an empty usergroup field as a single element list with no id/name""" if value == [{"$type": "Core.Models.Utilities.UserGroupSelection, Core"}]: value = [] return super(UserGroupField, self).set_swimlane(value) def cast_to_python(self, value): """Convert JSON definition to UserGroup object""" # v2.x does not provide a distinction between users and groups at the field selection level, can only return # UserGroup instances instead of specific User or Group instances if value is not None: value = UserGroup(self.record._swimlane, value) return value def cast_to_swimlane(self, value): """Dump UserGroup back to JSON representation""" if value is not None: value = value.get_usergroup_selection() return value
<commit_msg>Add basic validation of ui state. <commit_before> from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') <commit_after> from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') self.selector_widget.added.connect(self.on_selection_changed) self.selector_widget.removed.connect(self.on_selection_changed) self.validate() def on_selection_changed(self, items): '''Handle selection change.''' self.validate() def validate(self): '''Validate options and update UI state.''' self.export_button.setEnabled(False) if not self.selector_widget.items(): return self.export_button.setEnabled(True)
<commit_msg>Fix revision numbers in migration 0177 <commit_before>from alembic import op revision = '0176_alter_billing_columns' down_revision = '0175_drop_job_statistics_table' def upgrade(): op.execute("INSERT INTO notification_status_types (name) VALUES ('pending-virus-check')") op.execute("INSERT INTO notification_status_types (name) VALUES ('virus-scan-failed')") def downgrade(): op.execute("UPDATE notifications SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'") op.execute("UPDATE notification_history SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'") op.execute("UPDATE notifications SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'") op.execute("UPDATE notification_history SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'") op.execute("DELETE FROM notification_status_types WHERE name in ('pending-virus-check', 'virus-scan-failed')") <commit_after>from alembic import op revision = '0177_add_virus_scan_statuses' down_revision = '0176_alter_billing_columns' def upgrade(): op.execute("INSERT INTO notification_status_types (name) VALUES ('pending-virus-check')") op.execute("INSERT INTO notification_status_types (name) VALUES ('virus-scan-failed')") def downgrade(): op.execute("UPDATE notifications SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'") op.execute("UPDATE notification_history SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'") op.execute("UPDATE notifications SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'") op.execute("UPDATE notification_history SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'") op.execute("DELETE FROM notification_status_types WHERE name in ('pending-virus-check', 'virus-scan-failed')")
<commit_msg>Use pdbkdf_sha256 hasher for testing too. <commit_before>import factory from django.contrib.auth.hashers import make_password from keybar.models.user import User class UserFactory(factory.DjangoModelFactory): email = factory.Sequence(lambda i: '{0}@none.none'.format(i)) is_active = True class Meta: model = User @classmethod def _prepare(cls, create, **kwargs): raw_password = kwargs.pop('raw_password', 'secret') if 'password' not in kwargs: kwargs['password'] = make_password(raw_password, hasher='md5') return super(UserFactory, cls)._prepare(create, **kwargs) <commit_after>import factory from django.contrib.auth.hashers import make_password from keybar.models.user import User class UserFactory(factory.DjangoModelFactory): email = factory.Sequence(lambda i: '{0}@none.none'.format(i)) is_active = True class Meta: model = User @classmethod def _prepare(cls, create, **kwargs): raw_password = kwargs.pop('raw_password', 'secret') if 'password' not in kwargs: kwargs['password'] = make_password(raw_password, hasher='pbkdf2_sha256') return super(UserFactory, cls)._prepare(create, **kwargs)
<commit_msg>Fix re-evaluation loop with assignment expression <commit_before>package com.madisp.bad.expr; import com.madisp.bad.eval.BadConverter; import com.madisp.bad.eval.Scope; import com.madisp.bad.eval.Watcher; /** * Created with IntelliJ IDEA. * User: madis * Date: 3/27/13 * Time: 7:02 PM */ public class AssignExpression implements Expression { private final Expression expr; private final VarExpression var; public AssignExpression(VarExpression var, Expression expr) { this.var = var; this.expr = expr; } @Override public Object value(Scope scope) { Object newValue = BadConverter.object(expr.value(scope)); scope.setVar(var.getBase(scope), var.getIdentifier(), newValue); return newValue; } @Override public void addWatcher(Scope scope, Watcher w) { expr.addWatcher(scope, w); var.addWatcher(scope, w); } } <commit_after>package com.madisp.bad.expr; import com.madisp.bad.eval.BadConverter; import com.madisp.bad.eval.Scope; import com.madisp.bad.eval.Watcher; /** * Created with IntelliJ IDEA. * User: madis * Date: 3/27/13 * Time: 7:02 PM */ public class AssignExpression implements Expression { private final Expression expr; private final VarExpression var; public AssignExpression(VarExpression var, Expression expr) { this.var = var; this.expr = expr; } @Override public Object value(Scope scope) { Object newValue = BadConverter.object(expr.value(scope)); scope.setVar(var.getBase(scope), var.getIdentifier(), newValue); return newValue; } @Override public void addWatcher(Scope scope, Watcher w) { expr.addWatcher(scope, w); // we don't need to watch var as it will trigger re-evaluation loop when this expression is watched // var.addWatcher(scope, w); } }
<commit_msg>Remove conditional code testing JDK 8 <commit_before>package io.quarkus.deployment; import java.util.Optional; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.SslNativeConfigBuildItem; import io.quarkus.deployment.builditem.nativeimage.RuntimeReinitializedClassBuildItem; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; public class SslProcessor { private static final String JAVA_11_PLUS_SSL_LOGGER = "sun.security.ssl.SSLLogger"; private static final String JAVA_8_PLUS_SSL_LOGGER = "sun.security.ssl.Debug"; SslConfig ssl; @ConfigRoot(phase = ConfigPhase.BUILD_TIME) static class SslConfig { /** * Enable native SSL support. */ @ConfigItem(name = "native") Optional<Boolean> native_; } @BuildStep SslNativeConfigBuildItem setupNativeSsl() { return new SslNativeConfigBuildItem(ssl.native_); } @BuildStep void runtime(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized) { registerIfExists(reinitialized, JAVA_11_PLUS_SSL_LOGGER); registerIfExists(reinitialized, JAVA_8_PLUS_SSL_LOGGER); } private void registerIfExists(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized, String className) { try { Class.forName(className, false, Thread.currentThread().getContextClassLoader()); reinitialized.produce(new RuntimeReinitializedClassBuildItem(className)); } catch (ClassNotFoundException ignored) { } } } <commit_after>package io.quarkus.deployment; import java.util.Optional; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.SslNativeConfigBuildItem; import io.quarkus.deployment.builditem.nativeimage.RuntimeReinitializedClassBuildItem; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; public class SslProcessor { private static final String JAVA_11_PLUS_SSL_LOGGER = "sun.security.ssl.SSLLogger"; SslConfig ssl; @ConfigRoot(phase = ConfigPhase.BUILD_TIME) static class SslConfig { /** * Enable native SSL support. */ @ConfigItem(name = "native") Optional<Boolean> native_; } @BuildStep SslNativeConfigBuildItem setupNativeSsl() { return new SslNativeConfigBuildItem(ssl.native_); } @BuildStep void runtime(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized) { reinitialized.produce(new RuntimeReinitializedClassBuildItem(JAVA_11_PLUS_SSL_LOGGER)); } }
<commit_msg>Remove redundantly declared Stream object <commit_before> namespace TailProduce { class Stream; class StreamsRegistry { public: struct StreamsRegistryEntry { // The pointer to an instance of the stream is owned by TailProduce framework. // * For static frameworks (streams list is fully available at compile time), // these pointers point to existing, statically initialized, members // of the instance of cover TailProduce class. // * For dynamic frameworks, they point to dynamically allocated instances // of per-stream implementations, which are also owned by the instance // of the cover TailProduce class. const Stream* impl; std::string name; std::string entry_type; std::string order_key_type; }; std::vector<StreamsRegistryEntry> streams; std::set<std::string> names; void Add(TailProduce::Stream* impl, const std::string& name, const std::string& entry_type, const std::string& order_key_type) { if (names.find(name) != names.end()) { LOG(FATAL) << "Attempted to register the '" << name << "' stream more than once."; } names.insert(name); streams.push_back(StreamsRegistryEntry{impl, name, entry_type, order_key_type}); } }; struct Stream { Stream(StreamsRegistry& registry, const std::string& stream_name, const std::string& entry_type_name, const std::string& order_key_type_name) { registry.Add(this, stream_name, entry_type_name, order_key_type_name); } }; }; #endif <commit_after> namespace TailProduce { class Stream; class StreamsRegistry { public: struct StreamsRegistryEntry { // The pointer to an instance of the stream is owned by TailProduce framework. // * For static frameworks (streams list is fully available at compile time), // these pointers point to existing, statically initialized, members // of the instance of cover TailProduce class. // * For dynamic frameworks, they point to dynamically allocated instances // of per-stream implementations, which are also owned by the instance // of the cover TailProduce class. const Stream* impl; std::string name; std::string entry_type; std::string order_key_type; }; std::vector<StreamsRegistryEntry> streams; std::set<std::string> names; void Add(TailProduce::Stream* impl, const std::string& name, const std::string& entry_type, const std::string& order_key_type) { if (names.find(name) != names.end()) { LOG(FATAL) << "Attempted to register the '" << name << "' stream more than once."; } names.insert(name); streams.push_back(StreamsRegistryEntry{impl, name, entry_type, order_key_type}); } }; }; #endif
<commit_msg>Set font size correctly on Mac and non-Mac. <commit_before>/* * Qumulus UML editor * Author: Frank Erens * */ #include "Diagram.h" #include "Style.h" QUML_BEGIN_NAMESPACE_UD Diagram::Diagram(QString name, double resolution) : mName(name), mResolution(resolution) { auto s = new Style; setLocalStyle(s); s->setFontName("sans-serif"); s->setFontSize(12.0); } Diagram::Diagram(const Diagram& d) : Shape(d) { } QUML_END_NAMESPACE_UD <commit_after>/* * Qumulus UML editor * Author: Frank Erens * */ #include "Diagram.h" #include "Style.h" QUML_BEGIN_NAMESPACE_UD constexpr static float kFontSize = #ifdef Q_OS_MAC 12.0; #else 10.0; #endif Diagram::Diagram(QString name, double resolution) : mName(name), mResolution(resolution) { auto s = new Style; setLocalStyle(s); s->setFontName("sans-serif"); s->setFontSize(kFontSize); } Diagram::Diagram(const Diagram& d) : Shape(d) { } QUML_END_NAMESPACE_UD
<commit_msg>Fix missing close socket error <commit_before> from multiprocessing import Process import sys from fluxghost.http_server_base import HttpServerBase, logger def fork_entry(request, client, server): from fluxghost.http_handler import HttpHandler HttpHandler(request, client, server) def check_autoreload(): if "fluxghost.http_handler" in sys.modules: logger.error("Warning!! The fluxghost.http_handler has been " "loaded before fork, auto-reload moudle function is" " not work anymore.") return if "fluxclient" in sys.modules: logger.error("Warning!! The fluxclient has been " "loaded before fork, auto-reload moudle function is" " not work anymore.") return class HttpServer(HttpServerBase): def on_accept(self): check_autoreload() request, client = self.sock.accept() w = Process(target=fork_entry, args=(request, client, self)) w.daemon = True w.start() <commit_after> from multiprocessing import Process import sys from fluxghost.http_server_base import HttpServerBase, logger def fork_entry(request, client, server): from fluxghost.http_handler import HttpHandler HttpHandler(request, client, server) def check_autoreload(): if "fluxghost.http_handler" in sys.modules: logger.error("Warning!! The fluxghost.http_handler has been " "loaded before fork, auto-reload moudle function is" " not work anymore.") return if "fluxclient" in sys.modules: logger.error("Warning!! The fluxclient has been " "loaded before fork, auto-reload moudle function is" " not work anymore.") return class HttpServer(HttpServerBase): def on_accept(self): check_autoreload() request, client = self.sock.accept() w = Process(target=fork_entry, args=(request, client, self)) w.daemon = True w.start() request.close()
<commit_msg>Adjust tests to new pizza ids <commit_before>package org.scenarioo.pizza.pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import static org.junit.jupiter.api.Assertions.*; public class SelectPizzaPage extends BasePage { public static void assertPageIsShown() { assertTrue(getStepElement().isDisplayed(), "Expected page to be displayed"); } public static void selectPizzaVerdura() { getWebDriver().findElement(By.id("v")).click(); } public static void clickNextButton() { getStepElement().findElement(By.className("next")).click(); } private static WebElement getStepElement() { return getWebDriver().findElement(By.id("step-selectPizza")); } } <commit_after>package org.scenarioo.pizza.pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import static org.junit.jupiter.api.Assertions.*; public class SelectPizzaPage extends BasePage { public static void assertPageIsShown() { assertTrue(getStepElement().isDisplayed(), "Expected page to be displayed"); } public static void selectPizzaVerdura() { getWebDriver().findElement(By.id("pizza-verdura")).click(); } public static void clickNextButton() { getStepElement().findElement(By.className("next")).click(); } private static WebElement getStepElement() { return getWebDriver().findElement(By.id("step-selectPizza")); } }
<commit_msg>fix: Update the tab/window width to be fit all available space if possible <commit_before>import React, { useRef, useEffect } from 'react' import { observer } from 'mobx-react-lite' import Scrollbar from 'libs/Scrollbar' import ReactResizeDetector from 'react-resize-detector' import Loading from './Loading' import { useStore } from './hooks/useStore' import Window from './Window' export default observer(() => { const { windowStore, userStore, focusStore: { setContainerRef } } = useStore() const scrollbarRef = useRef(null) const onResize = () => { const { height } = scrollbarRef.current.getBoundingClientRect() windowStore.updateHeight(height) } useEffect(() => setContainerRef(scrollbarRef)) const resizeDetector = ( <ReactResizeDetector handleHeight refreshMode='throttle' refreshOptions={{ leading: true, trailing: true }} refreshRate={500} onResize={onResize} /> ) const { initialLoading, windows, visibleColumn } = windowStore if (initialLoading) { return ( <div ref={scrollbarRef}> <Loading /> {resizeDetector} </div> ) } const width = visibleColumn <= 4 ? 100 / visibleColumn + '%' : `${userStore.tabWidth}rem` const list = windows.map((window) => ( <Window key={window.id} width={width} win={window} /> )) return ( <Scrollbar scrollbarRef={scrollbarRef}> {list} {resizeDetector} </Scrollbar> ) }) <commit_after>import React, { useRef, useEffect } from 'react' import { observer } from 'mobx-react-lite' import Scrollbar from 'libs/Scrollbar' import ReactResizeDetector from 'react-resize-detector' import Loading from './Loading' import { useStore } from './hooks/useStore' import Window from './Window' export default observer(() => { const { windowStore, userStore, focusStore: { setContainerRef } } = useStore() const scrollbarRef = useRef(null) const onResize = () => { const { height } = scrollbarRef.current.getBoundingClientRect() windowStore.updateHeight(height) } useEffect(() => setContainerRef(scrollbarRef)) const resizeDetector = ( <ReactResizeDetector handleHeight refreshMode='throttle' refreshOptions={{ leading: true, trailing: true }} refreshRate={500} onResize={onResize} /> ) const { initialLoading, windows, visibleColumn } = windowStore if (initialLoading) { return ( <div ref={scrollbarRef}> <Loading /> {resizeDetector} </div> ) } const width = `calc(max(${100 / visibleColumn}%, ${userStore.tabWidth}rem))` const list = windows.map((window) => ( <Window key={window.id} width={width} win={window} /> )) return ( <Scrollbar scrollbarRef={scrollbarRef}> {list} {resizeDetector} </Scrollbar> ) })
<commit_msg>Remove trailing numbers from base. <commit_before>package org.metaborg.meta.nabl2.solver; import java.io.Serializable; import java.util.Map; import com.google.common.collect.Maps; public class Fresh implements Serializable { private static final long serialVersionUID = 42L; private final Map<String,Integer> counters; public Fresh() { counters = Maps.newConcurrentMap(); } public String fresh(String base) { // to prevent accidental name clashes, ensure the base contains no dashes, // and then use dashes as our connecting character. base = base.replaceAll("-", "_"); int k = counters.getOrDefault(base, 0) + 1; counters.put(base, k); return base + "-" + k; } public void reset() { counters.clear(); } }<commit_after>package org.metaborg.meta.nabl2.solver; import java.io.Serializable; import java.util.Map; import com.google.common.collect.Maps; public class Fresh implements Serializable { private static final long serialVersionUID = 42L; private final Map<String,Integer> counters; public Fresh() { counters = Maps.newConcurrentMap(); } public String fresh(String base) { // remove any number suffix from the base base = base.replaceFirst("-[0-9]+$", ""); // to prevent accidental name clashes, ensure the base contains no dashes, // and then use dashes as our connecting character. base = base.replaceAll("-", "_"); int k = counters.getOrDefault(base, 0) + 1; counters.put(base, k); return base + "-" + k; } public void reset() { counters.clear(); } }
<commit_msg>fix(Engine): Call Dispatcher.Listen last in Engine.Run <commit_before>package engine import ( "github.com/coreos/coreinit/machine" "github.com/coreos/coreinit/registry" ) type Engine struct { dispatcher *Dispatcher watcher *JobWatcher registry *registry.Registry machine *machine.Machine } func New(reg *registry.Registry, events *registry.EventStream, mach *machine.Machine) *Engine { scheduler := NewScheduler() watcher := NewJobWatcher(reg, scheduler, mach) dispatcher := NewDispatcher(reg, events, watcher, mach) return &Engine{dispatcher, watcher, reg, mach} } func (engine *Engine) Run() { engine.dispatcher.Listen() engine.watcher.StartHeartbeatThread() engine.watcher.StartRefreshThread() } <commit_after>package engine import ( "github.com/coreos/coreinit/machine" "github.com/coreos/coreinit/registry" ) type Engine struct { dispatcher *Dispatcher watcher *JobWatcher registry *registry.Registry machine *machine.Machine } func New(reg *registry.Registry, events *registry.EventStream, mach *machine.Machine) *Engine { scheduler := NewScheduler() watcher := NewJobWatcher(reg, scheduler, mach) dispatcher := NewDispatcher(reg, events, watcher, mach) return &Engine{dispatcher, watcher, reg, mach} } func (engine *Engine) Run() { engine.watcher.StartHeartbeatThread() engine.watcher.StartRefreshThread() engine.dispatcher.Listen() }
<commit_msg>Remove `objects' group as useless <commit_before>from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) forms['object'] = self._make_global_entity() for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms def _make_global_entity(self): global_form = EntityForm() for _, score, form in self._entities: global_form.add_form(score, form) return global_form <commit_after>from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms
<commit_msg>Create copy of input array <commit_before>/* * Copyright 2004-present Facebook. All Rights Reserved. */ package com.facebook.presto.operator; import com.facebook.presto.block.Block; import com.google.common.base.Preconditions; public class Page { private final Block[] blocks; public Page(Block... blocks) { Preconditions.checkNotNull(blocks, "blocks is null"); Preconditions.checkArgument(blocks.length > 0, "blocks is empty"); this.blocks = blocks; } public int getChannelCount() { return blocks.length; } public int getPositionCount() { return blocks[0].getPositionCount(); } public Block[] getBlocks() { return blocks.clone(); } public Block getBlock(int channel) { return blocks[channel]; } } <commit_after>/* * Copyright 2004-present Facebook. All Rights Reserved. */ package com.facebook.presto.operator; import com.facebook.presto.block.Block; import com.google.common.base.Preconditions; import java.util.Arrays; public class Page { private final Block[] blocks; public Page(Block... blocks) { Preconditions.checkNotNull(blocks, "blocks is null"); Preconditions.checkArgument(blocks.length > 0, "blocks is empty"); this.blocks = Arrays.copyOf(blocks, blocks.length); } public int getChannelCount() { return blocks.length; } public int getPositionCount() { return blocks[0].getPositionCount(); } public Block[] getBlocks() { return blocks.clone(); } public Block getBlock(int channel) { return blocks[channel]; } }
<commit_msg>Fix tests by passing default settings object rather than empty dict. <commit_before>from contextlib import contextmanager from os import path from unittest import TestCase from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd_packages import six from canaryd.plugin import get_plugin_by_name class TestPluginRealStates(TestCase): def test_meta_plugin(self): plugin = get_plugin_by_name('meta') plugin.get_state({}) @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError('Broken tests: {0} not in commands: {1}'.format( command, commands.keys(), )) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state({}) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise <commit_after>from contextlib import contextmanager from os import path from unittest import TestCase from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd_packages import six from canaryd.plugin import get_plugin_by_name from canaryd.settings import CanarydSettings class TestPluginRealStates(TestCase): def test_meta_plugin(self): plugin = get_plugin_by_name('meta') plugin.get_state({}) @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') test_settings = CanarydSettings() @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError('Broken tests: {0} not in commands: {1}'.format( command, commands.keys(), )) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state(self.test_settings) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
<commit_msg>Add first trip details as well <commit_before>import emission.core.get_database as edb for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"}) last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1)) last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, last trip = {last_trip_time}") <commit_after>import emission.core.get_database as edb for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"}) first_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", 1).limit(1)) first_trip_time = first_trip[0]["data"]["end_fmt_time"] if len(first_trip) > 0 else None last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1)) last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, first trip = {first_trip_time}, last trip = {last_trip_time}")
<commit_msg>Use struct instead of closure <commit_before>use errors::*; use rsa::Rsa; use bignum::BigNumTrait; use bignum::OpensslBigNum as BigNum; pub fn run() -> Result<(), Error> { let bits = 512; let rsa = Rsa::<BigNum>::generate(bits); let m = BigNumTrait::gen_random(bits - 1); let c = rsa.encrypt(&m); let oracle = |x: &BigNum| -> Option<BigNum> { if *x == c { return None; } Some(rsa.decrypt(x)) }; let s = BigNum::gen_random(bits - 1); //TODO We should check that s > 1 and that s and rsa.n() have no common divisors let t = s .invmod(rsa.n()) .ok_or_else(|| err_msg("s and n are not coprime"))?; let c2 = &(&c * &rsa.encrypt(&s)) % rsa.n(); let m2 = oracle(&c2).ok_or_else(|| err_msg("wrong input to oracle"))?; compare_eq(m, &(&m2 * &t) % rsa.n()) } <commit_after>use errors::*; use rsa::Rsa; use bignum::BigNumTrait; use bignum::OpensslBigNum as BigNum; const BITS:usize = 512; struct Server { rsa: Rsa<BigNum>, cleartext: BigNum, ciphertext: BigNum, } impl Server { fn new() -> Self { let rsa = Rsa::<BigNum>::generate(BITS); let cleartext = BigNumTrait::gen_random(BITS - 1); let ciphertext = rsa.encrypt(&cleartext); Server { rsa, cleartext, ciphertext } } fn n(&self) -> &BigNum { &self.rsa.n() } fn get_ciphertext(&self) -> &BigNum { &self.ciphertext } fn encrypt(&self, cleartext: &BigNum) -> BigNum { self.rsa.encrypt(cleartext) } fn decrypt(&self, ciphertext: &BigNum) -> Option<BigNum> { // Reject ciphertext itself if ciphertext == &self.ciphertext { return None; } Some(self.rsa.decrypt(ciphertext)) } fn verify_solution(&self, candidate: &BigNum) -> Result<(), Error> { compare_eq(&self.cleartext, candidate) } } pub fn run() -> Result<(), Error> { let server = Server::new(); let ciphertext = server.get_ciphertext(); let n = server.n(); let s = &BigNum::from_u32(2); let t = &s.invmod(n).unwrap(); // unwrap is ok let altered_ciphertext = &(ciphertext * &server.encrypt(s)) % n; let altered_cleartext = server .decrypt(&altered_ciphertext) .ok_or_else(|| err_msg("wrong input to oracle"))?; let cleartext = &(&altered_cleartext * t) % n; server.verify_solution(&cleartext) }
<commit_msg>Add test store unicode object <commit_before>from .base import IntegrationTest, AsyncUnitTestCase class BasicKVTests(IntegrationTest, AsyncUnitTestCase): def test_no_returnbody(self): async def go(): bucket = self.client.bucket(self.bucket_name) o = await bucket.new(self.key_name, "bar") await o.store(return_body=False) self.assertEqual(o.vclock, None) self.loop.run_until_complete(go()) def test_is_alive(self): self.assertTrue(self.client.is_alive()) def test_store_and_get(self): async def go(): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = await bucket.new('foo', rand) await obj.store() obj = await bucket.get('foo') self.assertTrue(obj.exists) self.assertEqual(obj.bucket.name, self.bucket_name) self.assertEqual(obj.key, 'foo') self.assertEqual(obj.data, rand) obj2 = await bucket.new('baz', rand, 'application/json') obj2.charset = 'UTF-8' await obj2.store() obj2 = await bucket.get('baz') self.assertEqual(obj2.data, rand) self.loop.run_until_complete(go()) <commit_after>from .base import IntegrationTest, AsyncUnitTestCase class BasicKVTests(IntegrationTest, AsyncUnitTestCase): def test_no_returnbody(self): async def go(): bucket = self.client.bucket(self.bucket_name) o = await bucket.new(self.key_name, "bar") await o.store(return_body=False) self.assertEqual(o.vclock, None) self.loop.run_until_complete(go()) def test_is_alive(self): self.assertTrue(self.client.is_alive()) def test_store_and_get(self): async def go(): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = await bucket.new('foo', rand) await obj.store() obj = await bucket.get('foo') self.assertTrue(obj.exists) self.assertEqual(obj.bucket.name, self.bucket_name) self.assertEqual(obj.key, 'foo') self.assertEqual(obj.data, rand) obj2 = await bucket.new('baz', rand, 'application/json') obj2.charset = 'UTF-8' await obj2.store() obj2 = await bucket.get('baz') self.assertEqual(obj2.data, rand) self.loop.run_until_complete(go()) def test_store_object_with_unicode(self): async def go(): bucket = self.client.bucket(self.bucket_name) data = {'føø': u'éå'} obj = await bucket.new('foo', data) await obj.store() obj = await bucket.get('foo') self.assertEqual(obj.data, data) self.loop.run_until_complete(go())
<commit_msg>Add python3 support to stop Steve whinging <commit_before>from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSRequestHandler( SimpleHTTPRequestHandler ): def end_headers( self ): self.send_header( 'Access-Control-Allow-Origin', '*' ) SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test( CORSRequestHandler, BaseHTTPServer.HTTPServer )<commit_after>try: from http.server import SimpleHTTPRequestHandler import http.server as BaseHTTPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSRequestHandler( SimpleHTTPRequestHandler ): def end_headers( self ): self.send_header( 'Access-Control-Allow-Origin', '*' ) SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test( CORSRequestHandler, BaseHTTPServer.HTTPServer )
<commit_msg>Make sure looking up by id works correctly <commit_before>import motor import error from tornado import gen class Connection(object): def __init__(self, host='localhost', port=None, db=None): self.host = host self.port = port self.db = db class Database(object): def __init__(self, connection): if not isinstance(connection, Connection): raise error.StormError('connection must be instance of storm.db.Connection') self.connection = connection self.is_connected = False class MongoDb(Database): def connect(self): if self.is_connected: return self.motor_client = motor.MotorClient( self.connection.host, self.connection.port ).open_sync() self.db = self.motor_client[self.connection.db] self.is_connected = True @gen.coroutine def select_one(self, table, **args): self.connect() result = yield motor.Op(getattr(self.db, table).find_one, args) if result is None: raise error.StormNotFoundError("Object of type: %s not found with args: %s" % (table, args)) callback = args.get('callback') if callback is None: raise gen.Return(result) callback(result) @gen.coroutine def insert(self, table, data, callback=None): self.connect() result = yield motor.Op(self.db[table].insert, data) if callback is None: raise gen.Return(result) callback(result) <commit_after>import motor import error from tornado import gen from bson.objectid import ObjectId class Connection(object): def __init__(self, host='localhost', port=None, db=None): self.host = host self.port = port self.db = db class Database(object): def __init__(self, connection): if not isinstance(connection, Connection): raise error.StormError('connection must be instance of storm.db.Connection') self.connection = connection self.is_connected = False class MongoDb(Database): def connect(self): if self.is_connected: return self.motor_client = motor.MotorClient( self.connection.host, self.connection.port ).open_sync() self.db = self.motor_client[self.connection.db] self.is_connected = True @gen.coroutine def select_one(self, table, **kwargs): self.connect() if '_id' in kwargs: kwargs['_id'] = ObjectId(kwargs['_id']) result = yield motor.Op(getattr(self.db, table).find_one, **kwargs) if result is None: raise error.StormNotFoundError("Object of type: %s not found with args: %s" % (table, kwargs)) callback = kwargs.get('callback') if callback is None: raise gen.Return(result) callback(result) @gen.coroutine def insert(self, table, data, callback=None): self.connect() result = yield motor.Op(self.db[table].insert, data) if callback is None: raise gen.Return(result) callback(result)
<commit_msg>Remove obsolete imports, add logging <commit_before>import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, client_encoding='utf8') Session = sessionmaker(bind=engine) @contextmanager def session_scope(SessionFactory=None): """Provide a transactional scope around a series of operations.""" if SessionFactory is None: SessionFactory = Session session = SessionFactory() try: yield session except SQLAlchemyError as e: _logger.error("Database error %s", e) session.rollback() raise OperationInterruptedException(e) else: session.commit() finally: session.close() def init_db(conn=None): from rtrss.models import Base if conn is None: from database import engine as conn Base.metadata.create_all(bind=conn) def clear_db(conn=None): from rtrss.models import Base if conn is None: from database import engine as conn Base.metadata.drop_all(bind=conn) <commit_after>import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, client_encoding='utf8') Session = sessionmaker(bind=engine) @contextmanager def session_scope(SessionFactory=None): """Provide a transactional scope around a series of operations.""" if SessionFactory is None: SessionFactory = Session session = SessionFactory() try: yield session except SQLAlchemyError as e: _logger.error("Database error %s", e) session.rollback() raise OperationInterruptedException(e) else: session.commit() finally: session.close() def init_db(conn=None): _logger.info('Initializing database') from rtrss.models import Base Base.metadata.create_all(bind=conn) def clear_db(conn=None): _logger.info('Clearing database') from rtrss.models import Base Base.metadata.drop_all(bind=conn)
<commit_msg>Include kafka-check, bump to v0.2.6 <commit_before>from setuptools import setup from setuptools import find_packages from yelp_kafka_tool import __version__ setup( name="yelp-kafka-tool", version=__version__, author="Distributed systems team", author_email="team-dist-sys@yelp.com", description="Kafka management tools", packages=find_packages(exclude=["scripts", "tests"]), data_files=[ ("bash_completion.d", ["bash_completion.d/kafka-info"]), ], scripts=[ "scripts/kafka-info", "scripts/kafka-reassignment", "scripts/kafka-partition-manager", "scripts/kafka-consumer-manager", "scripts/yelpkafka", ], install_requires=[ "argcomplete", "kazoo>=2.0.post2,<3.0.0", "PyYAML<4.0.0", "yelp-kafka>=4.0.0,<5.0.0", "requests<3.0.0" ], ) <commit_after>from setuptools import setup from setuptools import find_packages from yelp_kafka_tool import __version__ setup( name="yelp-kafka-tool", version=__version__, author="Distributed systems team", author_email="team-dist-sys@yelp.com", description="Kafka management tools", packages=find_packages(exclude=["scripts", "tests"]), data_files=[ ("bash_completion.d", ["bash_completion.d/kafka-info"]), ], scripts=[ "scripts/kafka-info", "scripts/kafka-reassignment", "scripts/kafka-partition-manager", "scripts/kafka-consumer-manager", "scripts/yelpkafka", "scripts/kafka-check", ], install_requires=[ "argcomplete", "kazoo>=2.0.post2,<3.0.0", "PyYAML<4.0.0", "yelp-kafka>=4.0.0,<5.0.0", "requests<3.0.0" ], )
<commit_msg>Add passing test for default image <commit_before>from django.test import Client, TestCase from django.contrib.auth.models import User HOME = '/' REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' class UnauthenticatedUser(TestCase): """Create unauth user for testing.""" def setUp(self): """Setup unauth user.""" client = Client() self.home = client.get(HOME) self.login = client.get(LOGIN) self.logout = client.get(LOGOUT) self.register = client.get(REGISTER) def test_no_user_in_db(self): """No user i db.""" self.assertFalse(User.objects.count()) def test_homepage(self): """Test homepage can be reached.""" self.assertEqual(self.home.status_code, 200) def test_login(self): """Test login cna be reached.""" self.assertEqual(self.login.status_code, 200) def test_logout(self): """Test logout can be reached.""" self.assertEqual(self.logout.status_code, 200) def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200) <commit_after>"""Tests for project level urls and views.""" from __future__ import unicode_literals from django.contrib.staticfiles import finders from django.test import Client, TestCase from django.contrib.auth.models import User HOME = '/' REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg') class UnauthenticatedUser(TestCase): """Create unauth user for testing.""" def setUp(self): """Setup unauth user.""" client = Client() self.home = client.get(HOME) self.login = client.get(LOGIN) self.logout = client.get(LOGOUT) self.register = client.get(REGISTER) def test_no_user_in_db(self): """No user i db.""" self.assertFalse(User.objects.count()) def test_homepage(self): """Test homepage can be reached.""" self.assertEqual(self.home.status_code, 200) def test_login(self): """Test login cna be reached.""" self.assertEqual(self.login.status_code, 200) def test_logout(self): """Test logout can be reached.""" self.assertEqual(self.logout.status_code, 200) def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200) def test_default_image(self): """Test default image shows up.""" img_path = self.home.context['image'] self.assertEqual(img_path, DEFAULT_IMAGE)
<commit_msg>Clean up some namespace things <commit_before> using System::Window; class DisplayThreadEntry : public System::ThreadEntry { public: virtual ~DisplayThreadEntry() {} virtual void *Run(void *arg) { Window *mainWindow = Window::Create(); int exitValue = mainWindow->DoMessageLoop(); delete mainWindow; } }; int applicationMain() { DisplayThreadEntry displayThreadEntry; System::Thread *displayThread = System::Thread::Create(&displayThreadEntry); displayThread->Start(); displayThread->Wait(); return 0; } <commit_after> using System::Window; using System::Thread; using System::ThreadEntry; class DisplayThreadEntry : public ThreadEntry { public: virtual ~DisplayThreadEntry() {} virtual void *Run(void *arg) { Window *mainWindow = Window::Create(); int exitValue = mainWindow->DoMessageLoop(); delete mainWindow; } }; int applicationMain() { DisplayThreadEntry displayThreadEntry; Thread *displayThread = Thread::Create(&displayThreadEntry); displayThread->Start(); displayThread->Wait(); return 0; }
<commit_msg>Remove glob imports from sympy.geometry. <commit_before>from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg from sympy.geometry.util import * from sympy.geometry.exceptions import * from sympy.geometry.curve import Curve <commit_after>from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \ intersection from sympy.geometry.exceptions import GeometryError from sympy.geometry.curve import Curve
<commit_msg>Add some docstring and the saveConfiguration method <commit_before>package config import ( "encoding/json" "fmt" "io/ioutil" "log" "os" ) type Configuration struct { Username string `json:"username"` Password string RememberMe bool `json:"remember_me"` } func configWizard() *Configuration { configuration := new(Configuration) fmt.Println("Welcome to gotify !\nThis wizard will help you set up gotify, follow it carefully !") StartWizard(configuration) return configuration } func LoadConfig() *Configuration { if _, err := os.Stat("config.json"); os.IsNotExist(err) { configuration := configWizard() return configuration } file, err := ioutil.ReadFile("config.json") if err != nil { log.Fatal(err) } configuration := new(Configuration) err = json.Unmarshal(file, &configuration) if err != nil { log.Fatal(err) } return configuration } <commit_after>package config import ( "encoding/json" "fmt" "io/ioutil" "log" "os" ) type Configuration struct { Username string `json:"username"` Password string RememberMe bool `json:"remember_me"` } // Starts the wizard config func configWizard() *Configuration { configuration := new(Configuration) fmt.Println("Welcome to gotify !\nThis wizard will help you set up gotify, follow it carefully !") StartWizard(configuration) err := saveConfig(configuration) if err != nil { log.Fatal(err) } return configuration } // Save the configuration in the config.json file func saveConfig(configuration *Configuration) error { config, err := json.Marshal(configuration) if err != nil { return err } err = ioutil.WriteFile("config.json", config, 0644) return err } // Load the configuration from config.json or launch the wizard if it does not exists func LoadConfig() *Configuration { if _, err := os.Stat("config.json"); os.IsNotExist(err) { configuration := configWizard() return configuration } file, err := ioutil.ReadFile("config.json") if err != nil { log.Fatal(err) } configuration := new(Configuration) err = json.Unmarshal(file, &configuration) if err != nil { log.Fatal(err) } return configuration }
<commit_msg>Change repository urls to proper for this version <commit_before>// Copyright (c) 2016-2020 The Karbowanec developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UPDATE_H #define UPDATE_H #include <QObject> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> const static QString KARBO_UPDATE_URL = "https://api.github.com/repos/Karbovanets/karbowanecwallet/tags"; const static QString KARBO_DOWNLOAD_URL = "https://github.com/Karbovanets/karbowanecwallet/releases/"; class Updater : public QObject { Q_OBJECT public: explicit Updater(QObject *parent = 0); ~Updater() { delete manager; } void checkForUpdate(); signals: public slots: void replyFinished (QNetworkReply *reply); private: QNetworkAccessManager *manager; }; #endif // UPDATE_H <commit_after>// Copyright (c) 2016-2020 The Karbowanec developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UPDATE_H #define UPDATE_H #include <QObject> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> const static QString KARBO_UPDATE_URL = "https://api.github.com/repos/seredat/karbowanecwallet/tags"; const static QString KARBO_DOWNLOAD_URL = "https://github.com/seredat/karbowanecwallet/releases/"; class Updater : public QObject { Q_OBJECT public: explicit Updater(QObject *parent = 0); ~Updater() { delete manager; } void checkForUpdate(); signals: public slots: void replyFinished (QNetworkReply *reply); private: QNetworkAccessManager *manager; }; #endif // UPDATE_H
<commit_msg>Remove downloaded file before updating counter <commit_before> import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries)) try: ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write) except ftplib.all_errors as error: sys.stderr.write('%s\n' % error) continue count = 0 for record in gzip.open(filename, 'rb'): print('%s\t%s' % (year, record.decode('ISO-8859-1').strip())) count += 1 sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count)) os.remove(filename) break else: ftp.quit() sys.exit(1) ftp.quit() <commit_after> import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries)) try: ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write) except ftplib.all_errors as error: sys.stderr.write('%s\n' % error) continue count = 0 for record in gzip.open(filename, 'rb'): print('%s\t%s' % (year, record.decode('ISO-8859-1').strip())) count += 1 os.remove(filename) sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count)) break else: ftp.quit() sys.exit(1) ftp.quit()
<commit_msg>[IMP] Replace partial domain by (1,'=',1) <commit_before> from openerp import models, api POSTED_MOVE_DOMAIN = ('move_id.state', '=', 'posted') class PaymentOrderCreate(models.TransientModel): _inherit = 'payment.order.create' @api.model def extend_payment_order_domain(self, payment_order, domain): if POSTED_MOVE_DOMAIN in domain: domain.remove(POSTED_MOVE_DOMAIN) return super(PaymentOrderCreate, self)\ .extend_payment_order_domain(payment_order, domain) <commit_after> from openerp import models, api POSTED_MOVE_DOMAIN = ('move_id.state', '=', 'posted') class PaymentOrderCreate(models.TransientModel): _inherit = 'payment.order.create' @api.model def extend_payment_order_domain(self, payment_order, domain): if POSTED_MOVE_DOMAIN in domain: pos = domain.index(POSTED_MOVE_DOMAIN) domain[pos] = (1, '=', 1) return super(PaymentOrderCreate, self)\ .extend_payment_order_domain(payment_order, domain)
<commit_msg>Make sure that async is exported as async The async function is the default export of the async module, so we need to export it on the test module as a named export "async" <commit_before>import './chaiMoment'; export * from './mockPromise'; export * from './angularFixture'; <commit_after>import './chaiMoment'; import async from './async'; export { async }; export * from './mockPromise'; export * from './angularFixture';
<commit_msg>Add missing definitions - GeneProductType; Database; GeneProductId<commit_before>package uk.ac.ebi.quickgo.webservice.definitions; /** * @Author Tony Wardell * Date: 18/06/2015 * Time: 10:59 * Created with IntelliJ IDEA. */ public enum WebServiceFilter { GoSlim, Qualifier, EcoEvidence, Reference, With, AssignedBy, Taxon, Aspect, GoTerm, GoRelations; } <commit_after>package uk.ac.ebi.quickgo.webservice.definitions; /** * @Author Tony Wardell * Date: 18/06/2015 * Time: 10:59 * Created with IntelliJ IDEA. */ public enum WebServiceFilter { GoSlim, Qualifier, EcoEvidence, Reference, With, AssignedBy, Taxon, Aspect, GoTerm, GoRelations, Database, GeneProductType, GeneProductId; }
<commit_msg>Update lazy helper to support the idea of a reset on bad state. <commit_before> class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from pyvirtualdisplay import Display display = Display(visible=0, size=(800, 600)) display.start() from selenium import webdriver # Configure headless mode chrome_options = webdriver.ChromeOptions() #Oops chrome_options.add_argument('--verbose') chrome_options.add_argument('--ignore-certificate-errors') log_path = "/tmp/chromelogpanda{0}".format(os.getpid()) if not os.path.exists(log_path): os.mkdir(log_path) chrome_options.add_argument("--log-path {0}/log.txt".format(log_path)) chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver class LazyPool(object): _pool = None @classmethod def get(cls): if cls._pool is None: import urllib3 cls._pool = urllib3.PoolManager() return cls._pool <commit_after> class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from pyvirtualdisplay import Display cls._display = display display = Display(visible=0, size=(1024, 768)) display.start() from selenium import webdriver # Configure headless mode chrome_options = webdriver.ChromeOptions() #Oops chrome_options.add_argument('--verbose') chrome_options.add_argument('--ignore-certificate-errors') log_path = "/tmp/chromelogpanda{0}".format(os.getpid()) if not os.path.exists(log_path): os.mkdir(log_path) chrome_options.add_argument("--log-path {0}/log.txt".format(log_path)) chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver @classmethod def reset(cls): cls._display.stop() cls._driver.Dispose() class LazyPool(object): _pool = None @classmethod def get(cls): if cls._pool is None: import urllib3 cls._pool = urllib3.PoolManager() return cls._pool
<commit_msg>Set up data tabulation for gs <commit_before> import os from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) def groundstates_all(self): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] # write table as groundstates.out file. def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """ <commit_after> import os import numpy as np from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) def groundstates_all(self, outname="groundstates.csv"): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] columns = [] #turn list of rows into list of columns # write table as groundstates.out file. writer = IO(outname, self.loc) headers = np.array(['Structures', 'S', 'T', 'P', 'D', 'Q']) writer.tabulate_data(columns, headers, 'Structures') def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """
<commit_msg>Add functionality to copy any missing files to the other folder <commit_before>import os dropboxFiles = [] localFiles = [] for dirpath, dirnames, filenames in os.walk( '/media/itto/TOSHIBA EXT/Photos/Dropbox/ITTO/Southeast Asia 2017'): dropboxFiles += filenames for dirpath, dirnames, filenames in os.walk( '/media/itto/TOSHIBA EXT/Photos/Southeast Asia'): if ('Process' not in dirpath): localFiles += filenames localNotInDropbox = [] for file in localFiles: if file not in dropboxFiles: localNotInDropbox.append(file) print('************') for file in dropboxFiles: if file not in localFiles: print(file) print(len(localNotInDropbox))<commit_after>import os from shutil import copyfile FOLDER_A = '/media/itto/TOSHIBA EXT/Photos/Southeast Asia' FOLDER_B = '/media/itto/disk/PRIVATE/AVCHD/BDMV/STREAM' files_a = [] files_b = [] for dirpath, dirnames, filenames in os.walk(FOLDER_A): files_a += filenames for dirpath, dirnames, filenames in os.walk(FOLDER_B): files_b += filenames inA_notB = [] inB_notA = [] for file in files_b: if file not in files_a: inB_notA.append(file) for file in files_a: if file not in files_b: inA_notB.append(file) print('{} in Folder A. {} in Folder B.'.format(len(files_a), len(files_b))) print('In A but not B: {}'.format(len(inA_notB))) print('In B but not A: {}'.format(len(inB_notA))) def EnsureFolder(path): if os.path.isdir(path): pass else: # Make folder os.mkdir(path) def CopyLeftoverFromBToA(): for file in inB_notA: EnsureFolder(os.path.join(FOLDER_A, 'transfer')) src = os.path.join(FOLDER_B, file) dst = os.path.join(FOLDER_A, 'transfer', file) if not os.path.exists(dst): print('Copying {}'.format(file)) copyfile(src, dst) else: print('{} previously copied'.format(file))
<commit_msg>Replace prints by an exception <commit_before> from astropy import units as u from poliastro.twobody import Orbit from poliastro.constants import J2000 @u.quantity_input(a=u.m) def compute_soi(body, a=None): """Approximated radius of the Laplace Sphere of Influence (SOI) for a body. Parameters ---------- body : `~poliastro.bodies.Body` Astronomical body which the SOI's radius is computed for a : float or None, optional Semimajor Axis of the body's orbit Returns ------- astropy.units.quantity.Quantity Approximated radius of the Sphere of Influence (SOI) [m] """ # Compute semimajor axis at epoch J2000 for the body if it was not # introduced by the user if a is None: try: ss = Orbit.from_body_ephem(body, J2000) a = ss.a r_SOI = a * (body.k / body.parent.k)**(2 / 5) return r_SOI.decompose() except KeyError: print("To compute the semimajor axis for Moon", " and Pluto use the JPL ephemeris: ") print(">>> from astropy.coordinates import solar_system_ephemeris") print('>>> solar_system_ephemeris.set("jpl")') pass <commit_after> from astropy import units as u from poliastro.twobody import Orbit from poliastro.constants import J2000 @u.quantity_input(a=u.m) def compute_soi(body, a=None): """Approximated radius of the Laplace Sphere of Influence (SOI) for a body. Parameters ---------- body : `~poliastro.bodies.Body` Astronomical body which the SOI's radius is computed for a : float or None, optional Semimajor Axis of the body's orbit Returns ------- astropy.units.quantity.Quantity Approximated radius of the Sphere of Influence (SOI) [m] """ # Compute semimajor axis at epoch J2000 for the body if it was not # introduced by the user if a is None: try: ss = Orbit.from_body_ephem(body, J2000) a = ss.a r_SOI = a * (body.k / body.parent.k)**(2 / 5) return r_SOI.decompose() except KeyError: raise RuntimeError( """To compute the semimajor axis for Moon and Pluto use the JPL ephemeris: >>> from astropy.coordinates import solar_system_ephemeris >>> solar_system_ephemeris.set("jpl")""")
<commit_msg>Add a comment to py3 byte string decode. <commit_before>from django.contrib import auth from django.contrib.auth.middleware import AuthenticationMiddleware import base64 class AutologinAuthenticationMiddleware(AuthenticationMiddleware): def process_request(self, request): if 'autologin' not in request.COOKIES: return if request.COOKIES['autologin'] == '': auth.logout(request) return autologin_cookie_value = base64.b64decode(request.COOKIES['autologin']) autologin_cookie_value = autologin_cookie_value.decode('utf8') username = autologin_cookie_value.split(':')[0] password = autologin_cookie_value.split(':')[1] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) <commit_after>from django.contrib import auth from django.contrib.auth.middleware import AuthenticationMiddleware import base64 class AutologinAuthenticationMiddleware(AuthenticationMiddleware): def process_request(self, request): if 'autologin' not in request.COOKIES: return if request.COOKIES['autologin'] == '': auth.logout(request) return autologin_cookie_value = base64.b64decode(request.COOKIES['autologin']) # Py3 uses a bytes string here, so we need to decode to utf-8 autologin_cookie_value = autologin_cookie_value.decode('utf-8') username = autologin_cookie_value.split(':')[0] password = autologin_cookie_value.split(':')[1] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user)
<commit_msg>Resolve naming conflict between Authenticate method name and enum name. <commit_before> class User { public: enum AuthenticateFlag { Authenticate = 0x0000, Encrypt = 0x0001, Decrypt = 0x0002 }; User(); User(QString username, QString password); User(QString username, QByteArray auth_salt, QByteArray key_salt, QByteArray iv, QByteArray auth_hash, QVector<PwEntry> password_entries); QString username; QByteArray auth_salt; QByteArray key_salt; QByteArray iv; QByteArray auth_hash; QVector<PwEntry> password_entries; bool isDecrypted; int Authenticate(QString password, AuthenticateFlag auth_mode); int AddPwEntry(PwEntry password_entry); private: void EncryptAllPwEntries(QString password); void DecryptAllPwEntries(QString password); }; #endif // USER_H <commit_after> class User { public: enum AuthenticateFlag { Auth = 0x0000, Encrypt = 0x0001, Decrypt = 0x0002 }; User(); User(QString username, QString password); User(QString username, QByteArray auth_salt, QByteArray key_salt, QByteArray iv, QByteArray auth_hash, QVector<PwEntry> password_entries); QString username; QByteArray auth_salt; QByteArray key_salt; QByteArray iv; QByteArray auth_hash; QVector<PwEntry> password_entries; bool isDecrypted; int Authenticate(QString password, User::AuthenticateFlag auth_mode); int AddPwEntry(PwEntry password_entry); private: void EncryptAllPwEntries(QString password); void DecryptAllPwEntries(QString password); }; #endif // USER_H
<commit_msg>Add test for go correspondance file begin <commit_before> import sys import os import argparse import re def format_go_correspondance(args): go = {} with open(args.go_correspondance_input, "r") as go_correspondance_input: for line in go_correspondance_input.readlines(): split_line = line[:-1].split('\t') go_name = split_line[0] if split_line[1] == "": continue slim_go_names = split_line[1].split(';') for split_go_name in slim_go_names: go.setdefault(split_go_name,[]).append(go_name) with open(args.go_correspondance_output,"w") as go_correspondance_output: for go_name in go: go_correspondance_output.write(go_name + '\t') go_correspondance_output.write("\t".join(go[go_name]) + "\n") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--go_correspondance_input', required=True) parser.add_argument('--go_correspondance_output', required=True) args = parser.parse_args() format_go_correspondance(args)<commit_after> import sys import os import argparse import re def format_go_correspondance(args): go = {} with open(args.go_correspondance_input, "r") as go_correspondance_input: for line in go_correspondance_input.readlines(): if not line.startswith('GO'): continue print line split_line = line[:-1].split('\t') go_name = split_line[0] if split_line[1] == "": continue slim_go_names = split_line[1].split(';') for split_go_name in slim_go_names: go.setdefault(split_go_name,[]).append(go_name) with open(args.go_correspondance_output,"w") as go_correspondance_output: for go_name in go: go_correspondance_output.write(go_name + '\t') go_correspondance_output.write("\t".join(go[go_name]) + "\n") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--go_correspondance_input', required=True) parser.add_argument('--go_correspondance_output', required=True) args = parser.parse_args() format_go_correspondance(args)
<commit_msg>Remove warning suppression that Eclipse doesn't like <commit_before>/* * SafeUriStringImpl.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client; import com.google.gwt.safehtml.shared.SafeUri; public class SafeUriStringImpl implements SafeUri { public SafeUriStringImpl(String value) { value_ = value; } @Override public String asString() { return value_; } @Override public int hashCode() { return value_.hashCode(); } @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) @Override public boolean equals(Object o) { if (o == null ^ value_ == null) return false; if (value_ == null) return false; return value_.equals(o.toString()); } @Override public String toString() { return value_; } private final String value_; } <commit_after>/* * SafeUriStringImpl.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client; import com.google.gwt.safehtml.shared.SafeUri; public class SafeUriStringImpl implements SafeUri { public SafeUriStringImpl(String value) { value_ = value; } @Override public String asString() { return value_; } @Override public int hashCode() { return value_.hashCode(); } @Override public boolean equals(Object o) { if (o == null ^ value_ == null) return false; if (value_ == null) return false; return value_.equals(o.toString()); } @Override public String toString() { return value_; } private final String value_; }
<commit_msg>Add explanation about using __slots__ <commit_before>"""Models for the response of the configuration object.""" from __future__ import division, print_function, unicode_literals from readthedocs.config.utils import to_dict class Base(object): """ Base class for every configuration. Each inherited class should define its attibutes in the `__slots__` attribute. """ def __init__(self, **kwargs): for name in self.__slots__: setattr(self, name, kwargs[name]) def as_dict(self): return { name: to_dict(getattr(self, name)) for name in self.__slots__ } class Build(Base): __slots__ = ('image',) class Python(Base): __slots__ = ('version', 'install', 'use_system_site_packages') class PythonInstallRequirements(Base): __slots__ = ('requirements',) class PythonInstall(Base): __slots__ = ('path', 'method', 'extra_requirements',) class Conda(Base): __slots__ = ('environment',) class Sphinx(Base): __slots__ = ('builder', 'configuration', 'fail_on_warning') class Mkdocs(Base): __slots__ = ('configuration', 'fail_on_warning') class Submodules(Base): __slots__ = ('include', 'exclude', 'recursive') <commit_after>"""Models for the response of the configuration object.""" from __future__ import division, print_function, unicode_literals from readthedocs.config.utils import to_dict class Base(object): """ Base class for every configuration. Each inherited class should define its attibutes in the `__slots__` attribute. We are using `__slots__` so we can't add more attributes by mistake, this is similar to a namedtuple. """ def __init__(self, **kwargs): for name in self.__slots__: setattr(self, name, kwargs[name]) def as_dict(self): return { name: to_dict(getattr(self, name)) for name in self.__slots__ } class Build(Base): __slots__ = ('image',) class Python(Base): __slots__ = ('version', 'install', 'use_system_site_packages') class PythonInstallRequirements(Base): __slots__ = ('requirements',) class PythonInstall(Base): __slots__ = ('path', 'method', 'extra_requirements',) class Conda(Base): __slots__ = ('environment',) class Sphinx(Base): __slots__ = ('builder', 'configuration', 'fail_on_warning') class Mkdocs(Base): __slots__ = ('configuration', 'fail_on_warning') class Submodules(Base): __slots__ = ('include', 'exclude', 'recursive')