text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Check the value of the Boolean as well. Props @m4dc4p | package com.tozny.sdk.realm.methods.link_challenge;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tozny.sdk.ToznyApiRequest;
import javax.annotation.Nullable;
/**
* Constructs a Request for invoking the "realm.link_challenge" method.
*/
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class LinkChallengeRequest implements ToznyApiRequest {
@JsonProperty(required=true) private String method = "realm.link_challenge";
@JsonProperty(required=true) private String destination;
@JsonProperty private String context;
@JsonProperty private String callback;
@JsonProperty private String hostname;
@JsonProperty private String send;
public LinkChallengeRequest(String destination, @Nullable String context, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) {
this.destination = destination;
this.context = context;
this.callback = callback;
this.hostname = hostname;
if (send == null || send ) {
this.send = "yes";
} else {
this.send = "no";
}
}
public String getMethod() {
return method;
}
public String getDestination() {
return destination;
}
@Nullable
public String getContext() {
return context;
}
@Nullable
public String getCallback() {
return callback;
}
@Nullable
public String getHostname() {
return hostname;
}
@Nullable
public Boolean getSend() {
return send.equals("yes");
}
}
| package com.tozny.sdk.realm.methods.link_challenge;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tozny.sdk.ToznyApiRequest;
import javax.annotation.Nullable;
/**
* Constructs a Request for invoking the "realm.link_challenge" method.
*/
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class LinkChallengeRequest implements ToznyApiRequest {
@JsonProperty(required=true) private String method = "realm.link_challenge";
@JsonProperty(required=true) private String destination;
@JsonProperty private String context;
@JsonProperty private String callback;
@JsonProperty private String hostname;
@JsonProperty private String send;
public LinkChallengeRequest(String destination, @Nullable String context, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) {
this.destination = destination;
this.context = context;
this.callback = callback;
this.hostname = hostname;
if (send == null) {
this.send = "yes";
} else {
this.send = "no";
}
}
public String getMethod() {
return method;
}
public String getDestination() {
return destination;
}
@Nullable
public String getContext() {
return context;
}
@Nullable
public String getCallback() {
return callback;
}
@Nullable
public String getHostname() {
return hostname;
}
@Nullable
public Boolean getSend() {
return send.equals("yes");
}
}
|
Move expected test failure to TestCase class. | """Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
| """Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
class AccountsTestCase(tests.DDPServerTestCase):
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
|
Add endpoints for external transform and debug | package util;
import com.google.gson.JsonObject;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;
/**
* Retrofit interfaces wrapping Filestack API.
*/
public class FilestackService {
public interface Api {
String URL = "https://www.filestackapi.com/api/file/";
@POST("{handle}")
Call<ResponseBody> overwrite(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature, @Body RequestBody body);
@DELETE("{handle}")
Call<ResponseBody> delete(@Path("handle") String handle, @Query("key") String key,
@Query("policy") String policy, @Query("signature") String signature);
}
public interface Cdn {
String URL = "https://cdn.filestackcontent.com/";
@GET("{handle}")
@Streaming
Call<ResponseBody> get(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature);
}
public interface Process {
String URL = "https://process.filestackapi.com/";
@Streaming
@GET("{tasks}/{handle}")
Call<ResponseBody> get(@Path("tasks") String tasks, @Path("handle") String handle);
@GET("debug/{tasks}/{handle}")
Call<JsonObject> debug(@Path("tasks") String tasks, @Path("handle") String handle);
@Streaming
@GET("{key}/{tasks}/{url}")
Call<ResponseBody> getExternal(@Path("key") String key, @Path("tasks") String tasks,
@Path("url") String url);
@GET("{key}/debug/{tasks}/{url}")
Call<JsonObject> debugExternal(@Path("key") String key, @Path("tasks") String tasks,
@Path("url") String url);
}
}
| package util;
import com.google.gson.JsonObject;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;
/**
* Retrofit interfaces wrapping Filestack API.
*/
public class FilestackService {
public interface Api {
String URL = "https://www.filestackapi.com/api/file/";
@POST("{handle}")
Call<ResponseBody> overwrite(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature, @Body RequestBody body);
@DELETE("{handle}")
Call<ResponseBody> delete(@Path("handle") String handle, @Query("key") String key,
@Query("policy") String policy, @Query("signature") String signature);
}
public interface Cdn {
String URL = "https://cdn.filestackcontent.com/";
@GET("{handle}")
@Streaming
Call<ResponseBody> get(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature);
}
public interface Process {
String URL = "https://process.filestackapi.com/";
@Streaming
@GET("{tasks}/{handle}")
Call<ResponseBody> get(@Path("tasks") String tasks, @Path("handle") String handle);
@GET("debug/{tasks}/{handle}")
Call<JsonObject> debug(@Path("tasks") String tasks, @Path("handle") String handle);
}
}
|
Add transfering timeout callback arguments to done
Closes: #150
PR-URL: https://github.com/metarhia/metasync/pull/153
Reviewed-By: Timur Shemsedinov <[email protected]> | 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
if (!timer) {
timer = setTimeout(() => {
timer = null;
if (wait) throttled();
}, timeout);
if (args) fn(...args);
else fn();
wait = false;
} else {
wait = true;
}
};
};
api.metasync.debounce = (
timeout,
fn,
args = []
) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), timeout);
};
};
api.metasync.timeout = (
// Set timeout for function execution
timeout, // time interval
asyncFunction, // async function to be executed
// done - callback function
done // callback function on done
) => {
let finished = false;
done = api.metasync.cb(done);
const timer = setTimeout(() => {
finished = true;
done(null);
}, timeout);
asyncFunction((...args) => {
if (!finished) {
clearTimeout(timer);
finished = true;
done(...args);
}
});
};
};
| 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
if (!timer) {
timer = setTimeout(() => {
timer = null;
if (wait) throttled();
}, timeout);
if (args) fn(...args);
else fn();
wait = false;
} else {
wait = true;
}
};
};
api.metasync.debounce = (
timeout,
fn,
args = []
) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), timeout);
};
};
api.metasync.timeout = (
// Set timeout for function execution
timeout, // time interval
asyncFunction, // async function to be executed
// done - callback function
done // callback function on done
) => {
let finished = false;
done = api.metasync.cb(done);
const timer = setTimeout(() => {
finished = true;
done(null);
}, timeout);
asyncFunction((err, data) => {
if (!finished) {
clearTimeout(timer);
finished = true;
done(err, data);
}
});
};
};
|
Fix missing LICENCE in dist package | #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='[email protected]',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
| #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='[email protected]',
packages=find_packages(exclude=['examples', 'tests']),
package_data={'': ['LICENSE',
'README.rst']},
include_package_data=True,
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
Include templates, etc, with install | from setuptools import setup, find_packages
from sys import version_info
assert version_info >= (2,7)
setup(
name='molly',
version='2.0dev',
packages=find_packages(exclude=['tests']),
include_package_data=True,
url='http://mollyproject.org/',
author='The Molly Project',
setup_requires=['setuptools'],
tests_require=['unittest2', 'mock'],
test_suite='unittest2.collector',
install_requires=[
'celery',
'cssmin',
'Flask',
'Flask-Assets',
'Flask-Babel',
'Flask-Cache',
'Flask-PyMongo',
'Flask-Script',
'Flask-StatsD',
'geojson',
'gunicorn',
'imposm.parser',
'phonenumbers==5.7b2',
'python-dateutil',
'python-memcached',
'raven',
'requests',
'Shapely',
'supervisor'
],
entry_points={
'console_scripts': [
'mollyui = molly.command:ui_main',
'mollyrest = molly.command:rest_main',
'mollyd = molly.command:mollyd',
'mollydebugd = molly.command:mollydebugd',
'mollyctl = molly.command:mollyctl',
'mollydebugctl = molly.command:mollydebugctl'
]
}
)
| from setuptools import setup, find_packages
from sys import version_info
assert version_info >= (2,7)
setup(
name='molly',
version='2.0dev',
packages=find_packages(exclude=['tests']),
url='http://mollyproject.org/',
author='The Molly Project',
setup_requires=['setuptools'],
tests_require=['unittest2', 'mock'],
test_suite='unittest2.collector',
install_requires=[
'celery',
'cssmin',
'Flask',
'Flask-Assets',
'Flask-Babel',
'Flask-Cache',
'Flask-PyMongo',
'Flask-Script',
'Flask-StatsD',
'geojson',
'gunicorn',
'imposm.parser',
'phonenumbers==5.7b2',
'python-dateutil',
'python-memcached',
'raven',
'requests',
'Shapely',
'supervisor'
],
entry_points={
'console_scripts': [
'mollyui = molly.command:ui_main',
'mollyrest = molly.command:rest_main',
'mollyd = molly.command:mollyd',
'mollydebugd = molly.command:mollydebugd',
'mollyctl = molly.command:mollyctl',
'mollydebugctl = molly.command:mollydebugctl'
]
}
)
|
Update Hearts lambda function to new DB schema. | 'use strict';
const db = require('../utils/database');
/**
* Fetches a user ID from the database.
* @constructor
* @param {integer} userId - The user's ID
* @return {integer} The number of Hearts a user has.
*/
const getHeartsForUser = (userId) => {
return db.get({
TableName: 'Users',
Key: {
id: userId,
},
})
.then( data => data.Item.vcCurrent);
};
const handler = (event) => {
if (!event.params.id) {
return Promise.resolve({
statusCode: 400,
body: JSON.stringify({ message: 'The id query param must be set to a valid user id' }),
});
}
let userId = event.params.id;
return getHeartsForUser(userId)
.then(
(hearts) => {
return {
statusCode: 200,
body: JSON.stringify({ message: `User ${userId} has ${hearts} hearts!` }),
};
},
(err) => {
// console.log('Error:', err);
return {
statusCode: 404,
body: JSON.stringify({ message: `User ID ${userId} not found ` }),
};
}
);
};
const serverlessHandler = (event, context, callback) => {
handler(event)
.then( response => callback(null, response) );
}
module.exports = {
handler: handler,
serverlessHandler: serverlessHandler,
}
| 'use strict';
const db = require('../utils/database');
/**
* Fetches a user ID from the database.
* @constructor
* @param {integer} userId - The user's ID
* @return {integer} The number of Hearts a user has.
*/
const getHeartsForUser = (userId) => {
return db.get({
TableName: 'Users',
Key: {
UserId: userId,
},
})
.then( data => data.Item.VcCurrent);
};
const handler = (event) => {
if (!event.params.id) {
return Promise.resolve({
statusCode: 400,
body: JSON.stringify({ message: 'The id query param must be set to a valid user id' }),
});
}
let userId = parseInt(event.params.id, 10) || 0;
return getHeartsForUser(userId)
.then(
(hearts) => {
return {
statusCode: 200,
body: JSON.stringify({ message: `User ${userId} has ${hearts} hearts!` }),
};
},
(err) => {
// console.log('Error:', err);
return {
statusCode: 404,
body: JSON.stringify({ message: `User ID ${userId} not found ` }),
};
}
);
};
const serverlessHandler = (event, context, callback) => {
handler(event)
.then( response => callback(null, response) );
}
module.exports = {
handler: handler,
serverlessHandler: serverlessHandler,
}
|
Fix wrong module name in migrations | from django.utils.encoding import smart_str
from kitsune.products.models import Product
from taggit.models import Tag
from kitsune.questions.models import Question
tags_to_migrate = {
# source tag -> product
'desktop': ['firefox'],
'mobile': ['mobile']
}
def assert_equals(a, b):
assert a == b, '%s != %s' % (a, b)
def run():
# Get all the tags to migrate.
tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys()))
total_affected = 0
# For each tag, get the question and add a product for it.
for tag in tags:
for product_slug in tags_to_migrate[tag.slug]:
product = Product.objects.get(slug=product_slug)
# Assign the product to all the questions tagged with tag.
# Pull in 5000 at a time from the db.
n = 5000
qs = Question.objects.filter(tags__slug=tag.slug)
count = qs.count()
print '%s %s questions to work on...' % (count, product_slug)
for i in range(0, count, n):
for question in qs[i:i + n]:
question.products.add(product)
print 'Added product "%s" to question "%s"' % (
smart_str(product.slug), smart_str(question.title))
total_affected += 1
print 'Done! (%d)' % total_affected
| from django.utils.encoding import smart_str
from kitsune.products.models import Product
from kitsune.taggit.models import Tag
from kitsune.questions.models import Question
tags_to_migrate = {
# source tag -> product
'desktop': ['firefox'],
'mobile': ['mobile']
}
def assert_equals(a, b):
assert a == b, '%s != %s' % (a, b)
def run():
# Get all the tags to migrate.
tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys()))
total_affected = 0
# For each tag, get the question and add a product for it.
for tag in tags:
for product_slug in tags_to_migrate[tag.slug]:
product = Product.objects.get(slug=product_slug)
# Assign the product to all the questions tagged with tag.
# Pull in 5000 at a time from the db.
n = 5000
qs = Question.objects.filter(tags__slug=tag.slug)
count = qs.count()
print '%s %s questions to work on...' % (count, product_slug)
for i in range(0, count, n):
for question in qs[i:i + n]:
question.products.add(product)
print 'Added product "%s" to question "%s"' % (
smart_str(product.slug), smart_str(question.title))
total_affected += 1
print 'Done! (%d)' % total_affected
|
Break lines so they don't overstep right margin | package org.CG.infrastructure;
import javax.media.opengl.GL;
/**
*
* @author ldavid
*/
public abstract class Drawing {
protected Point start;
protected ColorByte color;
protected boolean finished;
protected int glDrawingType = GL.GL_POINTS;
public Drawing() {
// All drawings, except by polygons, are initiated with finished
// as true, as they don't allow second clicks.
finished = true;
}
abstract public Drawing updateLastCoordinate(Point point);
public Drawing setNextCoordinate(Point point) {
if (finished) {
throw new RuntimeException(
"Cannot set next coordinate if drawing is already finished.");
}
return this;
}
public void draw(GL gl) {
gl.glColor3ub(color.getRed(), color.getGreen(), color.getBlue());
gl.glBegin(glDrawingType);
drawShape(gl);
gl.glEnd();
}
abstract protected void drawShape(GL gl);
public Drawing translate(Point point) {
return setStart(point);
}
public Drawing setStart(Point start) {
this.start = start;
return this;
}
public Drawing setColor(ColorByte color) {
this.color = color;
return this;
}
public Drawing setFinished(boolean f) {
finished = f;
return this;
}
public boolean getFinished() {
return finished;
}
}
| package org.CG.infrastructure;
import javax.media.opengl.GL;
/**
*
* @author ldavid
*/
public abstract class Drawing {
protected Point start;
protected ColorByte color;
protected boolean finished;
protected int glDrawingType = GL.GL_POINTS;
public Drawing() {
// All drawings, except by polygons, are initiated with finished as true, as they don't allow second clicks.
finished = true;
}
abstract public Drawing updateLastCoordinate(Point point);
public Drawing setNextCoordinate(Point point) {
if (finished) {
throw new RuntimeException("Cannot set next coordinate if drawing is already finished.");
}
return this;
}
public void draw(GL gl) {
gl.glColor3ub(color.getRed(), color.getGreen(), color.getBlue());
gl.glBegin(glDrawingType);
drawShape(gl);
gl.glEnd();
}
abstract protected void drawShape(GL gl);
public Drawing translate(Point point) {
return setStart(point);
}
public Drawing setStart(Point start) {
this.start = start;
return this;
}
public Drawing setColor(ColorByte color) {
this.color = color;
return this;
}
public Drawing setFinished(boolean f) {
finished = f;
return this;
}
public boolean getFinished() {
return finished;
}
}
|
Allow late subscribers to immediately get the visibility status | package com.gramboid.rxappfocus;
import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import rx.Observable;
import rx.subjects.ReplaySubject;
/**
* Provides Observables to monitor app visibility.
*/
public class AppFocusProvider {
private boolean changingConfig;
private int foregroundCounter;
private final ReplaySubject<Boolean> subject = ReplaySubject.createWithSize(1);
private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() {
@Override
public void onActivityStarted(Activity activity) {
if (changingConfig) {
// ignore activity start, just a config change
changingConfig = false;
} else {
incrementVisibleCounter();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (activity.isChangingConfigurations()) {
// ignore activity stop, just a config change
changingConfig = true;
} else {
decrementVisibleCounter();
}
}
};
private void incrementVisibleCounter() {
final boolean justBecomingVisible = !isVisible();
foregroundCounter++;
if (justBecomingVisible) {
subject.onNext(true);
}
}
private void decrementVisibleCounter() {
foregroundCounter--;
if (!isVisible()) {
subject.onNext(false);
}
}
public AppFocusProvider(Application app) {
app.registerActivityLifecycleCallbacks(callbacks);
}
public boolean isVisible() {
return foregroundCounter > 0;
}
public Observable<Boolean> getAppFocus() {
return subject;
}
} | package com.gramboid.rxappfocus;
import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import rx.Observable;
import rx.subjects.PublishSubject;
/**
* Provides Observables to monitor app visibility.
*/
public class AppFocusProvider {
private boolean changingConfig;
private int foregroundCounter;
private final PublishSubject<Boolean> subject = PublishSubject.create();
private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() {
@Override
public void onActivityStarted(Activity activity) {
if (changingConfig) {
// ignore activity start, just a config change
changingConfig = false;
} else {
incrementVisibleCounter();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (activity.isChangingConfigurations()) {
// ignore activity stop, just a config change
changingConfig = true;
} else {
decrementVisibleCounter();
}
}
};
private void incrementVisibleCounter() {
final boolean justBecomingVisible = !isVisible();
foregroundCounter++;
if (justBecomingVisible) {
subject.onNext(true);
}
}
private void decrementVisibleCounter() {
foregroundCounter--;
if (!isVisible()) {
subject.onNext(false);
}
}
public AppFocusProvider(Application app) {
app.registerActivityLifecycleCallbacks(callbacks);
}
public boolean isVisible() {
return foregroundCounter > 0;
}
public Observable<Boolean> getAppFocus() {
return subject;
}
} |
BUGFIX: Fix typo 'showNotificatons' -> 'showNotifications'. | package repo
type SettingsData struct {
PaymentDataInQR *bool `json:"paymentDataInQR"`
ShowNotifications *bool `json:"showNotifications"`
ShowNsfw *bool `json:"showNsfw"`
ShippingAddresses *[]ShippingAddress `json:"shippingAddresses"`
LocalCurrency *string `json:"localCurrency"`
Country *string `json:"country"`
Language *string `json:"language"`
TermsAndConditions *string `json:"termsAndConditions"`
RefundPolicy *string `json:"refundPolicy"`
BlockedNodes *[]string `json:"blockedNodes"`
StoreModerators *[]string `json:"storeModerators"`
SMTPSettings *SMTPSettings `json:"smtpSettings"`
}
type ShippingAddress struct {
Name string `json:"name"`
Company string `json:"company"`
AddressLineOne string `json:"addressLineOne"`
AddressLineTwo string `json:"addressLineTwo"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
PostalCode string `json:"postalCode"`
AddressNotes string `json:"addressNotes"`
}
type SMTPSettings struct {
Notifications bool `json:"notifications"`
ServerAddress string `json:"serverAddress"`
Username string `json:"username"`
Password string `json:"password"`
SenderEmail string `json:"senderEmail"`
RecipientEmail string `json:"recipientEmail"`
}
| package repo
type SettingsData struct {
PaymentDataInQR *bool `json:"paymentDataInQR"`
ShowNotifications *bool `json:"showNotificatons"`
ShowNsfw *bool `json:"showNsfw"`
ShippingAddresses *[]ShippingAddress `json:"shippingAddresses"`
LocalCurrency *string `json:"localCurrency"`
Country *string `json:"country"`
Language *string `json:"language"`
TermsAndConditions *string `json:"termsAndConditions"`
RefundPolicy *string `json:"refundPolicy"`
BlockedNodes *[]string `json:"blockedNodes"`
StoreModerators *[]string `json:"storeModerators"`
SMTPSettings *SMTPSettings `json:"smtpSettings"`
}
type ShippingAddress struct {
Name string `json:"name"`
Company string `json:"company"`
AddressLineOne string `json:"addressLineOne"`
AddressLineTwo string `json:"addressLineTwo"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
PostalCode string `json:"postalCode"`
AddressNotes string `json:"addressNotes"`
}
type SMTPSettings struct {
Notifications bool `json:"notifications"`
ServerAddress string `json:"serverAddress"`
Username string `json:"username"`
Password string `json:"password"`
SenderEmail string `json:"senderEmail"`
RecipientEmail string `json:"recipientEmail"`
}
|
Save one request at feed managing. | angular.module('caco.feed.crtl')
.controller('FeedManageCrtl', function ($rootScope, $scope, $stateParams, $location, Feeds, FeedREST, FeedUrlLookupREST) {
$rootScope.module = 'feed';
$rootScope.modulePath = $location.path();
if ($stateParams.id) {
Feeds.getOne($stateParams.id, function (feed) {
$scope.feed = feed;
})
} else {
Feeds.get(function (feeds) {
$scope.feeds = feeds;
});
}
$scope.lookup = function () {
FeedUrlLookupREST.lookup({q: $scope.lookupUrl}, {}, function (data) {
if (data && data.responseStatus == 200) {
$scope.feed = data.responseData;
}
});
};
$scope.add = function () {
Feeds.add($scope.feed, function (feeds) {
$scope.feeds = feeds;
$location.path('/feed/manage');
});
};
$scope.edit = function () {
Feeds.edit($scope.feed, function (feeds) {
$scope.feeds = feeds;
$location.path('/feed/manage');
});
};
$scope.delete = function (id) {
if (!confirm('Confirm delete')) {
return;
}
Feeds.remove({id: id}, function (feeds) {
$scope.feeds = feeds;
$location.path('/feed/manage');
});
};
}); | angular.module('caco.feed.crtl')
.controller('FeedManageCrtl', function ($rootScope, $scope, $stateParams, $location, Feeds, FeedREST, FeedUrlLookupREST) {
$rootScope.module = 'feed';
$rootScope.modulePath = $location.path();
Feeds.get(function (feeds) {
$scope.feeds = feeds;
});
if ($stateParams.id) {
Feeds.getOne($stateParams.id, function (feed) {
$scope.feed = feed;
})
}
$scope.lookup = function () {
FeedUrlLookupREST.lookup({q: $scope.lookupUrl}, {}, function (data) {
if (data && data.responseStatus == 200) {
$scope.feed = data.responseData;
}
});
};
$scope.add = function () {
Feeds.add($scope.feed, function (feeds) {
$scope.feeds = feeds;
$location.path('/feed/manage');
});
};
$scope.edit = function () {
Feeds.edit($scope.feed, function (feeds) {
$scope.feeds = feeds;
$location.path('/feed/manage');
});
};
$scope.delete = function (id) {
if (!confirm('Confirm delete')) {
return;
}
Feeds.remove({id: id}, function (feeds) {
$scope.feeds = feeds;
$location.path('/feed/manage');
});
};
}); |
Add Firefox 3.6 to Sauce | "use strict";
module.exports = function(config) {
var customLaunchers = {
iOSSafari: {
base: "SauceLabs",
browserName: "iphone",
version: "5.1"
},
ie7: {
base: "SauceLabs",
browserName: "internet explorer",
version: "7.0"
},
ie8: {
base: "SauceLabs",
browserName: "internet explorer",
version: "8.0"
},
ie9: {
base: "SauceLabs",
browserName: "internet explorer",
version: "9.0"
},
ff3dot6: {
base: "SauceLabs",
browserName: "firefox",
version: "3.6"
}
};
config.set({
basePath: "",
frameworks: ["jasmine"],
captureTimeout: 120000,
browserNoActivityTimeout: 60000,
files: [
"../src/**/*.js",
"../test/**/*_spec.js"
],
sauceLabs: {
testName: "HTML5 placeholder polyfill"
},
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
reporters: ["dots", "saucelabs"],
singleRun: true
});
};
| "use strict";
module.exports = function(config) {
var customLaunchers = {
iOSSafari: {
base: "SauceLabs",
browserName: "iphone",
version: "5.1"
},
ie7: {
base: "SauceLabs",
browserName: "internet explorer",
version: "7.0"
},
ie8: {
base: "SauceLabs",
browserName: "internet explorer",
version: "8.0"
},
ie9: {
base: "SauceLabs",
browserName: "internet explorer",
version: "9.0"
}
};
config.set({
basePath: "",
frameworks: ["jasmine"],
captureTimeout: 120000,
browserNoActivityTimeout: 60000,
files: [
"../src/**/*.js",
"../test/**/*_spec.js"
],
sauceLabs: {
testName: "HTML5 placeholder polyfill"
},
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
reporters: ["dots", "saucelabs"],
singleRun: true
});
};
|
Fix creation of json for image (pandoc 1.12.3.3)
At least with pandoc 1.12.3.3 otherwise you get an error
pandoc: when expecting a [a], encountered Object instead | #!/usr/bin/env python
"""
Pandoc filter to process code blocks with class "graphviz" into
graphviz-generated images.
"""
import pygraphviz
import hashlib
import os
import sys
from pandocfilters import toJSONFilter, Str, Para, Image
def sha1(x):
return hashlib.sha1(x).hexdigest()
imagedir = "graphviz-images"
def graphviz(key, value, format, meta):
if key == 'CodeBlock':
[[ident,classes,keyvals], code] = value
caption = "caption"
if "graphviz" in classes:
G = pygraphviz.AGraph(string = code)
G.layout()
filename = sha1(code)
if format == "html":
filetype = "png"
elif format == "latex":
filetype = "pdf"
else:
filetype = "png"
alt = Str(caption)
src = imagedir + '/' + filename + '.' + filetype
if not os.path.isfile(src):
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
G.draw(src)
sys.stderr.write('Created image ' + src + '\n')
tit = ""
return Para([Image([alt], [src,tit])])
if __name__ == "__main__":
toJSONFilter(graphviz)
| #!/usr/bin/env python
"""
Pandoc filter to process code blocks with class "graphviz" into
graphviz-generated images.
"""
import pygraphviz
import hashlib
import os
import sys
from pandocfilters import toJSONFilter, Str, Para, Image
def sha1(x):
return hashlib.sha1(x).hexdigest()
imagedir = "graphviz-images"
def graphviz(key, value, format, meta):
if key == 'CodeBlock':
[[ident,classes,keyvals], code] = value
caption = "caption"
if "graphviz" in classes:
G = pygraphviz.AGraph(string = code)
G.layout()
filename = sha1(code)
if format == "html":
filetype = "png"
elif format == "latex":
filetype = "pdf"
else:
filetype = "png"
alt = Str(caption)
src = imagedir + '/' + filename + '.' + filetype
if not os.path.isfile(src):
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
G.draw(src)
sys.stderr.write('Created image ' + src + '\n')
tit = ""
return Para([Image(alt, [src,tit])])
if __name__ == "__main__":
toJSONFilter(graphviz)
|
Use JavaScript to intercept space bar event. | var Cloudy = {
isPlayerPage: function() {
return $("#audioplayer").length == 1;
},
sendEpisodeToCloudy: function() {
var episodeTitle = $(".titlestack .title").text();
var showTitle = $(".titlestack .caption2").text();
var details = {
"show_title": showTitle,
"episode_title": episodeTitle
};
webkit.messageHandlers.episodeHandler.postMessage(details);
},
installPlaybackHandlers: function() {
var player = $("#audioplayer")[0];
player.addEventListener("play", Cloudy.playerDidPlay);
player.addEventListener("pause", Cloudy.playerDidPause);
},
playerDidPlay: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": true
});
},
playerDidPause: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": false
});
},
togglePlaybackState: function() {
var player = $("#audioplayer")[0];
player.paused ? player.play() : player.pause();
},
installSpaceHandler: function() {
$(window).keypress(function(event) {
if (event.keyCode == 32) {
event.preventDefault();
Cloudy.togglePlaybackState();
}
});
}
};
$(function() {
if (Cloudy.isPlayerPage()) {
Cloudy.installPlaybackHandlers();
Cloudy.installSpaceHandler();
Cloudy.sendEpisodeToCloudy();
}
else {
webkit.messageHandlers.episodeHandler.postMessage(null);
}
});
| var Cloudy = {
isPlayerPage: function() {
return $("#audioplayer").length == 1;
},
sendEpisodeToCloudy: function() {
var episodeTitle = $(".titlestack .title").text();
var showTitle = $(".titlestack .caption2").text();
var details = {
"show_title": showTitle,
"episode_title": episodeTitle
};
webkit.messageHandlers.episodeHandler.postMessage(details);
},
installPlaybackHandlers: function() {
var player = $("#audioplayer")[0];
player.addEventListener("play", Cloudy.playerDidPlay);
player.addEventListener("pause", Cloudy.playerDidPause);
},
playerDidPlay: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": true
});
},
playerDidPause: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": false
});
},
togglePlaybackState: function() {
var player = $("#audioplayer")[0];
player.paused ? player.play() : player.pause();
}
};
$(function() {
if (Cloudy.isPlayerPage()) {
Cloudy.installPlaybackHandlers();
Cloudy.sendEpisodeToCloudy();
}
else {
webkit.messageHandlers.episodeHandler.postMessage(null);
}
});
|
Set webpack mode to silence warning | var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};
// This is to filter out node_modules as we don't want them
// to be made part of any bundles.
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
// jscs:disable requireTemplateStrings
nodeModules[mod] = 'commonjs ' + mod;
// jscs:enable requireTemplateStrings
});
module.exports = {
mode: 'production',
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'dist'),
filename: 'dispensary.js',
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
exclude: /(node_modules|bower_components)/,
test: /\.js$/,
// babel options are in .babelrc
use: [
{loader: 'babel-loader'}
],
},
{
test: /\.txt$/,
use: [
{loader: 'raw-loader'}
],
},
],
},
externals: nodeModules,
plugins: [
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true,
entryOnly: false,
}),
],
resolve: {
extensions: ['.js', '.json'],
modules: [
'node_modules',
],
},
devtool: 'sourcemap',
};
| var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};
// This is to filter out node_modules as we don't want them
// to be made part of any bundles.
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
// jscs:disable requireTemplateStrings
nodeModules[mod] = 'commonjs ' + mod;
// jscs:enable requireTemplateStrings
});
module.exports = {
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'dist'),
filename: 'dispensary.js',
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
exclude: /(node_modules|bower_components)/,
test: /\.js$/,
// babel options are in .babelrc
use: [
{loader: 'babel-loader'}
],
},
{
test: /\.txt$/,
use: [
{loader: 'raw-loader'}
],
},
],
},
externals: nodeModules,
plugins: [
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true,
entryOnly: false,
}),
],
resolve: {
extensions: ['.js', '.json'],
modules: [
'node_modules',
],
},
devtool: 'sourcemap',
};
|
[MOD] Use browse record instead of ids | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, api
class StockQuant(models.Model):
_inherit = 'stock.quant'
@api.multi
def merge_stock_quants(self):
pending_quants = self.filtered(lambda x: True)
for quant2merge in self:
if (quant2merge in pending_quants and
not quant2merge.reservation_id):
quants = self.search(
[('id', '!=', quant2merge.id),
('product_id', '=', quant2merge.product_id.id),
('lot_id', '=', quant2merge.lot_id.id),
('package_id', '=', quant2merge.package_id.id),
('location_id', '=', quant2merge.location_id.id),
('reservation_id', '=', False),
('propagated_from_id', '=',
quant2merge.propagated_from_id.id)])
for quant in quants:
if (self._get_latest_move(quant2merge) ==
self._get_latest_move(quant)):
quant2merge.qty += quant.qty
quant2merge.cost += quant.cost
pending_quants -= quant
quant.sudo().unlink()
@api.model
def quants_unreserve(self, move):
quants = move.reserved_quant_ids
super(StockQuant, self).quants_unreserve(move)
quants.merge_stock_quants()
| # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, api
class StockQuant(models.Model):
_inherit = 'stock.quant'
@api.multi
def merge_stock_quants(self):
pending_quants_ids = self.ids
for quant2merge in self:
if (quant2merge.id in pending_quants_ids and
not quant2merge.reservation_id):
quants = self.search(
[('id', '!=', quant2merge.id),
('product_id', '=', quant2merge.product_id.id),
('lot_id', '=', quant2merge.lot_id.id),
('package_id', '=', quant2merge.package_id.id),
('location_id', '=', quant2merge.location_id.id),
('reservation_id', '=', False),
('propagated_from_id', '=',
quant2merge.propagated_from_id.id)])
for quant in quants:
if (self._get_latest_move(quant2merge) ==
self._get_latest_move(quant)):
quant2merge.qty += quant.qty
quant2merge.cost += quant.cost
if quant.id in pending_quants_ids:
pending_quants_ids.remove(quant.id)
quant.sudo().unlink()
@api.model
def quants_unreserve(self, move):
quants = move.reserved_quant_ids
super(StockQuant, self).quants_unreserve(move)
quants.merge_stock_quants()
|
Fix wrong sessions time interval parameter datatype | <?php
declare(strict_types=1);
namespace Cortex\Fort\Http\Controllers\Backend;
use Carbon\Carbon;
use Cortex\Fort\Models\Role;
use Cortex\Fort\Models\User;
use Cortex\Fort\Models\Ability;
use Rinvex\Fort\Models\Session;
use Illuminate\Support\Facades\DB;
use Cortex\Foundation\Http\Controllers\AuthorizedController;
class DashboardController extends AuthorizedController
{
/**
* {@inheritdoc}
*/
protected $resource = 'dashboard';
/**
* {@inheritdoc}
*/
protected $resourceAbilityMap = ['home' => 'access'];
/**
* Show the dashboard home.
*
* @return \Illuminate\Http\Response
*/
public function home()
{
// Get statistics
$stats = [
'abilities' => ['route' => route('backend.abilities.index'), 'count' => Ability::count()],
'roles' => ['route' => route('backend.roles.index'), 'count' => Role::count()],
'users' => ['route' => route('backend.users.index'), 'count' => User::count()],
];
// Get online users
$sessions = Session::users(config('rinvex.fort.online_interval'))->groupBy(['user_id'])->with(['user'])->get(['user_id', DB::raw('MAX(last_activity) as last_activity')]);
return view('cortex/fort::backend.pages.home', compact('sessions', 'stats'));
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Fort\Http\Controllers\Backend;
use Carbon\Carbon;
use Cortex\Fort\Models\Role;
use Cortex\Fort\Models\User;
use Cortex\Fort\Models\Ability;
use Rinvex\Fort\Models\Session;
use Illuminate\Support\Facades\DB;
use Cortex\Foundation\Http\Controllers\AuthorizedController;
class DashboardController extends AuthorizedController
{
/**
* {@inheritdoc}
*/
protected $resource = 'dashboard';
/**
* {@inheritdoc}
*/
protected $resourceAbilityMap = ['home' => 'access'];
/**
* Show the dashboard home.
*
* @return \Illuminate\Http\Response
*/
public function home()
{
// Get statistics
$stats = [
'abilities' => ['route' => route('backend.abilities.index'), 'count' => Ability::count()],
'roles' => ['route' => route('backend.roles.index'), 'count' => Role::count()],
'users' => ['route' => route('backend.users.index'), 'count' => User::count()],
];
// Get online users
$onlineInterval = Carbon::now()->subMinutes(config('rinvex.fort.online_interval'));
$sessions = Session::users($onlineInterval)->groupBy(['user_id'])->with(['user'])->get(['user_id', DB::raw('MAX(last_activity) as last_activity')]);
return view('cortex/fort::backend.pages.home', compact('sessions', 'stats'));
}
}
|
Fix REPL and add quit() command | import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'
print 'Type %r to exit REPL' % QUIT_STR
run = True
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
# Infinite REPL
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
if input == QUIT_STR:
break
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(cmd)
except (OverflowError, SyntaxError, ValueError):
print traceback.format_exc().rstrip()
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
try:
out = eval(ret)
except:
print traceback.format_exc().rstrip()
else:
if out is not None:
print "%r" % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, diesel_repl))
a.run()
| '''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(input)
except SyntaxError, e:
# TODO Pretty print traceback
print e
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
#interp.runcode(ret)
exec cmd
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
|
Copy uploads from correct source | var config = require('../src/config/config')
var client = require('mongodb').MongoClient
var fs = require('fs-extra')
client.connect(config.database.host+'vegodev', function(err, db){
if (err) throw err
//Drop vegodev database if it exists
db.dropDatabase(function(err, result) {
var adminDb = db.admin()
//Get a fresh copy
adminDb.command({
copydb: 1,
fromdb: 'vegosvar',
todb: 'vegodev'
}, function(err, result) {
if (err) throw err
if(result.ok) {
console.log('Database copied successfully')
}
//Copy uploads folder
var source = '/var/www/vegosvar.se/src/uploads'
var destination = '/var/www/dev.vegosvar.se/src/uploads'
//assume this directory has a lot of files and folders
fs.emptyDir(destination, function (err) {
if (err) throw err
fs.copy(source, destination, function (err) {
if (err) throw err
console.log('Uploads folder copied successfully')
if('environment' in config && config.environment === 'development') {
//Set all pages to published
db.collection('pages').update({}, {
$set: {
accepted: true
}
}, {
multi: true
}, function(err, result) {
db.close()
})
} else {
db.close()
}
})
})
})
})
})
| var config = require('../src/config/config')
var client = require('mongodb').MongoClient
var fs = require('fs-extra')
client.connect(config.database.host+'vegodev', function(err, db){
if (err) throw err
//Drop vegodev database if it exists
db.dropDatabase(function(err, result) {
var adminDb = db.admin()
//Get a fresh copy
adminDb.command({
copydb: 1,
fromdb: 'vegosvar',
todb: 'vegodev'
}, function(err, result) {
if (err) throw err
if(result.ok) {
console.log('Database copied successfully')
}
//Copy uploads folder
var source = '/var/www/beta.vegosvar.se/src/uploads'
var destination = '/var/www/dev.vegosvar.se/src/uploads'
//assume this directory has a lot of files and folders
fs.emptyDir(destination, function (err) {
if (err) throw err
fs.copy(source, destination, function (err) {
if (err) throw err
console.log('Uploads folder copied successfully')
if('environment' in config && config.environment === 'development') {
//Set all pages to published
db.collection('pages').update({}, {
$set: {
accepted: true
}
}, {
multi: true
}, function(err, result) {
db.close()
})
} else {
db.close()
}
})
})
})
})
})
|
Allow running tests with postgres | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASE_ENGINE = db_engine,
DATABASE_NAME = db_name,
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Fix AnyUrlField migration issue on Django 1.11. | """
Optional integration with django-any-urlfield
"""
from __future__ import absolute_import
from django.db import models
from fluent_utils.django_compat import is_installed
if is_installed('any_urlfield'):
from any_urlfield.models import AnyUrlField as BaseUrlField
else:
BaseUrlField = models.URLField
# subclassing here so South or Django migrations detect a single class.
class AnyUrlField(BaseUrlField):
"""
A CharField that can either refer to a CMS page ID, or external URL.
If *django-any-urlfield* is not installed, only regular URLs can be used.
"""
def __init__(self, *args, **kwargs):
if 'max_length' not in kwargs:
kwargs['max_length'] = 300 # Standardize
super(AnyUrlField, self).__init__(*args, **kwargs)
def south_field_triple(self):
# Masquerade as normal URLField, so the soft-dependency also exists in the migrations.
from south.modelsinspector import introspector
path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__)
args, kwargs = introspector(self)
return (path, args, kwargs)
def deconstruct(self):
# For Django 1.7 migrations, masquerade as normal URLField too
name, path, args, kwargs = super(AnyUrlField, self).deconstruct()
path = "django.db.models.{}".format(models.URLField.__name__)
return name, path, args, kwargs
| """
Optional integration with django-any-urlfield
"""
from __future__ import absolute_import
from django.db import models
from fluent_utils.django_compat import is_installed
if is_installed('any_urlfield'):
from any_urlfield.models import AnyUrlField as BaseUrlField
else:
BaseUrlField = models.URLField
# subclassing here so South or Django migrations detect a single class.
class AnyUrlField(BaseUrlField):
"""
A CharField that can either refer to a CMS page ID, or external URL.
If *django-any-urlfield* is not installed, only regular URLs can be used.
"""
def __init__(self, *args, **kwargs):
if 'max_length' not in kwargs:
kwargs['max_length'] = 300 # Standardize
super(AnyUrlField, self).__init__(*args, **kwargs)
def south_field_triple(self):
# Masquerade as normal URLField, so the soft-dependency also exists in the migrations.
from south.modelsinspector import introspector
path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__)
args, kwargs = introspector(self)
return (path, args, kwargs)
def deconstruct(self):
# For Django 1.7 migrations, masquerade as normal URLField too
name, path, args, kwargs = super(AnyUrlField, self).deconstruct()
path = "{0}.{1}".format(models.URLField.__module__, models.URLField.__name__)
return name, path, args, kwargs
|
Reduce frequency of 'random' ssl tests. | from cgi import FieldStorage
from logging import debug, error, info
from time import time
from trackon import tracker
MAX_MIN_INTERVAL = 60*60*5
DEFAULT_CHECK_INTERVAL = 60*15
def main():
args = FieldStorage()
now = int(time())
if 'tracker-address' in args:
t = args['tracker-address'].value
r = tracker.check(t)
nxt = DEFAULT_CHECK_INTERVAL
if 'response' in r and 'min interval' in r['response']:
nxt = r['response']['min interval']
if nxt > MAX_MIN_INTERVAL:
nxt = MAX_MIN_INTERVAL
r['next-check'] = now+nxt
tracker.update(t, r)
if 'error' in r:
info("Update failed for %s: %s" % (t, r['error']))
else:
ti = tracker.allinfo() or {}
for t in ti:
if 'next-check' not in ti[t] or ti[t]['next-check'] < now:
# Gross hack: 0.2% of the time we try over https
if ti[t].get('ssl', True) or (now%500 == 0):
t = t.replace('http://', 'https://')
tracker.schedule_update(t)
if __name__ == '__main__':
main()
| from cgi import FieldStorage
from logging import debug, error, info
from time import time
from trackon import tracker
MAX_MIN_INTERVAL = 60*60*5
DEFAULT_CHECK_INTERVAL = 60*15
def main():
args = FieldStorage()
now = int(time())
if 'tracker-address' in args:
t = args['tracker-address'].value
r = tracker.check(t)
nxt = DEFAULT_CHECK_INTERVAL
if 'response' in r and 'min interval' in r['response']:
nxt = r['response']['min interval']
if nxt > MAX_MIN_INTERVAL:
nxt = MAX_MIN_INTERVAL
r['next-check'] = now+nxt
tracker.update(t, r)
if 'error' in r:
info("Update failed for %s: %s" % (t, r['error']))
else:
ti = tracker.allinfo() or {}
for t in ti:
if 'next-check' not in ti[t] or ti[t]['next-check'] < now:
# Gross hack: 1% of the time we try over https
if ti[t].get('ssl', True) or (now%100 == 0):
t = t.replace('http://', 'https://')
tracker.schedule_update(t)
if __name__ == '__main__':
main()
|
Print email recipients on startup | 'use strict';
const schedule = require('node-schedule');
const jenkins = require('./lib/jenkins');
const redis = require('./lib/redis');
const gitter = require('./lib/gitter');
const sendgrid = require('./lib/sendgrid');
const pkg = require('./package.json');
console.log(new Date(), `Staring ${pkg.name} v${pkg.version}`);
console.log(new Date(), process.env.SENDGRID_RECIPIENTS.split(','));
schedule.scheduleJob(process.env.CRON_INTERVAL, function() {
console.log(new Date(), 'Running Cron Job...');
console.log(new Date(), 'Fetching Jenkins nodes...');
jenkins.getComputers(function(err, nodes) {
if (err) { throw err; }
console.log(new Date(), `Found ${nodes.length} Jenkins nodes.`);
console.log(new Date(), 'Checking changed Jenkins nodes...');
redis.jenkinsChanged(nodes, function(err, changed) {
if (err) { throw err; }
console.log(new Date(), `${changed.length} node(s) changed.`);
if (changed.length > 0) {
console.log(new Date(), 'Posting to Gitter...');
gitter.post(changed, function(err) {
if (err) { throw err; }
console.log(new Date(), 'Gitter: Ok!');
});
console.log(new Date(), 'Notifying via Sendgrid...');
sendgrid.notify(changed, function(err) {
if (err) { throw err; }
console.log(new Date(), 'Sendgrid: Ok!');
});
}
});
});
});
| 'use strict';
const schedule = require('node-schedule');
const jenkins = require('./lib/jenkins');
const redis = require('./lib/redis');
const gitter = require('./lib/gitter');
const sendgrid = require('./lib/sendgrid');
const pkg = require('./package.json');
console.log(new Date(), `Staring ${pkg.name} v${pkg.version}`);
schedule.scheduleJob(process.env.CRON_INTERVAL, function() {
console.log(new Date(), 'Running Cron Job...');
console.log(new Date(), 'Fetching Jenkins nodes...');
jenkins.getComputers(function(err, nodes) {
if (err) { throw err; }
console.log(new Date(), `Found ${nodes.length} Jenkins nodes.`);
console.log(new Date(), 'Checking changed Jenkins nodes...');
redis.jenkinsChanged(nodes, function(err, changed) {
if (err) { throw err; }
console.log(new Date(), `${changed.length} node(s) changed.`);
if (changed.length > 0) {
console.log(new Date(), 'Posting to Gitter...');
gitter.post(changed, function(err) {
if (err) { throw err; }
console.log(new Date(), 'Gitter: Ok!');
});
console.log(new Date(), 'Notifying via Sendgrid...');
sendgrid.notify(changed, function(err) {
if (err) { throw err; }
console.log(new Date(), 'Sendgrid: Ok!');
});
}
});
});
});
|
BAP-11307: Create notice popup for xlsx grid export
- fix maximum number | <?php
namespace Oro\Bundle\DataGridBundle\Extension\Export;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
const XLSX_MAX_EXPORT_RECORDS = 10000;
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder();
$builder->root('export')
->treatTrueLike(
[
'csv' => [
'label' => 'oro.grid.export.csv'
],
'xlsx' => [
'label' => 'oro.grid.export.xlsx',
'show_max_export_records_dialog' => true,
'max_export_records' => self::XLSX_MAX_EXPORT_RECORDS
]
]
)
->treatFalseLike([])
->treatNullLike([])
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('label')
->cannotBeEmpty()
->end()
->booleanNode('show_max_export_records_dialog')
->end()
->integerNode('max_export_records')
->end()
->end()
->end();
return $builder;
}
}
| <?php
namespace Oro\Bundle\DataGridBundle\Extension\Export;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
const XLSX_MAX_EXPORT_RECORDS = 10;
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder();
$builder->root('export')
->treatTrueLike(
[
'csv' => [
'label' => 'oro.grid.export.csv'
],
'xlsx' => [
'label' => 'oro.grid.export.xlsx',
'show_max_export_records_dialog' => true,
'max_export_records' => self::XLSX_MAX_EXPORT_RECORDS
]
]
)
->treatFalseLike([])
->treatNullLike([])
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('label')
->cannotBeEmpty()
->end()
->booleanNode('show_max_export_records_dialog')
->end()
->integerNode('max_export_records')
->end()
->end()
->end();
return $builder;
}
}
|
Fix ui/main to call ui/ui correctly. | define(['./client_secrets', 'ui/ui'], function (secrets, ui) {
var client_id = secrets.web.client_id,
scopes = [
'https://www.googleapis.com/auth/drive'
],
authorization = null;
var attemptAuthorization = function (immediate) {
gapi.auth.authorize(
{
'client_id': client_id,
'scope': scopes,
'immediate': immediate
},
function (result) {
console.log('Google auth result: ', result);
if (result && !result.error) {
console.log('Google Drive authorization successful.');
ui.googleDriveAuthorizationSuccess();
} else if (immediate) {
console.log('Retrying authorization without immediacy');
} else {
console.error("Couldn't authorize with the Google Drive API.");
ui.googleDriveAuthorizationFailed();
}
}
);
};
return {
authorize: function () {
attemptAuthorization(true);
}
};
}); | define(['./client_secrets', 'ui/main'], function (secrets, ui) {
var client_id = secrets.web.client_id,
scopes = [
'https://www.googleapis.com/auth/drive'
],
authorization = null;
var attemptAuthorization = function (immediate) {
gapi.auth.authorize(
{
'client_id': client_id,
'scope': scopes,
'immediate': immediate
},
function (result) {
console.log('Google auth result: ', result);
if (result && !result.error) {
console.log('Google Drive authorization successful.');
ui.googleDriveAuthorizationSuccess();
} else if (immediate) {
console.log('Retrying authorization without immediacy');
} else {
console.error("Couldn't authorize with the Google Drive API.");
ui.googleDriveAuthorizationFailed();
}
}
);
};
return {
authorize: function () {
attemptAuthorization(true);
}
};
}); |
Correct duration when no commands is logged | <?php
namespace Blablacar\MemcachedBundle\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Blablacar\MemcachedBundle\Memcached\ClientLogger;
class MemcachedDataCollector extends DataCollector
{
protected $clients = array();
public function addClient($name, ClientLogger $client)
{
$this->clients[$name] = $client;
}
/**
* {@inheritDoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
foreach ($this->clients as $name => $client) {
foreach ($client->getCommands() as $command) {
$this->data[] = array(
'command' => $command['name'],
'arguments' => implode(', ', $command['arguments']),
'duration' => $command['duration'],
'connection' => $name,
'return' => implode(', ', $command['return'])
);
}
$client->reset();
}
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'memcached';
}
/**
* getCommands
*
* @return array
*/
public function getCommands()
{
return $this->data;
}
/**
* getDuration
*
* @return int
*/
public function getDuration()
{
if (null === $this->data) {
return 0;
}
$time = 0;
foreach ($this->data as $data) {
$time += $data['duration'];
}
return $time;
}
}
| <?php
namespace Blablacar\MemcachedBundle\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Blablacar\MemcachedBundle\Memcached\ClientLogger;
class MemcachedDataCollector extends DataCollector
{
protected $clients = array();
public function addClient($name, ClientLogger $client)
{
$this->clients[$name] = $client;
}
/**
* {@inheritDoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
foreach ($this->clients as $name => $client) {
foreach ($client->getCommands() as $command) {
$this->data[] = array(
'command' => $command['name'],
'arguments' => implode(', ', $command['arguments']),
'duration' => $command['duration'],
'connection' => $name,
'return' => implode(', ', $command['return'])
);
}
$client->reset();
}
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'memcached';
}
/**
* getCommands
*
* @return array
*/
public function getCommands()
{
return $this->data;
}
/**
* getDuration
*
* @return int
*/
public function getDuration()
{
$time = 0;
foreach ($this->data as $data) {
$time += $data['duration'];
}
return $time;
}
}
|
Add filter argument to filter aggregation. | <?php
/*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\ElasticsearchDSL\Aggregation;
use ONGR\ElasticsearchDSL\Aggregation\Type\BucketingTrait;
use ONGR\ElasticsearchDSL\BuilderInterface;
/**
* Class representing FilterAggregation.
*/
class FilterAggregation extends AbstractAggregation
{
use BucketingTrait;
/**
* @var BuilderInterface
*/
protected $filter;
/**
* Inner aggregations container init.
*
* @param string $name
* @param BuilderInterface $filter
*/
public function __construct($name, BuilderInterface $filter = null)
{
parent::__construct($name);
if ($filter !== null) {
$this->setFilter($filter);
}
}
/**
* Sets a filter.
*
* @param BuilderInterface $filter
*/
public function setFilter(BuilderInterface $filter)
{
$this->filter = $filter;
}
/**
* {@inheritdoc}
*/
public function setField($field)
{
throw new \LogicException("Filter aggregation, doesn't support `field` parameter");
}
/**
* {@inheritdoc}
*/
public function getArray()
{
if (!$this->filter) {
throw new \LogicException("Filter aggregation `{$this->getName()}` has no filter added");
}
$filterData = [$this->filter->getType() => $this->filter->toArray()];
return $filterData;
}
/**
* {@inheritdoc}
*/
public function getType()
{
return 'filter';
}
}
| <?php
/*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\ElasticsearchDSL\Aggregation;
use ONGR\ElasticsearchDSL\Aggregation\Type\BucketingTrait;
use ONGR\ElasticsearchDSL\BuilderInterface;
/**
* Class representing FilterAggregation.
*/
class FilterAggregation extends AbstractAggregation
{
use BucketingTrait;
/**
* @var BuilderInterface
*/
protected $filter;
/**
* Sets a filter.
*
* @param BuilderInterface $filter
*/
public function setFilter(BuilderInterface $filter)
{
$this->filter = $filter;
}
/**
* {@inheritdoc}
*/
public function setField($field)
{
throw new \LogicException("Filter aggregation, doesn't support `field` parameter");
}
/**
* {@inheritdoc}
*/
public function getArray()
{
if (!$this->filter) {
throw new \LogicException("Filter aggregation `{$this->getName()}` has no filter added");
}
$filterData = [$this->filter->getType() => $this->filter->toArray()];
return $filterData;
}
/**
* {@inheritdoc}
*/
public function getType()
{
return 'filter';
}
}
|
Add comment about async dictionary | define(['./helpers/trie'], function(Trie){
function BoggleSolver(board){
var solutions = new Set();
var solArray;
var trie = Trie.loadDictionary();
solve(board, solutions); // with big dictionary, might want to make this asynchronous
function addNeighbor(sequence, n) {
if(!n.visited) solveCell(n, sequence + n.value);
}
function solveCell(cell, sequence) {
if(!sequence) sequence = cell.value;
if(!trie.sequence(sequence)) return;
if(valid(sequence)) solutions.add(sequence);
cell.visited = true;
cell.neighbors.forEach(addNeighbor.bind(null, sequence));
cell.visited = false;
}
function solve(board, solutions) {
board.eachCell(solveCell);
}
function valid(seq) {
return seq.length > 2 && trie.contains(seq);
}
this.check = function(word) {
return solutions.has(word.toUpperCase());
}
var getSolutions = function() {
if(!solArray) solArray = Array.from(solutions).sort();
return solArray;
}
Object.defineProperty(this, 'solutions', {
get: getSolutions
})
}
return BoggleSolver;
});
| define(['./helpers/trie'], function(Trie){
function BoggleSolver(board){
var solutions = new Set();
var solArray;
var trie = Trie.loadDictionary();
solve(board, solutions);
function addNeighbor(sequence, n) {
if(!n.visited) solveCell(n, sequence + n.value);
}
function solveCell(cell, sequence) {
if(!sequence) sequence = cell.value;
if(!trie.sequence(sequence)) return;
if(valid(sequence)) solutions.add(sequence);
cell.visited = true;
cell.neighbors.forEach(addNeighbor.bind(null, sequence));
cell.visited = false;
}
function solve(board, solutions) {
board.eachCell(solveCell);
}
function valid(seq) {
return seq.length > 2 && trie.contains(seq);
}
this.check = function(word) {
return solutions.has(word.toUpperCase());
}
var getSolutions = function() {
if(!solArray) solArray = Array.from(solutions).sort();
return solArray;
}
Object.defineProperty(this, 'solutions', {
get: getSolutions
})
}
return BoggleSolver;
});
|
Adjust code style to reduce lines of code :bear: | import datetime
from django.utils.timezone import utc
from .models import Ticket
class TicketServices():
def edit_ticket_once(self, **kwargs):
id_list = kwargs.get('id_list')
edit_tags = kwargs.get('edit_tags')
edit_requester = kwargs.get('edit_requester')
edit_subject = kwargs.get('edit_subject')
edit_due_at = kwargs.get('edit_due_at')
edit_assignee = kwargs.get('edit_assignee')
if edit_tags:
Ticket.objects.filter(pk__in=id_list).update(tags=edit_tags)
if edit_subject:
Ticket.objects.filter(pk__in=id_list).update(subject=edit_subject)
if edit_requester:
Ticket.objects.filter(pk__in=id_list).update(
requester=edit_requester
)
if edit_due_at:
Ticket.objects.filter(pk__in=id_list).update(
due_at=datetime.datetime.strptime(
edit_due_at, '%m/%d/%Y'
).replace(tzinfo=utc)
)
if edit_assignee:
Ticket.objects.filter(pk__in=id_list).update(
assignee=edit_assignee
)
| import datetime
from django.utils.timezone import utc
from .models import Ticket
class TicketServices():
def edit_ticket_once(self, **kwargs):
id_list = kwargs.get('id_list')
edit_tags = kwargs.get('edit_tags')
edit_requester = kwargs.get('edit_requester')
edit_subject = kwargs.get('edit_subject')
edit_due_at = kwargs.get('edit_due_at')
edit_assignee = kwargs.get('edit_assignee')
if edit_tags:
Ticket.objects.filter(
pk__in=id_list
).update(tags=edit_tags)
if edit_subject:
Ticket.objects.filter(
pk__in=id_list
).update(subject=edit_subject)
if edit_requester:
Ticket.objects.filter(
pk__in=id_list
).update(requester=edit_requester)
if edit_due_at:
Ticket.objects.filter(
pk__in=id_list
).update(
due_at=datetime.datetime.strptime(
edit_due_at, "%m/%d/%Y"
).replace(tzinfo=utc)
)
if edit_assignee:
Ticket.objects.filter(
pk__in=id_list
).update(assignee=edit_assignee)
|
Improve speed of targeting by removing unecessary asset updates | import { Component } from "react";
import { withApollo } from "react-apollo";
import gql from "graphql-tag";
const assetPath = `${window.location.protocol}//${window.location.host}/assets`;
export default (assetKey, simulatorId, extension, CORS) => {
return `${assetPath}${assetKey}/${simulatorId}.${extension}`;
};
class AssetComponent extends Component {
constructor(props) {
super(props);
this.state = {
src: `${assetPath}${props.asset}/default.${props.extension || "svg"}`
};
}
state = { src: "http://unsplash.it/300" };
componentWillMount() {
this.updateAsset(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.asset !== this.props.asset) {
this.updateAsset(nextProps);
}
}
updateAsset(props) {
const query = gql`
query GetAsset($assetKey: String!, $simulatorId: ID) {
asset(assetKey: $assetKey, simulatorId: $simulatorId) {
assetKey
url
}
}
`;
const variables = {
assetKey: props.asset,
simulatorId: props.simulatorId
};
props.client
.query({
query,
variables
})
.then(res => {
this.setState({
src: res.data.asset.url
});
});
}
render() {
const { children } = this.props;
const { src } = this.state;
return children({ src });
}
}
export const Asset = withApollo(AssetComponent);
| import { Component } from "react";
import { withApollo } from "react-apollo";
import gql from "graphql-tag";
const assetPath = `${window.location.protocol}//${window.location.host}/assets`;
export default (assetKey, simulatorId, extension, CORS) => {
return `${assetPath}${assetKey}/${simulatorId}.${extension}`;
};
class AssetComponent extends Component {
constructor(props) {
super(props);
this.state = {
src: `${assetPath}${props.asset}/default.${props.extension || "svg"}`
};
}
state = { src: "http://unsplash.it/300" };
componentWillMount() {
this.updateAsset(this.props);
}
componentWillReceiveProps(nextProps) {
this.updateAsset(nextProps);
}
updateAsset(props) {
const query = gql`
query GetAsset($assetKey: String!, $simulatorId: ID) {
asset(assetKey: $assetKey, simulatorId: $simulatorId) {
assetKey
url
}
}
`;
const variables = {
assetKey: props.asset,
simulatorId: props.simulatorId
};
props.client
.query({
query,
variables
})
.then(res => {
this.setState({
src: res.data.asset.url
});
});
}
render() {
const { children } = this.props;
const { src } = this.state;
return children({ src });
}
}
export const Asset = withApollo(AssetComponent);
|
Allow render opts to div. | # -*- coding: utf-8 -*-
from riot.layout import render_layout, patch_layout
def test_render_div():
assert render_layout([
'div', {}, []
]) == [
'div',
{
'div_char': u' ',
'top': 0,
'bottom': 0,
}
]
def test_render_div_with_opts():
assert render_layout([
'div', {
'char': '{ opts.custom_char }',
'top': '{ opts.custom_top }',
'bottom': '{ opts.custom_bottom }',
}, []
], {
'custom_char': u'x',
'custom_top': '1',
'custom_bottom': '1',
}) == [
'div',
{
'div_char': u'x',
'top': 1,
'bottom': 1,
}
]
def test_render_div_with_div_char():
el = render_layout([
'div', {
'char': u'-',
'top': 1,
'bottom': 1
}, []
]) == [
'div',
{
'div_char': u'-',
'top': 1,
'bottom': 1,
}
]
def test_patch_div():
# call div._invalidate()
el1 = [
'div',
{
'div_char': u' ',
'top': 0,
'bottom': 0,
}
]
el2 = [
'div',
{
'div_char': u'-',
'top': 1,
'bottom': 1,
}
]
assert patch_layout(el1, el2) == [
('.div_char', u'-'),
('.top', 1),
('.bottom', 1),
]
| # -*- coding: utf-8 -*-
from riot.layout import render_layout, patch_layout
def test_render_div():
assert render_layout([
'div', {}, []
]) == [
'div',
{
'div_char': u' ',
'top': 0,
'bottom': 0,
}
]
def test_render_div_with_div_char():
el = render_layout([
'div', {
'char': u'-',
'top': 1,
'bottom': 1
}, []
]) == [
'div',
{
'div_char': u'-',
'top': 1,
'bottom': 1,
}
]
def test_patch_div():
# call div._invalidate()
el1 = [
'div',
{
'div_char': u' ',
'top': 0,
'bottom': 0,
}
]
el2 = [
'div',
{
'div_char': u'-',
'top': 1,
'bottom': 1,
}
]
assert patch_layout(el1, el2) == [
('.div_char', u'-'),
('.top', 1),
('.bottom', 1),
]
|
Remove parse in Progam collection. | define([
'backbone',
'App.config',
'App.models.Program'
], function(Backbone, config, ProgramModel) {
'use strict';
return Backbone.Collection.extend({
model : ProgramModel,
url : config.data.programs,
findByCandidate: function(id) {
return this.find(function(model) {
if (model.get('candidate')) return model.get('candidate').id === id;
});
},
findByTheme: function(id) {
var models = [];
this.each(function(model) {
var projects = _.filter(model.get('projects'), function(project) {
return project.theme.id === id;
});
if (projects.length > 0) {
model.attributes.projects = projects;
models.push(model);
}
});
return new this.constructor(models);
},
findByThemeAndGroupByCandidate: function(id) {
var models = this.findByTheme(id);
models = new this.constructor(models.shuffle());
models = models.groupBy(function(m) { return m.get('candidate').name; });
Object.keys(models).forEach(function(key) {
models[key] = models[key][0].toJSON();
});
return models;
},
candidateProjects: function(id) {
var model = this.findByCandidate(id);
if (!model) return;
var projects = model.get('projects');
return _.groupBy(projects, function(obj) { return obj.theme.name; });
}
});
});
| define([
'App.config',
'App.models.Program',
'backbone'
], function(config, ProgramModel, Backbone) {
'use strict';
return Backbone.Collection.extend({
model : ProgramModel,
url : config.data.programs,
parse: function(res) {
return res.programs;
},
findByCandidate: function(id) {
return this.find(function(model) {
if (model.get('candidate')) return model.get('candidate').id === id;
});
},
findByTheme: function(id) {
var models = [];
this.each(function(model) {
var projects = _.filter(model.get('projects'), function(project) {
return project.theme.id === id;
});
if (projects.length > 0) {
model.attributes.projects = projects;
models.push(model);
}
});
return new this.constructor(models);
},
findByThemeAndGroupByCandidate: function(id) {
var models = this.findByTheme(id);
models = new this.constructor(models.shuffle());
models = models.groupBy(function(m) { return m.get('candidate').name; });
Object.keys(models).forEach(function(key) {
models[key] = models[key][0].toJSON();
});
return models;
},
candidateProjects: function(id) {
var model = this.findByCandidate(id);
if (!model) return;
var projects = model.get('projects');
return _.groupBy(projects, function(obj) { return obj.theme.name; });
}
});
});
|
Handle no roles on users table | import React, {PropTypes} from 'react'
const UsersTable = ({users}) => (
<div className="panel panel-minimal">
<div className="panel-body">
<table className="table v-center">
<thead>
<tr>
<th>User</th>
<th>Roles</th>
<th>Permissions</th>
</tr>
</thead>
<tbody>
{
users.length ? users.map((user) => (
<tr key={user.name}>
<td>{user.name}</td>
<td>{users.roles && user.roles.map((r) => r.name).join(', ')}</td>
<td>{user.permissions.map((p) => p.scope).join(', ')}</td>
</tr>
)) : (() => (
<tr className="table-empty-state">
<th colSpan="5">
<p>You don't have any Users,<br/>why not create one?</p>
</th>
</tr>
))()
}
</tbody>
</table>
</div>
</div>
)
const {
arrayOf,
shape,
string,
} = PropTypes
UsersTable.propTypes = {
users: arrayOf(shape({
name: string.isRequired,
roles: arrayOf(shape({
name: string,
})),
permissions: arrayOf(shape({
name: string,
scope: string.isRequired,
})),
})),
}
export default UsersTable
| import React, {PropTypes} from 'react'
const UsersTable = ({users}) => (
<div className="panel panel-minimal">
<div className="panel-body">
<table className="table v-center">
<thead>
<tr>
<th>User</th>
<th>Roles</th>
<th>Permissions</th>
</tr>
</thead>
<tbody>
{
users.length ? users.map((user) => (
<tr key={user.name}>
<td>{user.name}</td>
<td>{user.roles.map((r) => r.name).join(', ')}</td>
<td>{user.permissions.map((p) => p.scope).join(', ')}</td>
</tr>
)) : (() => (
<tr className="table-empty-state">
<th colSpan="5">
<p>You don't have any Users,<br/>why not create one?</p>
</th>
</tr>
))()
}
</tbody>
</table>
</div>
</div>
)
const {
arrayOf,
shape,
string,
} = PropTypes
UsersTable.propTypes = {
users: arrayOf(shape({
name: string.isRequired,
roles: arrayOf(shape({
name: string,
})),
permissions: arrayOf(shape({
name: string,
scope: string.isRequired,
})),
})),
}
export default UsersTable
|
Use ascii in logging message | import logging
from flask import current_app, request, abort
from flask.blueprints import Blueprint
from sipa.utils.git_utils import update_repo
logger = logging.getLogger(__name__)
bp_hooks = Blueprint('hooks', __name__, url_prefix='/hooks')
@bp_hooks.route('/update-content', methods=['POST'])
def content_hook():
auth_key = current_app.config.get('GIT_UPDATE_HOOK_TOKEN')
if not auth_key:
# no key configured (default) → feature not enabled
abort(404)
key = request.args.get('token')
if not key:
logger.debug("`update-content` called without Token",
extra={'data': {'request_args': request.args}})
abort(401)
if key != auth_key:
logger.warning("`update-content` called with wrong Token",
extra={'data': {'request_args': request.args,
'auth_key': auth_key}})
abort(403)
logger.info("Update hook triggered. Fetching content.")
reload_necessary = update_repo(current_app.config['FLATPAGES_ROOT'])
if reload_necessary:
try:
import uwsgi
except ImportError:
logger.debug("UWSGI not present, skipping reload")
pass
else:
logger.debug("Reloading UWSGI...")
uwsgi.reload()
# 204: No content
# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#204
return "", 204
| import logging
from flask import current_app, request, abort
from flask.blueprints import Blueprint
from sipa.utils.git_utils import update_repo
logger = logging.getLogger(__name__)
bp_hooks = Blueprint('hooks', __name__, url_prefix='/hooks')
@bp_hooks.route('/update-content', methods=['POST'])
def content_hook():
auth_key = current_app.config.get('GIT_UPDATE_HOOK_TOKEN')
if not auth_key:
# no key configured (default) → feature not enabled
abort(404)
key = request.args.get('token')
if not key:
logger.debug("`update-content` called without Token",
extra={'data': {'request_args': request.args}})
abort(401)
if key != auth_key:
logger.warning("`update-content` called with wrong Token",
extra={'data': {'request_args': request.args,
'auth_key': auth_key}})
abort(403)
logger.info("Update hook triggered. Fetching content.")
reload_necessary = update_repo(current_app.config['FLATPAGES_ROOT'])
if reload_necessary:
try:
import uwsgi
except ImportError:
logger.debug("UWSGI not present, skipping reload")
pass
else:
logger.debug("Reloading UWSGI…")
uwsgi.reload()
# 204: No content
# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#204
return "", 204
|
Add SCSS support.
node-sass already support SCSS but this plugin only allows SASS file extension. | var Q = require('q');
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var sass = require('node-sass');
// Compile a SASS file into a css
function renderSASS(input, output) {
var d = Q.defer();
sass.render({
file: input
}, function (e, out) {
if (e) return d.reject(e);
fs.writeFileSync(output, out.css);
d.resolve();
});
return d.promise;
}
module.exports = {
hooks: {
// Compile sass as CSS
init: function() {
var book = this;
var styles = book.config.get('styles');
return _.reduce(styles, function(prev, filename, type) {
return prev.then(function() {
var extension = path.extname(filename).toLowerCase();
if (extension != '.sass' && extension != '.scss') return;
book.log.info.ln('compile sass file: ', filename);
// Temporary CSS file
var tmpfile = type+'-'+Date.now()+'.css';
// Replace config
book.config.set('styles.'+type, tmpfile);
return renderSASS(
book.resolve(filename),
path.resolve(book.options.output, tmpfile)
);
});
}, Q());
}
}
};
| var Q = require('q');
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var sass = require('node-sass');
// Compile a SASS file into a css
function renderSASS(input, output) {
var d = Q.defer();
sass.render({
file: input
}, function (e, out) {
if (e) return d.reject(e);
fs.writeFileSync(output, out.css);
d.resolve();
});
return d.promise;
}
module.exports = {
hooks: {
// Compile sass as CSS
init: function() {
var book = this;
var styles = book.config.get('styles');
return _.reduce(styles, function(prev, filename, type) {
return prev.then(function() {
if (path.extname(filename).toLowerCase() != '.sass') return;
book.log.info.ln('compile sass file: ', filename);
// Temporary CSS file
var tmpfile = type+'-'+Date.now()+'.css';
// Replace config
book.config.set('styles.'+type, tmpfile);
return renderSASS(
book.resolve(filename),
path.resolve(book.options.output, tmpfile)
);
});
}, Q());
}
}
};
|
Add run solver first exception type | #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
class RunSolverFirst(Exception):
pass
class BaseSolver(object):
task = None
best_solution = None
best_distance = float('inf')
search_time = None
cycles = 0
def __init__(self, task):
self.task = task
def run(self):
start_time = datetime.now()
self.best_solution, self.best_distance, self.cycles = self.run_search()
finish_time = datetime.now()
self.search_time = finish_time - start_time
def run_search(self):
# dummy - this is where one should implement the algorithm
pass
def get_summary(self):
if self.best_solution is None:
raise RunSolverFirst(u'Run the solver first')
txt = (
'========== {solver_name} ==========\n'
'run {cycles} cycles for: {search_time}\n'
'best found solution: {best_solution}\n'
'distance: {distance}\n'
)
return txt.format(
solver_name=str(self.__class__),
cycles=self.cycles,
search_time=self.search_time,
best_solution=self.best_solution,
distance=self.best_distance
)
| #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
class BaseSolver(object):
task = None
best_solution = None
best_distance = float('inf')
search_time = None
cycles = 0
def __init__(self, task):
self.task = task
def run(self):
start_time = datetime.now()
self.best_solution, self.best_distance, self.cycles = self.run_search()
finish_time = datetime.now()
self.search_time = finish_time - start_time
def run_search(self):
# dummy - this is where one should implement the algorithm
pass
def get_summary(self):
if self.best_solution is None:
return u'Run the solver first'
txt = (
'========== {solver_name} ==========\n'
'run {cycles} cycles for: {search_time}\n'
'best found solution: {best_solution}\n'
'distance: {distance}\n'
)
return txt.format(
solver_name=str(self.__class__),
cycles=self.cycles,
search_time=self.search_time,
best_solution=self.best_solution,
distance=self.best_distance
)
|
Update PHPDoc on config manifest proxy constructor | <?php
namespace LeKoala\DebugBar\Proxy;
use SilverStripe\Config\Collections\CachedConfigCollection;
class ConfigManifestProxy extends CachedConfigCollection
{
/**
* @var CachedConfigCollection
*/
protected $parent;
/**
* @var array
*/
protected static $configCalls = [];
/**
* @param CachedConfigCollection $parent
*/
public function __construct(CachedConfigCollection $parent)
{
$this->parent = $parent;
$this->collection = $this->parent->getCollection();
$this->cache = $this->parent->getCache();
$this->flush = $this->parent->getFlush();
$this->collectionCreator = $this->parent->getCollectionCreator();
}
/**
* Monitor calls made to get configuration during a request
*
* {@inheritDoc}
*/
public function get($class, $name = null, $excludeMiddleware = 0)
{
$result = parent::get($class, $name, $excludeMiddleware);
if (!isset(self::$configCalls[$class][$name])) {
self::$configCalls[$class][$name] = [
'calls' => 0,
'result' => null
];
}
self::$configCalls[$class][$name]['calls']++;
self::$configCalls[$class][$name]['result'] = $result;
return $result;
}
/**
* Return a list of all config calls made during the request, including how many times they were called
* and the result
*
* @return array
*/
public static function getConfigCalls()
{
return self::$configCalls;
}
}
| <?php
namespace LeKoala\DebugBar\Proxy;
use SilverStripe\Config\Collections\CachedConfigCollection;
class ConfigManifestProxy extends CachedConfigCollection
{
/**
* @var CachedConfigCollection
*/
protected $parent;
/**
* @var array
*/
protected static $configCalls = [];
/**
* @param ConfigCollectionInterface $parent
*/
public function __construct(CachedConfigCollection $parent)
{
$this->parent = $parent;
$this->collection = $this->parent->getCollection();
$this->cache = $this->parent->getCache();
$this->flush = $this->parent->getFlush();
$this->collectionCreator = $this->parent->getCollectionCreator();
}
/**
* Monitor calls made to get configuration during a request
*
* {@inheritDoc}
*/
public function get($class, $name = null, $excludeMiddleware = 0)
{
$result = parent::get($class, $name, $excludeMiddleware);
if (!isset(self::$configCalls[$class][$name])) {
self::$configCalls[$class][$name] = [
'calls' => 0,
'result' => null
];
}
self::$configCalls[$class][$name]['calls']++;
self::$configCalls[$class][$name]['result'] = $result;
return $result;
}
/**
* Return a list of all config calls made during the request, including how many times they were called
* and the result
*
* @return array
*/
public static function getConfigCalls()
{
return self::$configCalls;
}
}
|
Update the commit_over_52 template tag to be more efficient.
Replaced several list comprehensions with in-database operations and map calls for significantly improved performance. | from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True)
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
weeks = map(str, weeks)
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
def usage(user, package):
using = package.usage.filter(username=user) or False
count = 0
if using:
count = package.usage.count() - 1
return {
"using": using,
"count": count,
"package": package,
"show_count": True
}
@register.inclusion_tag('package/templatetags/usage.html')
def usage_no_count(user, package):
using = package.usage.filter(username=user) or False
count = 0
return {
"using": using,
"count": count,
"package": package,
"show_count": False
} | from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = [x.commit_date for x in Commit.objects.filter(package=package)]
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
weeks = [str(x) for x in weeks]
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
def usage(user, package):
using = package.usage.filter(username=user) or False
count = 0
if using:
count = package.usage.count() - 1
return {
"using": using,
"count": count,
"package": package,
"show_count": True
}
@register.inclusion_tag('package/templatetags/usage.html')
def usage_no_count(user, package):
using = package.usage.filter(username=user) or False
count = 0
return {
"using": using,
"count": count,
"package": package,
"show_count": False
} |
Use `execFile` instead of `exec` | import {execFile} from 'child_process';
import semver from 'semver';
const {major, minor, patch} = semver.parse(atom.appVersion);
const atomVersion = `${major}.${minor}.${patch}`;
const requiredVersion = '>=1.14.0';
import GitPromptServer from '../lib/git-prompt-server';
// Will not pass on Appveyor
if (process.platform !== 'win32' && semver.satisfies(atomVersion, requiredVersion)) {
describe('GitPromptServer', function() {
it('prompts for user input and writes the response to stdout', async function() {
this.timeout(10000);
const server = new GitPromptServer();
const {helper, socket, electron} = await server.start(question => {
assert.equal(question, 'What... is your favorite color?\u0000');
return 'Green. I mean blue! AAAhhhh...';
});
let err, stdout;
await new Promise((resolve, reject) => {
execFile(electron,
[helper, socket, 'What... is your favorite color?'],
{
env: {
ELECTRON_RUN_AS_NODE: 1,
ELECTRON_NO_ATTACH_CONSOLE: 1,
},
}, (_err, _stdout, _stderr) => {
err = _err;
stdout = _stdout;
resolve();
});
});
assert.ifError(err);
assert.equal(stdout, 'Green. I mean blue! AAAhhhh...\n');
await server.terminate();
});
});
}
| import {exec} from 'child_process';
import semver from 'semver';
const {major, minor, patch} = semver.parse(atom.appVersion);
const atomVersion = `${major}.${minor}.${patch}`;
const requiredVersion = '>=1.14.0';
import GitPromptServer from '../lib/git-prompt-server';
// Will not pass on Appveyor
if (process.platform !== 'win32' && semver.satisfies(atomVersion, requiredVersion)) {
describe('GitPromptServer', function() {
it('prompts for user input and writes the response to stdout', async function() {
this.timeout(10000);
const server = new GitPromptServer();
const {helper, socket, electron} = await server.start(question => {
assert.equal(question, 'What... is your favorite color?\u0000');
return 'Green. I mean blue! AAAhhhh...';
});
let err, stdout;
await new Promise((resolve, reject) => {
const command = `"${electron}" "${helper}" "${socket}" "What... is your favorite color?"`;
exec(command, {
env: {
ELECTRON_RUN_AS_NODE: 1,
ELECTRON_NO_ATTACH_CONSOLE: 1,
},
}, (_err, _stdout, _stderr) => {
err = _err;
stdout = _stdout;
resolve();
});
});
assert.ifError(err);
assert.equal(stdout, 'Green. I mean blue! AAAhhhh...\n');
await server.terminate();
});
});
}
|
Add a `travis` task for grunt. | module.exports = function(grunt) {
'use strict';
// Configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jscs: {
options: {
config: '.jscsrc'
},
bin: 'bin/**/*.js',
grunt: 'Gruntfile.js',
lib: 'lib/**/*.js',
test: '<%= nodeunit.all %>'
},
jshint: {
options: {
jshintrc: true
},
bin: 'bin/**/*.js',
grunt: 'Gruntfile.js',
lib: 'lib/**/*.js',
test: '<%= nodeunit.all %>'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: ['test/**/*.js']
},
release: {
options: {}
}
});
// Load tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'test']);
grunt.registerTask('default', ['lint', 'test']);
};
| module.exports = function(grunt) {
'use strict';
// Configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jscs: {
options: {
config: '.jscsrc'
},
bin: 'bin/**/*.js',
grunt: 'Gruntfile.js',
lib: 'lib/**/*.js',
test: '<%= nodeunit.all %>'
},
jshint: {
options: {
jshintrc: true
},
bin: 'bin/**/*.js',
grunt: 'Gruntfile.js',
lib: 'lib/**/*.js',
test: '<%= nodeunit.all %>'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: ['test/**/*.js']
},
release: {
options: {}
}
});
// Load tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('default', ['lint', 'test']);
};
|
Fix the imports in the tests of dropbox | import os
from path import path
from tests.utils.testdriver import TestDriver
from tests.utils.tempdirs import dirs
from onitu.drivers.dropbox.dropboxDriver import dropboxDriver
class Driver(TestDriver):
def __init__(self, *args, **options):
if 'root' not in options:
options['root'] = dirs.create()
if 'key' not in options:
options['key'] = "38jd72msqedx5n9"
if 'secret' not in options:
options['secret'] = "g4favy0bgjstt2w"
if 'changes_timer' not in options:
options['changes_timer'] = 600.0
self.dropbox = dropboxDriver(options)
super(Driver, self).__init__('dropbox',
*args,
**options)
@property
def root(self):
return path(self.options['root'])
def close(self):
self.drop.delete_file('/')
def mkdir(self, subdirs):
self.drop.create_dir(subdirs+"/toto")
def write(self, filename, content):
metadata = {"size": len(content), "filename": filename}
self.drop.upload_chunk(metadata, 0, content, len(content))
def generate(self, filename, size):
self.write(filename, os.urandom(size))
def unlink(self, filename):
self.drop.delete_file(filename)
def checksum(self, filename):
return "LOL----LOL"
| import os
from path import path
from tests.utils.testdriver import TestDriver
from tests.utils.tempdirs import dirs
from onitu.drivers.dropbox.libDropbox import LibDropbox
class Driver(TestDriver):
def __init__(self, *args, **options):
if 'root' not in options:
options['root'] = dirs.create()
if 'key' not in options:
options['key'] = "38jd72msqedx5n9"
if 'secret' not in options:
options['secret'] = "g4favy0bgjstt2w"
if 'changes_timer' not in options:
options['changes_timer'] = 600.0
self.google_drive = LibDrive(options)
super(Driver, self).__init__('dropbox',
*args,
**options)
@property
def root(self):
return path(self.options['root'])
def close(self):
self.drop.delete_file('/')
def mkdir(self, subdirs):
self.drop.create_dir(subdirs+"/toto")
def write(self, filename, content):
metadata = {"size": len(content), "filename": filename}
self.drop.upload_chunk(metadata, 0, content, len(content))
def generate(self, filename, size):
self.write(filename, os.urandom(size))
def unlink(self, filename):
self.drop.delete_file(filename)
def checksum(self, filename):
return "LOL----LOL"
|
Add instructions and improve formatting | import React from 'react';
import { Modal } from 'react-bootstrap';
export default class ListSignupFormCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
subscribeKey: this.props.subscribeKey,
showModal: false
};
}
showModal() {
this.setState({
showModal: true
});
}
componentWillReceiveProps(props) {
this.setState({
showModal: props.showModal,
subscribeKey: props.subscribeKey
})
}
closeModal() {
this.setState({
showModal: false
});
}
render() {
const actionUrl = `${window.location.origin}/api/list/subscribe`;
return (
<Modal show={this.state.showModal} onHide={this.closeModal.bind(this)}>
<div className="modal-content">
<div className="modal-header">
<h3 class="modal-title">Embeddable subscription form</h3>
</div>
<div className="modal-body">
<h4>Allow users to sign up to your mailing list by embedding this HTML code into your website</h4>
<br/>
<textarea className="form-control" rows="5">
{`
<form action="${actionUrl}" target="_blank">
<label for="signup-email">Email</label>
<input type="email" value="" name="email" label="signup-email">
<input type="hidden" name="subscribeKey" value="${this.state.subscribeKey}" />
<input type="submit" value="Subscribe" name="Subscribe">
</form>
`}
</textarea>
</div>
<div className="modal-footer"></div>
</div>
</Modal>
);
}
}
| import React from 'react';
import { Modal } from 'react-bootstrap';
export default class ListSignupFormCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
subscribeKey: this.props.subscribeKey,
showModal: false
};
}
showModal() {
this.setState({
showModal: true
});
}
componentWillReceiveProps(props) {
this.setState({
showModal: props.showModal,
subscribeKey: props.subscribeKey
})
}
closeModal() {
this.setState({
showModal: false
});
}
render() {
const actionUrl = `${window.location.origin}/api/list/subscribe`;
return (
<Modal show={this.state.showModal} onHide={this.closeModal.bind(this)}>
<div className="modal-content">
<div className="modal-header">
<h4 class="modal-title">Modal title</h4>
</div>
<div className="modal-body">
{`
<form action="${actionUrl}" target="_blank">
<label for="signup-email">Email</label>
<input type="email" value="" name="email" label="signup-email">
<input type="hidden" name="subscribeKey" value="${this.state.subscribeKey}" />
<input type="submit" value="Subscribe" name="Subscribe">
</form>
`}
</div>
<div className="modal-footer">Footer</div>
</div>
</Modal>
);
}
}
|
Clear assets box view cache when starting ccw | <?php
use Symfony\Component\Process\Process;
class Kwf_Controller_Action_Cli_Web_ClearCacheWatcherController extends Kwf_Controller_Action_Cli_Abstract
{
public static function getHelp()
{
return 'watch filesystem for modification and clear affected caches';
}
public function indexAction()
{
$port = Kwf_Assets_WebpackConfig::getDevServerPort();
$cmd = "NODE_PATH=vendor/koala-framework/koala-framework/node_modules_build vendor/bin/node node_modules/.bin/webpack-dev-server --progress --host=0.0.0.0 --port=$port --color";
if (Kwf_Assets_WebpackConfig::getDevServerPublic()) {
$cmd .= " --public=".Kwf_Assets_WebpackConfig::getDevServerPublic();
}
echo $cmd."\n";
$process = new Process($cmd);
$process->setTimeout(null);
$process->start(function ($type, $buffer) {
if (Process::ERR === $type) {
fwrite(STDERR, $buffer);
} else {
fwrite(STDOUT, $buffer);
}
});
file_put_contents('temp/webpack-dev-server-pid', $process->getPid());
$cmd = "php bootstrap.php clear-view-cache --class=Kwc_Box_Assets_Component --force";
system($cmd);
$ret = $process->wait();
exit($ret);
}
}
| <?php
use Symfony\Component\Process\Process;
class Kwf_Controller_Action_Cli_Web_ClearCacheWatcherController extends Kwf_Controller_Action_Cli_Abstract
{
public static function getHelp()
{
return 'watch filesystem for modification and clear affected caches';
}
public function indexAction()
{
$port = Kwf_Assets_WebpackConfig::getDevServerPort();
$cmd = "NODE_PATH=vendor/koala-framework/koala-framework/node_modules_build vendor/bin/node node_modules/.bin/webpack-dev-server --progress --host=0.0.0.0 --port=$port --color";
if (Kwf_Assets_WebpackConfig::getDevServerPublic()) {
$cmd .= " --public=".Kwf_Assets_WebpackConfig::getDevServerPublic();
}
echo $cmd."\n";
$process = new Process($cmd);
$process->setTimeout(null);
$process->start(function ($type, $buffer) {
if (Process::ERR === $type) {
fwrite(STDERR, $buffer);
} else {
fwrite(STDOUT, $buffer);
}
});
file_put_contents('temp/webpack-dev-server-pid', $process->getPid());
$ret = $process->wait();
exit($ret);
}
}
|
Hide button, enable timer for swal, note confirm color is white swal doesn't completely hide the button | var cancelAppointment = function(timeslot_id) {
$("#modal_remote").modal('hide');
swal({
title: "Are you sure?",
text: "You will be removed from this appointment.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel my appointment.",
cancelButtonText: "No, I don't want to cancel.",
closeOnConfirm: false,
closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "PATCH",
url: "/api/timeslots/" + timeslot_id + "/cancel",
beforeSend: customBlockUi(this)
}).done(function(){
swal({
title: "Cancelled",
text: "Your mentoring appointment has been cancelled.",
confirmButtonColor: "#FFFFFF",
showConfirmButton: false,
allowOutsideClick: true,
timer: 1500,
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
});
}
| var cancelAppointment = function(timeslot_id) {
$("#modal_remote").modal('hide');
swal({
title: "Are you sure?",
text: "You will be removed from this appointment.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel my appointment.",
cancelButtonText: "No, I don't want to cancel.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "PATCH",
url: "/api/timeslots/" + timeslot_id + "/cancel",
beforeSend: customBlockUi(this)
}).done(function(){
swal({
title: "Cancelled",
text: "Your mentoring appointment has been cancelled.",
confirmButtonColor: "#66BB6A",
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
else {
swal({
title: "Never Mind!",
text: "Your Appointment is still on!",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
}
|
Add parameter to get single post/user/tag | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions } from 'redux-ghost';
import JsonTree from 'react-json-tree';
import './app.css';
const App = ({ actions, blog }) => {
return (
<div className="wrapper">
<h1>Redux Ghost Blog</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.</p>
<h2>Posts</h2>
<button onClick={actions.getPosts}>Load Posts</button>
<button onClick={() => actions.getPost(1)}>Load Post</button>
<h2>Tags</h2>
<button onClick={actions.getTags}>Load Tags</button>
<button onClick={() => actions.getTag(1)}>Load Tag</button>
<h2>Users</h2>
<button onClick={actions.getUsers}>Load Users</button>
<button onClick={() => actions.getUser(1)}>Load User</button>
<h2>Reset</h2>
<button onClick={actions.reset}>Reset</button>
<JsonTree data={blog} theme="monokai" />
</div>
);
}
const mapStateToProps = ({ blog }) => ({
blog,
});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(actions, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(App);
| import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions } from 'redux-ghost';
import JsonTree from 'react-json-tree';
import './app.css';
const App = ({ actions, blog }) => {
return (
<div className="wrapper">
<h1>Redux Ghost Blog</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.</p>
<h2>Posts</h2>
<button onClick={actions.getPosts}>Load Posts</button>
<button onClick={() => actions.getPost(1)}>Load Post</button>
<button onClick={actions.getPost}>Load Post2</button>
<h2>Tags</h2>
<button onClick={actions.getTags}>Load Tags</button>
<button onClick={actions.getTag}>Load Tag</button>
<h2>Users</h2>
<button onClick={actions.getUsers}>Load Users</button>
<button onClick={actions.getUser}>Load User</button>
<h2>Reset</h2>
<button onClick={actions.reset}>Reset</button>
<JsonTree data={blog} theme="monokai" />
</div>
);
}
const mapStateToProps = ({ blog }) => ({
blog,
});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(actions, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(App);
|
[Tests] Remove twig loader override to use StringLoader. The loader always returns true for template existence checks and it's deprecated. Shouldn't be too big of a problem as we are already project fixture directory. | <?php
namespace Bolt\Tests\Controller;
use Bolt\Configuration\Validation\Validator;
use Bolt\Tests\BoltUnitTest;
use Symfony\Component\HttpFoundation\Request;
abstract class ControllerUnitTest extends BoltUnitTest
{
private $app;
protected function setUp()
{
$this->resetDb();
$this->addDefaultUser($this->getApp());
$this->addSomeContent();
}
protected function setRequest(Request $request)
{
$this->getApp()->offsetSet('request', $request);
$this->getApp()->offsetGet('request_stack')->push($request);
}
/**
* @return Request $request
*/
protected function getRequest()
{
return $this->getApp()->offsetGet('request');
}
protected function getApp($boot = true)
{
if (!$this->app) {
$this->app = $this->makeApp();
}
return $this->app;
}
protected function makeApp()
{
$app = parent::makeApp();
$app->initialize();
$verifier = new Validator($app['controller.exception'], $app['config'], $app['resources']);
$verifier->checks();
$app->boot();
return $app;
}
protected function getFlashBag()
{
return $this->getService('logger.flash');
}
protected function tearDown()
{
parent::tearDown();
$this->app = null;
}
abstract protected function controller();
}
| <?php
namespace Bolt\Tests\Controller;
use Bolt\Configuration\Validation\Validator;
use Bolt\Tests\BoltUnitTest;
use Symfony\Component\HttpFoundation\Request;
abstract class ControllerUnitTest extends BoltUnitTest
{
private $app;
protected function setUp()
{
$this->resetDb();
$this->addDefaultUser($this->getApp());
$this->addSomeContent();
}
protected function setRequest(Request $request)
{
$this->getApp()->offsetSet('request', $request);
$this->getApp()->offsetGet('request_stack')->push($request);
}
/**
* @return Request $request
*/
protected function getRequest()
{
return $this->getApp()->offsetGet('request');
}
protected function getApp($boot = true)
{
if (!$this->app) {
$this->app = $this->makeApp();
}
return $this->app;
}
protected function makeApp()
{
$app = parent::makeApp();
$app->initialize();
$app['twig.loader'] = new \Twig_Loader_Chain([new \Twig_Loader_String()]);
$verifier = new Validator($app['controller.exception'], $app['config'], $app['resources']);
$verifier->checks();
$app->boot();
return $app;
}
protected function getFlashBag()
{
return $this->getService('logger.flash');
}
protected function tearDown()
{
parent::tearDown();
$this->app = null;
}
abstract protected function controller();
}
|
Fix email collection js bug. | $(document).ready(function() {
var $join = $('#landing-join'),
$landingEmailForm = $join.find('form'),
$landingEmailInput = $join.find('.landing-email-input'),
$landingEmailSubmit = $join.find('.landing-email-submit'),
$landingEmailSpinner = $landingEmailSubmit.find('.fa-spinner'),
$landingSubmitText = $landingEmailSubmit.find('.landing-submit-text'),
$successMsg = $join.find('.alert-success'),
$failureMsg = $join.find('.alert-danger'),
subscribePath = window.config.subscribePath,
authenticityToken = window.config.authenticityToken;
$landingEmailForm.on('submit', function(e) {
e.preventDefault();
var email = $landingEmailInput.val(),
data = { authenticity_token: authenticityToken, email: email };
if (email) {
$.post(subscribePath, data, success).fail(failure);
$landingEmailSpinner.removeClass('hide');
$landingSubmitText.addClass('hide');
$landingEmailSubmit.prop('disabled', true);
}
function success() {
$successMsg.removeClass('hide');
$failureMsg.addClass('hide');
$landingEmailSpinner.addClass('hide');
$landingSubmitText.removeClass('hide');
}
function failure() {
$failureMsg.removeClass('hide');
$successMsg.addClass('hide');
$landingEmailSubmit.prop('disabled', false);
$landingEmailSpinner.addClass('hide');
$landingSubmitText.removeClass('hide');
}
});
});
| $(document).ready(function() {
var $join = $('#landing-join'),
$landingEmailForm = $join.find('form'),
$landingEmailInput = $join.find('.landing-email-input'),
$landingEmailSubmit = $join.find('.landing-email-submit'),
$landingEmailSpinner = $landingEmailSubmit.find('.fa-spinner'),
$landingSubmitText = $landingEmailSubmit.find('.landing-submit-text'),
$successMsg = $join.find('.alert-success'),
$failureMsg = $join.find('.alert-danger'),
subscribePath = window.config.subscribePath,
authenticityToken = window.config.authenticityToken;
$landingEmailForm.on('submit', function() {
var email = $landingEmailInput.val(),
data = { authenticity_token: authenticityToken, email: email };
if (email) {
$.post(subscribePath, data, success).fail(failure);
$landingEmailSpinner.removeClass('hide');
$landingSubmitText.addClass('hide');
$landingEmailSubmit.prop('disabled', true);
}
function success() {
$successMsg.removeClass('hide');
$failureMsg.addClass('hide');
$landingEmailSpinner.addClass('hide');
$landingSubmitText.removeClass('hide');
}
function failure() {
$failureMsg.removeClass('hide');
$successMsg.addClass('hide');
$landingEmailSubmit.prop('disabled', false);
$landingEmailSpinner.addClass('hide');
$landingSubmitText.removeClass('hide');
}
});
});
|
Fix typo in package name.
Cairp: what you get when you mix cairo with carp. Or perhaps a cairn
made of carp? | #!/usr/bin/env python
from distutils.core import setup
def main ():
dlls = ["bin/%s" % dll for dll in ["libcairo-2.dll"]]
licenses = ["doc/%s" % license for license in ["LICENSE-LGPL.TXT",
"LICENSE-CAIRO.TXT"]]
others = ["README.rst", "LICENSE.rst"]
long_description = """ This package contains dynamic link dependencies required to run the
python-cairo library on Microsoft Windows.
Please see README.rst for more details."""
classifiers = ["Development Status :: 6 - Mature",
"Environment :: Win32 (MS Windows)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: MIT License", "License :: zlib/libpng License",
"Operating System :: Microsoft",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries"]
return setup(name="cairo-dependencies", version="0.1",
maintainer="Jonathan McManus", maintainer_email="[email protected]", author="various",
url="http://www.github.com/jmcb/python-cairo-dependencies",
download_url="http://www.wxwhatever.com/jmcb/cairo", platforms="Microsoft Windows",
description="Dynamic link library dependencies for pycairo.",
license="GNU LGPLv2, MIT, MPL.",
data_files=[("lib/site-packages/cairo", dlls), ("doc/python-cairo", licenses + others)],
long_description=long_description, classifiers=classifiers)
if __name__=="__main__":
main ()
| #!/usr/bin/env python
from distutils.core import setup
def main ():
dlls = ["bin/%s" % dll for dll in ["libcairo-2.dll"]]
licenses = ["doc/%s" % license for license in ["LICENSE-LGPL.TXT",
"LICENSE-CAIRO.TXT"]]
others = ["README.rst", "LICENSE.rst"]
long_description = """ This package contains dynamic link dependencies required to run the
python-cairo library on Microsoft Windows.
Please see README.rst for more details."""
classifiers = ["Development Status :: 6 - Mature",
"Environment :: Win32 (MS Windows)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: MIT License", "License :: zlib/libpng License",
"Operating System :: Microsoft",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries"]
return setup(name="cairp-dependencies", version="0.1",
maintainer="Jonathan McManus", maintainer_email="[email protected]", author="various",
url="http://www.github.com/jmcb/python-cairo-dependencies",
download_url="http://www.wxwhatever.com/jmcb/cairo", platforms="Microsoft Windows",
description="Dynamic link library dependencies for pycairo.",
license="GNU LGPLv2, MIT, MPL.",
data_files=[("lib/site-packages/cairo", dlls), ("doc/python-cairo", licenses + others)],
long_description=long_description, classifiers=classifiers)
if __name__=="__main__":
main ()
|
Convert perms to a string | from resource_management import *
import os
def create_hdfs_dir(path, owner, perms):
Execute('hadoop fs -mkdir -p '+path, user='hdfs')
Execute('hadoop fs -chown ' + owner + ' ' + path, user='hdfs')
Execute('hadoop fs -chmod ' + str(perms) + ' ' + path, user='hdfs')
def package(name):
import params
Execute(params.package_mgr + ' install -y ' + name, user='root')
def add_repo(source, dest):
import params
if not os.path.isfile(dest + params.repo_file):
Execute('cp ' + source + ' ' + dest)
Execute(params.key_cmd)
Execute(params.cache_cmd)
def cdap_config():
import params
# We're only setup for *NIX, for now
Directory( params.etc_prefix_dir,
mode=0755
)
Directory( params.cdap_conf_dir,
owner = params.cdap_user,
group = params.user_group,
recursive = True
)
XmlConfig( "cdap-site.xml",
conf_dir = params.cdap_conf_dir,
configurations = params.config['configurations']['cdap-site'],
configuration_attributes=params.config['configuration_attributes']['cdap-site'],
owner = params.cdap_user,
group = params.user_group
)
File(format("{cdap_conf_dir}/cdap-env.sh"),
owner = params.cdap_user,
content=InlineTemplate(params.cdap_env_sh_template)
)
| from resource_management import *
import os
def create_hdfs_dir(path, owner, perms):
Execute('hadoop fs -mkdir -p '+path, user='hdfs')
Execute('hadoop fs -chown ' + owner + ' ' + path, user='hdfs')
Execute('hadoop fs -chmod ' + perms + ' ' + path, user='hdfs')
def package(name):
import params
Execute(params.package_mgr + ' install -y ' + name, user='root')
def add_repo(source, dest):
import params
if not os.path.isfile(dest + params.repo_file):
Execute('cp ' + source + ' ' + dest)
Execute(params.key_cmd)
Execute(params.cache_cmd)
def cdap_config():
import params
# We're only setup for *NIX, for now
Directory( params.etc_prefix_dir,
mode=0755
)
Directory( params.cdap_conf_dir,
owner = params.cdap_user,
group = params.user_group,
recursive = True
)
XmlConfig( "cdap-site.xml",
conf_dir = params.cdap_conf_dir,
configurations = params.config['configurations']['cdap-site'],
configuration_attributes=params.config['configuration_attributes']['cdap-site'],
owner = params.cdap_user,
group = params.user_group
)
File(format("{cdap_conf_dir}/cdap-env.sh"),
owner = params.cdap_user,
content=InlineTemplate(params.cdap_env_sh_template)
)
|
Disable prop-types rule because Flow | const commonRules = require("./rules");
module.exports = {
parser: "babel-eslint",
plugins: ["react", "babel", "flowtype", "prettier", "import"],
env: {
browser: true,
es6: true,
jest: true,
node: true,
},
parserOptions: {
sourceType: "module",
ecmaFeatures: {
modules: true,
jsx: true,
},
},
settings: {
flowtype: {
onlyFilesWithFlowAnnotation: true,
},
react: {
version: "detect",
},
},
rules: Object.assign(
{},
{
"prettier/prettier": [
"error",
{
printWidth: 120,
tabWidth: 4,
useTabs: false,
semi: true,
singleQuote: false,
trailingComma: "es5",
bracketSpacing: true,
jsxBracketSameLine: true,
},
],
},
commonRules,
{ "flowtype/require-return-type": ["warn", "always", { excludeArrowFunctions: true }] },
{ "react/prop-types": "off" }
),
};
| const commonRules = require("./rules");
module.exports = {
parser: "babel-eslint",
plugins: ["react", "babel", "flowtype", "prettier", "import"],
env: {
browser: true,
es6: true,
jest: true,
node: true,
},
parserOptions: {
sourceType: "module",
ecmaFeatures: {
modules: true,
jsx: true,
},
},
settings: {
flowtype: {
onlyFilesWithFlowAnnotation: true,
},
react: {
version: "detect",
},
},
rules: Object.assign(
{},
{
"prettier/prettier": [
"error",
{
printWidth: 120,
tabWidth: 4,
useTabs: false,
semi: true,
singleQuote: false,
trailingComma: "es5",
bracketSpacing: true,
jsxBracketSameLine: true,
},
],
},
commonRules,
{ "flowtype/require-return-type": ["warn", "always", { excludeArrowFunctions: true }] }
),
};
|
Allow partitionAssigners to be configured | const { createLogger, LEVELS: { INFO } } = require('./loggers')
const LoggerConsole = require('./loggers/console')
const Cluster = require('./cluster')
const createProducer = require('./producer')
const createConsumer = require('./consumer')
const { assign } = Object
module.exports = class Client {
constructor({
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
logLevel = INFO,
logCreator = LoggerConsole,
}) {
this.logger = createLogger({ level: logLevel, logCreator })
this.createCluster = () =>
new Cluster({
logger: this.logger,
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
})
}
/**
* @public
*/
producer({ createPartitioner, retry } = {}) {
const cluster = this.createCluster()
return createProducer({
retry: assign({}, cluster.retry, retry),
logger: this.logger,
cluster,
createPartitioner,
})
}
/**
* @public
*/
consumer(
{
groupId,
partitionAssigners,
sessionTimeout,
heartbeatInterval,
maxBytesPerPartition,
minBytes,
maxBytes,
maxWaitTimeInMs,
retry,
} = {}
) {
const cluster = this.createCluster()
return createConsumer({
retry: assign({}, cluster.retry, retry),
logger: this.logger,
cluster,
groupId,
partitionAssigners,
sessionTimeout,
heartbeatInterval,
maxBytesPerPartition,
minBytes,
maxBytes,
maxWaitTimeInMs,
})
}
}
| const { createLogger, LEVELS: { INFO } } = require('./loggers')
const LoggerConsole = require('./loggers/console')
const Cluster = require('./cluster')
const createProducer = require('./producer')
const createConsumer = require('./consumer')
const { assign } = Object
module.exports = class Client {
constructor({
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
logLevel = INFO,
logCreator = LoggerConsole,
}) {
this.logger = createLogger({ level: logLevel, logCreator })
this.createCluster = () =>
new Cluster({
logger: this.logger,
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
})
}
/**
* @public
*/
producer({ createPartitioner, retry } = {}) {
const cluster = this.createCluster()
return createProducer({
retry: assign({}, cluster.retry, retry),
logger: this.logger,
cluster,
createPartitioner,
})
}
/**
* @public
*/
consumer(
{
groupId,
createPartitionAssigner,
sessionTimeout,
heartbeatInterval,
maxBytesPerPartition,
minBytes,
maxBytes,
maxWaitTimeInMs,
retry,
} = {}
) {
const cluster = this.createCluster()
return createConsumer({
retry: assign({}, cluster.retry, retry),
logger: this.logger,
cluster,
groupId,
createPartitionAssigner,
sessionTimeout,
heartbeatInterval,
maxBytesPerPartition,
minBytes,
maxBytes,
maxWaitTimeInMs,
})
}
}
|
Clean tmp directory before tests. | 'use strict';
const loadGruntTasks = require('load-grunt-tasks');
const rollupPluginBabel = require('rollup-plugin-babel');
module.exports = function register(grunt) {
loadGruntTasks(grunt);
grunt.initConfig({
eslint: {
all: ['lib', 'test'],
},
clean: {
all: ['dist', 'tmp'],
},
rollup: {
all: {
options: {
external: 'react',
plugins: [
rollupPluginBabel(),
],
format: 'cjs',
},
files: {
'dist/index.js': 'lib/index.js',
},
},
},
babel: {
all: {
files: [{
expand: true,
cwd: 'lib/',
src: '**/*.js',
dest: 'tmp/',
}],
},
},
mochaTest: {
test: {
options: {
timeout: 500,
},
src: [
'test/boot.js',
'test/**/*.test.js',
],
},
},
});
grunt.registerTask('prepublish', ['eslint', 'clean', 'babel', 'rollup']);
grunt.registerTask('test', ['prepublish', 'mochaTest']);
grunt.registerTask('default', ['test']);
};
| 'use strict';
const loadGruntTasks = require('load-grunt-tasks');
const rollupPluginBabel = require('rollup-plugin-babel');
module.exports = function register(grunt) {
loadGruntTasks(grunt);
grunt.initConfig({
eslint: {
all: ['lib', 'test'],
},
clean: {
all: ['dist'],
},
rollup: {
all: {
options: {
external: 'react',
plugins: [
rollupPluginBabel(),
],
format: 'cjs',
},
files: {
'dist/index.js': 'lib/index.js',
},
},
},
babel: {
all: {
files: [{
expand: true,
cwd: 'lib/',
src: '**/*.js',
dest: 'tmp/',
}],
},
},
mochaTest: {
test: {
options: {
timeout: 500,
},
src: [
'test/boot.js',
'test/**/*.test.js',
],
},
},
});
grunt.registerTask('prepublish', ['eslint', 'clean', 'babel', 'rollup']);
grunt.registerTask('test', ['prepublish', 'mochaTest']);
grunt.registerTask('default', ['test']);
};
|
Add loading_embedly variable to parent scope | /**
* Created by moran on 12/06/14.
*/
(function (module) {
module.directive('emEmbed', ['embedlyService', function(embedlyService) {
return {
restrict: 'E',
scope:{
urlsearch: '@',
maxwidth: '@'
},
controller: 'emEmbedCtrl',
link: function(scope, element) {
scope.$parent.loading_embedly = false;
scope.$watch('urlsearch', function(newVal) {
var previousEmbedCode = scope.embedCode;
if (newVal) {
scope.$parent.loading_embedly = true;
embedlyService.embed(newVal, scope.maxwidth)
.then(function(data){
scope.$parent.loading_embedly = false;
switch(data.data.type) {
case 'video':
scope.embedCode = data.data.html;
break;
case 'photo':
scope.embedCode = '<img src="' + data.data.url + '">';
break;
default:
scope.embedCode = '';
}
if(previousEmbedCode !== scope.embedCode) {
// embed code was changed from last call and has to be replaced in DOM
element.html('<div>' + scope.embedCode + '</div>');
}
}, function(error) {
// promise rejected
scope.$parent.loading_embedly = false;
var previousEmbedCode = scope.embedCode;
scope.embedCode = '';
if(previousEmbedCode !== scope.embedCode) {
element.html('<div>' + scope.embedCode + '</div>');
}
});
}
});
}
};
}])
})(angularEmbedly); | /**
* Created by moran on 12/06/14.
*/
(function (module) {
module.directive('emEmbed', ['embedlyService', function(embedlyService) {
return {
restrict: 'E',
scope:{
urlsearch: '@',
maxwidth: '@'
},
controller: 'emEmbedCtrl',
link: function(scope, element) {
scope.$watch('urlsearch', function(newVal) {
var previousEmbedCode = scope.embedCode;
if (newVal) {
embedlyService.embed(newVal, scope.maxwidth)
.then(function(data){
switch(data.data.type) {
case 'video':
scope.embedCode = data.data.html;
break;
case 'photo':
scope.embedCode = '<img src="' + data.data.url + '">';
break;
default:
scope.embedCode = '';
}
if(previousEmbedCode !== scope.embedCode) {
// embed code was changed from last call and has to be replaced in DOM
element.html('<div>' + scope.embedCode + '</div>');
}
}, function(error) {
// promise rejected
var previousEmbedCode = scope.embedCode;
scope.embedCode = '';
if(previousEmbedCode !== scope.embedCode) {
element.html('<div>' + scope.embedCode + '</div>');
}
});
}
});
}
};
}])
})(angularEmbedly); |
Add h5py as a dep | #!/usr/bin/env python
from distutils.core import setup
from setuptools import setup, find_packages
from setuptools.command.install import install as _install
setup(name='tagnews',
version='1.0.1',
description=('automatically tag articles with justice-related categories'
' and extract location information'),
author='Kevin Rose',
url='https://github.com/chicago-justice-project/article-tagging',
package_dir={'': 'lib'},
packages=['tagnews',
'tagnews.utils',
'tagnews.crimetype',
'tagnews.crimetype.models.binary_stemmed_logistic',
'tagnews.geoloc',
'tagnews.geoloc.models.lstm',
'tagnews.tests'],
install_requires=['nltk', 'numpy>=1.13', 'scikit-learn==0.19.0', 'pandas', 'scipy',
'tensorflow>=1.4', 'h5py', 'keras'],
# tests_require=['pytest'],
package_data={'tagnews': ['crimetype/models/binary_stemmed_logistic/*.pkl',
'geoloc/models/lstm/saved/*.hdf5',
'data/glove.6B.50d.txt']},
python_requires=">=3.5", # for now
zip_safe=False,
)
| #!/usr/bin/env python
from distutils.core import setup
from setuptools import setup, find_packages
from setuptools.command.install import install as _install
setup(name='tagnews',
version='1.0.1',
description=('automatically tag articles with justice-related categories'
' and extract location information'),
author='Kevin Rose',
url='https://github.com/chicago-justice-project/article-tagging',
package_dir={'': 'lib'},
packages=['tagnews',
'tagnews.utils',
'tagnews.crimetype',
'tagnews.crimetype.models.binary_stemmed_logistic',
'tagnews.geoloc',
'tagnews.geoloc.models.lstm',
'tagnews.tests'],
install_requires=['nltk', 'numpy>=1.13', 'scikit-learn==0.19.0', 'pandas', 'scipy',
'tensorflow>=1.4', 'keras'],
# tests_require=['pytest'],
package_data={'tagnews': ['crimetype/models/binary_stemmed_logistic/*.pkl',
'geoloc/models/lstm/saved/*.hdf5',
'data/glove.6B.50d.txt']},
python_requires=">=3.5", # for now
zip_safe=False,
)
|
Make cent package a requirement | '''
Flask-Cent
-----------
Flask-Cent is a flask extension for centrifugal/cent
'''
import os
import sys
from setuptools import setup
module_path = os.path.join(os.path.dirname(__file__), 'flask_cent.py')
version_line = [line for line in open(module_path)
if line.startswith('__version_info__')][0]
__version__ = '.'.join(eval(version_line.split('__version_info__ = ')[-1]))
setup(name='Flask-Cent',
version=__version__,
url='https://github.com/breakbase/flask-cent',
license='MIT',
author="BreakBase.com",
author_email='[email protected]',
description='centrifugal/cent client for flask',
long_description=__doc__,
py_modules=['flask_cent'],
zip_safe=False,
platforms='any',
test_suite='nose.collector',
install_requires=[
'Flask',
'blinker',
'cent',
],
tests_require=[
'nose',
'blinker',
'speaklater',
'mock',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
])
| '''
Flask-Cent
-----------
Flask-Cent is a flask extension for centrifugal/cent
'''
import os
import sys
from setuptools import setup
module_path = os.path.join(os.path.dirname(__file__), 'flask_cent.py')
version_line = [line for line in open(module_path)
if line.startswith('__version_info__')][0]
__version__ = '.'.join(eval(version_line.split('__version_info__ = ')[-1]))
setup(name='Flask-Cent',
version=__version__,
url='https://github.com/breakbase/flask-cent',
license='MIT',
author="BreakBase.com",
author_email='[email protected]',
description='centrifugal/cent client for flask',
long_description=__doc__,
py_modules=['flask_cent'],
zip_safe=False,
platforms='any',
test_suite='nose.collector',
install_requires=[
'Flask',
'blinker',
],
tests_require=[
'nose',
'blinker',
'speaklater',
'mock',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
])
|
Store callback as a property
- so that it can be overriden | <?php
namespace PhpQuickbooks\Auth;
use Wheniwork\OAuth1\Client\Server\Intuit;
class QuickbooksAuth
{
/**
* @var \Wheniwork\OAuth1\Client\Server\Intuit
*/
protected $oauth;
/**
* @var string
*/
protected $consumer_key;
/**
* @var string
*/
protected $consumer_secret;
/**
* @var string
*/
protected $callback;
public function __construct(
string $consumer_key,
string $consumer_secret,
$callback = 'http://localhost:8080/auth/authorize_callback.php'
) {
$this->consumer_key = $consumer_key;
$this->consumer_secret = $consumer_secret;
$this->callback = $callback;
$this->initServer();
}
protected function initServer()
{
$this->oauth = new Intuit([
'identifier' => $this->consumer_key,
'secret' => $this->consumer_secret,
'callback_uri' => $this->callback
]);
}
public function getRequestToken()
{
$temporaryCredentials = $this->oauth->getTemporaryCredentials();
$_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
session_write_close();
$this->oauth->authorize($temporaryCredentials);
}
public function getTokenCredentials(string $oauth_token, string $oauth_verifier)
{
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
return $this->oauth->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
}
}
| <?php
namespace PhpQuickbooks\Auth;
use Wheniwork\OAuth1\Client\Server\Intuit;
class QuickbooksAuth
{
/**
* @var \Wheniwork\OAuth1\Client\Server\Intuit
*/
protected $oauth;
/**
* @var string
*/
protected $consumer_key;
/**
* @var string
*/
protected $consumer_secret;
public function __construct(string $consumer_key, string $consumer_secret)
{
$this->consumer_key = $consumer_key;
$this->consumer_secret = $consumer_secret;
$this->initServer();
}
protected function initServer()
{
$this->oauth = new Intuit([
'identifier' => $this->consumer_key,
'secret' => $this->consumer_secret,
'callback_uri' => 'http://localhost:8080/auth/authorize_callback.php',
]);
}
public function getRequestToken()
{
$temporaryCredentials = $this->oauth->getTemporaryCredentials();
$_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
session_write_close();
$this->oauth->authorize($temporaryCredentials);
}
public function getTokenCredentials(string $oauth_token, string $oauth_verifier)
{
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
return $this->oauth->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
}
}
|
Use implode instead of join function | <?php
/*
* This file is part of the SKTwigExtensionsBundle package.
*
* (c) Sebastian Kroczek <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SK\TwigExtensionsBundle\Twig;
use Symfony\Component\Routing\RouterInterface;
class RoutingExtraTwigExtension extends \Twig_Extension
{
/**
* @var RouterInterface
*/
private $router;
/**
* TwigExtension constructor.
*
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('link', array($this, 'link'), array('is_safe' => array('html'))),
);
}
public function link($route, $text, array $routeParameter = array(), array $attr = array())
{
$attr['href'] = $this->router->generate($route, $routeParameter);
$attrString = '';
foreach ($attr as $i => $a) {
$attrString .= ' '.$i.'="'.(is_array($a) ? implode(' ', $a) : $a).'"';
}
return sprintf('<a%s>%s</a>', $attrString, $text);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'sk_routing_extra_extension';
}
}
| <?php
/*
* This file is part of the SKTwigExtensionsBundle package.
*
* (c) Sebastian Kroczek <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SK\TwigExtensionsBundle\Twig;
use Symfony\Component\Routing\RouterInterface;
class RoutingExtraTwigExtension extends \Twig_Extension
{
/**
* @var RouterInterface
*/
private $router;
/**
* TwigExtension constructor.
*
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('link', array($this, 'link'), array('is_safe' => array('html'))),
);
}
public function link($route, $text, array $routeParameter = array(), array $attr = array())
{
$attr['href'] = $this->router->generate($route, $routeParameter);
$attrString = '';
foreach ($attr as $i => $a) {
$attrString .= ' '.$i.'="'.(is_array($a) ? join(' ', $a) : $a).'"';
}
return sprintf('<a%s>%s</a>', $attrString, $text);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'sk_routing_extra_extension';
}
}
|
Add the signature for compose() | <?php
namespace F;
function curry($f, array $args)
{
$meta = new \ReflectionFunction($f);
return curryN($meta->getNumberOfParameters(), $f, $args);
}
function curryN($arity, $f, array $args)
{
$accumulate = function (array $appliedArgs, $totalArgsCount) use ($f, $args, &$accumulate)
{
if (count($appliedArgs) + count($args) >= $totalArgsCount) {
return call_user_func_array($f, array_merge($args, $appliedArgs));
}
return function ($x) use (&$accumulate, $appliedArgs, $totalArgsCount)
{
$append = function ($item, array $list)
{
$list[] = $item;
return $list;
};
return $accumulate($append($x, $appliedArgs), $totalArgsCount);
};
};
return $accumulate([], $arity);
}
// compose :: ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z)
function compose(array $fs)
{
return function () use ($fs)
{
$args = func_get_args();
foreach (array_reverse($fs) as $f) {
$args = [call_user_func_array($f, $args)];
}
return $args[0];
};
}
// prop :: s -> {s: a} -> Maybe a
function prop($name, array $valuesByKey)
{
return new Maybe(isset($valuesByKey[$name]) ? $valuesByKey[$name] : null);
}
| <?php
namespace F;
function curry($f, array $args)
{
$meta = new \ReflectionFunction($f);
return curryN($meta->getNumberOfParameters(), $f, $args);
}
function curryN($arity, $f, array $args)
{
$accumulate = function (array $appliedArgs, $totalArgsCount) use ($f, $args, &$accumulate)
{
if (count($appliedArgs) + count($args) >= $totalArgsCount) {
return call_user_func_array($f, array_merge($args, $appliedArgs));
}
return function ($x) use (&$accumulate, $appliedArgs, $totalArgsCount)
{
$append = function ($item, array $list)
{
$list[] = $item;
return $list;
};
return $accumulate($append($x, $appliedArgs), $totalArgsCount);
};
};
return $accumulate([], $arity);
}
function compose(array $fs)
{
return function () use ($fs)
{
$args = func_get_args();
foreach (array_reverse($fs) as $f) {
$args = [call_user_func_array($f, $args)];
}
return $args[0];
};
}
// prop :: s -> {s: a} -> Maybe a
function prop($name, array $valuesByKey)
{
return new Maybe(isset($valuesByKey[$name]) ? $valuesByKey[$name] : null);
}
|
Use arrow functions instead of vm variable (WAL-400) | const volumeSnapshots = {
templateUrl: 'views/partials/filtered-list.html',
controller: VolumeSnapshotsListController,
controllerAs: 'ListController',
bindings: {
resource: '<'
}
};
export default volumeSnapshots;
// @ngInject
function VolumeSnapshotsListController(
baseResourceListController,
$scope,
$timeout,
actionUtilsService) {
var controllerScope = this;
var ResourceController = baseResourceListController.extend({
init: function() {
this.controllerScope = controllerScope;
this.listActions = null;
var list_type = 'snapshots';
var fn = this._super.bind(this);
this.loading = true;
actionUtilsService.loadNestedActions(this, controllerScope.resource, list_type).then(result => {
this.listActions = result;
fn();
});
$scope.$on('actionApplied', function(event, name) {
if (name === 'snapshot') {
$timeout(function() {
controllerScope.resetCache();
});
}
});
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no snapshots yet';
options.noMatchesText = 'No snapshots found matching filter.';
return options;
},
getFilter: function() {
return {
source_volume_uuid: controllerScope.resource.uuid,
resource_type: 'OpenStackTenant.Snapshot'
};
},
getTableActions: function() {
return this.listActions;
},
});
controllerScope.__proto__ = new ResourceController();
}
| const volumeSnapshots = {
templateUrl: 'views/partials/filtered-list.html',
controller: VolumeSnapshotsListController,
controllerAs: 'ListController',
bindings: {
resource: '<'
}
};
export default volumeSnapshots;
// @ngInject
function VolumeSnapshotsListController(
baseResourceListController,
$scope,
$timeout,
actionUtilsService) {
var controllerScope = this;
var ResourceController = baseResourceListController.extend({
init: function() {
this.controllerScope = controllerScope;
this.listActions = null;
var list_type = 'snapshots';
var fn = this._super.bind(this);
var vm = this;
actionUtilsService.loadNestedActions(this, controllerScope.resource, list_type).then(function(result) {
vm.listActions = result;
fn();
});
$scope.$on('actionApplied', function(event, name) {
if (name === 'snapshot') {
$timeout(function() {
controllerScope.resetCache();
});
}
});
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no snapshots yet';
options.noMatchesText = 'No snapshots found matching filter.';
return options;
},
getFilter: function() {
return {
source_volume_uuid: controllerScope.resource.uuid,
resource_type: 'OpenStackTenant.Snapshot'
};
},
getTableActions: function() {
return this.listActions;
},
});
controllerScope.__proto__ = new ResourceController();
}
|
Change error message when caching fails
see also: http://stackoverflow.com/questions/27722349/less-js-error-msg-failed-to-save/27750286 | // Cache system is a bit outdated and could do with work
module.exports = function(window, options, logger) {
var cache = null;
if (options.env !== 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
return {
setCSS: function(path, lastModified, styles) {
if (cache) {
logger.info('saving ' + path+ ' to cache.');
try {
cache.setItem(path, styles);
cache.setItem(path + ':timestamp', lastModified);
} catch(e) {
//TODO - could do with adding more robust error handling
logger.error('failed to save "' + path + '" to local storage for caching.');
}
}
},
getCSS: function(path, webInfo) {
var css = cache && cache.getItem(path),
timestamp = cache && cache.getItem(path + ':timestamp');
if (timestamp && webInfo.lastModified &&
(new Date(webInfo.lastModified).valueOf() ===
new Date(timestamp).valueOf())) {
// Use local copy
return css;
}
}
};
};
| // Cache system is a bit outdated and could do with work
module.exports = function(window, options, logger) {
var cache = null;
if (options.env !== 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
return {
setCSS: function(path, lastModified, styles) {
if (cache) {
logger.info('saving ' + path+ ' to cache.');
try {
cache.setItem(path, styles);
cache.setItem(path + ':timestamp', lastModified);
} catch(e) {
//TODO - could do with adding more robust error handling
logger.error('failed to save');
}
}
},
getCSS: function(path, webInfo) {
var css = cache && cache.getItem(path),
timestamp = cache && cache.getItem(path + ':timestamp');
if (timestamp && webInfo.lastModified &&
(new Date(webInfo.lastModified).valueOf() ===
new Date(timestamp).valueOf())) {
// Use local copy
return css;
}
}
};
};
|
Remove console log statement in sidebar controller. | angular.module('app.sidebar').controller('SidebarCtrl', ['$scope', 'organizationService', 'spaceService', function ($scope, organizationService, spaceService) {
$scope.organizations = [];
// get all spaces
var getSpacesPromise = spaceService.getSpaces();
// get all organizations
organizationService.getOrganizations().then(function(response) {
var data = response.data;
// create organization objects
angular.forEach(data.resources, function(organization, i) {
var objectOrganization = {
id: organization.metadata.guid,
name: organization.entity.name,
spaces: []
};
$scope.organizations.push(objectOrganization);
});
// push the space objects to the organizations
getSpacesPromise.then(function(response) {
var data = response.data;
// create space objects
angular.forEach(data.resources, function(space, i) {
var objectSpace = {
id: space.metadata.guid,
organizationId: space.entity.organization_guid,
name: space.entity.name
};
for (var j = 0; j < $scope.organizations.length; j++) {
if ($scope.organizations[j].id === objectSpace.organizationId) {
$scope.organizations[j].spaces.push(objectSpace);
break;
}
}
});
}, function (err) {
// TODO: error handling
});
}, function (err) {
// TODO: error handling
});
}]); | angular.module('app.sidebar').controller('SidebarCtrl', ['$scope', 'organizationService', 'spaceService', function ($scope, organizationService, spaceService) {
$scope.organizations = [];
// get all spaces
var getSpacesPromise = spaceService.getSpaces();
// get all organizations
organizationService.getOrganizations().then(function(response) {
var data = response.data;
// create organization objects
angular.forEach(data.resources, function(organization, i) {
var objectOrganization = {
id: organization.metadata.guid,
name: organization.entity.name,
spaces: []
};
$scope.organizations.push(objectOrganization);
});
// push the space objects to the organizations
getSpacesPromise.then(function(response) {
var data = response.data;
// create space objects
angular.forEach(data.resources, function(space, i) {
var objectSpace = {
id: space.metadata.guid,
organizationId: space.entity.organization_guid,
name: space.entity.name
};
for (var j = 0; j < $scope.organizations.length; j++) {
if ($scope.organizations[j].id === objectSpace.organizationId) {
console.log(objectSpace);
$scope.organizations[j].spaces.push(objectSpace);
break;
}
}
});
}, function (err) {
// TODO: error handling
});
}, function (err) {
// TODO: error handling
});
}]); |
Fix copyright notice in source file | /**
* JavaScript Utm Extractor v0.1.0
* https://github.com/ertrade/js-utm-extractor
*
* Copyright JSC ERTrade, 2016
* Released under the MIT license
*/
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var _OldUtmExtractor = window.UtmExtractor;
var api = window.UtmExtractor = factory();
api.noConflict = function () {
window.UtmExtractor = _OldUtmExtractor;
return api;
};
}
}(function () {
'use strict';
var api = function(source) {
if (arguments.length < 1 && (typeof location !== 'undefined')) {
source = location.search;
}
var utm_labels = {};
var parts = source.substr(1).split('&');
var length = parts.length;
var i = 0;
for (; i < length; ++i) {
var item = parts[i];
if (item && /^utm_/.test(item)) {
var tmp = item.split('=');
utm_labels[tmp[0]] = decodeURIComponent(tmp[1]);
}
}
return utm_labels;
};
api.extract = api;
return api;
}));
| /**
* JavaScript Utm Extractor v0.1.0
* https://github.com/ertrade/js-utm-extractor
*
* Copyright Anton Vakhrushev, 2016
* Released under the MIT license
*/
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var _OldUtmExtractor = window.UtmExtractor;
var api = window.UtmExtractor = factory();
api.noConflict = function () {
window.UtmExtractor = _OldUtmExtractor;
return api;
};
}
}(function () {
'use strict';
var api = function(source) {
if (arguments.length < 1 && (typeof location !== 'undefined')) {
source = location.search;
}
var utm_labels = {};
var parts = source.substr(1).split('&');
var length = parts.length;
var i = 0;
for (; i < length; ++i) {
var item = parts[i];
if (item && /^utm_/.test(item)) {
var tmp = item.split('=');
utm_labels[tmp[0]] = decodeURIComponent(tmp[1]);
}
}
return utm_labels;
};
api.extract = api;
return api;
}));
|
Improve performance of CollectionConfigurationManager by replacing XmldbURI with CollectionURI.
svn path=/trunk/eXist/; revision=6526 | package org.exist.collections;
import static org.junit.Assert.*;
import org.junit.Test;
public class CollectionURITest {
@Test
public void append() {
CollectionURI uri = new CollectionURI("/db");
uri.append("test1");
assertTrue(uri.equals(new CollectionURI("/db/test1")));
assertEquals(uri.toString(), "/db/test1");
assertEquals(uri.hashCode(), new String("/db/test1").hashCode());
uri.append("test2");
assertTrue(uri.equals(new CollectionURI("/db/test1/test2")));
assertEquals(uri.toString(), "/db/test1/test2");
assertEquals(uri.hashCode(), new String("/db/test1/test2").hashCode());
uri = new CollectionURI("/db/system/config");
uri.append("/db/test");
assertEquals(uri.toString(), "/db/system/config/db/test");
assertTrue(uri.equals(new CollectionURI("/db/system/config/db/test")));
}
@Test
public void remove() {
CollectionURI uri = new CollectionURI("/db/test1/test2");
uri.removeLastSegment();
assertTrue(uri.equals(new CollectionURI("/db/test1")));
assertEquals(uri.toString(), "/db/test1");
uri.removeLastSegment();
assertTrue(uri.equals(new CollectionURI("/db")));
assertEquals(uri.toString(), "/db");
uri.append("testMe");
assertTrue(uri.equals(new CollectionURI("/db/testMe")));
assertEquals(uri.toString(), "/db/testMe");
uri.removeLastSegment();
assertTrue(uri.equals(new CollectionURI("/db")));
assertEquals(uri.toString(), "/db");
}
}
| package org.exist.collections;
import static org.junit.Assert.*;
import org.junit.Test;
public class CollectionURITest {
@Test
public void append() {
CollectionURI uri = new CollectionURI("/db");
uri.append("test1");
assertTrue(uri.equals(new CollectionURI("/db/test1")));
assertEquals(uri.toString(), "/db/test1");
assertEquals(uri.hashCode(), new String("/db/test1").hashCode());
uri.append("test2");
assertTrue(uri.equals(new CollectionURI("/db/test1/test2")));
assertEquals(uri.toString(), "/db/test1/test2");
assertEquals(uri.hashCode(), new String("/db/test1/test2").hashCode());
}
@Test
public void remove() {
CollectionURI uri = new CollectionURI("/db/test1/test2");
uri.removeLastSegment();
assertTrue(uri.equals(new CollectionURI("/db/test1")));
assertEquals(uri.toString(), "/db/test1");
uri.removeLastSegment();
assertTrue(uri.equals(new CollectionURI("/db")));
assertEquals(uri.toString(), "/db");
uri.append("testMe");
assertTrue(uri.equals(new CollectionURI("/db/testMe")));
assertEquals(uri.toString(), "/db/testMe");
uri.removeLastSegment();
assertTrue(uri.equals(new CollectionURI("/db")));
assertEquals(uri.toString(), "/db");
}
}
|
Update package version to 2.1.0 | # encoding: utf-8
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-emoji',
version='2.1.0',
packages=find_packages(exclude=('test',)),
include_package_data=True,
license='BSD License',
description='A simple django app to use emojis on your website',
long_description=README,
url='https://github.com/gaqzi/django-emoji/',
author='Björn Andersson',
author_email='[email protected]',
install_requires=[
'django',
],
tests_require=[
'django_nose',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| # encoding: utf-8
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-emoji',
version='2.0.0',
packages=find_packages(exclude=('test',)),
include_package_data=True,
license='BSD License',
description='A simple django app to use emojis on your website',
long_description=README,
url='https://github.com/gaqzi/django-emoji/',
author='Björn Andersson',
author_email='[email protected]',
install_requires=[
'django',
],
tests_require=[
'django_nose',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Move contextual task execution to make more sense | package com.jenjinstudios.io.concurrency;
import com.jenjinstudios.io.ExecutionContext;
import com.jenjinstudios.io.Message;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
/**
* Executes ExecutableMessage objects which have been read.
*
* @author Caleb Brinkman
*/
public class ExecutionTask implements Runnable
{
private final MessageQueue messageQueue;
private final ExecutionContext executionContext;
private final Collection<Consumer<ExecutionContext>> contextualTasks;
/**
* Construct a new ExecuteTask that will execute messages from the given MessageQueue.
*
* @param messageQueue The MessageQueue.
* @param executionContext The context in which messages should execute.
* @param contextualTasks Tasks which should be invoked in synchronous fashion with the execution context.
*/
public ExecutionTask(
MessageQueue messageQueue,
ExecutionContext executionContext,
Collection<Consumer<ExecutionContext>> contextualTasks
)
{
this.messageQueue = messageQueue;
this.executionContext = executionContext;
this.contextualTasks = contextualTasks;
}
@Override
public void run() {
final List<Message> incoming = messageQueue.getIncomingAndClear();
incoming.forEach(message -> {
Message response = message.execute(executionContext);
if (response != null) {
messageQueue.queueOutgoing(response);
}
contextualTasks.forEach(consumer -> consumer.accept(executionContext));
});
}
}
| package com.jenjinstudios.io.concurrency;
import com.jenjinstudios.io.ExecutionContext;
import com.jenjinstudios.io.Message;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
/**
* Executes ExecutableMessage objects which have been read.
*
* @author Caleb Brinkman
*/
public class ExecutionTask implements Runnable
{
private final MessageQueue messageQueue;
private final ExecutionContext executionContext;
private final Collection<Consumer<ExecutionContext>> contextualTasks;
/**
* Construct a new ExecuteTask that will execute messages from the given MessageQueue.
*
* @param messageQueue The MessageQueue.
* @param executionContext The context in which messages should execute.
* @param contextualTasks Tasks which should be invoked in synchronous fashion with the execution context.
*/
public ExecutionTask(
MessageQueue messageQueue,
ExecutionContext executionContext,
Collection<Consumer<ExecutionContext>> contextualTasks
)
{
this.messageQueue = messageQueue;
this.executionContext = executionContext;
this.contextualTasks = contextualTasks;
}
@Override
public void run() {
final List<Message> incoming = messageQueue.getIncomingAndClear();
incoming.forEach(message -> {
Message response = message.execute(executionContext);
if (response != null) {
messageQueue.queueOutgoing(response);
}
});
contextualTasks.forEach(consumer -> consumer.accept(executionContext));
}
}
|
Change shortcut key for deploy to server | /**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
define(([], function () {
var DeployMenu = {
id: "deploy",
label: "Deploy",
items: [
{
id: "deploy-to-server",
label: "Deploy To Server",
command: {
id: "deploy-to-server",
shortcuts: {
mac: {
key: "command+shift+d",
label: "\u2318\u21E7D"
},
other: {
key: "ctrl+shift+d",
label: "Ctrl+Shift+D"
}
}
},
disabled: false
}
]
};
return DeployMenu;
}));
| /**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
define(([], function () {
var DeployMenu = {
id: "deploy",
label: "Deploy",
items: [
{
id: "deploy-to-server",
label: "Deploy To Server",
command: {
id: "deploy-to-server",
shortcuts: {
mac: {
key: "shift+d",
label: "\u21E7D"
},
other: {
key: "shift+d",
label: "Shift+D"
}
}
},
disabled: false
}
]
};
return DeployMenu;
}));
|
Use existing date to calculate | package com.alexstyl.specialdates.date;
import android.content.res.Resources;
import com.alexstyl.specialdates.R;
import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.events.peopleevents.EventType;
/**
* A representation of an event, affiliated to a contact
*/
public final class ContactEvent {
private final EventType eventType;
private final Contact contact;
private final Date date;
public ContactEvent(EventType eventType, Date date, Contact contact) {
this.eventType = eventType;
this.date = date;
this.contact = contact;
}
public String getLabel(Resources resources) {
if (eventType == EventType.BIRTHDAY) {
if (date.hasYear()) {
int age = Date.CURRENT_YEAR - date.getYear();
if (age > 0) {
return resources.getString(R.string.turns_age, age);
}
}
}
return resources.getString(eventType.nameRes());
}
public Date getDate() {
return date;
}
public EventType getType() {
return eventType;
}
public int getYear() {
return date.getYear();
}
public Contact getContact() {
return contact;
}
}
| package com.alexstyl.specialdates.date;
import android.content.res.Resources;
import com.alexstyl.specialdates.R;
import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.events.peopleevents.EventType;
/**
* A representation of an event, affiliated to a contact
*/
public final class ContactEvent {
private final EventType eventType;
private final Contact contact;
private final Date date;
public ContactEvent(EventType eventType, Date date, Contact contact) {
this.eventType = eventType;
this.date = date;
this.contact = contact;
}
public String getLabel(Resources resources) {
if (eventType == EventType.BIRTHDAY) {
Date birthday = contact.getDateOfBirth();
if (birthday.hasYear()) {
int age = date.getYear() - birthday.getYear();
if (age > 0) {
return resources.getString(R.string.turns_age, age);
}
}
}
return resources.getString(eventType.nameRes());
}
public Date getDate() {
return date;
}
public EventType getType() {
return eventType;
}
public int getYear() {
return date.getYear();
}
public Contact getContact() {
return contact;
}
}
|
Use build() result for test | !function (assert, path) {
'use strict';
require('vows').describe('Integration test').addBatch({
'When minifying a CSS file': {
topic: function () {
var callback = this.callback,
topic;
require('publishjs')({
cache: false,
log: false,
processors: {
less: require('../index')
}
}).build(function (pipe, callback) {
pipe.from(path.resolve(path.dirname(module.filename), 'integration-test-files'))
.less()
.run(callback);
}, callback);
},
'should returns a compiled version': function (topic) {
assert.equal(Object.getOwnPropertyNames(topic).length, 1);
assert.equal(topic['default.css'].toString(), 'html body {\n font-family: Arial;\n}\n');
}
}
}).export(module);
}(
require('assert'),
require('path')
); | !function (assert, path) {
'use strict';
require('vows').describe('Integration test').addBatch({
'When minifying a CSS file': {
topic: function () {
var callback = this.callback,
topic;
require('publishjs')({
cache: false,
log: false,
processors: {
less: require('../index')
}
}).build(function (pipe) {
pipe.from(path.resolve(path.dirname(module.filename), 'integration-test-files'))
.less()
.run(callback);
}, callback);
},
'should returns a compiled version': function (topic) {
assert.equal(Object.getOwnPropertyNames(topic).length, 1);
assert.equal(topic['default.css'].buffer.toString(), 'html body {\n font-family: Arial;\n}\n');
}
}
}).export(module);
}(
require('assert'),
require('path')
); |
Refactor and extend test for Feature | /*******************************************************************************
* Copyright 2014, 2016 gwt-ol3
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package ol;
/**
* Test for {@link Feature}.
*
* @author Tino Desjardins
*
*/
public class FeatureTest extends GwtOL3BaseTestCase {
private static final String FEATURE_ID = "#1";
private static final String GEOMETRY_NAME = "geometry";
public void testFeature() {
injectUrlAndTest(new TestWithInjection() {
@Override
public void test() {
Feature feature = new Feature();
assertNotNull(feature);
assertTrue(feature instanceof Object);
assertTrue(feature instanceof Observable);
feature.setId(FEATURE_ID);
assertEquals(FEATURE_ID, feature.getId());
feature.setGeometryName(GEOMETRY_NAME);
assertEquals(GEOMETRY_NAME, feature.getGeometryName());
}
});
}
}
| /*******************************************************************************
* Copyright 2014, 2016 gwt-ol3
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package ol;
/**
* Test for {@link Feature}.
*
* @author Tino Desjardins
*
*/
public class FeatureTest extends GwtOL3BaseTestCase {
private static final String FEATURE_ID = "#1";
public void testAttribution() {
injectUrlAndTest(new TestWithInjection() {
@Override
public void test() {
Feature feature = new Feature();
assertNotNull(feature);
assertTrue(feature instanceof Object);
assertTrue(feature instanceof Observable);
feature.setId(FEATURE_ID);
assertEquals(FEATURE_ID, feature.getId());
}
});
}
}
|
Fix incorrect libxau library name | from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class LibxauConan(ConanFile):
name = "libxau"
version = "1.0.8"
license = "Custom https://cgit.freedesktop.org/xorg/lib/libXau/tree/COPYING"
url = "https://github.com/trigger-happy/conan-packages"
description = "X11 authorisation library"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=False"
generators = "cmake"
def source(self):
pkgLink = 'https://xorg.freedesktop.org/releases/individual/lib/libXau-{version}.tar.bz2'.format(version=self.version)
self.run("curl -JOL " + pkgLink)
self.run("tar xf libXau-{version}.tar.bz2".format(version=self.version))
def build(self):
envBuild = AutoToolsBuildEnvironment(self)
installPrefix=os.getcwd()
with tools.chdir("libXau-{version}".format(version=self.version)):
with tools.environment_append(envBuild.vars):
self.run("./configure --prefix={0}".format(installPrefix))
self.run("make install")
def package(self):
self.copy("lib/*", dst=".", keep_path=True)
self.copy("include/*", dst=".", keep_path=True)
def package_info(self):
self.cpp_info.libs = ["Xau"]
| from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class LibxauConan(ConanFile):
name = "libxau"
version = "1.0.8"
license = "Custom https://cgit.freedesktop.org/xorg/lib/libXau/tree/COPYING"
url = "https://github.com/trigger-happy/conan-packages"
description = "X11 authorisation library"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=False"
generators = "cmake"
def source(self):
pkgLink = 'https://xorg.freedesktop.org/releases/individual/lib/libXau-{version}.tar.bz2'.format(version=self.version)
self.run("curl -JOL " + pkgLink)
self.run("tar xf libXau-{version}.tar.bz2".format(version=self.version))
def build(self):
envBuild = AutoToolsBuildEnvironment(self)
installPrefix=os.getcwd()
with tools.chdir("libXau-{version}".format(version=self.version)):
with tools.environment_append(envBuild.vars):
self.run("./configure --prefix={0}".format(installPrefix))
self.run("make install")
def package(self):
self.copy("lib/*", dst=".", keep_path=True)
self.copy("include/*", dst=".", keep_path=True)
def package_info(self):
self.cpp_info.libs = ["libXau"]
|
Fix typos in Result and Check docstrings | # -*- coding: utf-8 -*-
"""Base classes."""
import time
class Result(object):
"""Provides results of a Check.
Attributes:
availability (bool): Availability, usually reflects outcome of a check.
runtime (float): Time consumed running the check, in seconds.
message (string): Additional explainations for the result.
timestamp (int): UTC timestamp of the check.
"""
def __init__(self, availability, runtime, message, timestamp=time.time()):
"""Initialise Result.
Args:
See class attributes.
"""
self.availability = availability
self.runtime = runtime
self.message = message
self.timestamp = timestamp
@property
def api_serialised(self):
"""Return serialisable data for API result submissions."""
return {'availability': self.availability,
'runtime': self.runtime,
'message': self.message,
'timestamp': self.timestamp}
class Check(object):
"""Performs checks for availability of resources.
This should be inherited by checking implementations.
"""
def __init__(self, **kwargs):
"""Initialise Check."""
pass
def check(self):
"""Check if specified resource is availabile.
Called without arguments.
Returns:
gefion.checkers.Result
"""
raise NotImplementedError
| # -*- coding: utf-8 -*-
"""Base classes."""
import time
class Result(object):
"""Provides results of a Check.
Attributes:
availability (bool): Availability, usually reflects outcome of a check.
runtime (float): Time consumed running the check, in seconds.
message (string): Additional explainations for the result.
timestamp (int): UTC timestamp of the check.
"""
def __init__(self, availability, runtime, message, timestamp=time.time()):
"""Initialise Result.
Args:
See class attributes.
"""
self.availability = availability
self.runtime = runtime
self.message = message
self.timestamp = timestamp
@property
def api_serialised(self):
"""Return serialisable data for API monitor assignments."""
return {'availability': self.availability,
'runtime': self.runtime,
'message': self.message,
'timestamp': self.timestamp}
class Check(object):
"""Performs checks for availability of resources.
This should be inherited by checking implementations.
"""
def __init__(self, **kwargs):
"""Initialise Check."""
pass
def check(self):
"""Check if specified resource is availability.
Called without arguments.
Returns:
gefion.checkers.Result
"""
raise NotImplementedError
|
Use single quotes for strings | import React, { Component, PropTypes } from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
class Filter extends Component {
constructor(props){
super(props);
this.state = {filterValue : this.props.query};
this.inputChanged = this.inputChanged.bind(this);
}
componentWillUnmount(){
if(this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
}
inputChanged(event){
this.setState({filterValue: event.target.value});
if (this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
this.timeout = window.setTimeout(()=>{
this.props.config.eventHandler(
{
type:'filter-change',
id: this.props.config.id,
column: this.props.column,
query: this.state.filterValue
}
);
}, 300);
}
render(){
return(
<FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={'Filter...'} />
);
}
}
Filter.propTypes = {
query: PropTypes.string,
config: PropTypes.object,
column: PropTypes.string.isRequired
};
export default Filter;
| import React, { Component, PropTypes } from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
class Filter extends Component {
constructor(props){
super(props);
this.state = {filterValue : this.props.query};
this.inputChanged = this.inputChanged.bind(this);
}
componentWillUnmount(){
if(this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
}
inputChanged(event){
this.setState({filterValue: event.target.value});
if (this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
this.timeout = window.setTimeout(()=>{
this.props.config.eventHandler(
{
type:'filter-change',
id: this.props.config.id,
column: this.props.column,
query: this.state.filterValue
}
);
}, 300);
}
render(){
return(
<FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={"Filter..."} />
);
}
}
Filter.propTypes = {
query: PropTypes.string,
config: PropTypes.object,
column: PropTypes.string.isRequired
};
export default Filter;
|
Remove the file name display when attempting to read | package goatee
import (
"encoding/json"
"io/ioutil"
"log"
"os"
)
type configuration struct {
Redis Redis
Web Web
}
type Redis struct {
Host string
}
type Web struct {
Host string
}
var (
DEBUG = false
Config = new(configuration)
)
func getEnv() string {
env := os.Getenv("GO_ENV")
if env == "" || env == "development" {
DEBUG = true
return "development"
}
return env
}
func LoadConfig(path string) *configuration {
var file[]byte
var err error
var paths = []string{os.Getenv("HOME") + "/.config/goatee", "/etc/goatee"}
// If path is defined, prepend it to paths
if (len(path) > 0) {
paths = append([]string{path}, paths...)
}
// Try to find a config file to use
found := false
for _, path := range(paths) {
file, err = ioutil.ReadFile(path + string(os.PathSeparator) + getEnv() + ".json")
if err == nil {
log.Printf("Reading configuration from: %s", path)
found = true
break
}
}
if !found {
log.Fatalf("Error reading config file.")
}
err = json.Unmarshal(file, &Config)
if err != nil {
log.Fatalf("Error parsing JSON: %s", err.Error())
}
return Config
}
| package goatee
import (
"encoding/json"
"io/ioutil"
"log"
"os"
)
type configuration struct {
Redis Redis
Web Web
}
type Redis struct {
Host string
}
type Web struct {
Host string
}
var (
DEBUG = false
Config = new(configuration)
)
func getEnv() string {
env := os.Getenv("GO_ENV")
if env == "" || env == "development" {
DEBUG = true
return "development"
}
return env
}
func LoadConfig(path string) *configuration {
var file[]byte
var err error
var paths = []string{os.Getenv("HOME") + "/.config/goatee", "/etc/goatee"}
// If path is defined, prepend it to paths
if (len(path) > 0) {
paths = append([]string{path}, paths...)
}
// Try to find a config file to use
found := false
for _, path := range(paths) {
log.Printf(path)
file, err = ioutil.ReadFile(path + string(os.PathSeparator) + getEnv() + ".json")
if err == nil {
log.Printf("Reading configuration from: %s", path)
found = true
break
}
}
if !found {
log.Fatalf("Error reading config file.")
}
err = json.Unmarshal(file, &Config)
if err != nil {
log.Fatalf("Error parsing JSON: %s", err.Error())
}
return Config
}
|
Fix making threads daemonic on Python 3.2 | #
# Copyright 2014 Infoxchange Australia
#
# 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.
"""
Satellite processes started by Forklift itself to provide services.
"""
import os
import threading
from time import sleep
def start_satellite(target, args=(), kwargs=None, stop=None):
"""
Start a process configured to run the target but kill it after the parent
exits.
"""
if kwargs is None:
kwargs = {}
pid = os.fork()
if pid == 0:
# Run target daemonized.
payload = threading.Thread(
target=target,
args=args,
kwargs=kwargs,
)
payload.daemon = True
payload.start()
# Cannot wait for the process that's not our child
ppid = os.getppid()
try:
while True:
os.kill(ppid, 0)
sleep(1)
except OSError:
if stop:
stop()
os._exit(os.EX_OK) # pylint:disable=protected-access
| #
# Copyright 2014 Infoxchange Australia
#
# 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.
"""
Satellite processes started by Forklift itself to provide services.
"""
import os
import threading
from time import sleep
def start_satellite(target, args=(), kwargs=None, stop=None):
"""
Start a process configured to run the target but kill it after the parent
exits.
"""
if kwargs is None:
kwargs = {}
pid = os.fork()
if pid == 0:
# Run target daemonized.
payload = threading.Thread(
target=target,
args=args,
kwargs=kwargs,
daemon=True,
)
payload.start()
# Cannot wait for the process that's not our child
ppid = os.getppid()
try:
while True:
os.kill(ppid, 0)
sleep(1)
except OSError:
if stop:
stop()
os._exit(os.EX_OK) # pylint:disable=protected-access
|
Add missing space before link | /*globals $, GOVUK, suchi */
/*jslint
white: true,
browser: true */
$(function() {
"use strict";
function browserWarning() {
var container = $('<div id="global-browser-prompt"></div>'),
text = $('<p>For a safer, faster, better experience online you should upgrade your browser. </p>'),
findMoreLink = $('<a href="/help/browsers">Find out more about browsers</a>'),
closeLink = $('<a href="#" class="dismiss" title="Dismiss this message">Close</a>');
return container.append(text.append(findMoreLink, closeLink));
}
// we don't show the message when the cookie warning is also there
if (GOVUK.cookie('seen_cookie_message')) {
if (suchi.isOld(navigator.userAgent)) {
if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
var $prompt = browserWarning();
$('#global-cookie-message').after($prompt);
$prompt.show();
$prompt.on("click", ".dismiss", function(e) {
$prompt.hide();
// the warning is dismissable for 2 weeks
GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 14 });
});
}
}
// We're not showing the message on first visit
GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
}
});
| /*globals $, GOVUK, suchi */
/*jslint
white: true,
browser: true */
$(function() {
"use strict";
function browserWarning() {
var container = $('<div id="global-browser-prompt"></div>'),
text = $('<p>For a safer, faster, better experience online you should upgrade your browser.</p>'),
findMoreLink = $('<a href="/help/browsers">Find out more about browsers</a>'),
closeLink = $('<a href="#" class="dismiss" title="Dismiss this message">Close</a>');
return container.append(text.append(findMoreLink, closeLink));
}
// we don't show the message when the cookie warning is also there
if (GOVUK.cookie('seen_cookie_message')) {
if (suchi.isOld(navigator.userAgent)) {
if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
var $prompt = browserWarning();
$('#global-cookie-message').after($prompt);
$prompt.show();
$prompt.on("click", ".dismiss", function(e) {
$prompt.hide();
// the warning is dismissable for 2 weeks
GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 14 });
});
}
}
// We're not showing the message on first visit
GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
}
});
|
Fix JS error after project pdf file. | (function () {
'use strict';
angular.module('OpenSlidesApp.mediafiles.projector', ['OpenSlidesApp.mediafiles'])
.config([
'slidesProvider',
function(slidesProvider) {
slidesProvider.registerSlide('mediafiles/mediafile', {
template: 'static/templates/mediafiles/slide_mediafile.html'
});
}
])
.controller('SlideMediafileCtrl', [
'$scope',
'Mediafile',
function($scope, Mediafile) {
// load mediafile object
var mediafile = Mediafile.get($scope.element.id);
$scope.mediafile = mediafile;
// Allow the elements to render properly
setTimeout(function() {
if ($scope.mediafile) {
if ($scope.mediafile.is_pdf) {
$scope.pdfName = mediafile.title;
$scope.pdfUrl = mediafile.mediafileUrl;
} else if ($scope.mediafile.is_video) {
var player = angular.element.find('#video-player')[0];
if ($scope.element.playing) {
player.play();
} else {
player.pause();
}
}
}
}, 0);
}
]);
})();
| (function () {
'use strict';
angular.module('OpenSlidesApp.mediafiles.projector', ['OpenSlidesApp.mediafiles'])
.config([
'slidesProvider',
function(slidesProvider) {
slidesProvider.registerSlide('mediafiles/mediafile', {
template: 'static/templates/mediafiles/slide_mediafile.html'
});
}
])
.controller('SlideMediafileCtrl', [
'$scope',
'Mediafile',
function($scope, Mediafile) {
// load mediafile object
var mediafile = Mediafile.get($scope.element.id);
$scope.mediafile = mediafile;
// Allow the elements to render properly
setTimeout(function() {
if ($scope.mediafile.is_pdf) {
$scope.pdfName = mediafile.title;
$scope.pdfUrl = mediafile.mediafileUrl;
} else if ($scope.mediafile.is_video) {
var player = angular.element.find('#video-player')[0];
if ($scope.element.playing) {
player.play();
} else {
player.pause();
}
}
}, 0);
}
]);
})();
|
Revert "Remove resolve in top level"
This reverts commit 27c6b92e18e69f1e705596414467abd9ff660157. | import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import resolve from '@rollup/plugin-node-resolve';
import copy from "rollup-plugin-copy";
export default {
input: ['source/gltf-sample-viewer.js'],
output: [
{
file: 'dist/gltf-viewer.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/gltf-viewer.module.js',
format: 'esm',
sourcemap: true,
}
],
plugins: [
glslify(),
resolve({
browser: true,
preferBuiltins: false,
dedupe: ['gl-matrix', 'axios', 'jpeg-js', 'fast-png']
}),
copy({
targets: [
{
src: [
"assets/images/lut_charlie.png",
"assets/images/lut_ggx.png",
"assets/images/lut_sheen_E.png",
], dest: "dist/assets"
},
{ src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" }
]
}),
commonjs(),
]
};
| import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import resolve from '@rollup/plugin-node-resolve';
import copy from "rollup-plugin-copy";
export default {
input: ['source/gltf-sample-viewer.js'],
output: [
{
file: 'dist/gltf-viewer.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/gltf-viewer.module.js',
format: 'esm',
sourcemap: true,
}
],
plugins: [
glslify(),
copy({
targets: [
{
src: [
"assets/images/lut_charlie.png",
"assets/images/lut_ggx.png",
"assets/images/lut_sheen_E.png",
], dest: "dist/assets"
},
{ src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" }
]
}),
commonjs(),
]
};
|
Update to follow the new observation format
(follow the vision input of OpenAI ATARI environment) | import numpy as np
import matplotlib.pyplot as plt
class Agent(object):
def __init__(self, dim_action):
self.dim_action = dim_action
def act(self, ob, reward, done, vision_on):
#print("ACT!")
# Get an Observation from the environment.
# Each observation vectors are numpy array.
# focus, opponents, track sensors are scaled into [0, 1]. When the agent
# is out of the road, sensor variables return -1/200.
# rpm, wheelSpinVel are raw values and then needed to be preprocessed.
# vision is given as a tensor with size of (64*64, 3) = (4096, 3) <-- rgb
# and values are in [0, 255]
if vision_on is False:
focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel = ob
else:
focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel, vision = ob
""" The code below is for checking the vision input. This is very heavy for real-time Control
So you may need to remove.
"""
print(vision.shape)
"""
img = np.ndarray((64,64,3))
for i in range(3):
img[:, :, i] = 255 - vision[:, i].reshape((64, 64))
plt.imshow(img, origin='lower')
plt.draw()
plt.pause(0.001)
"""
return np.tanh(np.random.randn(self.dim_action)) # random action
| import numpy as np
import matplotlib.pyplot as plt
class Agent(object):
def __init__(self, dim_action):
self.dim_action = dim_action
def act(self, ob, reward, done, vision):
#print("ACT!")
# Get an Observation from the environment.
# Each observation vectors are numpy array.
# focus, opponents, track sensors are scaled into [0, 1]. When the agent
# is out of the road, sensor variables return -1/200.
# rpm, wheelSpinVel are raw values and then needed to be preprocessed.
# vision is given as a tensor with size of (3, 64, 64) <-- rgb
# and values are in [0, 255]
if vision is False:
focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel = ob
else:
focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel, vision = ob
""" The code below is for checking the vision input. This is very heavy for real-time Control
So you may need to remove.
"""
"""
img = np.ndarray((64,64,3))
for i in range(3):
img[:, :, i] = 255 - vision[i]
plt.imshow(img, origin='lower')
plt.draw()
plt.pause(0.001)
"""
return np.tanh(np.random.randn(self.dim_action)) # random action
|
Add trailing newline in file | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
| import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
|
Improve method name for search input change | import { updateQuery, fetchQuery, addSearch, isSearching } from '../actions';
import { search } from '../actions/SearchAPI';
import Icon from './Icon';
export default class SearchForm extends React.Component {
constructor() {
super()
this._debouncedSearch = _.debounce(this._debouncedSearch, 300)
}
render() {
return (
<form onSubmit={e => e.preventDefault()}>
<div className='relative'>
<input onChange={this._handleInputChange.bind(this)}
id='Search'
type='text'
autoComplete='off'
placeholder='Search Wikipedia'
defaultValue={this.props.Search.queries[this.props.index]}
className='field border-bottom search__input'/>
<div className='search-icon'><Icon size="18px" icon="search" fill={'silver'} /></div>
</div>
</form>
);
}
_handleInputChange(e) {
e.persist()
this._debouncedSearch(e.target.value.trim())
}
_debouncedSearch(query) {
const {dispatch, index} = this.props;
dispatch(updateQuery(index, query))
dispatch(isSearching(true))
if (query) {
search(query, this._handleResults.bind(this));
} else {
this._handleResults([])
}
}
_handleResults(results) {
this.props.dispatch(addSearch(results, this.props.index))
this.props.dispatch(isSearching(false))
}
}
| import { updateQuery, fetchQuery, addSearch, isSearching } from '../actions';
import { search } from '../actions/SearchAPI';
import Icon from './Icon';
export default class SearchForm extends React.Component {
constructor() {
super()
this._debouncedSearch = _.debounce(this._debouncedSearch, 300)
}
render() {
return (
<form onSubmit={e => e.preventDefault()}>
<div className='relative'>
<input onChange={this._handleKeyUp.bind(this)}
id='Search'
type='text'
autoComplete='off'
placeholder='Search Wikipedia'
defaultValue={this.props.Search.queries[this.props.index]}
className='field border-bottom search__input'/>
<div className='search-icon'><Icon size="18px" icon="search" fill={'silver'} /></div>
</div>
</form>
);
}
_handleKeyUp(e) {
e.persist()
this._debouncedSearch(e.target.value.trim())
}
_debouncedSearch(query) {
const {dispatch, index} = this.props;
dispatch(updateQuery(index, query))
dispatch(isSearching(true))
if (query) {
search(query, this._handleResults.bind(this));
} else {
this._handleResults([])
}
}
_handleResults(results) {
this.props.dispatch(addSearch(results, this.props.index))
this.props.dispatch(isSearching(false))
}
}
|
Set date lang on the localized middleware | <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Middleware;
use Closure;
use Illuminate\Config\Repository;
use Jenssegers\Date\Date;
class Localize
{
/**
* Array of languages Cachet can use.
*
* @var array
*/
protected $langs;
/**
* Config repository.
*
* @var \Illuminate\Config\Repository
*/
protected $config;
/**
* Constructs a new localize instance.
*
* @param \Illuminate\Config\Repository $config
*
* @return void
*/
public function __construct(Repository $config)
{
$this->config = $config;
$this->langs = $config->get('langs');
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$supportedLanguages = $request->getLanguages();
$userLanguage = $this->config->get('app.locale');
foreach ($supportedLanguages as $language) {
$language = substr($language, 0, 2);
if (isset($this->langs[$language])) {
$userLanguage = $language;
break;
}
}
app('translator')->setLocale($userLanguage);
Date::setLocale($userLanguage);
return $next($request);
}
}
| <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Middleware;
use Closure;
use Illuminate\Config\Repository;
class Localize
{
/**
* Array of languages Cachet can use.
*
* @var array
*/
protected $langs;
/**
* Config repository.
*
* @var \Illuminate\Config\Repository
*/
protected $config;
/**
* Constructs a new localize instance.
*
* @param \Illuminate\Config\Repository $config
*
* @return void
*/
public function __construct(Repository $config)
{
$this->config = $config;
$this->langs = $config->get('langs');
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$supportedLanguages = $request->getLanguages();
$userLanguage = $this->config->get('app.locale');
foreach ($supportedLanguages as $language) {
$language = substr($language, 0, 2);
if (isset($this->langs[$language])) {
$userLanguage = $language;
break;
}
}
app('translator')->setLocale($userLanguage);
return $next($request);
}
}
|
Load jpg and gif via file-loader | const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const extractSass = new ExtractTextPlugin({
filename: "index.css"
});
const config = {
entry: "./src/js/index.ts",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'build')
},
resolve: {
extensions: ['.js', '.json', '.ts']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.scss$/,
loader: extractSass.extract({
use: ['css-loader', 'postcss-loader', 'sass-loader'],
fallback: 'style-loader'
})
},
{
test: /\.(jpg|gif|png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader',
options: {
limit: 1000
}
}
]
},
plugins: [
extractSass
]
};
if(process.env.NODE_ENV === 'development') {
config.devServer = {
hot: true,
publicPath: '/build/'
};
config.plugins.push(
new webpack.HotModuleReplacementPlugin()
);
}
module.exports = config;
| const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const extractSass = new ExtractTextPlugin({
filename: "index.css"
});
const config = {
entry: "./src/js/index.ts",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'build')
},
resolve: {
extensions: ['.js', '.json', '.ts']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.scss$/,
loader: extractSass.extract({
use: ['css-loader', 'postcss-loader', 'sass-loader'],
fallback: 'style-loader'
})
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader',
options: {
limit: 1000
}
}
]
},
plugins: [
extractSass
]
};
if(process.env.NODE_ENV === 'development') {
config.devServer = {
hot: true,
publicPath: '/build/'
};
config.plugins.push(
new webpack.HotModuleReplacementPlugin()
);
}
module.exports = config;
|
Remove mensagem de erro bem chata | <?php
/**
* Created by PhpStorm.
* User: eduardo
* Date: 04/02/14
* Time: 10:54
*/
namespace Cacic\RelatorioBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function relatorioMenu(FactoryInterface $factory, array $options)
{
$logger = $this->container->get('logger');
// Cria menu
$menu = $factory->createItem('root');
//$menu->addChild('Configurações', array('route' => 'cacic_relatorio_hardware_configuracoes'));
// Carrega lista de classes WMI para coleta
$em = $this->container->get('doctrine')->getManager();
$classes = $em->getRepository('CacicCommonBundle:ComputadorColeta')->menu();
// Adiciona cada uma das classes como slug para um controller
foreach ($classes as $wmiClass) {
$menu->addChild($wmiClass['nmClassName'], array(
'route' => 'cacic_relatorio_hardware_wmi',
'routeParameters' => array(
'classe' => $wmiClass['nmClassName']
)
));
}
return $menu;
}
} | <?php
/**
* Created by PhpStorm.
* User: eduardo
* Date: 04/02/14
* Time: 10:54
*/
namespace Cacic\RelatorioBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function relatorioMenu(FactoryInterface $factory, array $options)
{
$logger = $this->container->get('logger');
// Cria menu
$menu = $factory->createItem('root');
//$menu->addChild('Configurações', array('route' => 'cacic_relatorio_hardware_configuracoes'));
// Carrega lista de classes WMI para coleta
$em = $this->container->get('doctrine')->getEntityManager();
$classes = $em->getRepository('CacicCommonBundle:ComputadorColeta')->menu();
// Adiciona cada uma das classes como slug para um controller
foreach ($classes as $wmiClass) {
$menu->addChild($wmiClass['nmClassName'], array(
'route' => 'cacic_relatorio_hardware_wmi',
'routeParameters' => array(
'classe' => $wmiClass['nmClassName']
)
));
}
return $menu;
}
} |
Change package name from falcor-server to falcor-express
Reviewed by @jhusain | var express = require('express');
var app = express();
var FalcorServer = require('falcor-express');
var Cache = require('../../data/Cache');
var falcor = require('../../../index');
var Rx = require('rx');
var edgeCaseCache = require('./../../data/EdgeCase')();
var fullCacheModel = new falcor.Model({cache: Cache()}).materialize();
var edgeCaseModel = new falcor.Model({cache: edgeCaseCache}).materialize();
// Simple middleware to handle get/post
app.use('/falcor', FalcorServer.expressMiddleware(function() {
return {
get: function(paths) {
return fullCacheModel.
get.apply(fullCacheModel, paths).
toJSONG();
}
};
}));
app.use('/falcor.edge', FalcorServer.expressMiddleware(function() {
return {
get: function(paths) {
return edgeCaseModel.
get.apply(edgeCaseModel, paths).
toJSONG();
}
};
}));
module.exports = function(port) {
// Note: Will never complete unless explicitly closed.
return Rx.Observable.create(function(observer) {
var server = app.listen(port, function(err) {
if (err) {
observer.onError(err);
return;
}
observer.onNext();
});
return function() {
server.close();
};
});
};
| var express = require('express');
var app = express();
var FalcorServer = require('falcor-server');
var Cache = require('../../data/Cache');
var falcor = require('../../../index');
var Rx = require('rx');
var edgeCaseCache = require('./../../data/EdgeCase')();
var fullCacheModel = new falcor.Model({cache: Cache()}).materialize();
var edgeCaseModel = new falcor.Model({cache: edgeCaseCache}).materialize();
// Simple middleware to handle get/post
app.use('/falcor', FalcorServer.expressMiddleware(function() {
return {
get: function(paths) {
return fullCacheModel.
get.apply(fullCacheModel, paths).
toJSONG();
}
};
}));
app.use('/falcor.edge', FalcorServer.expressMiddleware(function() {
return {
get: function(paths) {
return edgeCaseModel.
get.apply(edgeCaseModel, paths).
toJSONG();
}
};
}));
module.exports = function(port) {
// Note: Will never complete unless explicitly closed.
return Rx.Observable.create(function(observer) {
var server = app.listen(port, function(err) {
if (err) {
observer.onError(err);
return;
}
observer.onNext();
});
return function() {
server.close();
};
});
};
|
Add child_id params as well to prevent clash in some cases | (function($) {
jQuery.fn.comboEdit = function(options){
options.selector = jQuery(this).selector;
var onClick = function(e){
var toBeReplaced = jQuery(this);
var data = {};
var parent_id = jQuery(this).parent().parent().find("."+options.parentIdClass).val();
data.parent_id = parent_id;
jQuery.get(options.getComboBoxURL, data, function(response){
toBeReplaced.replaceWith(response);
jQuery('option').click(function(){
var theValue = jQuery(this).val();
var toBeReplaced = jQuery(this).parent().parent();
data.id = theValue;
data.child_id = theValue;
data.parent_id = parent_id;
jQuery.post(options.submitURL, data, function(response){
toBeReplaced.replaceWith(response);
jQuery(options.selector).click(onClick);
}, 'html');
});
}, 'html');
}
return this.each(function(){
jQuery(this).click(onClick);
});
}
})(jQuery); | (function($) {
jQuery.fn.comboEdit = function(options){
options.selector = jQuery(this).selector;
var onClick = function(e){
var toBeReplaced = jQuery(this);
var data = {};
var parent_id = jQuery(this).parent().parent().find("."+options.parentIdClass).val();
data.parent_id = parent_id;
jQuery.get(options.getComboBoxURL, data, function(response){
toBeReplaced.replaceWith(response);
jQuery('option').click(function(){
var theValue = jQuery(this).val();
var toBeReplaced = jQuery(this).parent().parent();
data.id = theValue;
jQuery.post(options.submitURL, data, function(response){
toBeReplaced.replaceWith(response);
jQuery(options.selector).click(onClick);
}, 'html');
});
}, 'html');
}
return this.each(function(){
jQuery(this).click(onClick);
});
}
})(jQuery); |
Fix "logout" preference after crash fix.
(became no longer clickable)
Now giving an onClickListener to a preference only if it doesn't already
have a listener.
Change-Id: I93b25da9485477737f877abae34188d0243bebd4 | package org.wikipedia.settings;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.wikipedia.R;
public class PreferenceMultiLine extends Preference {
public PreferenceMultiLine(Context ctx, AttributeSet attrs, int defStyle) {
super(ctx, attrs, defStyle);
}
public PreferenceMultiLine(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
public PreferenceMultiLine(Context ctx) {
super(ctx);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
TextView textView = (TextView) view.findViewById(android.R.id.title);
if (textView != null) {
textView.setSingleLine(false);
}
// Intercept the click listener for this preference, and if the preference has an intent,
// launch the intent ourselves, so that we can catch the exception if the intent fails.
// (but only do this if the preference doesn't already have a click listener)
if (this.getOnPreferenceClickListener() == null) {
this.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (preference.getIntent() != null) {
try {
getContext().startActivity(preference.getIntent());
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(), getContext().getString(R.string.error_browser_not_found), Toast.LENGTH_LONG).show();
}
return true;
}
return false;
}
});
}
}
}
| package org.wikipedia.settings;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.wikipedia.R;
public class PreferenceMultiLine extends Preference {
public PreferenceMultiLine(Context ctx, AttributeSet attrs, int defStyle) {
super(ctx, attrs, defStyle);
}
public PreferenceMultiLine(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
public PreferenceMultiLine(Context ctx) {
super(ctx);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
TextView textView = (TextView) view.findViewById(android.R.id.title);
if (textView != null) {
textView.setSingleLine(false);
}
// Intercept the click listener for this preference, and if the preference has an intent,
// launch the intent ourselves, so that we can catch the exception if the intent fails.
this.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (preference.getIntent() != null) {
try {
getContext().startActivity(preference.getIntent());
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(), getContext().getString(R.string.error_browser_not_found), Toast.LENGTH_LONG).show();
}
return true;
}
return false;
}
});
}
}
|
Remove unused properties from popover component. | FileDrop.ConfirmPopoverComponent = Ember.Component.extend({
classNames: ['popover-confirm'],
isShowingDidChange: function () {
!!this.get('isShowing') ? this.show() : this.hide();
}.observes('isShowing'),
didInsertElement: function () {
this._super();
this.$().hide();
},
// Uber hacky way to make Bootstrap 'popover' plugin work with Ember metamorph
show: function () {
// Delay until related properties are computed
Ember.run.next(this, function () {
var html = this.$().html();
// Content needs to be visible,
// so that popover position is calculated properly.
this.$().show();
this.$().popover({
html: true,
content: html,
placement: 'top'
});
this.$().popover('show');
this.$().hide();
});
},
hide: function () {
this.$().popover('destroy');
},
actions: {
confirm: function () {
this.hide();
this.sendAction('confirm');
},
cancel: function() {
this.hide();
this.sendAction('cancel');
}
}
});
| FileDrop.ConfirmPopoverComponent = Ember.Component.extend({
classNames: ['popover-confirm'],
// TODO: move 'label' and 'filename' somewhere else (separate view)?
label: function () {
var email = this.get('peer.email'),
addr = this.get('peer.local_ip');
return email || addr;
}.property('peer.email', 'peer.local_ip'),
filename: function () {
var file = this.get('peer.transfer.file');
return file ? file.name : null;
}.property('peer.transfer.file'),
isShowingDidChange: function () {
!!this.get('isShowing') ? this.show() : this.hide();
}.observes('isShowing'),
didInsertElement: function () {
this._super();
this.$().hide();
},
// Uber hacky way to make Bootstrap 'popover' plugin work with Ember metamorph
show: function () {
// Delay until related properties are computed
Ember.run.next(this, function () {
var html = this.$().html();
// Content needs to be visible,
// so that popover position is calculated properly.
this.$().show();
this.$().popover({
html: true,
content: html,
placement: 'top'
});
this.$().popover('show');
this.$().hide();
});
},
hide: function () {
this.$().popover('destroy');
},
actions: {
confirm: function () {
this.hide();
this.sendAction('confirm');
},
cancel: function() {
this.hide();
this.sendAction('cancel');
}
}
});
|
Move that block to see if that is what is causing the issue | <h3>Change Access</h3>
<form class="form-horizontal">
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-8 control-label" for="access-type">Select Access Type</label>
<div class="col-md-8">
<?php
$types = $dal->getAccessTypes();
$selected_user = $_GET['for'];
$curr = $dal->getUserAccessLevel($selected_user);
$level_options = '';
?>
<select id="access-type" name="access-type" class="form-control">
<option disabled>Select Access Type</option>
<?php
foreach ($types as $row) {
return '';
//$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
}
echo $level_options;
/*
if ($types) {
foreach ($types as $row) {
$option = "<option value='".$row['type']."' ";
if ($row['type'] == $curr) {
$option .= "selected>$row['type']</option>";
} else {
$option .= ">$row['type']</option>";
}
echo $option;
}
}
*/
?>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-8 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
| <h3>Change Access</h3>
<form class="form-horizontal">
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-8 control-label" for="access-type">Select Access Type</label>
<div class="col-md-8">
<select id="access-type" name="access-type" class="form-control">
<option disabled>Select Access Type</option>
<?php
$types = $dal->getAccessTypes();
$selected_user = $_GET['for'];
$curr = $dal->getUserAccessLevel($selected_user);
$level_options = '';
foreach ($types as $row) {
return '';
//$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
}
echo $level_options;
/*
if ($types) {
foreach ($types as $row) {
$option = "<option value='".$row['type']."' ";
if ($row['type'] == $curr) {
$option .= "selected>$row['type']</option>";
} else {
$option .= ">$row['type']</option>";
}
echo $option;
}
}
*/
?>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-8 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
|
Allow CORS access to the /info/ endpoint | package org.marsik.elshelves.backend.app.servlet;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
if (req instanceof HttpServletRequest) {
String url = ((HttpServletRequest) req).getRequestURI();
if (url.startsWith("/v1/") || url.startsWith("/info/")) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"x-requested-with, origin, authorization, accept, content-type");
}
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
| package org.marsik.elshelves.backend.app.servlet;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
if (req instanceof HttpServletRequest) {
String url = ((HttpServletRequest) req).getRequestURI();
if (url.startsWith("/v1/")) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"x-requested-with, origin, authorization, accept, content-type");
}
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
|
Fix repository interface generator bug that ignores their namespace | <?php
namespace Graze\Dal\Generator;
class RepositoryGenerator extends AbstractClassGenerator implements GeneratorInterface
{
/**
* @var array
*/
private $config;
/**
* @var bool
*/
private $generateInterfaces;
/**
* @param array $config
* @param bool $generateInterfaces
*/
public function __construct(array $config, $generateInterfaces = false)
{
$this->config = $config;
$this->generateInterfaces = $generateInterfaces;
}
/**
* @return array
*/
protected function buildClassGenerators()
{
$repositories = [];
foreach ($this->config as $config) {
if (! array_key_exists('repository', $config)) {
continue;
}
$repository = $this->getClassGenerator($config['repository']);
$repository->setExtendedClass('\\Graze\Dal\Repository\EntityRepository');
if ($this->generateInterfaces) {
$interfaceGenerator = $this->buildInterfaceGeneratorFromClassGenerator($repository);
$repositories[$interfaceGenerator->getNamespaceName() . '\\' . $interfaceGenerator->getName()] = $interfaceGenerator;
}
$repositories[$config['repository']] = $repository;
}
return $repositories;
}
}
| <?php
namespace Graze\Dal\Generator;
class RepositoryGenerator extends AbstractClassGenerator implements GeneratorInterface
{
/**
* @var array
*/
private $config;
/**
* @var bool
*/
private $generateInterfaces;
/**
* @param array $config
* @param bool $generateInterfaces
*/
public function __construct(array $config, $generateInterfaces = false)
{
$this->config = $config;
$this->generateInterfaces = $generateInterfaces;
}
/**
* @return array
*/
protected function buildClassGenerators()
{
$repositories = [];
foreach ($this->config as $config) {
if (! array_key_exists('repository', $config)) {
continue;
}
$repository = $this->getClassGenerator($config['repository']);
$repository->setExtendedClass('\\Graze\Dal\Repository\EntityRepository');
if ($this->generateInterfaces) {
$interfaceGenerator = $this->buildInterfaceGeneratorFromClassGenerator($repository);
$repositories[$interfaceGenerator->getName()] = $interfaceGenerator;
}
$repositories[$config['repository']] = $repository;
}
return $repositories;
}
}
|
Enable switches if it's function is to switch on/off lights. | import R from 'ramda';
import React, {PropTypes} from 'react';
import {Switch} from 'react-mdl/lib';
import Component from 'react-pure-render/component';
export default class AddrLine extends Component {
static propTypes = {
actions: PropTypes.object,
address: PropTypes.object,
msg: PropTypes.object,
}
render() {
const {actions: {writeGroupAddr: updateAddr}, address: addr} = this.props;
const toggleAddrVal = (addr) => addr.set('value', !addr.value | 0);
const switchable = (addr) => addr.func === 'light';
return (
<section className="row">
<div className="col-xs-2">
<span className="box">{addr.id}</span>
</div>
<div className="col-xs-6">
<span className="box">{addr.name}</span>
</div>
<div className="col-xs-1">
<span className="box">{R.isNil(addr.value) ? '???' : addr.value}</span>
</div>
<div className="col-xs-2">
<span className="box">
<Switch checked={!!addr.value} disabled={!switchable(addr)} id={addr.id} onChange={() => updateAddr(toggleAddrVal(addr.set('type', 'DPT3')))} />
</span>
</div>
</section>
);
}
}
| import R from 'ramda';
import React, {PropTypes} from 'react';
import {Switch} from 'react-mdl/lib';
import Component from 'react-pure-render/component';
export default class AddrLine extends Component {
static propTypes = {
actions: PropTypes.object,
address: PropTypes.object,
msg: PropTypes.object,
}
render() {
const {actions: {writeGroupAddr: updateAddr}, address: addr} = this.props;
const toggleAddrVal = (addr) => addr.set('value', !addr.value | 0);
const switchable = (addr) => addr.type === 'switch';
return (
<section className="row">
<div className="col-xs-2">
<span className="box">{addr.id}</span>
</div>
<div className="col-xs-6">
<span className="box">{addr.name}</span>
</div>
<div className="col-xs-1">
<span className="box">{R.isNil(addr.value) ? '???' : addr.value}</span>
</div>
<div className="col-xs-2">
<span className="box">
<Switch checked={!!addr.value} disabled={!switchable(addr)} id={addr.id} onChange={() => updateAddr(toggleAddrVal(addr.set('type', 'DPT3')))} />
</span>
</div>
</section>
);
}
}
|
[android] Revert discount value for hotel price | package com.mapswithme.maps.widget.placepage;
import android.support.annotation.NonNull;
public class HotelPriceInfo
{
@NonNull
private final String mId;
@NonNull
private final String mPrice;
@NonNull
private final String mCurrency;
private final int mDiscount;
private final boolean mHasSmartDeal;
public HotelPriceInfo(@NonNull String id, @NonNull String price, @NonNull String currency,
int discount, boolean hasSmartDeal)
{
mId = id;
mPrice = price;
mCurrency = currency;
mDiscount = discount;
mHasSmartDeal = hasSmartDeal;
}
@NonNull
public String getId()
{
return mId;
}
@NonNull
public String getPrice()
{
return mPrice;
}
@NonNull
public String getCurrency()
{
return mCurrency;
}
public int getDiscount()
{
return mDiscount;
}
public boolean hasSmartDeal()
{
return mHasSmartDeal;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("HotelPriceInfo{");
sb.append("mId='").append(mId).append('\'');
sb.append(", mPrice='").append(mPrice).append('\'');
sb.append(", mCurrency='").append(mCurrency).append('\'');
sb.append(", mDiscount=").append(mDiscount);
sb.append(", mHasSmartDeal=").append(mHasSmartDeal);
sb.append('}');
return sb.toString();
}
}
| package com.mapswithme.maps.widget.placepage;
import android.support.annotation.NonNull;
public class HotelPriceInfo
{
@NonNull
private final String mId;
@NonNull
private final String mPrice;
@NonNull
private final String mCurrency;
private final int mDiscount;
private final boolean mHasSmartDeal;
public HotelPriceInfo(@NonNull String id, @NonNull String price, @NonNull String currency,
int discount, boolean hasSmartDeal)
{
mId = id;
mPrice = price;
mCurrency = currency;
mDiscount = discount;
mHasSmartDeal = hasSmartDeal;
}
@NonNull
public String getId()
{
return mId;
}
@NonNull
public String getPrice()
{
return mPrice;
}
@NonNull
public String getCurrency()
{
return mCurrency;
}
public int getDiscount()
{
return 20;
}
public boolean hasSmartDeal()
{
return mHasSmartDeal;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("HotelPriceInfo{");
sb.append("mId='").append(mId).append('\'');
sb.append(", mPrice='").append(mPrice).append('\'');
sb.append(", mCurrency='").append(mCurrency).append('\'');
sb.append(", mDiscount=").append(mDiscount);
sb.append(", mHasSmartDeal=").append(mHasSmartDeal);
sb.append('}');
return sb.toString();
}
}
|
Fix blog - Part 2 | <!DOCTYPE html>
<html>
<head>
<title>OpenSprites Blog</title>
<link href='../navbar.css' type="text/css" rel=stylesheet>
<link href='/blogmainstyle.css' type="text/css" rel=stylesheet>
<?php include("header.php"); ?>
</head>
<body>
<?php include("includes.php"); ?>
<div id="entries"></div>
<?php include("../footer.html"); ?>
<script>
var on_page_limit = 5;
var count = <?php
if(isset($_GET['count'])) {
$number = $_GET['count'];
} else {
$number = 0;
foreach(glob("entries/*.xml") as $filename) {
if(is_numeric(substr($filename, 8, -4))) {
$number++;
}
}
}
echo $number;
?>;
function backcall(r) {
$("#entries").append(r).append('<hr>');
$('code').wrap('<div>').each(function(i, block) {
hljs.highlightBlock(block);
});
i--;
if(i > 0) {
entries += blog_load_html(i.toString(), function(r) {
backcall(r);
});
}
}
var entries = "";
var i = count;
entries += blog_load_html(i.toString(), function(r) {
backcall(r);
});
</script>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<title>OpenSprites Blog</title>
<link href='../navbar.css' type="text/css" rel=stylesheet>
<link href='../main-style.css' type="text/css" rel=stylesheet>
<?php include("header.php"); ?>
</head>
<body>
<?php include("includes.php"); ?>
<div id="entries"></div>
<?php include("../footer.html"); ?>
<script>
var on_page_limit = 5;
var count = <?php
if(isset($_GET['count'])) {
$number = $_GET['count'];
} else {
$number = 0;
foreach(glob("entries/*.xml") as $filename) {
if(is_numeric(substr($filename, 8, -4))) {
$number++;
}
}
}
echo $number;
?>;
function backcall(r) {
$("#entries").append(r).append('<hr>');
$('code').wrap('<div>').each(function(i, block) {
hljs.highlightBlock(block);
});
i--;
if(i > 0) {
entries += blog_load_html(i.toString(), function(r) {
backcall(r);
});
}
}
var entries = "";
var i = count;
entries += blog_load_html(i.toString(), function(r) {
backcall(r);
});
</script>
</body>
</html>
|
Add Tom Hanks in a way that's actually reachable | import re
from pal.services.service import Service
from pal.services.service import wrap_response
class JokeService(Service):
_JOKES = {
'open the pod bay doors pal':
"I'm sorry, Jeff, I'm afraid I can't do that.",
'laws of robotics':
"1. A robot may not injure a human being or, through inaction, "
"allow a human being to come to harm.\n2. A robot must obey the "
"orders given it by human beings, except where such orders would "
"conflict with the First Law.\n3. A robot must protect its own "
"existence as long as such protection does not conflict with the "
"First or Second Law.",
'knock knock': "Who's there?",
'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.",
}
def applies_to_me(self, client, feature_request_type):
return True
def get_confidence(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return 9001
return 0
@wrap_response
def go(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return self._JOKES[joke]
return ('ERROR', 'Tom Hanks was in 1 movies.')
| import re
from pal.services.service import Service
from pal.services.service import wrap_response
class JokeService(Service):
_JOKES = {
'open the pod bay doors pal':
"I'm sorry, Jeff, I'm afraid I can't do that.",
'laws of robotics':
"1. A robot may not injure a human being or, through inaction, "
"allow a human being to come to harm.\n2. A robot must obey the "
"orders given it by human beings, except where such orders would "
"conflict with the First Law.\n3. A robot must protect its own "
"existence as long as such protection does not conflict with the "
"First or Second Law.",
'knock knock': "Who's there?",
}
def applies_to_me(self, client, feature_request_type):
return True
def get_confidence(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return 9001
return 0
@wrap_response
def go(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return self._JOKES[joke]
return ('ERROR', 'Tom Hanks was in 1 movies.')
|
Fix missing constants for CRONUS calculator | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
define('CRONUS_BASE', 'http://hess.ess.washington.edu/');
define('CRONUS_URI', CRONUS_BASE . 'cgi-bin/matweb');
class Calculator {
function send($submitText, $calcType) {
// prepare for a curl call
$fields = array(
'requesting_ip' => getRealIp(),
'mlmfile' => 'al_be_' . $calcType . '_many_v22',
'text_block' => $submitText,
);
$options = array(
CURLOPT_POST => count($fields),
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($fields),
CURLOPT_CONNECTTIMEOUT => 90,
CURLOPT_TIMEOUT => 200,
);
// send the request with curl
$ch = curl_init(CRONUS_URI);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (!$result) {
die('Error retrieving calculator result:<br>' . curl_error($ch));
}
curl_close($ch);
$rep = '<head><base href="' . CRONUS_BASE . '" />';
$html = str_replace('<head>', $rep, $result);
return $html;
}
} | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Calculator {
function send($submitText, $calcType) {
// prepare for a curl call
$fields = array(
'requesting_ip' => getRealIp(),
'mlmfile' => 'al_be_' . $calcType . '_many_v22',
'text_block' => $submitText,
);
$options = array(
CURLOPT_POST => count($fields),
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($fields),
CURLOPT_CONNECTTIMEOUT => 90,
CURLOPT_TIMEOUT => 200,
);
// send the request with curl
$ch = curl_init(CRONUS_URI);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (!$result) {
die('Error retrieving calculator result:<br>' . curl_error($ch));
}
curl_close($ch);
$rep = '<head><base href="' . CRONUS_BASE . '" />';
$html = str_replace('<head>', $rep, $result);
return $html;
}
} |
Reorder close order of HttpConnection resources
In theory it's probably a good idea to close the various streams
associated with a socket before we close the socket itself. | package net.zephyrizing.http_server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import net.zephyrizing.http_server.HttpRequest;
public class HttpConnectionImpl implements HttpConnection {
private Socket socket;
private BufferedReader socketIn;
private PrintWriter socketOut;
public HttpConnectionImpl(Socket socket, BufferedReader socketIn, PrintWriter socketOut) {
this.socket = socket;
this.socketIn = socketIn;
this.socketOut = socketOut;
}
@Override
public void close() throws IOException {
socketIn.close();
socketOut.close();
socket.close();
}
@Override
public HttpRequest getRequest() {
List<String> lines = new ArrayList<String>();
String line;
try {
while (null != (line = socketIn.readLine())) {
lines.add(line);
}
return new HttpRequest(lines);
} catch (IOException e) {
return null;
}
}
@Override
public void send(HttpResponse response) {
socketOut.print("HTTP/1.1 200 OK\r\n");
socketOut.flush();
}
}
| package net.zephyrizing.http_server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import net.zephyrizing.http_server.HttpRequest;
public class HttpConnectionImpl implements HttpConnection {
private Socket socket;
private BufferedReader socketIn;
private PrintWriter socketOut;
public HttpConnectionImpl(Socket socket, BufferedReader socketIn, PrintWriter socketOut) {
this.socket = socket;
this.socketIn = socketIn;
this.socketOut = socketOut;
}
@Override
public void close() throws IOException {
socket.close();
socketIn.close();
socketOut.close();
}
@Override
public HttpRequest getRequest() {
List<String> lines = new ArrayList<String>();
String line;
try {
while (null != (line = socketIn.readLine())) {
lines.add(line);
}
return new HttpRequest(lines);
} catch (IOException e) {
return null;
}
}
@Override
public void send(HttpResponse response) {
socketOut.print("HTTP/1.1 200 OK\r\n");
socketOut.flush();
}
}
|
Fix incorrect text range selection in annotator | package org.plugin.dot;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.plugin.dot.psi.DotId;
import org.plugin.dot.psi.impl.DotDotgraphStmtImpl;
import static org.plugin.dot.DotPSITreeUtil.getNotMentionedNodeIds;
/**
* Dot annotator highlights and annotates dot language code based on following rule:
* all nodes which are used in edges but not declared explicitly will be
* annotated as "No such such node specified in graph"
*/
public class DotAnnotator implements Annotator {
/**
* The method annotates all nodes which are used in edges but not declared explicitly
*
* @param element element you would like to annotate
* @param holder annotation holder
*/
@Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof DotDotgraphStmtImpl) {
for (DotId id : getNotMentionedNodeIds(element)) {
TextRange range = new TextRange(id.getTextRange().getStartOffset(),
id.getTextRange().getEndOffset());
Annotation annotation = holder.createInfoAnnotation(range, "No such such node specified in graph");
annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
}
}
}
| package org.plugin.dot;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.plugin.dot.psi.DotId;
import org.plugin.dot.psi.impl.DotDotgraphStmtImpl;
import static org.plugin.dot.DotPSITreeUtil.getNotMentionedNodeIds;
/**
* Dot annotator highlights and annotates dot language code based on following rule:
* all nodes which are used in edges but not declared explicitly will be
* annotated as "No such such node specified in graph"
*/
public class DotAnnotator implements Annotator {
/**
* The method annotates all nodes which are used in edges but not declared explicitly
*
* @param element element you would like to annotate
* @param holder annotation holder
*/
@Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof DotDotgraphStmtImpl) {
for (DotId id : getNotMentionedNodeIds(element)) {
TextRange range = new TextRange(id.getTextRange().getStartOffset(),
id.getTextRange().getStartOffset());
Annotation annotation = holder.createInfoAnnotation(range, "No such such node specified in graph");
annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
}
}
}
|
Remove extra dependency for class builder | package org.xblackcat.sjpu.builder;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Functional builder allows only one abstract method per class/interface.
*
* @author xBlackCat
*/
public class FunctionalClassBuilder<Base> extends ClassBuilder<Base> {
public FunctionalClassBuilder(IDefiner definerF, IMethodBuilder... builders) {
super(definerF, builders);
}
@Override
public <T extends Base> Class<? extends T> build(
Class<T> target
) throws GeneratorException {
int abstractCount = 0;
for (Method m : target.getMethods()) {
if (Modifier.isAbstract(m.getModifiers())) {
abstractCount++;
}
}
for (Method m : target.getDeclaredMethods()) {
if (!Modifier.isPublic(m.getModifiers()) && Modifier.isAbstract(m.getModifiers())) {
abstractCount++;
}
}
if (abstractCount != 1) {
throw new GeneratorException(
"Only single abstract method is allowed for implementation of functional interface/class. "
+ BuilderUtils.getName(target) + " has " + abstractCount
);
}
return super.build(target);
}
}
| package org.xblackcat.sjpu.builder;
import org.xblackcat.sjpu.storage.IFunctionalAH;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Functional builder allows only one abstract method per class/interface.
*
* @author xBlackCat
*/
public class FunctionalClassBuilder<Base> extends ClassBuilder<Base> {
public FunctionalClassBuilder(IDefiner definerF, IMethodBuilder... builders) {
super(definerF, builders);
}
@Override
public <T extends Base> Class<? extends T> build(
Class<T> target
) throws GeneratorException {
int abstractCount = 0;
for (Method m : target.getMethods()) {
if (Modifier.isAbstract(m.getModifiers())) {
abstractCount++;
}
}
for (Method m : target.getDeclaredMethods()) {
if (!Modifier.isPublic(m.getModifiers()) && Modifier.isAbstract(m.getModifiers())) {
abstractCount++;
}
}
if (abstractCount != 1) {
throw new GeneratorException(
"Only single abstract method is allowed for implementation of " +
BuilderUtils.getName(IFunctionalAH.class) + ". " + BuilderUtils.getName(target) + " has " +
abstractCount
);
}
return super.build(target);
}
}
|
Add missing packages to backend | from setuptools import setup, find_packages
setup(
name="maguire",
version="0.1",
url='https://github.com/picsadotcom/maguire',
license='BSD',
author='Picsa',
author_email='[email protected]',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
'djangorestframework==3.6.4',
'django-rest-auth',
'dj-database-url',
'psycopg2',
'raven',
'gunicorn',
'django-filter',
'whitenoise',
'celery',
'redis',
'pytz',
'python-dateutil',
'django-cors-middleware',
'django-reversion',
'graphene<2.0',
'graphene-django<2.0.0',
'graphql-core<2.0',
'pendulum',
'django-role-permissions==1.2.1',
'django-celery-beat',
'boto3',
'django-storages',
'opbeat',
'postmarker',
'django-extensions',
],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from setuptools import setup, find_packages
setup(
name="maguire",
version="0.1",
url='https://github.com/picsadotcom/maguire',
license='BSD',
author='Picsa',
author_email='[email protected]',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
'djangorestframework==3.6.4',
'django-rest-auth',
'dj-database-url',
'psycopg2',
'raven',
'gunicorn',
'django-filter',
'whitenoise',
'celery',
'redis',
'pytz',
'python-dateutil',
'django-cors-middleware',
'django-reversion',
'graphene<2.0',
'graphene-django<2.0.0',
'graphql-core<2.0',
'pendulum',
'django-role-permissions==1.2.1',
'django-celery-beat',
'boto3',
'django-storages',
'opbeat',
],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.