Search Results

Search found 4969 results on 199 pages for 'def'.

Page 8/199 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Downloading a file from the internet with '&' in URL using wget

    - by matt_tm
    Hi, I'm trying to download a file from a URL that looks like this: http://pdf.example.com/filehandle.ashx?p1=ABC&p2=DEF.pdf Within the browser, this link prompts me to download a file called x.pdf irrespective of what DEF is (but 'x.pdf' is the right content). However using wget, I get the following: >wget.exe http://pdf.example.com/filehandle.ashx?p1=ABC&p2=DEF.pdf SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc syswgetrc = C:\Program Files\GnuWin32/etc/wgetrc --2011-01-06 07:52:05-- http://pdf.example.com/filehandle.ashx?p1=ABC Resolving pdf.example.com... 99.99.99.99 Connecting to pdf.example.com|99.99.99.99|:80... connected. HTTP request sent, awaiting response... 500 Internal Server Error 2011-01-06 07:52:08 ERROR 500: Internal Server Error. 'p2' is not recognized as an internal or external command, operable program or batch file. This is on a Windows Vista system Edit1 >wget.exe "http://pdf.example.com/filehandle.ashx?p1=ABC&p2=DEF.pdf" SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc syswgetrc = C:\Program Files\GnuWin32/etc/wgetrc --2011-02-06 10:18:31-- http://pdf.example.com/filehandle.ashx?p1=ABC&p2=DEF.pdf Resolving pdf.example.com... 99.99.99.99 Connecting to pdf.example.com|99.99.99.99|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 4568 (4.5K) [image/JPEG] Saving to: `filehandle.ashx@p1=ABC&p2=DEF.pdf' 100%[======================================>] 4,568 --.-K/s in 0.1s 2011-02-06 10:18:33 (30.0 KB/s) - `filehandle.ashx@p1=ABC&p2=DEF.pdf' saved [4568/4568]

    Read the article

  • Strange Flash AS3 xml Socket behavior

    - by Rnd_d
    I have a problem which I can't understand. To understand it I wrote a socket client on AS3 and a server on python/twisted, you can see the code of both applications below. Let's launch two clients at the same time, arrange them so that you can see both windows and press connection button in both windows. Then press and hold any button. What I'm expecting: Client with pressed button sends a message "some data" to the server, then the server sends this message to all the clients(including the original sender) . Then each client moves right the button 'connectButton' and prints a message to the log with time in the following format: "min:secs:milliseconds". What is going wrong: The motion is smooth in the client that sends the message, but in all other clients the motion is jerky. This happens because messages to those clients arrive later than to the original sending client. And if we have three clients (let's name them A,B,C) and we send a message from A, the sending time log of B and C will be the same. Why other clients recieve this messages later than the original sender? By the way, on ubuntu 10.04/chrome all the motion is smooth. Two clients are launched in separated chromes. windows screenshot Can't post linux screenshot, need more than 10 reputation to post more hyperlinks. Listing of log, four clients simultaneously: [16:29:33.280858] 62.140.224.1 >> some data [16:29:33.280912] 87.249.9.98 << some data [16:29:33.280970] 87.249.9.98 << some data [16:29:33.281025] 87.249.9.98 << some data [16:29:33.281079] 62.140.224.1 << some data [16:29:33.323267] 62.140.224.1 >> some data [16:29:33.323326] 87.249.9.98 << some data [16:29:33.323386] 87.249.9.98 << some data [16:29:33.323440] 87.249.9.98 << some data [16:29:33.323493] 62.140.224.1 << some data [16:29:34.123435] 62.140.224.1 >> some data [16:29:34.123525] 87.249.9.98 << some data [16:29:34.123593] 87.249.9.98 << some data [16:29:34.123648] 87.249.9.98 << some data [16:29:34.123702] 62.140.224.1 << some data AS3 client code package { import adobe.utils.CustomActions; import flash.display.Sprite; import flash.events.DataEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.SecurityErrorEvent; import flash.net.XMLSocket; import flash.system.Security; import flash.text.TextField; public class Main extends Sprite { private var socket :XMLSocket; private var textField :TextField = new TextField; private var connectButton :TextField = new TextField; public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(event:Event = null):void { socket = new XMLSocket(); socket.addEventListener(Event.CONNECT, connectHandler); socket.addEventListener(DataEvent.DATA, dataHandler); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); addChild(textField); textField.y = 50; textField.width = 780; textField.height = 500; textField.border = true; connectButton.selectable = false; connectButton.border = true; connectButton.addEventListener(MouseEvent.MOUSE_DOWN, connectMouseDownHandler); connectButton.width = 105; connectButton.height = 20; connectButton.text = "click here to connect"; addChild(connectButton); } private function connectHandler(event:Event):void { textField.appendText("Connect\n"); textField.appendText("Press and hold any key\n"); } private function dataHandler(event:DataEvent):void { var now:Date = new Date(); textField.appendText(event.data + " time = " + now.getMinutes() + ":" + now.getSeconds() + ":" + now.getMilliseconds() + "\n"); connectButton.x += 2; } private function keyDownHandler(event:KeyboardEvent):void { socket.send("some data"); } private function connectMouseDownHandler(event:MouseEvent):void { var connectAddress:String = "ep1c.org"; var connectPort:Number = 13250; Security.loadPolicyFile("xmlsocket://" + connectAddress + ":" + String(connectPort)); socket.connect(connectAddress, connectPort); } } } Python server code from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineOnlyReceiver import datetime class EchoProtocol(LineOnlyReceiver): ##### name = "" id = 0 delimiter = chr(0) ##### def getName(self): return self.transport.getPeer().host def connectionMade(self): self.id = self.factory.getNextId() print "New connection from %s - id:%s" % (self.getName(), self.id) self.factory.clientProtocols[self.id] = self def connectionLost(self, reason): print "Lost connection from "+ self.getName() del self.factory.clientProtocols[self.id] self.factory.sendMessageToAllClients(self.getName() + " has disconnected.") def lineReceived(self, line): print "[%s] %s >> %s" % (datetime.datetime.now().time(), self, line) if line=="<policy-file-request/>": data = """<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"> <!-- Policy file for xmlsocket://ep1c.org --> <cross-domain-policy> <allow-access-from domain="*" to-ports="%s" /> </cross-domain-policy>""" % PORT self.send(data) else: self.factory.sendMessageToAllClients( line ) def send(self, line): print "[%s] %s << %s" % (datetime.datetime.now().time(), self, line) if line: self.transport.write( str(line) + chr(0)) else: print "Nothing to send" def __str__(self): return self.getName() class ChatProtocolFactory(ServerFactory): protocol = EchoProtocol def __init__(self): self.clientProtocols = {} self.nextId = 0 def getNextId(self): id = self.nextId self.nextId += 1 return id def sendMessageToAllClients(self, msg): for client in self.clientProtocols: self.clientProtocols[client].send(msg) def sendMessageToClient(self, id, msg): self.clientProtocols[id].send(msg) PORT = 13250 print "Starting Server" factory = ChatProtocolFactory() reactor.listenTCP(PORT, factory) reactor.run()

    Read the article

  • MSVC Compiler options with mojo-native in Maven

    - by graham.reeds
    I'm trying to set up a test environment with Maven to build VC++ and I am way behind on this. I have 3 source files that I builds a dll (once I get this fixed it should be a simple matter to add the unit-tests): hook.cpp hook.h hook.def This is compiled, on the command line, with the following: C:\Develop\hook\src\main\msvc>cl -o hook.dll Hook.cpp /D HOOK_DLLEXPORT /link /DLL /DEF:"Hook.def" Which produces the expected obj, dll, lib and exp files. So now to get this working in Maven2 with the Mojo-native plugin. With no options Maven w/Mojo gives me this (truncated) output: [INFO] [native:initialize {execution: default-initialize}] [INFO] [native:unzipinc {execution: default-unzipinc}] [INFO] [native:javah {execution: default-javah}] [INFO] [native:compile {execution: default-compile}] [INFO] cmd.exe /X /C "cl -IC:\Develop\hook\src\main\msvc /FoC:\Develop\hook\targ et\objs\Hook.obj -c C:\Develop\hook\src\main\msvc\Hook.cpp" Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. Hook.cpp [INFO] [native:link {execution: default-link}] [INFO] cmd.exe /X /C "link.exe /out:C:\Develop\hook\target\hook.dll target\objs\ Hook.obj" Microsoft (R) Incremental Linker Version 9.00.30729.01 Copyright (C) Microsoft Corporation. All rights reserved. LINK : fatal error LNK1561: entry point must be defined [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Error executing command line. Exit code:1561 mojo-native gives options for manipulating the compiler/linker options but gives no example of usage. No matter what I tweak in these settings I get the error of: [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:native-maven -plugin:1.0-alpha-4 (found static expression: '-o hook.dll Hook.cpp /D HOOK_DLLEXPORT /link /DLL /DEF:"Hook.def"' which may act as a default value). Cause: Cannot assign configuration entry 'compilerStartOptions' to 'interface ja va.util.List' from '-o hook.dll Hook.cpp /D HOOK_DLLEXPORT /link /DLL /DEF:"Hook .def"', which is of type class java.lang.String The relevant part of my pom.xml looks like this: <configuration> <sources> <source> <directory>src/main/msvc</directory> <includes> <include>**/*.cpp</include> </includes> </source> </sources> <compilerProvider>msvc</compilerProvider> <compilerExecutable>cl</compilerExecutable> <!-- cl -o hook.dll Hook.cpp /D HOOK_DLLEXPORT /link /DLL /DEF:"Hook.def" --> <compilerStartOptions>-o hook.dll Hook.cpp /D HOOK_DLLEXPORT /link /DLL /DEF:"Hook.def"</compilerStartOptions> <!-- <compilerMiddleOptions></compilerMiddleOptions> <compilerEndOptions></compilerEndOptions> <linkerStartOptions></linkerStartOptions> <linkerMiddleOptions></linkerMiddleOptions> <linkerEndOptions></linkerEndOptions> --> </configuration> How do I manipulate the compiler to produce a DLL like the command line version does? Or should I give up and just use exec?

    Read the article

  • Simple Observation in Django: How Can I Correctly Modify The `attrs` sent to __new__ of a Django Mod

    - by DGGenuine
    Hello, I'm a strong proponent of the observer pattern, and this is what I'd like to be able to do in my Django models.py: class AModel(Model): __metaclass__ = SomethingMagical @post_save(AnotherModel) @classmethod def observe_another_model_saved(klass, sender, instance, created, **kwargs): pass @pre_init('YetAnotherModel') @classmethod def observe_yet_another_model_initializing(klass, sender, *args, **kwargs): pass @post_delete('DifferentApp.SomeModel') @classmethod def observe_some_model_deleted(klass, sender, **kwargs): pass This would connect a signal with sender = the decorator's argument and receiver = the decorated method. Right now my signal connection code all exists in __init__.py which is okay, but a little unmaintainable. I want this code all in one place, the models.py file. Thanks to helpful feedback from the community I'm very close (I think.) (I'm using a metaclass solution instead of the class decorator solution in the previous question/answer because you can't set attributes on classmethods, which I need.) I am having a strange error I don't understand. At the end of my post are the contents of a models.py that you can pop into a fresh project/application to see the error. Set your database to sqlite and add the application to installed apps. This is the error: Validating models... Unhandled exception in thread started by Traceback (most recent call last): File "/Library/Python/2.6/site-packages//lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 253, in validate raise CommandError("One or more models did not validate:\n%s" % error_text) django.core.management.base.CommandError: One or more models did not validate: local.myothermodel: 'my_model' has a relation with model MyModel, which has either not been installed or is abstract. I've indicated a few different things you can comment in/out to fix the error. First, if you don't modify the attrs sent to the metaclass's __new__, then the error does not arise. (Note even if you copy the dictionary element by element into a new dictionary, it still fails; only using the exact attrs dictionary works.) Second, if you reference the first model by class rather than by string, the error also doesn't arise regardless of what you do in __new__. I appreciate your help. I'll be githubbing the solution if and when it works. Maybe other people would enjoy a simplified way to use Django signals to observe application happenings. #models.py from django.db import models from django.db.models.base import ModelBase from django.db.models import signals import pdb class UnconnectedMethodWrapper(object): sender = None method = None signal = None def __init__(self, signal, sender, method): self.signal = signal self.sender = sender self.method = method def post_save(sender): return _make_decorator(signals.post_save, sender) def _make_decorator(signal, sender): def decorator(view): return UnconnectedMethodWrapper(signal, sender, view) return decorator class ConnectableModel(ModelBase): """ A meta class for any class that will have static or class methods that need to be connected to signals. """ def __new__(cls, name, bases, attrs): unconnecteds = {} ## NO WORK newattrs = {} for name, attr in attrs.iteritems(): if isinstance(attr, UnconnectedMethodWrapper): unconnecteds[name] = attr newattrs[name] = attr.method #replace the UnconnectedMethodWrapper with the method it wrapped. else: newattrs[name] = attr ## NO WORK # newattrs = {} # for name, attr in attrs.iteritems(): # newattrs[name] = attr ## WORKS # newattrs = attrs new = super(ConnectableModel, cls).__new__(cls, name, bases, newattrs) for name, unconnected in unconnecteds.iteritems(): _connect_signal(unconnected.signal, unconnected.sender, getattr(new, name), new._meta.app_label) return new def _connect_signal(signal, sender, receiver, default_app_label): # full implementation also accepts basestring as sender and will look up model accordingly signal.connect(sender=sender, receiver=receiver) class MyModel(models.Model): __metaclass__ = ConnectableModel @post_save('In my application this string matters') @classmethod def observe_it(klass, sender, instance, created, **kwargs): pass @classmethod def normal_class_method(klass): pass class MyOtherModel(models.Model): ## WORKS # my_model = models.ForeignKey(MyModel) ## NO WORK my_model = models.ForeignKey('MyModel')

    Read the article

  • Google App Engine - Secure Cookies

    - by tponthieux
    I'd been searching for a way to do cookie based authentication/sessions in Google App Engine because I don't like the idea of memcache based sessions, and I also don't like the idea of forcing users to create google accounts just to use a website. I stumbled across someone's posting that mentioned some signed cookie functions from the Tornado framework and it looks like what I need. What I have in mind is storing a user's id in a tamper proof cookie, and maybe using a decorator for the request handlers to test the authentication status of the user, and as a side benefit the user id will be available to the request handler for datastore work and such. The concept would be similar to forms authentication in ASP.NET. This code comes from the web.py module of the Tornado framework. According to the docstrings, it "Signs and timestamps a cookie so it cannot be forged" and "Returns the given signed cookie if it validates, or None." I've tried to use it in an App Engine Project, but I don't understand the nuances of trying to get these methods to work in the context of the request handler. Can someone show me the right way to do this without losing the functionality that the FriendFeed developers put into it? The set_secure_cookie, and get_secure_cookie portions are the most important, but it would be nice to be able to use the other methods as well. #!/usr/bin/env python import Cookie import base64 import time import hashlib import hmac import datetime import re import calendar import email.utils import logging def _utf8(s): if isinstance(s, unicode): return s.encode("utf-8") assert isinstance(s, str) return s def _unicode(s): if isinstance(s, str): try: return s.decode("utf-8") except UnicodeDecodeError: raise HTTPError(400, "Non-utf8 argument") assert isinstance(s, unicode) return s def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self,"_cookies"): self._cookies = Cookie.BaseCookie() if "Cookie" in self.request.headers: try: self._cookies.load(self.request.headers["Cookie"]) except: self.clear_all_cookies() return self._cookies def _cookie_signature(self,*parts): self.require_setting("cookie_secret","secure cookies") hash = hmac.new(self.application.settings["cookie_secret"], digestmod=hashlib.sha1) for part in parts:hash.update(part) return hash.hexdigest() def get_cookie(self,name,default=None): """Gets the value of the cookie with the given name,else default.""" if name in self.cookies: return self.cookies[name].value return default def set_cookie(self,name,value,domain=None,expires=None,path="/", expires_days=None): """Sets the given cookie name/value with the given options.""" name = _utf8(name) value = _utf8(value) if re.search(r"[\x00-\x20]",name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r:%r" % (name,value)) if not hasattr(self,"_new_cookies"): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta( days=expires_days) if expires: timestamp = calendar.timegm(expires.utctimetuple()) new_cookie[name]["expires"] = email.utils.formatdate( timestamp,localtime=False,usegmt=True) if path: new_cookie[name]["path"] = path def clear_cookie(self,name,path="/",domain=None): """Deletes the cookie with the given name.""" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name,value="",path=path,expires=expires, domain=domain) def clear_all_cookies(self): """Deletes all the cookies the user sent with this request.""" for name in self.cookies.iterkeys(): self.clear_cookie(name) def set_secure_cookie(self,name,value,expires_days=30,**kwargs): """Signs and timestamps a cookie so it cannot be forged""" timestamp = str(int(time.time())) value = base64.b64encode(value) signature = self._cookie_signature(name,value,timestamp) value = "|".join([value,timestamp,signature]) self.set_cookie(name,value,expires_days=expires_days,**kwargs) def get_secure_cookie(self,name,include_name=True,value=None): """Returns the given signed cookie if it validates,or None""" if value is None:value = self.get_cookie(name) if not value:return None parts = value.split("|") if len(parts) != 3:return None if include_name: signature = self._cookie_signature(name,parts[0],parts[1]) else: signature = self._cookie_signature(parts[0],parts[1]) if not _time_independent_equals(parts[2],signature): logging.warning("Invalid cookie signature %r",value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r",value) return None try: return base64.b64decode(parts[0]) except: return None uid=1234|1234567890|d32b9e9c67274fa062e2599fd659cc14 Parts: 1. uid is the name of the key 2. 1234 is your value in clear 3. 1234567890 is the timestamp 4. d32b9e9c67274fa062e2599fd659cc14 is the signature made from the value and the timestamp

    Read the article

  • Having different database sorting order (default_scope) for two different views

    - by Juniper747
    In my model (pins.rb), I have two sorting orders: default_scope order: 'pins.featured DESC' #for adding featured posts to the top of a list default_scope order: 'pins.created_at DESC' #for adding the remaining posts beneath the featured posts This sorting order (above) is how I want my 'pins view' (index.html.erb) to look. Which is just a list of ALL user posts. In my 'users view' (show.html.erb) I am using the same model (pins.rb) to list only current_user pins. HOWEVER, I want to sorting order to ignore the "featured" default scope and only use the second scope: default_scope order: 'pins.created_at DESC' How can I accomplish this? I tried doing something like this: default_scope order: 'pins.featured DESC', only: :index default_scope order: 'pins.created_at DESC' But that didn't fly... UPDATE I updated my model to define a scope: scope :featy, order: 'pins.featured DESC' default_scope order: 'pins.created_at DESC' And updated my pins view to: <%= render @pins.featy %> However, now when I open my pins view, I get the error: undefined method `featy' for #<Array:0x00000100ddbc78> UPDATE 2 User.rb class User < ActiveRecord::Base attr_accessible :name, :email, :username, :password, :password_confirmation, :avatar, :password_reset_token, :password_reset_sent_at has_secure_password has_many :pins, dependent: :destroy #destroys user posts when user is destroyed # has_many :featured_pins, order: 'featured DESC', class_name: "Pin", source: :pin has_attached_file :avatar, :styles => { :medium => "300x300#", :thumb => "120x120#" } before_save { |user| user.email = user.email.downcase } before_save { |user| user.username = user.username.downcase } before_save :create_remember_token before_save :capitalize_name validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i VALID_USERNAME_REGEX = /^[A-Za-z0-9]+(?:[_][A-Za-z0-9]+)*$/ validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :username, presence: true, format: { with: VALID_USERNAME_REGEX }, uniqueness: { case_sensitive: false } validates :password, length: { minimum: 6 }, on: :create #on create, because was causing erros on pw_reset Pin.rb class Pin < ActiveRecord::Base attr_accessible :content, :title, :privacy, :date, :dark, :bright, :fragmented, :hashtag, :emotion, :user_id, :imagesource, :imageowner, :featured belongs_to :user before_save :capitalize_title before_validation :generate_slug validates :content, presence: true, length: { maximum: 8000 } validates :title, presence: true, length: { maximum: 24 } validates :imagesource, presence: { message: "Please search and choose an image" }, length: { maximum: 255 } validates_inclusion_of :privacy, :in => [true, false] validates :slug, uniqueness: true, presence: true, exclusion: {in: %w[signup signin signout home info privacy]} # for sorting featured and newest posts first default_scope order: 'pins.created_at DESC' scope :featured_order, order: 'pins.featured DESC' def to_param slug # or "#{id}-#{name}".parameterize end def generate_slug # makes the url slug address bar freindly self.slug ||= loop do random_token = Digest::MD5.hexdigest(Time.zone.now.to_s + title)[0..9]+"-"+"#{title}".parameterize break random_token unless Pin.where(slug: random_token).exists? end end protected def capitalize_title self.title = title.split.map(&:capitalize).join(' ') end end users_controller.rb class UsersController < ApplicationController before_filter :signed_in_user, only: [:edit, :update, :show] before_filter :correct_user, only: [:edit, :update, :show] before_filter :admin_user, only: :destroy def index if !current_user.admin? redirect_to root_path end end def menu @user = current_user end def show @user = User.find(params[:id]) @pins = @user.pins current_user.touch(:last_log_in) #sets the last log in time if [email protected]? render 'pages/info/' end end def new @user = User.new end pins_controller.rb class PinsController < ApplicationController before_filter :signed_in_user, except: [:show] # GET /pins, GET /pins.json def index #Live Feed @pins = Pin.all @featured_pins = Pin.featured_order respond_to do |format| format.html # index.html.erb format.json { render json: @pins } end end # GET /pins, GET /pins.json def show #single Pin View @pin = Pin.find_by_slug!(params[:id]) require 'uri' #this gets the photo's id from the stored uri @image_id = URI(@pin.imagesource).path.split('/').second if @pin.privacy == true #check for private pins if signed_in? if @pin.user_id == current_user.id respond_to do |format| format.html # show.html.erb format.json { render json: @pin } end else redirect_to home_path, notice: "Prohibited 1" end else redirect_to home_path, notice: "Prohibited 2" end else respond_to do |format| format.html # show.html.erb format.json { render json: @pin } end end end # GET /pins, GET /pins.json def new @pin = current_user.pins.new respond_to do |format| format.html # new.html.erb format.json { render json: @pin } end end # GET /pins/1/edit def edit @pin = current_user.pins.find_by_slug!(params[:id]) end Finally, on my index.html.erb I have: <%= render @featured_pins %>

    Read the article

  • 11415 compile errors FTW?!

    - by Koning Baard
    Hello. This is something I've really never seen but, I downloaded the source code of the sine wave example at http://www.audiosynth.com/sinewavedemo.html . It is in an old Project Builder Project format, and I want to compile it with Xcode (GCC). However, Xcode gives me 11415 compile errors. The first few are (all in the precompilation of AppKit.h): /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:31:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:31: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:33:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:33: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:35:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:35: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:36:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:36: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:37:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:37: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:38:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:38: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:40:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:40: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:42:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:42: error: expected identifier or '(' before '@' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:48:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:48: error: expected identifier or '(' before '@' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:54:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:54: error: expected identifier or '(' before '@' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:59:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:59: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:61:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:61: error: expected identifier or '(' before '@' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:69:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:69: error: expected identifier or '(' before '+' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:71:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:71: error: expected identifier or '(' before '+' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:39:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:39: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:40:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:40: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:41:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:41: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:42:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:42: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:43:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:43: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:44:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:44: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:45:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:45: error: expected identifier or '(' before '-' token /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:46:0 /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:46: error: expected identifier or '(' before '-' token Some of the code is: HAL.c /* * HAL.c * Sinewave * * Created by james on Fri Apr 27 2001. * Copyright (c) 2001 __CompanyName__. All rights reserved. * */ #include "HAL.h" #include "math.h" appGlobals gAppGlobals; OSStatus appIOProc (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* device); #define FailIf(cond, handler) \ if (cond) { \ goto handler; \ } #define FailWithAction(cond, action, handler) \ if (cond) { \ { action; } \ goto handler; \ } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HAL Sample Code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //#define noErr 0 //#define false 0 OSStatus SetupHAL (appGlobalsPtr globals) { OSStatus err = noErr; UInt32 count, bufferSize; AudioDeviceID device = kAudioDeviceUnknown; AudioStreamBasicDescription format; // get the default output device for the HAL count = sizeof(globals->device); // it is required to pass the size of the data to be returned err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &count, (void *) &device); fprintf(stderr, "kAudioHardwarePropertyDefaultOutputDevice %d\n", err); if (err != noErr) goto Bail; // get the buffersize that the default device uses for IO count = sizeof(globals->deviceBufferSize); // it is required to pass the size of the data to be returned err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyBufferSize, &count, &bufferSize); fprintf(stderr, "kAudioDevicePropertyBufferSize %d %d\n", err, bufferSize); if (err != noErr) goto Bail; // get a description of the data format used by the default device count = sizeof(globals->deviceFormat); // it is required to pass the size of the data to be returned err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &count, &format); fprintf(stderr, "kAudioDevicePropertyStreamFormat %d\n", err); fprintf(stderr, "sampleRate %g\n", format.mSampleRate); fprintf(stderr, "mFormatFlags %08X\n", format.mFormatFlags); fprintf(stderr, "mBytesPerPacket %d\n", format.mBytesPerPacket); fprintf(stderr, "mFramesPerPacket %d\n", format.mFramesPerPacket); fprintf(stderr, "mChannelsPerFrame %d\n", format.mChannelsPerFrame); fprintf(stderr, "mBytesPerFrame %d\n", format.mBytesPerFrame); fprintf(stderr, "mBitsPerChannel %d\n", format.mBitsPerChannel); if (err != kAudioHardwareNoError) goto Bail; FailWithAction(format.mFormatID != kAudioFormatLinearPCM, err = paramErr, Bail); // bail if the format is not linear pcm // everything is ok so fill in these globals globals->device = device; globals->deviceBufferSize = bufferSize; globals->deviceFormat = format; Bail: return (err); } /* struct AudioStreamBasicDescription { Float64 mSampleRate; // the native sample rate of the audio stream UInt32 mFormatID; // the specific encoding type of audio stream UInt32 mFormatFlags; // flags specific to each format UInt32 mBytesPerPacket; // the number of bytes in a packet UInt32 mFramesPerPacket; // the number of frames in each packet UInt32 mBytesPerFrame; // the number of bytes in a frame UInt32 mChannelsPerFrame; // the number of channels in each frame UInt32 mBitsPerChannel; // the number of bits in each channel }; typedef struct AudioStreamBasicDescription AudioStreamBasicDescription; */ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // This is a simple playThru ioProc. It simply places the data in the input buffer back into the output buffer. // Watch out for feedback from Speakers to Microphone OSStatus appIOProc (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* appGlobals) { appGlobalsPtr globals = appGlobals; int i; double phase = gAppGlobals.phase; double amp = gAppGlobals.amp; double pan = gAppGlobals.pan; double freq = gAppGlobals.freq * 2. * 3.14159265359 / globals->deviceFormat.mSampleRate; int numSamples = globals->deviceBufferSize / globals->deviceFormat.mBytesPerFrame; // assume floats for now.... float *out = outOutputData->mBuffers[0].mData; for (i=0; i<numSamples; ++i) { float wave = sin(phase) * amp; phase = phase + freq; *out++ = wave * (1.0-pan); *out++ = wave * pan; } gAppGlobals.phase = phase; return (kAudioHardwareNoError); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OSStatus StartPlayingThruHAL(appGlobalsPtr globals) { OSStatus err = kAudioHardwareNoError; if (globals->soundPlaying) return 0; globals->phase = 0.0; err = AudioDeviceAddIOProc(globals->device, appIOProc, (void *) globals); // setup our device with an IO proc if (err != kAudioHardwareNoError) goto Bail; err = AudioDeviceStart(globals->device, appIOProc); // start playing sound through the device if (err != kAudioHardwareNoError) goto Bail; globals->soundPlaying = true; // set the playing status global to true Bail: return (err); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OSStatus StopPlayingThruHAL(appGlobalsPtr globals) { OSStatus err = kAudioHardwareNoError; if (!globals->soundPlaying) return 0; err = AudioDeviceStop(globals->device, appIOProc); // stop playing sound through the device if (err != kAudioHardwareNoError) goto Bail; err = AudioDeviceRemoveIOProc(globals->device, appIOProc); // remove the IO proc from the device if (err != kAudioHardwareNoError) goto Bail; globals->soundPlaying = false; // set the playing status global to false Bail: return (err); } Sinewave.m // // a very simple Cocoa CoreAudio app // by James McCartney [email protected] www.audiosynth.com // // Sinewave - this class implements a sine oscillator with dezippered control of frequency, pan and amplitude // #import "Sinewave.h" // define a C struct from the Obj-C object so audio callback can access data typedef struct { @defs(Sinewave); } sinewavedef; // this is the audio processing callback. OSStatus appIOProc (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr) { sinewavedef* def = defptr; // get access to Sinewave's data int i; // load instance vars into registers double phase = def->phase; double amp = def->amp; double pan = def->pan; double freq = def->freq; double ampz = def->ampz; double panz = def->panz; double freqz = def->freqz; int numSamples = def->deviceBufferSize / def->deviceFormat.mBytesPerFrame; // assume floats for now.... float *out = outOutputData->mBuffers[0].mData; for (i=0; i<numSamples; ++i) { float wave = sin(phase) * ampz; // generate sine wave phase = phase + freqz; // increment phase // write output *out++ = wave * (1.0-panz); // left channel *out++ = wave * panz; // right channel // de-zipper controls panz = 0.001 * pan + 0.999 * panz; ampz = 0.001 * amp + 0.999 * ampz; freqz = 0.001 * freq + 0.999 * freqz; } // save registers back to object def->phase = phase; def->freqz = freqz; def->ampz = ampz; def->panz = panz; return kAudioHardwareNoError; } @implementation Sinewave - (void) setup { OSStatus err = kAudioHardwareNoError; UInt32 count; device = kAudioDeviceUnknown; initialized = NO; // get the default output device for the HAL count = sizeof(device); // it is required to pass the size of the data to be returned err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &count, (void *) &device); if (err != kAudioHardwareNoError) { fprintf(stderr, "get kAudioHardwarePropertyDefaultOutputDevice error %ld\n", err); return; } // get the buffersize that the default device uses for IO count = sizeof(deviceBufferSize); // it is required to pass the size of the data to be returned err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyBufferSize, &count, &deviceBufferSize); if (err != kAudioHardwareNoError) { fprintf(stderr, "get kAudioDevicePropertyBufferSize error %ld\n", err); return; } fprintf(stderr, "deviceBufferSize = %ld\n", deviceBufferSize); // get a description of the data format used by the default device count = sizeof(deviceFormat); // it is required to pass the size of the data to be returned err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &count, &deviceFormat); if (err != kAudioHardwareNoError) { fprintf(stderr, "get kAudioDevicePropertyStreamFormat error %ld\n", err); return; } if (deviceFormat.mFormatID != kAudioFormatLinearPCM) { fprintf(stderr, "mFormatID != kAudioFormatLinearPCM\n"); return; } if (!(deviceFormat.mFormatFlags & kLinearPCMFormatFlagIsFloat)) { fprintf(stderr, "Sorry, currently only works with float format....\n"); return; } initialized = YES; fprintf(stderr, "mSampleRate = %g\n", deviceFormat.mSampleRate); fprintf(stderr, "mFormatFlags = %08lX\n", deviceFormat.mFormatFlags); fprintf(stderr, "mBytesPerPacket = %ld\n", deviceFormat.mBytesPerPacket); fprintf(stderr, "mFramesPerPacket = %ld\n", deviceFormat.mFramesPerPacket); fprintf(stderr, "mChannelsPerFrame = %ld\n", deviceFormat.mChannelsPerFrame); fprintf(stderr, "mBytesPerFrame = %ld\n", deviceFormat.mBytesPerFrame); fprintf(stderr, "mBitsPerChannel = %ld\n", deviceFormat.mBitsPerChannel); } - (void)setAmpVal:(double)val { amp = val; } - (void)setFreqVal:(double)val { freq = val * 2. * 3.14159265359 / deviceFormat.mSampleRate; } - (void)setPanVal:(double)val { pan = val; } - (BOOL)start { OSStatus err = kAudioHardwareNoError; sinewavedef *def; if (!initialized) return false; if (soundPlaying) return false; // initialize phase and de-zipper filters. phase = 0.0; freqz = freq; ampz = amp; panz = pan; def = (sinewavedef *)self; err = AudioDeviceAddIOProc(device, appIOProc, (void *) def); // setup our device with an IO proc if (err != kAudioHardwareNoError) return false; err = AudioDeviceStart(device, appIOProc); // start playing sound through the device if (err != kAudioHardwareNoError) return false; soundPlaying = true; // set the playing status global to true return true; } - (BOOL)stop { OSStatus err = kAudioHardwareNoError; if (!initialized) return false; if (!soundPlaying) return false; err = AudioDeviceStop(device, appIOProc); // stop playing sound through the device if (err != kAudioHardwareNoError) return false; err = AudioDeviceRemoveIOProc(device, appIOProc); // remove the IO proc from the device if (err != kAudioHardwareNoError) return false; soundPlaying = false; // set the playing status global to false return true; } @end Can anyone help me compiling this example? I'd really appriciate it. Thanks

    Read the article

  • Rotating text in postscript

    - by Mrgreen
    I have the following postscript code: /outputtext { /data exch def /rot exch def /xfont exch def /Times-Roman findfont xfont scalefont setfont /y1 exch def /x1 exch def x1 y1 moveto rot rotate data show } def % x y fontsize rotation (text) outputtext 20 300 12 0 (text1) outputtext 20 400 12 90 (text2) outputtext 20 500 12 90 (text3) outputtext 20 600 12 0 (text4) outputtext showpage The function simply outputs text based on a x, y co-ords and the text to display, there is also a variable for rotation. For some reason when I output text with a rotation of 0 degrees, all other text that comes after that will not work, I can't seem to figure out why this is the case. In the example above, 'text1' and 'text2' will display, but not 3 and 4.

    Read the article

  • groovy thread for urls

    - by Srinath
    I wrote logic for testing urls using threads. This works good for less number of urls and failing with more than 400 urls to check . class URL extends Thread{ def valid def url URL( url ) { this.url = url } void run() { try { def connection = url.toURL().openConnection() connection.setConnectTimeout(10000) if(connection.responseCode == 200 ){ valid = Boolean.TRUE }else{ valid = Boolean.FALSE } } catch ( Exception e ) { valid = Boolean.FALSE } } } def threads = []; urls.each { ur - def reader = new URL(ur) reader.start() threads.add(reader); } while (threads.size() 0) { for(int i =0; i < threads.size();i++) { def tr = threads.get(i); if (!tr.isAlive()) { if(tr.valid == true){ threads.remove(i); i--; }else{ threads.remove(i); i--; } } } Could any one please tell me how to optimize the logic and where i was going wrong . thanks in advance.

    Read the article

  • Python Decorators and inheritance

    - by wheaties
    Help a guy out. Can't seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can't seem to get it working. class bar(object): def __init__(self): self.val = 4 def setVal(self,x): self.val = x def decor(self, func): def increment(self, x): return func( self, x ) + self.val return increment class foo(bar): def __init__(self): bar.__init__(self) @decor def add(self, x): return x Oops, name "decor" is not defined. Okay, how about @bar.decor? TypeError: unbound method "decor" must be called with a bar instance as first argument (got function instance instead) Ok, how about @self.decor? Name "self" is not defined. Ok, how about @foo.decor?! Name "foo" is not defined. AaaaAAaAaaaarrrrgggg... What am I doing wrong?

    Read the article

  • Error in writting a class.

    - by Richard
    I am running through a tutorial online at http://www.sthurlow.com/python/lesson08/ and I believe I understand how classes work in python, at least to some degree but when I run this code: class Shape: def init(self,x,y): self.x = x self.y = y description = "This shape has not been described yet" author = "Nobody has claimed to make this shape yet" def area(self): return self.x * self.y def perimeter(self): return 2 * self.x + 2 * self.y def describe(self,text): self.description = text def authorName(self,text): self.author = text def scaleSize(self,scale): self.x = self.x * scale self.y = self.y * scale I get this error: Traceback (most recent call last): File "Y:/python/Shape.py", line 1, in -toplevel- class Shape: File "Y:/python/Shape.py", line 17, in Shape self.y = self.y * scale NameError: name 'self' is not defined Any Help would be great Thanks Richard

    Read the article

  • Grails and googleJsonAPIService

    - by Calahad
    I am using the googleJsonAPIService to manipulate users (CRUD). This is how I get the Directory instance: def getBuilder() { def builder def httpTransport = googleJsonAPIService.makeTransport() def jsonFactory = googleJsonAPIService.makeJsonFactory() def requestInitialiser = googleJsonAPIService.getRequestInitialiser() builder = new Directory.Builder(httpTransport, jsonFactory, requestInitialiser); return builder } Directory getGoogleService() { Directory googleService = getBuilder().build() return googleService; } Once I have this service, I use it to get a user's details (in my own service) for example: def query = getGoogleService().users().get(id) return handleException { query.execute() } I manually populate a DTO with the result of that query, and this is where my question comes: Is there an elegant way to have this mapping (object returned to DTO) done automatically so all I have to do is pass the class of the object to be returned? This is the structure of the object returned by google : ["agreedToTerms":true,"changePasswordAtNextLogin":false, "creationTime":"2013-11-04T04:33:35.000Z", "emails":[{"address":"[email protected]","primary":true}],...]

    Read the article

  • Rails validation count limit on has_many :through

    - by Jeremy
    I've got the following models: Team, Member, Assignment, Role The Team model has_many Members. Each Member has_many roles through assignments. Role assignments are Captain and Runner. I have also installed devise and CanCan using the Member model. What I need to do is limit each Team to have a max of 1 captain and 5 runners. I found this example, and it seemed to work after some customization, but on update ('teams/1/members/4/edit'). It doesn't work on create ('teams/1/members/new'). But my other validation (validates :role_ids, :presence = true ) does work on both update and create. Any help would be appreciated. Update: I've found this example that would seem to be similar to my problem but I can't seem to make it work for my app. It seems that the root of the problem lies with how the count (or size) is performed before and during validation. For Example: When updating a record... It checks to see how many runners there are on a team and returns a count. (i.e. 5) Then when I select a role(s) to add to the member it takes the known count from the database (i.e. 5) and adds the proposed changes (i.e. 1), and then runs the validation check. (Team.find(self.team_id).members.runner.count 5) This works fine because it returns a value of 6 and 6 5 so the proposed update fails without saving and an error is given. But when I try to create a new member on the team... It checks to see how many runners there are on a team and returns a count. (i.e. 5) Then when I select a role(s) to add to the member it takes the known count from the database (i.e. 5) and then runs the validation check WITHOUT factoring in the proposed changes. This doesn't work because it returns a value of 5 known runner and 5 = 5 so the proposed update passes and the new member and role is saved to the database with no error. Member Model: class Member < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :password, :password_confirmation, :remember_me attr_accessible :age, :email, :first_name, :last_name, :sex, :shirt_size, :team_id, :assignments_attributes, :role_ids belongs_to :team has_many :assignments, :dependent => :destroy has_many :roles, through: :assignments accepts_nested_attributes_for :assignments scope :runner, joins(:roles).where('roles.title = ?', "Runner") scope :captain, joins(:roles).where('roles.title = ?', "Captain") validate :validate_runner_count validate :validate_captain_count validates :role_ids, :presence => true def validate_runner_count if Team.find(self.team_id).members.runner.count > 5 errors.add(:role_id, 'Error - Max runner limit reached') end end def validate_captain_count if Team.find(self.team_id).members.captain.count > 1 errors.add(:role_id, 'Error - Max captain limit reached') end end def has_role?(role_sym) roles.any? { |r| r.title.underscore.to_sym == role_sym } end end Member Controller: class MembersController < ApplicationController load_and_authorize_resource :team load_and_authorize_resource :member, :through => :team before_filter :get_team before_filter :initialize_check_boxes, :only => [:create, :update] def get_team @team = Team.find(params[:team_id]) end def index respond_to do |format| format.html # index.html.erb format.json { render json: @members } end end def show respond_to do |format| format.html # show.html.erb format.json { render json: @member } end end def new respond_to do |format| format.html # new.html.erb format.json { render json: @member } end end def edit end def create respond_to do |format| if @member.save format.html { redirect_to [@team, @member], notice: 'Member was successfully created.' } format.json { render json: [@team, @member], status: :created, location: [@team, @member] } else format.html { render action: "new" } format.json { render json: @member.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @member.update_attributes(params[:member]) format.html { redirect_to [@team, @member], notice: 'Member was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @member.errors, status: :unprocessable_entity } end end end def destroy @member.destroy respond_to do |format| format.html { redirect_to team_members_url } format.json { head :no_content } end end # Allow empty checkboxes # http://railscasts.com/episodes/17-habtm-checkboxes def initialize_check_boxes params[:member][:role_ids] ||= [] end end _Form Partial <%= form_for [@team, @member], :html => { :class => 'form-horizontal' } do |f| %> #... # testing the count... <ul> <li>Captain - <%= Team.find(@member.team_id).members.captain.size %></li> <li>Runner - <%= Team.find(@member.team_id).members.runner.size %></li> <li>Driver - <%= Team.find(@member.team_id).members.driver.size %></li> </ul> <div class="control-group"> <div class="controls"> <%= f.fields_for :roles do %> <%= hidden_field_tag "member[role_ids][]", nil %> <% Role.all.each do |role| %> <%= check_box_tag "member[role_ids][]", role.id, @member.role_ids.include?(role.id), id: dom_id(role) %> <%= label_tag dom_id(role), role.title %> <% end %> <% end %> </div> </div> #... <% end %>

    Read the article

  • 'int' object is not callable

    - by Oscar Reyes
    I'm trying to define a simply Fraction class And I'm getting this error: python fraction.py Traceback (most recent call last): File "fraction.py", line 20, in <module> f.numerator(2) TypeError: 'int' object is not callable The code follows: class Fraction(object): def __init__( self, n=0, d=0 ): self.numerator = n self.denominator = d def get_numerator(self): return self.numerator def get_denominator(self): return self.denominator def numerator(self, n): self.numerator = n def denominator( self, d ): self.denominator = d def prints( self ): print "%d/%d" %(self.numerator, self.denominator) if __name__ == "__main__": f = Fraction() f.numerator(2) f.denominator(5) f.prints() I thought it was because I had numerator(self) and numerator(self, n) but now I know Python doesn't have method overloading ( function overloading ) so I renamed to get_numerator but that's not the problems. What could it be?

    Read the article

  • Implicit parameter in Scalaz

    - by Thomas Jung
    I try to find out why the call Ø in scalaz.ListW.<^> works def <^>[B: Zero](f: NonEmptyList[A] => B): B = value match { case Nil => Ø case h :: t => f(Scalaz.nel(h, t)) } My minimal theory is: trait X[T]{ def y : T } object X{ implicit object IntX extends X[Int]{ def y = 42 } implicit object StringX extends X[String]{ def y = "y" } } trait Xs{ def ys[T](implicit x : X[T]) = x.y } class A extends Xs{ def z[B](implicit x : X[B]) : B = ys //the call Ø } Which produces: import X._ scala> new A().z[Int] res0: Int = 42 scala> new A().z[String] res1: String = y Is this valid? Can I achieve the same result with fewer steps?

    Read the article

  • how to create local dynamic varables

    - by xielingyun
    this is my code, i want to use eval() to get the rule status and eval() nead local varables, there is many classes inherit class base, so i should to rewrite get_stat() in every class.i just want to avoid this, an idea is to create dynamic varables in get_stat(),eg. in class b it dynamic create var a and b how to create dynamic varables in function? or any other way to avoid this stupid idea i use python 3.2.3, locals() does not work class base(object): def check(self): stat = get_stat() def get_stat(self): pass class b(base): rule = 'a > 5 and b < 3' a = 0 b = 0 def update_data(self, a, b): self.a = a self.b = b def get_stat(self): a = self.a b = self.b return eval(rule) class b(base): rule = 'd > 5 and e < 3' d = 0 e = 0 def update_data(self, d, e): self.d = d self.e = e def get_stat(self): d = self.d e = self.e return eval(rule)

    Read the article

  • Split a map using Groovy

    - by Tihom
    I want to split up a map into an array of maps. For example, if there is a map with 25 key/value pairs. I want an array of maps with no more than 10 elements in each map. How would I do this in groovy? I have a solution which I am not excited about, is there better groovy version: static def splitMap(m, count){ if (!m) return def keys = m.keySet().toList() def result = [] def num = Math.ceil(m?.size() / count) (1..num).each { def min = (it - 1) * count def max = it * count > keys.size() ? keys.size() - 1 : it * count - 1 result[it - 1] = [:] keys[min..max].each {k -> result[it - 1][k] = m[k] } } result } m is the map. Count is the max number of elements within the map.

    Read the article

  • fluent interface program in Ruby

    - by intern
    we have made the following code and trying to run it. class Numeric def gram self end alias_method :grams, :gram def of(name) ingredient = Ingredient.new(name) ingredient.quantity=self return ingredient end end class Ingredient def initialize(n) @@name= n end def quantity=(o) @@quantity = o return @@quantity end def name return @@name end def quantity return @@quantity end end e= 42.grams.of("Test") a= Ingredient.new("Testjio") puts e.quantity a.quantity=90 puts a.quantity puts e.quantity the problem which we are facing in it is that the output of puts a.quantity puts e.quantity is same even when the objects are different. what we observed is that second object i.e 'a' is replacing the value of the first object i.e. 'e'. the output is coming out to be 42 90 90 but the output required is 42 90 42 can anyone suggest why is it happening? it is not replacing the object as object id's are different..only the values of the objects are replaced.

    Read the article

  • fluent interface program in Ruby

    - by intern
    we have made the following code and trying to run it. class Numeric def gram self end alias_method :grams, :gram def of(name) ingredient = Ingredient.new(name) ingredient.quantity=self return ingredient end end class Ingredient def initialize(n) @@name= n end def quantity=(o) @@quantity = o return @@quantity end def name return @@name end def quantity return @@quantity end end e= 42.grams.of("Test") a= Ingredient.new("Testjio") puts e.quantity a.quantity=90 puts a.quantity puts e.quantity the problem which we are facing in it is that the output of puts a.quantity puts e.quantity is same even when the objects are different. what we observed is that second object i.e 'a' is replacing the value of the first object i.e. 'e'. the output is coming out to be 42 90 90 but the output required is 42 90 42 can anyone suggest why is it happening? it is not replacing the object as object id's are different..only the values of the objects are replaced.

    Read the article

  • Proper structure for many test cases in Python with unittest

    - by mellort
    I am looking into the unittest package, and I'm not sure of the proper way to structure my test cases when writing a lot of them for the same method. Say I have a fact function which calculates the factorial of a number; would this testing file be OK? import unittest class functions_tester(unittest.TestCase): def test_fact_1(self): self.assertEqual(1, fact(1)) def test_fact_2(self): self.assertEqual(2, fact(2)) def test_fact_3(self): self.assertEqual(6, fact(3)) def test_fact_4(self): self.assertEqual(24, fact(4)) def test_fact_5(self): self.assertFalse(1==fact(5)) def test_fact_6(self): self.assertRaises(RuntimeError, fact, -1) #fact(-1) if __name__ == "__main__": unittest.main() It seems sloppy to have so many test methods for one method. I'd like to just have one testing method and put a ton of basic test cases (ie 4! ==24, 3!==6, 5!==120, and so on), but unittest doesn't let you do that. What is the best way to structure a testing file in this scenario? Thanks in advance for the help.

    Read the article

  • pyramid traversal resource url no attribute __name__

    - by Santana
    So I have: resources.py: def _add(obj, name, parent): obj.__name__ = name obj.__parent__ = parent return obj class Root(object): __parent__ = __name__ = None def __init__(self, request): super(Root, self).__init__() self.request = request self.collection = request.db.post def __getitem__(self, key): if u'profile' in key: return Profile(self.request) class Profile(dict): def __init__(self, request): super(Profile, self).__init__() self.__name__ = u'profile' self.__parent__ = Root self.collection = request.db.posts def __getitem__(self, name): post = Dummy(self.collection.find_one(dict(username=name))) return _add(post, name, self) and I'm using MongoDB and pyramid_mongodb views.py: @view_config(context = Profile, renderer = 'templates/mytemplate.pt') def test_view(request): return {} and in mytemplate.pt: <p tal:repeat='item request.context'> ${item} </p> I can echo what's in the database (I'm using mongodb), but when I provided a URL for each item using resource_url() <p tal:repeat='item request.context'> <a href='${request.resource_url(item)}'>${item}</a> </p> I got an error: 'dict' object has no attribute '__name__', can someone help me?

    Read the article

  • Type parameterization in Scala

    - by horatius83
    So I'm learning Scala at the moment, and I'm trying to create an abstract vector class with a vector-space of 3 (x,y,z coordinates). I'm trying to add two of these vectors together with the following code: package math class Vector3[T](ax:T,ay:T,az:T) { def x = ax def y = ay def z = az override def toString = "<"+x+", "+y+", "+z+">" def add(that: Vector3[T]) = new Vector3(x+that.x, y+that.y, z+that.z) } The problem is I keep getting this error: error: type mismatch; found : T required: String def add(that: Vector3[T]) = new Vector3(x+that.x, y+that.y, z+that.z) I've tried commenting out the "toString" method above, but that doesn't seem to have any effect. Can anyone tell me what I'm doing wrong?

    Read the article

  • Working with nested models in ROR

    - by user487429
    Hi there, I'm trying to create an application where users can freely create shops and associated shop item for a specific shop is displayed when a show action is called but I seem to be doing something wrong. Any help here will be appreciated. I have attached shots of my code below. class ShopItem < ActiveRecord::Base belongs_to :shop def self.find_shop_items_for_sale find(:all, :order => "title", :conditions => ["shop_id = ?", @shop.id]) end end class Shop < ActiveRecord::Base has_many :shop_items end #Controllers class ShopsController < ApplicationController def new @shop = Shop.new end def create @shop = Shop.new(params[:shop]) @shop.user_id = current_user.id respond_to do |format| if @shop.save flash[:notice] = "Successfully created shop." format.html {redirect_to(all_shops_shops_url)} format.xml {render :xml => @shop, :status => :created, :location => @shop } else format.html {render :action => 'new'} format.xml { render :xml => @shop.errors, :status => :unprocessable_entity } end end end def show @shop = Shop.find(params[:id]) @shop_items = ShopItem.find_shop_items_for_sale @shop_cart = find_shop_cart end class ShopItemsController < ApplicationController def user @per_page ||= 5 @user = User.find(params[:id]) @shop_items = ShopItem.find(:all, :conditions=>["user_id = ?", @user.id], :order=>"id desc") end def show @shop_item = ShopItem.find(params[:id]) @shop = @shop_item.shop respond_to do |format| format.html # show.html.erb format.xml { render :xml => @shop_item } end end # GET /shop_items/new # GET /shop_items/new.xml def new @shop_item = ShopItem.new @shop = Shop.find(params[:id]) #@shop_items = ShopItem.paginate(:all, :condition=>["shop_id] = ?", @shop.id], :order=> "id desc", :page => params[:page],:per_page => @per_page) @shop_items = ShopItem.find(:all, :conditions=>["shop_id = ?", @shop.id], :order=> "id desc") @shop_item.shop_id = params[:id] respond_to do |format| format.html # new.html.erb format.xml { render :xml => @shop_item } end end # GET /shop_items/1/edit def edit @shop_item = ShopItem.find(params[:id]) end # POST /shop_items # POST /shop_items.xml def create @shop_item = ShopItem.new(params[:shop_item]) @shop_item.user_id = current_user.id respond_to do |format| if @shop_item.save flash[:notice] = 'Shop item was successfully created.' format.html { redirect_to(@shop_item) } format.xml { render :xml => @shop_item, :status => :created, :location => @shop_item } else @shop = Shop.find(@shop_item.shop_id) #@shop_items = ShopItem.paginate(:all, :condition =>["shop_id = ?", @shop.id], :order=> "id desc" , :page => params[:page], :per_page => @per_page) @shop_items = ShopItem.find(:all, :conditions =>["shop_id = ?", @shop.id], :order=> "id desc") format.html { render :action => "new" } format.xml { render :xml => @shop_item.errors, :status => :unprocessable_entity } end end end

    Read the article

  • Why does decorating a class break the descriptor protocol, thus preventing staticmethod objects from behaving as expected?

    - by Robru
    I need a little bit of help understanding the subtleties of the descriptor protocol in Python, as it relates specifically to the behavior of staticmethod objects. I'll start with a trivial example, and then iteratively expand it, examining it's behavior at each step: class Stub: @staticmethod def do_things(): """Call this like Stub.do_things(), with no arguments or instance.""" print "Doing things!" At this point, this behaves as expected, but what's going on here is a bit subtle: When you call Stub.do_things(), you are not invoking do_things directly. Instead, Stub.do_things refers to a staticmethod instance, which has wrapped the function we want up inside it's own descriptor protocol such that you are actually invoking staticmethod.__get__, which first returns the function that we want, and then gets called afterwards. >>> Stub <class __main__.Stub at 0x...> >>> Stub.do_things <function do_things at 0x...> >>> Stub.__dict__['do_things'] <staticmethod object at 0x...> >>> Stub.do_things() Doing things! So far so good. Next, I need to wrap the class in a decorator that will be used to customize class instantiation -- the decorator will determine whether to allow new instantiations or provide cached instances: def deco(cls): def factory(*args, **kwargs): # pretend there is some logic here determining # whether to make a new instance or not return cls(*args, **kwargs) return factory @deco class Stub: @staticmethod def do_things(): """Call this like Stub.do_things(), with no arguments or instance.""" print "Doing things!" Now, naturally this part as-is would be expected to break staticmethods, because the class is now hidden behind it's decorator, ie, Stub not a class at all, but an instance of factory that is able to produce instances of Stub when you call it. Indeed: >>> Stub <function factory at 0x...> >>> Stub.do_things Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'function' object has no attribute 'do_things' >>> Stub() <__main__.Stub instance at 0x...> >>> Stub().do_things <function do_things at 0x...> >>> Stub().do_things() Doing things! So far I understand what's happening here. My goal is to restore the ability for staticmethods to function as you would expect them to, even though the class is wrapped. As luck would have it, the Python stdlib includes something called functools, which provides some tools just for this purpose, ie, making functions behave more like other functions that they wrap. So I change my decorator to look like this: def deco(cls): @functools.wraps(cls) def factory(*args, **kwargs): # pretend there is some logic here determining # whether to make a new instance or not return cls(*args, **kwargs) return factory Now, things start to get interesting: >>> Stub <function Stub at 0x...> >>> Stub.do_things <staticmethod object at 0x...> >>> Stub.do_things() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'staticmethod' object is not callable >>> Stub() <__main__.Stub instance at 0x...> >>> Stub().do_things <function do_things at 0x...> >>> Stub().do_things() Doing things! Wait.... what? functools copies the staticmethod over to the wrapping function, but it's not callable? Why not? What did I miss here? I was playing around with this for a bit and I actually came up with my own reimplementation of staticmethod that allows it to function in this situation, but I don't really understand why it was necessary or if this is even the best solution to this problem. Here's the complete example: class staticmethod(object): """Make @staticmethods play nice with decorated classes.""" def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): """Provide the expected behavior inside decorated classes.""" return self.func(*args, **kwargs) def __get__(self, obj, objtype=None): """Re-implement the standard behavior for undecorated classes.""" return self.func def deco(cls): @functools.wraps(cls) def factory(*args, **kwargs): # pretend there is some logic here determining # whether to make a new instance or not return cls(*args, **kwargs) return factory @deco class Stub: @staticmethod def do_things(): """Call this like Stub.do_things(), with no arguments or instance.""" print "Doing things!" Indeed it works exactly as expected: >>> Stub <function Stub at 0x...> >>> Stub.do_things <__main__.staticmethod object at 0x...> >>> Stub.do_things() Doing things! >>> Stub() <__main__.Stub instance at 0x...> >>> Stub().do_things <function do_things at 0x...> >>> Stub().do_things() Doing things! What approach would you take to make a staticmethod behave as expected inside a decorated class? Is this the best way? Why doesn't the builtin staticmethod implement __call__ on it's own in order for this to just work without any fuss? Thanks.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >