Strange symfony i18n error - symfony1

I use symfony 1.4.11. In my site I have 3 languages in my site "se","en","no". In my backend, I use only en, and I have in settings:
all:
.settings:
default_culture: en
But in some module, when in frontend I have "se" language, have error :
Data file for "se" was not found.
In frontend I try, make i18n with database;
Stack trace:
stack trace
at ()
in SF_SYMFONY_LIB_DIR/i18n/sfCultureInfo.class.php line 301 ...
if (is_file($filename) == false)
{
throw new sfException(sprintf('Data file for "%s" was not found.', $file));
}
if (in_array($filename, $this->dataFiles) == false)
at sfCultureInfo->loadCultureData('se')
in SF_SYMFONY_LIB_DIR/i18n/sfCultureInfo.class.php line 217 ...
at sfCultureInfo->__construct('se')
in SF_SYMFONY_LIB_DIR/i18n/sfCultureInfo.class.php line 136 ...
at sfCultureInfo::getInstance('se')
in SF_SYMFONY_LIB_DIR/i18n/sfDateTimeFormatInfo.class.php line 186 ...
at sfDateTimeFormatInfo::getInstance('se')
in SF_SYMFONY_LIB_DIR/i18n/sfDateFormat.class.php line 100 ...
at sfDateFormat->__construct('se')
in SF_SYMFONY_LIB_DIR/helper/DateHelper.php line 57 ...
at format_date('2011-07-22 01:36:02', 'f')
in SF_ROOT_DIR/cache/backend/dev/modules/autoSfGuardUser/templates/_list_td_tabular.php line 5 ...
at require('/home/dan/WEB/www/europellets-dev.my/cache/backend/dev/modules/autoSfGuardUser/templates/_list_td_tabular.php')
in SF_SYMFONY_LIB_DIR/view/sfPHPView.class.php line 75 ...
at sfPHPView->renderFile('/home/dan/WEB/www/europellets-dev.my/cache/backend/dev/modules/autoSfGuardUser/templates/_list_td_tabular.php')
in SF_SYMFONY_LIB_DIR/view/sfPartialView.class.php line 124 ...
at sfPartialView->render()
in SF_SYMFONY_LIB_DIR/helper/PartialHelper.php line 218 ...
at get_partial('sfGuardUser/list_td_tabular', array('sf_guard_user' => object('sfOutputEscaperIteratorDecorator')))
in SF_SYMFONY_LIB_DIR/helper/PartialHelper.php line 180 ...
at include_partial('sfGuardUser/list_td_tabular', array('sf_guard_user' => object('sfOutputEscaperIteratorDecorator')))
in SF_ROOT_DIR/cache/backend/dev/modules/autoSfGuardUser/templates/_list.php line 31 ...
at require('/home/dan/WEB/www/europellets-dev.my/cache/backend/dev/modules/autoSfGuardUser/templates/_list.php')
in SF_SYMFONY_LIB_DIR/view/sfPHPView.class.php line 75 ...
at sfPHPView->renderFile('/home/dan/WEB/www/europellets-dev.my/cache/backend/dev/modules/autoSfGuardUser/templates/_list.php')
in SF_SYMFONY_LIB_DIR/view/sfPartialView.class.php line 124 ...
at sfPartialView->render()
in SF_SYMFONY_LIB_DIR/helper/PartialHelper.php line 218 ...
at get_partial('sfGuardUser/list', array('pager' => object('sfOutputEscaperIteratorDecorator'), 'sort' => object('sfOutputEscaperArrayDecorator'), 'helper' => object('sfGuardUserGeneratorHelper')))
in SF_SYMFONY_LIB_DIR/helper/PartialHelper.php line 180 ...
at include_partial('sfGuardUser/list', array('pager' => object('sfOutputEscaperIteratorDecorator'), 'sort' => object('sfOutputEscaperArrayDecorator'), 'helper' => object('sfGuardUserGeneratorHelper')))
in SF_ROOT_DIR/cache/backend/dev/modules/autoSfGuardUser/templates/indexSuccess.php line 19 ...
at require('/home/dan/WEB/www/europellets-dev.my/cache/backend/dev/modules/autoSfGuardUser/templates/indexSuccess.php')
in SF_SYMFONY_LIB_DIR/view/sfPHPView.class.php line 75 ...
at sfPHPView->renderFile('/home/dan/WEB/www/europellets-dev.my/cache/backend/dev/modules/autoSfGuardUser/templates/indexSuccess.php')
in SF_SYMFONY_LIB_DIR/view/sfPHPView.class.php line 185 ...
at sfPHPView->render()
in SF_SYMFONY_LIB_DIR/filter/sfExecutionFilter.class.php line 155 ...
at sfExecutionFilter->executeView('sfGuardUser', 'index', 'Success', array('configuration' => object('sfGuardUserGeneratorConfiguration'), 'helper' => object('sfGuardUserGeneratorHelper'), 'filters' => object('sfGuardUserFormFilter'), 'pager' => object('sfDoctrinePager'), 'sort' => array(null, null)))
in SF_SYMFONY_LIB_DIR/filter/sfExecutionFilter.class.php line 116 ...
at sfExecutionFilter->handleView(object('sfFilterChain'), object('sfGuardUserActions'), 'Success')
in SF_SYMFONY_LIB_DIR/filter/sfExecutionFilter.class.php line 47 ...
at sfExecutionFilter->execute(object('sfFilterChain'))
in SF_SYMFONY_LIB_DIR/filter/sfFilterChain.class.php line 53 ...
at sfFilterChain->execute()
in SF_SYMFONY_LIB_DIR/filter/sfRenderingFilter.class.php line 33 ...
at sfRenderingFilter->execute(object('sfFilterChain'))
in SF_SYMFONY_LIB_DIR/filter/sfFilterChain.class.php line 53 ...
at sfFilterChain->execute()
in SF_SYMFONY_LIB_DIR/controller/sfController.class.php line 238 ...
at sfController->forward('sfGuardUser', 'index')
in SF_SYMFONY_LIB_DIR/controller/sfFrontWebController.class.php line 48 ...
at sfFrontWebController->dispatch()
in SF_SYMFONY_LIB_DIR/util/sfContext.class.php line 170 ...
at sfContext->dispatch()
in SF_ROOT_DIR/web/backend_dev.php line 13 ...

This error means that there is no ICU data file inside SF_SYMFONY_LIB_DIR/i18n/data/ dir for the 'se' culture. Symfony supports many cultures, but not all. In your case, if 'se' is Swedish - use 'sv' code.
sv sv-SE Swedish
sv-FI sv-FI Swedish (Finland)
sv-SE sv-SE Swedish (Sweden)
If 'se' is not Swedish and it is not in out of the box list (see SF_SYMFONY_LIB_DIR/i18n/data/ dir) - use internal tokens instead of pattern (e.g. format_date($date, 'f') -> format_date($date, 'd MMMM YYYY, hh:mm')) formatDateHowTo

Related

dask: using compute() raised error 'apply() got an unexpected keyword argument 'how''?

dask 2.15.0 ,
pandas 1.0.3
unknown_dict = dict(map(lambda columnName:(columnName,'unknown'),columns_to_clean))
my_dataframe = my_dataframe.fillna(unknown_dict)
#no problem before compute
with ProgressBar():
print(my_dataframe.isnull().sum().compute()
my_dataframe.persist()
raised the following error message:
TypeError Traceback (most recent call
last) in
1 with ProgressBar():
----> 2 print(my_dataframe.isnull().sum().compute())
3 my_dataframe.persist()
C:\Users\KHS\lib\site-packages\dask\base.py in compute(self, **kwargs)
164 dask.base.compute
165 """
--> 166 (result,) = compute(self, traverse=False, **kwargs)
167 return result
168
C:\Users\KHS\lib\site-packages\dask\base.py in compute(*args,
**kwargs)
435 keys = [x.dask_keys() for x in collections]
436 postcomputes = [x.dask_postcompute() for x in collections]
--> 437 results = schedule(dsk, keys, **kwargs)
438 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
439
C:\Users\KHS\lib\site-packages\dask\threaded.py in get(dsk, result,
cache, num_workers, pool, **kwargs)
82 get_id=_thread_get_id,
83 pack_exception=pack_exception,
---> 84 **kwargs
85 )
86
C:\Users\KHS\lib\site-packages\dask\local.py in get_async(apply_async,
num_workers, dsk, result, cache, get_id, rerun_exceptions_locally,
pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)
484 _execute_task(task, data) # Re-execute locally
485 else:
--> 486 raise_exception(exc, tb)
487 res, worker_id = loads(res_info)
488 state["cache"][key] = res
C:\Users\KHS\lib\site-packages\dask\local.py in reraise(exc, tb)
314 if exc.traceback is not tb:
315 raise exc.with_traceback(tb)
--> 316 raise exc
317
318
C:\Users\KHS\lib\site-packages\dask\local.py in execute_task(key,
task_info, dumps, loads, get_id, pack_exception)
220 try:
221 task, data = loads(task_info)
--> 222 result = _execute_task(task, data)
223 id = get_id()
224 result = dumps((result, id))
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\core.py in (.0)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
113 """
114 if isinstance(arg, list):
--> 115 return [_execute_task(a, cache) for a in arg]
116 elif istask(arg):
117 func, args = arg[0], arg[1:]
C:\Users\KHS\lib\site-packages\dask\core.py in (.0)
113 """
114 if isinstance(arg, list):
--> 115 return [_execute_task(a, cache) for a in arg]
116 elif istask(arg):
117 func, args = arg[0], arg[1:]
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\optimization.py in call(self,
*args)
989 if not len(args) == len(self.inkeys):
990 raise ValueError("Expected %d args, got %d" % (len(self.inkeys), len(args)))
--> 991 return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
992
993 def reduce(self):
C:\Users\KHS\lib\site-packages\dask\core.py in get(dsk, out, cache)
149 for key in toposort(dsk):
150 task = dsk[key]
--> 151 result = _execute_task(task, cache)
152 cache[key] = result
153 result = _execute_task(out, cache)
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\core.py in (.0)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\core.py in (.0)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
113 """
114 if isinstance(arg, list):
--> 115 return [_execute_task(a, cache) for a in arg]
116 elif istask(arg):
117 func, args = arg[0], arg[1:]
C:\Users\KHS\lib\site-packages\dask\core.py in (.0)
113 """
114 if isinstance(arg, list):
--> 115 return [_execute_task(a, cache) for a in arg]
116 elif istask(arg):
117 func, args = arg[0], arg[1:]
C:\Users\KHS\lib\site-packages\dask\core.py in _execute_task(arg,
cache, dsk)
119 # temporaries by their reference count and can execute certain
120 # operations in-place.
--> 121 return func(*(_execute_task(a, cache) for a in args))
122 elif not ishashable(arg):
123 return arg
C:\Users\KHS\lib\site-packages\dask\utils.py in apply(func, args,
kwargs)
28 def apply(func, args, kwargs=None):
29 if kwargs:
---> 30 return func(*args, **kwargs)
31 else:
32 return func(*args)
TypeError: apply() got an unexpected keyword argument 'how'
Thank you 'quasiben', I've tried minimal code to reproduce the error, which was not possible.
However, reducing the dataset to 1 fourth its original size worked on my laptop. So I guess it has to do with knowing the threshold and limits of my system. Thank you.

Neo4j visualization with py2neo: TypeError: 'LabelSetView' object is not callable

I am trying to follow the example in
https://nicolewhite.github.io/neo4j-jupyter/hello-world.html
from scripts.vis import draw
import neo4jupyter
options = {"Person": "name", "Drink": "name", "Manufacturer": "name"}
draw(graph, options)
For this part of the code, I encounter this error:
ypeError Traceback (most recent call last)
<ipython-input-7-6a87e5426fa3> in <module>
3
4 options = {"Person": "name", "Drink": "name", "Manufacturer": "name"}
----> 5 draw(graph, options)
~\PycharmProjects\Knowledge_Graph\scripts\vis.py in draw(graph, options, physics, limit)
104 target_id = row[4]
105
--> 106 source_info = get_vis_info(source_node, source_id)
107
108 if source_info not in nodes:
~\PycharmProjects\Knowledge_Graph\scripts\vis.py in get_vis_info(node, id)
91
92 def get_vis_info(node, id):
---> 93 node_label = list(node.labels())[0]
94 prop_key = options.get(node_label)
95 vis_label = node.properties.get(prop_key, "")
TypeError: 'LabelSetView' object is not callable
I read online that there might be some issues with scripts.vis but I am not too sure how to resolve it
Please checkout the latest version from the below link and it fixes the problem
https://github.com/merqurio/neo4jupyter/issues/5

Unresolvable dependency resolving [Parameter #0 [ <required> $accountSid ]] in class Twilio\Jwt\AccessToken

I am trying to implement twilio chat using laravel. I have follow tutorial and try the source from github, https://github.com/TwilioDevEd/twiliochat-laravel. Works well in desktop, but when moving to linux enviroment, it shows error:
(1/1) BindingResolutionException
Unresolvable dependency resolving [Parameter #0 [ <required> $accountSid ]] in class Twilio\Jwt\AccessToken
The linux environment is using Laravel/Lumen 5.8.4
Here's the steps I have done :
composer require twilio/sdk
in routes/web.php :
//twilio
$router->group(['prefix' => 'twilio'], function() use ($router){
$router->post('/token',['uses' => 'TwilioController#generate','as' => 'token-generate']);
});
in app/Http/Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\ChatGrant;
class TwilioController extends Controller
{
public function generate(Request $request, AccessToken $accessToken, ChatGrant $chatGrant)
{
var_dump('test aja');
exit;
$appName = "allsmartchat";
$deviceId = $request->input("device");
$identity = $request->input("identity");
$TWILIO_CHAT_SERVICE_SID = 'IS****'; //my SID
$endpointId = $appName . ":" . $identity . ":" . $deviceId;
$accessToken->setIdentity($identity);
$chatGrant->setServiceSid($TWILIO_CHAT_SERVICE_SID);
$chatGrant->setEndpointId($endpointId);
$accessToken->addGrant($chatGrant);
$response = array(
'identity' => $identity,
'token' => $accessToken->toJWT()
);
return response()->json($response);
}
}
in app/Providers/TwilioAccessProvider.php :
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Twilio\Jwt\AccessToken;
class TwilioAccessTokenProvider extends ServiceProvider
{
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind(
AccessToken::class, function ($app) {
$TWILIO_ACCOUNT_SID = 'AC***';
$TWILIO_API_KEY = 'SK***';
$TWILIO_API_SECRET = '***';
$token = new AccessToken(
$TWILIO_ACCOUNT_SID,
$TWILIO_API_KEY,
$TWILIO_API_SECRET,
3600
);
return $token;
}
);
}
}
I use postman to get the token value, in localhost, it produces token :
{
"identity": null,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTS2E4OGQ2ZjVjNTEyNTkzMWMxMmYxYmFiYmFiZWY4MTU0LTE1NjM0MzkzOTQiLCJpc3MiOiJTS2E4OGQ2ZjVjNTEyNTkzMWMxMmYxYmFiYmFiZWY4MTU0Iiwic3ViIjoiQUFBQUNjZjMyMTdkNWU3NTEwMzA4ZjM2ZDZlYzNhZmJkOGNiZCIsImV4cCI6MTU2MzQ0Mjk5NCwiZ3JhbnRzIjp7ImNoYXQiOnsic2VydmljZV9zaWQiOiJJU2JjM2Y3N2Y2MjEzYjQ3MzliZTBlYTJiOTRiZTc4OWRmIiwiZW5kcG9pbnRfaWQiOiJUd2lsaW9DaGF0OjoifX19.OuAjJs_KGz-J_WTPlrCfAV_bjKmKCvSOTzj_ZGU0mUA"
}
but in server, it shows error :
(1/1) BindingResolutionException
Unresolvable dependency resolving [Parameter #0 [ <required> $accountSid ]] in class Twilio\Jwt\AccessToken
in Container.php line 973
at Container->unresolvablePrimitive(object(ReflectionParameter))
in Container.php line 911
at Container->resolvePrimitive(object(ReflectionParameter))
in Container.php line 852
at Container->resolveDependencies(array(object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter)))
in Container.php line 818
at Container->build('Twilio\\Jwt\\AccessToken')
in Container.php line 667
at Container->resolve('Twilio\\Jwt\\AccessToken', array())
in Container.php line 615
at Container->make('Twilio\\Jwt\\AccessToken', array())
in Application.php line 260
at Application->make('Twilio\\Jwt\\AccessToken')
in BoundMethod.php line 167
at BoundMethod::addDependencyForCallParameter(object(Application), object(ReflectionParameter), array(), array(object(Request)))
in BoundMethod.php line 121
at BoundMethod::getMethodDependencies(object(Application), array(object(TwilioController), 'generate'), array())
in BoundMethod.php line 32
at BoundMethod::Illuminate\Container\{closure}()
in BoundMethod.php line 90
at BoundMethod::callBoundMethod(object(Application), array(object(TwilioController), 'generate'), object(Closure))
in BoundMethod.php line 34
at BoundMethod::call(object(Application), array(object(TwilioController), 'generate'), array(), null)
in Container.php line 576
at Container->call(array(object(TwilioController), 'generate'), array())
in RoutesRequests.php line 376
at Application->callControllerCallable(array(object(TwilioController), 'generate'), array())
in RoutesRequests.php line 342
at Application->callLumenController(object(TwilioController), 'generate', array(true, array('uses' => 'App\\Http\\Controllers\\TwilioController#generate', 'as' => 'token-generate'), array()))
in RoutesRequests.php line 316
at Application->callControllerAction(array(true, array('uses' => 'App\\Http\\Controllers\\TwilioController#generate', 'as' => 'token-generate'), array()))
in RoutesRequests.php line 278
at Application->callActionOnArrayBasedRoute(array(true, array('uses' => 'App\\Http\\Controllers\\TwilioController#generate', 'as' => 'token-generate'), array()))
in RoutesRequests.php line 263
at Application->handleFoundRoute(array(true, array('uses' => 'App\\Http\\Controllers\\TwilioController#generate', 'as' => 'token-generate'), array()))
in RoutesRequests.php line 165
at Application->Laravel\Lumen\Concerns\{closure}(object(Request))
in RoutesRequests.php line 416
at Application->sendThroughPipeline(array(), object(Closure))
in RoutesRequests.php line 171
at Application->dispatch(null)
in RoutesRequests.php line 108
at Application->run()
in index.php line 28
Above solution is ok but also you can add this code in the App Provider it will definately work
First include the class
use Twilio\Jwt\AccessToken;
$this->app->bind(
AccessToken::class,
function ($app) {
$accountSid = config('services.twilio')['accountSid'];
$apiKey = config('services.twilio')['apiKey'];
$apiSecret = config('services.twilio')['apiSecret'];
return new AccessToken($accountSid, $apiKey, $apiSecret, 3600, 'identity');
}
);
solved,
you need to register service in bootstrap/app.php
$app->register(App\Providers\TwilioAccessTokenProvider::class);
$app->register(App\Providers\TwilioChatGrantProvider::class);
also in laravel, you need to register service in config/app.php
App\Providers\TwilioAccessTokenProvider::class,
App\Providers\TwilioChatGrantProvider::class,

Dask: ValueError: Integer column has NA values

I tried to use dask and found something that appears to be a bug in dask.dataframe.read_csv.
import dask.dataframe as dd
types = {'id': 'int16', 'Semana': 'uint8', 'Agencia_ID': 'uint16', 'Canal_ID': 'uint8',
'Ruta_SAK': 'uint16' ,'Cliente_ID': 'float32', 'Producto_ID': 'float32'}
name_map = {'Semana': 'week', 'Agencia_ID': 'agency', 'Canal_ID': 'channel',
'Ruta_SAK': 'route', 'Cliente_ID': 'client', 'Producto_ID': 'prod'}
test = dd.read_csv(os.path.join(datadir, 'test.csv'), usecols=types.keys(), dtype=types)
test = test.rename(columns=name_map)
gives :
ValueError: Integer column has NA values in column 1
However, the same pandas read_csv operation completes fine and does not yield any NA:
types = {'id': 'int16', 'Semana': 'uint8', 'Agencia_ID': 'uint16', 'Canal_ID': 'uint8',
'Ruta_SAK': 'uint16' ,'Cliente_ID': 'float32', 'Producto_ID': 'float32'}
name_map = {'Semana': 'week', 'Agencia_ID': 'agency', 'Canal_ID': 'channel',
'Ruta_SAK': 'route', 'Cliente_ID': 'client', 'Producto_ID': 'prod'}
test = pd.read_csv(os.path.join(datadir, 'test.csv'), usecols=types.keys(), dtype=types)
test = test.rename(columns=name_map)
test.isnull().any()
id False
week False
agency False
channel False
route False
client False
prod False
dtype: bool
Should I consider this to be an established bug and raise a JIRA for it?
Full traceback:
ValueError Traceback (most recent call last)
in ()
4 'Ruta_SAK': 'route', 'Cliente_ID': 'client', 'Producto_ID': 'prod'}
5
----> 6 test = dd.read_csv(os.path.join(datadir, 'test.csv'), usecols=types.keys(), dtype=types)
7 test = test.rename(columns=name_map)
D:\PROGLANG\Anaconda2\lib\site-packages\dask\dataframe\csv.pyc in read_csv(filename, blocksize, chunkbytes, collection, lineterminator, compression, sample, enforce, storage_options, **kwargs)
195 else:
196 header = sample.split(b_lineterminator)[0] + b_lineterminator
--> 197 head = pd.read_csv(BytesIO(sample), **kwargs)
198
199 df = read_csv_from_bytes(values, header, head, kwargs,
D:\PROGLANG\Anaconda2\lib\site-packages\pandas\io\parsers.pyc in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
560 skip_blank_lines=skip_blank_lines)
561
--> 562 return _read(filepath_or_buffer, kwds)
563
564 parser_f.name = name
D:\PROGLANG\Anaconda2\lib\site-packages\pandas\io\parsers.pyc in _read(filepath_or_buffer, kwds)
323 return parser
324
--> 325 return parser.read()
326
327 _parser_defaults = {
D:\PROGLANG\Anaconda2\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows)
813 raise ValueError('skip_footer not supported for iteration')
814
--> 815 ret = self._engine.read(nrows)
816
817 if self.options.get('as_recarray'):
D:\PROGLANG\Anaconda2\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows)
1312 def read(self, nrows=None):
1313 try:
-> 1314 data = self._reader.read(nrows)
1315 except StopIteration:
1316 if self._first_chunk:
pandas\parser.pyx in pandas.parser.TextReader.read (pandas\parser.c:8748)()
pandas\parser.pyx in pandas.parser.TextReader._read_low_memory (pandas\parser.c:9003)()
pandas\parser.pyx in pandas.parser.TextReader._read_rows (pandas\parser.c:10022)()
pandas\parser.pyx in pandas.parser.TextReader._convert_column_data (pandas\parser.c:11397)()
pandas\parser.pyx in pandas.parser.TextReader._convert_tokens (pandas\parser.c:12093)()
pandas\parser.pyx in pandas.parser.TextReader._convert_with_dtype (pandas\parser.c:13057)()
ValueError: Integer column has NA values in column 1

Declarative Authorization - Catch "Authorization::NotAuthorized" Exception

I'm currently using Declarative Authorization on my application, and trying to catch Exceptions from type Authorization::NotAuthorized.
I have an Entity that has a category. Depending on the role a user can create a new category when creating this entity. At my :before_validation callback I assign the category and want to be able to catch the authorization exception in case he doesn't have permission.
I could check it's role and make a conditional instruction, but then would have to write all the roles.
Exception is being thrown, but I'm not able to catch it, at the "new" instruction.
Code follows:
# Model
before_validation :set_category
def category_name
#category_name ||= category.name unless category.nil?
#category_name
end
def category_name=(name)
name.strip!
name.downcase!
#category_name = name
end
def set_category
if #category_name and not company.blank?
lookup_category = company.categories.not_deleted.find_by_name(#category_name)
begin
category = lookup_category.blank? ? company.categories.new(:name => #category_name) : lookup_category
rescue Authorization::NotAuthorized
errors.add(:category, I18n.t('activerecord.errors.messages.exclusion'))
end
end
end
# Controller
def create
#ticket = current_user.created_tickets.new(params[:ticket])
if #ticket.save # Line 88
...
Exception stack trace:
Authorization::NotAuthorized (No matching rules found for create for #<User id: 36,..."> (roles [:Requester], privileges [:create], context :categories).):
/Library/Ruby/Gems/1.8/gems/declarative_authorization-0.4.1/lib/declarative_authorization/authorization.rb:168:in `permit!'
/Library/Ruby/Gems/1.8/gems/declarative_authorization-0.4.1/lib/declarative_authorization/in_model.rb:131:in `using_access_control'
/Library/Ruby/Gems/1.8/gems/after_commit-1.0.7/lib/after_commit/connection_adapters.rb:12:in `transaction'
/Library/Ruby/Gems/1.8/gems/after_commit-1.0.7/lib/after_commit/connection_adapters.rb:12:in `transaction'
app/controllers/tickets_controller.rb:88:in `create'
Debugger goes inside the block:
# Debugger
lookup_category = company.categories.not_deleted.find_by_name(#category_name)
(rdb:3) list
[275, 284] in /Users/Pedro/projects/trunk/app/models/ticket.rb
275
276 def set_category
277 if #category_name and not self.company.blank?
278 begin
279 debugger
=> 280 lookup_category = company.categories.not_deleted.find_by_name(#category_name)
281 self.category = lookup_category.blank? ? company.categories.new(:name => #category_name) : lookup_category
282 rescue Authorization::NotAuthorized
283 self.errors.add(:category, I18n.t('activerecord.errors.messages.exclusion'))
284 end
(rdb:3) n
/Users/Pedro/projects/trunk/app/models/ticket.rb:281
self.category = lookup_category.blank? ? company.categories.new(:name => #category_name) : lookup_category
(rdb:3) list
[276, 285] in /Users/Pedro/projects/trunk/app/models/ticket.rb
276 def set_category
277 if #category_name and not self.company.blank?
278 begin
279 debugger
280 lookup_category = company.categories.not_deleted.find_by_name(#category_name)
=> 281 self.category = lookup_category.blank? ? company.categories.new(:name => #category_name) : lookup_category
282 rescue Authorization::NotAuthorized
283 self.errors.add(:category, I18n.t('activerecord.errors.messages.exclusion'))
284 end
285 end
(rdb:3) n
/Users/Pedro/.gem/ruby/1.8/gems/activesupport-2.3.8/lib/active_support/callbacks.rb:94
break result if terminator.call(result, object)
(rdb:3) list
[89, 98] in /Users/Pedro/.gem/ruby/1.8/gems/activesupport-2.3.8/lib/active_support/callbacks.rb
89 unless block_given?
90 send(enumerator) { |callback| callback.call(object) }
91 else
92 send(enumerator) do |callback|
93 result = callback.call(object)
=> 94 break result if terminator.call(result, object)
95 end
96 end
97 end
98
(rdb:3)
I'd say that it's breaking outside the begin ... rescue block and therefore not caught by the rescue. Try to do the same rescue on line 88 of your controller.
If you want to handle this in the validation process, maybe try to do a test on the roles or permissions of the user before creating your object instead of catching the exception that will only be thrown on creation.
It's not possible to catch the exception on a before callback. The best way I found to do this kind of validation is:
# Model code
begin
User.with_permissions_to :create, :categories # Raises exception if not permitted
... do whatever you want
rescue
... do whatever you want
end
Thanks for all the help

Resources